我使用 OpenAI API。我从 PowerPoint 演示文稿中提取了幻灯片文本,并为每张幻灯片编写了提示。现在,我想进行异步 API 调用,以便同时处理所有幻灯片。
这是异步主函数的代码:
for prompt in prompted_slides_text:
task = asyncio.create_task(api_manager.generate_answer(prompt))
tasks.append(task)
results = await asyncio.gather(*tasks)
Run Code Online (Sandbox Code Playgroud)
这是generate_answer函数:
@staticmethod
async def generate_answer(prompt):
"""
Send a prompt to OpenAI API and get the answer.
:param prompt: the prompt to send.
:return: the answer.
"""
completion = await openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
return completion.choices[0].message.content
Run Code Online (Sandbox Code Playgroud)
问题是:
对象 OpenAIObject 不能在“await”表达式中使用
我不知道如何等待generate_answer函数中的响应
将不胜感激任何帮助!