使用复杂提示词调用GPT-3.5-turbo API时出现连接错误求助
GPT-3.5-turbo API连接异常问题处理
问题描述
- 调用GPT-3.5-turbo API时,简单提示词(如「Hey」「Tell me [this]」「Summarize [this]」)可正常返回结果
- 使用「列出相关内容并解释……」这类复杂提示词时,触发连接错误,无其他变量变更,仅提示词复杂度不同
错误信息
APIConnectionError: Error communicating with OpenAI: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
运行环境与代码
运行环境:JupyterLab
调用代码:
def get_completion(prompt, model="gpt-3.5-turbo"): messages = [{"role": "user", "content": prompt}] response = openai.ChatCompletion.create( model=model, messages=messages, temperature=0, ) return response.choices[0].message["content"]
解决建议
- 增加超时设置:复杂提示词的处理时间更长,默认超时可能不足以完成请求。在API调用中添加
timeout参数延长超时时间,示例:response = openai.ChatCompletion.create( model=model, messages=messages, temperature=0, timeout=30 # 设置30秒超时,可根据情况调整 ) - 拆分复杂提示:将长提示或复杂任务拆分为多个简短请求,分步骤获取结果,减少单次请求的处理压力。
- 添加重试机制:针对临时连接异常,使用重试库(如
tenacity)实现自动重试,示例:from tenacity import retry, stop_after_attempt, wait_exponential @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10)) def get_completion(prompt, model="gpt-3.5-turbo"): messages = [{"role": "user", "content": prompt}] response = openai.ChatCompletion.create( model=model, messages=messages, temperature=0, timeout=30 ) return response.choices[0].message["content"] - 检查提示词长度:确认复杂提示词的token数量未超过gpt-3.5-turbo的4096 token上限,超过时会触发异常,可通过OpenAI的
tiktoken库计算token数。 - 排查网络限制:检查JupyterLab所在环境的网络是否存在防火墙、代理拦截,复杂请求可能被误判为异常流量,尝试切换网络或调整代理设置。
内容的提问来源于stack exchange,提问作者superbot
相关产品推荐
相关产品推荐

