OpenAI APIConnectionError捕获失败:模块无此属性问题求助
解决方案
1. 修复AttributeError: module 'openai' has no attribute 'APIConnectionError'
这个错误是因为APIConnectionError类属于openai.error子模块,而非直接挂载在openai根模块下。只需将捕获异常的代码修改为:
except openai.error.APIConnectionError: continue
2. 优化连接错误处理(减少丢包,提高翻译成功率)
直接跳过连接错误会丢失数据,更合理的方式是让backoff库自动重试这类错误,同时给API请求添加超时设置:
修改后的translate函数:
@backoff.on_exception(backoff.expo, (openai.error.RateLimitError, openai.error.APIConnectionError)) def translate(text, engine="text-davinci-002"): p = f'Transform this sentence from korean to english: {text}' # generate the response response = openai.Completion.create( engine=engine, prompt=p, temperature=.7, top_p=1, frequency_penalty=0, presence_penalty=0, stop=["12."], timeout=15 # 添加超时设置,避免无限等待 ) return response['choices'][0]['text']
修改后的循环捕获逻辑:
tag_in_eng = [] for tag in clean_tag: try: tag_in_eng.append(translate(tag)) except openai.error.APIConnectionError: # 如果重试多次仍失败,记录并标记失败项 print(f"Failed to translate: {tag}") tag_in_eng.append(None) continue
3. 额外建议
- 更新OpenAI库:在Colab中执行
!pip install --upgrade openai,旧版本可能存在错误类路径或网络请求的bug。 - 检查网络环境:Colab的网络偶尔会出现波动,若问题持续,可尝试重启Colab会话。
内容的提问来源于stack exchange,提问作者JungtaekChoi
相关产品推荐
相关产品推荐

