OpenAI API异步调用报错:OpenAIObject无法用于await表达式求助
问题解决:OpenAI异步调用报错"object OpenAIObject can't be used in 'await' expression"
错误原因
你当前使用的OpenAI Python库是同步版本,openai.ChatCompletion.create是同步阻塞方法,并非可等待的协程对象,因此在async函数中使用await会触发该错误。
解决方案
提供两种可行修复方式,可根据你的库版本选择:
方式1:使用OpenAI异步客户端(推荐,适配v1.x版本)
OpenAI Python库v1.x及以上版本提供了官方异步客户端,修改步骤如下:
- 先升级到最新版OpenAI库:
pip install --upgrade openai
- 修改
generate_answer函数:
from openai import AsyncOpenAI @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. """ client = AsyncOpenAI() completion = await client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}] ) return completion.choices[0].message.content
方式2:用asyncio.to_thread包装同步调用(适配旧版本或不想升级库的场景)
如果不想升级库,可通过asyncio.to_thread将同步方法放到线程中执行,避免阻塞事件循环:
import asyncio @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 asyncio.to_thread( openai.ChatCompletion.create, model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}] ) return completion.choices[0].message.content
主函数无需修改
你的异步主函数代码保持原样即可正常运行:
for prompt in prompted_slides_text: task = asyncio.create_task(api_manager.generate_answer(prompt)) tasks.append(task) results = await asyncio.gather(*tasks)
内容的提问来源于stack exchange,提问作者DanielG
相关产品推荐
相关产品推荐

