Connection error.
错误信息
LLM 响应错误: All chat models failed: APIConnectionError: Connection error.
AI 解决方案
🔍 报错分析
1. 🌐 错误翻译
原文:LLM 响应错误: All chat models failed: APIConnectionError: Connection error.
译文:LLM 响应错误:所有聊天模型均失败:API连接错误:连接失败。
2. 🎯 原因分析
3. 💡 解决方案
先检查 API 配置和网络连接,再通过重试机制保障请求的可靠性:
import os
import time
from openai import OpenAI, APIConnectionError
# 1. 确认API配置正确且网络通畅
os.environ["OPENAI_API_BASE"] = "正确的API地址(如官方地址或合规代理地址)"
os.environ["OPENAI_API_KEY"] = "有效的API密钥"
client = OpenAI()
def chat_with_retry(message, max_retries=3):
for attempt in range(max_retries):
try:
# 调用聊天接口
response = client.chat.completions.create(
model="gpt-3.5-turbo", # 根据实际模型替换
messages=[{"role": "user", "content": message}]
)
return response
except APIConnectionError:
if attempt < max_retries - 1:
# 失败后间隔一段时间再重试
time.sleep(2 ** attempt)
else:
print("多次连接失败,请检查网络或API配置")
raise
# 实际调用
try:
result = chat_with_retry("你好")
print(result.choices[0].message.content)
except Exception as e:
print(f"最终错误:{e}")
4. 🛡️ 预防措施
/v1/models)验证 API 地址和密钥的有效性,避免无效配置上线。curl或Postman手动测试 API 连通性,排查网络层问题;集成healthcheck模块,实时监测服务可用性。