‘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

相关文章

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

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

使用Python实现调用API获取图片存储到本地的方法

《使用Python实现调用API获取图片存储到本地的方法》开发一个自动化工具,用于从JSON数据源中提取图像ID,通过调用指定API获取未经压缩的原始图像文件,并确保下载结果与Postman等工具直接... 目录使用python实现调用API获取图片存储到本地1、项目概述2、核心功能3、环境准备4、代码实现

无法启动此程序因为计算机丢失api-ms-win-core-path-l1-1-0.dll修复方案

《无法启动此程序因为计算机丢失api-ms-win-core-path-l1-1-0.dll修复方案》:本文主要介绍了无法启动此程序,详细内容请阅读本文,希望能对你有所帮助... 在计算机使用过程中,我们经常会遇到一些错误提示,其中之一就是"api-ms-win-core-path-l1-1-0.dll丢失

python通过curl实现访问deepseek的API

《python通过curl实现访问deepseek的API》这篇文章主要为大家详细介绍了python如何通过curl实现访问deepseek的API,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编... API申请和充值下面是deepeek的API网站https://platform.deepsee

Java对接Dify API接口的完整流程

《Java对接DifyAPI接口的完整流程》Dify是一款AI应用开发平台,提供多种自然语言处理能力,通过调用Dify开放API,开发者可以快速集成智能对话、文本生成等功能到自己的Java应用中,本... 目录Java对接Dify API接口完整指南一、Dify API简介二、准备工作三、基础对接实现1.

一文详解如何在Vue3中封装API请求

《一文详解如何在Vue3中封装API请求》在现代前端开发中,API请求是不可避免的一部分,尤其是与后端交互时,下面我们来看看如何在Vue3项目中封装API请求,让你在实现功能时更加高效吧... 目录为什么要封装API请求1. vue 3项目结构2. 安装axIOS3. 创建API封装模块4. 封装API请求

Python 异步编程 asyncio简介及基本用法

《Python异步编程asyncio简介及基本用法》asyncio是Python的一个库,用于编写并发代码,使用协程、任务和Futures来处理I/O密集型和高延迟操作,本文给大家介绍Python... 目录1、asyncio是什么IO密集型任务特征2、怎么用1、基本用法2、关键字 async1、async

Python的time模块一些常用功能(各种与时间相关的函数)

《Python的time模块一些常用功能(各种与时间相关的函数)》Python的time模块提供了各种与时间相关的函数,包括获取当前时间、处理时间间隔、执行时间测量等,:本文主要介绍Python的... 目录1. 获取当前时间2. 时间格式化3. 延时执行4. 时间戳运算5. 计算代码执行时间6. 转换为指

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll

Kotlin 作用域函数apply、let、run、with、also使用指南

《Kotlin作用域函数apply、let、run、with、also使用指南》在Kotlin开发中,作用域函数(ScopeFunctions)是一组能让代码更简洁、更函数式的高阶函数,本文将... 目录一、引言:为什么需要作用域函数?二、作用域函China编程数详解1. apply:对象配置的 “流式构建器”最