我使用 asyncio 和 OpenAI API 来同时翻译一组文本。最初,一切都按预期进行,我看到 OpenAI 的答案打印在控制台中。然而,运行一段时间后,代码似乎挂起。 OpenAI 的后续答案不会打印在控制台中,我也没有看到任何“重试”消息。这是我的代码:
import asyncio
from aiohttp import ClientSession
import openai
import os
openai.api_key = os.getenv("OPENAI_API_KEY")
async def _atranslate(sem, messages, **model_kwargs):
max_retry = 2
async with sem:
while max_retry > 0:
try:
response = await openai.ChatCompletion.acreate(
messages=messages,
**model_kwargs
)
answer = response.choices[0]['message']['content']
print(answer)
return answer
except Exception as e:
print(e)
await asyncio.sleep(5)
max_retry -= 1
print('retrying...')
raise ConnectionError('cannot reach openai!')
async def atranslate(text_list: list, source=None, target='English', max_workers=3, **model_kwargs):
aio_session = ClientSession()
openai.aiosession.set(aio_session)
model_kwargs.setdefault('model', 'gpt-3.5-turbo')
model_kwargs.setdefault('temperature', 1)
model_kwargs.setdefault('timeout', 10)
template = 'Translate the following {source} text into {target}:{text}'
semaphore = asyncio.Semaphore(max_workers)
tasks = []
for text in text_list:
messages = [{
'role': 'user',
'content': template.format(
source=source,
target=target,
text=text
)}
]
tasks.append(asyncio.create_task(_atranslate(semaphore, messages, **model_kwargs)))
results = await asyncio.gather(*tasks)
await aio_session.close()
return results
if __name__ == '__main__':
textList = '... (some texts are omitted for brevity)'
translations = asyncio.run(atranslate(textList*20, 'Korean', 'English',30))
当我运行上面的代码时,它一开始运行良好,但一段时间后,它就挂起了。可能是什么原因造成的?有什么解决方案或建议来解决这个问题吗?
我尝试过更改超时参数或者干脆不引发ConnectionError,但它不起作用。我认为这可能是api使用限制的问题,但我不知道为什么它不抛出任何错误。
有两件事,首先我会将
ClientSession
的使用包装在 try...finally
中,或者将其用作 contextmanager
,如here所示。
此外,如果您非常确定某些异常会被某些地方吞掉,请尝试捕获
BaseException
而不是 Exception
。是的,有一个 BaseException
类无法捕获,并且 except Exception:
库有时会抛出从 asyncio
派生的异常。