‘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

相关文章

基于Flask框架添加多个AI模型的API并进行交互

《基于Flask框架添加多个AI模型的API并进行交互》:本文主要介绍如何基于Flask框架开发AI模型API管理系统,允许用户添加、删除不同AI模型的API密钥,感兴趣的可以了解下... 目录1. 概述2. 后端代码说明2.1 依赖库导入2.2 应用初始化2.3 API 存储字典2.4 路由函数2.5 应

Python异步编程中asyncio.gather的并发控制详解

《Python异步编程中asyncio.gather的并发控制详解》在Python异步编程生态中,asyncio.gather是并发任务调度的核心工具,本文将通过实际场景和代码示例,展示如何结合信号量... 目录一、asyncio.gather的原始行为解析二、信号量控制法:给并发装上"节流阀"三、进阶控制

python中time模块的常用方法及应用详解

《python中time模块的常用方法及应用详解》在Python开发中,时间处理是绕不开的刚需场景,从性能计时到定时任务,从日志记录到数据同步,时间模块始终是开发者最得力的工具之一,本文将通过真实案例... 目录一、时间基石:time.time()典型场景:程序性能分析进阶技巧:结合上下文管理器实现自动计时

C#集成DeepSeek模型实现AI私有化的流程步骤(本地部署与API调用教程)

《C#集成DeepSeek模型实现AI私有化的流程步骤(本地部署与API调用教程)》本文主要介绍了C#集成DeepSeek模型实现AI私有化的方法,包括搭建基础环境,如安装Ollama和下载DeepS... 目录前言搭建基础环境1、安装 Ollama2、下载 DeepSeek R1 模型客户端 ChatBo

SpringBoot快速接入OpenAI大模型的方法(JDK8)

《SpringBoot快速接入OpenAI大模型的方法(JDK8)》本文介绍了如何使用AI4J快速接入OpenAI大模型,并展示了如何实现流式与非流式的输出,以及对函数调用的使用,AI4J支持JDK8... 目录使用AI4J快速接入OpenAI大模型介绍AI4J-github快速使用创建SpringBoot

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Deepseek R1模型本地化部署+API接口调用详细教程(释放AI生产力)

《DeepseekR1模型本地化部署+API接口调用详细教程(释放AI生产力)》本文介绍了本地部署DeepSeekR1模型和通过API调用将其集成到VSCode中的过程,作者详细步骤展示了如何下载和... 目录前言一、deepseek R1模型与chatGPT o1系列模型对比二、本地部署步骤1.安装oll

浅析如何使用Swagger生成带权限控制的API文档

《浅析如何使用Swagger生成带权限控制的API文档》当涉及到权限控制时,如何生成既安全又详细的API文档就成了一个关键问题,所以这篇文章小编就来和大家好好聊聊如何用Swagger来生成带有... 目录准备工作配置 Swagger权限控制给 API 加上权限注解查看文档注意事项在咱们的开发工作里,API

一分钟带你上手Python调用DeepSeek的API

《一分钟带你上手Python调用DeepSeek的API》最近DeepSeek非常火,作为一枚对前言技术非常关注的程序员来说,自然都想对接DeepSeek的API来体验一把,下面小编就来为大家介绍一下... 目录前言免费体验API-Key申请首次调用API基本概念最小单元推理模型智能体自定义界面总结前言最

JAVA调用Deepseek的api完成基本对话简单代码示例

《JAVA调用Deepseek的api完成基本对话简单代码示例》:本文主要介绍JAVA调用Deepseek的api完成基本对话的相关资料,文中详细讲解了如何获取DeepSeekAPI密钥、添加H... 获取API密钥首先,从DeepSeek平台获取API密钥,用于身份验证。添加HTTP客户端依赖使用Jav