‘asyncio‘ with OpenAI API Call Hangs After Extended Run Time

2024-08-27 21:04

本文主要是介绍‘asyncio‘ with OpenAI API Call Hangs After Extended Run Time,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

题意:“使用 OpenAI API 调用时,asyncio 在长时间运行后挂起”

问题背景:

I'm using asyncio alongside the OpenAI API to translate a set of texts concurrently. Initially, everything works as expected, and I see the answers from OpenAI printed in the console. However, after running for a while, the code seems to hang. Subsequent answers from OpenAI are not printed in the console, and I don't see any "retrying" messages either. Here's my code:

“我在使用 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 = 2async 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 answerexcept Exception as e:print(e)await asyncio.sleep(5)max_retry -= 1print('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 resultsif __name__ == '__main__':textList = '... (some texts are omitted for brevity)'translations = asyncio.run(atranslate(textList*20, 'Korean', 'English',30))

When I run the above code, it starts off well but after some time, it simply hangs. What could be causing this? Are there any solutions or suggestions to address this issue?

“当我运行上述代码时,起初一切正常,但一段时间后,它就挂起了。可能是什么原因导致的?是否有解决方案或建议来解决这个问题?”

I have tried to change the timeout parameter or simply not raise ConnectionError, but it doesn't work.I think it might be the problem of api usage limits, but I don't know why it doesn't throw any error.

“我尝试更改超时参数或干脆不抛出 ConnectionError,但没有效果。我认为这可能是 API 使用限制的问题,但我不明白为什么它没有抛出任何错误。”

问题解决:

Two things, first I would wrap the use of ClientSession in try...finally, or use it as a contextmanager as shown here.

“两点建议:首先,我会将 ClientSession 的使用包装在 try...finally 中,或者像这里显示的那样将其用作 contextmanager。”

Also, if you are pretty sure that there are some exceptions getting swallowed somewhere, try to catch BaseException instead of Exception. Yes, there is a BaseException class which except Exception: won't catch, and the asyncio library throws exceptions derived from BaseException sometimes.

“此外,如果你确定某些异常在某处被吞掉了,可以尝试捕获 BaseException 而不是 Exception。是的,确实有一个 BaseException 类,而 except Exception: 并不会捕获它。asyncio 库有时会抛出从 BaseException 派生的异常。”

这篇关于‘asyncio‘ with OpenAI API Call Hangs After Extended Run Time的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1112768

相关文章

PHP应用中处理限流和API节流的最佳实践

《PHP应用中处理限流和API节流的最佳实践》限流和API节流对于确保Web应用程序的可靠性、安全性和可扩展性至关重要,本文将详细介绍PHP应用中处理限流和API节流的最佳实践,下面就来和小编一起学习... 目录限流的重要性在 php 中实施限流的最佳实践使用集中式存储进行状态管理(如 Redis)采用滑动

Python异步编程之await与asyncio基本用法详解

《Python异步编程之await与asyncio基本用法详解》在Python中,await和asyncio是异步编程的核心工具,用于高效处理I/O密集型任务(如网络请求、文件读写、数据库操作等),接... 目录一、核心概念二、使用场景三、基本用法1. 定义协程2. 运行协程3. 并发执行多个任务四、关键

Go语言使用net/http构建一个RESTful API的示例代码

《Go语言使用net/http构建一个RESTfulAPI的示例代码》Go的标准库net/http提供了构建Web服务所需的强大功能,虽然众多第三方框架(如Gin、Echo)已经封装了很多功能,但... 目录引言一、什么是 RESTful API?二、实战目标:用户信息管理 API三、代码实现1. 用户数据

Python用Flask封装API及调用详解

《Python用Flask封装API及调用详解》本文介绍Flask的优势(轻量、灵活、易扩展),对比GET/POST表单/JSON请求方式,涵盖错误处理、开发建议及生产环境部署注意事项... 目录一、Flask的优势一、基础设置二、GET请求方式服务端代码客户端调用三、POST表单方式服务端代码客户端调用四

SpringBoot结合Knife4j进行API分组授权管理配置详解

《SpringBoot结合Knife4j进行API分组授权管理配置详解》在现代的微服务架构中,API文档和授权管理是不可或缺的一部分,本文将介绍如何在SpringBoot应用中集成Knife4j,并进... 目录环境准备配置 Swagger配置 Swagger OpenAPI自定义 Swagger UI 底

使用Python的requests库调用API接口的详细步骤

《使用Python的requests库调用API接口的详细步骤》使用Python的requests库调用API接口是开发中最常用的方式之一,它简化了HTTP请求的处理流程,以下是详细步骤和实战示例,涵... 目录一、准备工作:安装 requests 库二、基本调用流程(以 RESTful API 为例)1.

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

Knife4j+Axios+Redis前后端分离架构下的 API 管理与会话方案(最新推荐)

《Knife4j+Axios+Redis前后端分离架构下的API管理与会话方案(最新推荐)》本文主要介绍了Swagger与Knife4j的配置要点、前后端对接方法以及分布式Session实现原理,... 目录一、Swagger 与 Knife4j 的深度理解及配置要点Knife4j 配置关键要点1.Spri

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis