(request=request) from err openai.APIConnectionError: Connection error.

2026年03月30日 09:46 状态: processing

🚨 错误信息

Traceback (most recent call last): File "/app/models/vlm_adapter.py", line 444, in extract_drawing_info response = self._call_api_with_logging( File "/app/models/vlm_adapter.py", line 189, in _call_api_with_logging response = self.client.chat.completions.create(**kwargs) File "/usr/local/lib/python3.10/site-packages/openai/_utils/_utils.py", line 286, in wrapper return func(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/openai/resources/chat/completions/completions.py", line 1211, in create return self._post( File "/usr/local/lib/python3.10/site-packages/openai/_base_client.py", line 1297, in post return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) File "/usr/local/lib/python3.10/site-packages/openai/_base_client.py", line 1037, in request raise APIConnectionError(request=request) from err openai.APIConnectionError: Connection error.

🤖 AI解决方案

1. 错误翻译


原文:openai.APIConnectionError: Connection error.
译文:OpenAI API连接错误:连接失败。


2. 原因分析


  • 根本原因:调用OpenAI Chat Completion API时无法建立网络连接。

  • 具体位置vlm_adapter.py第444行extract_drawing_info→第189行_call_api_with_logging_base_client.pyrequest方法,最终因连接失败抛出错误。

  • 3. 解决方案


    python
    import time
    from openai import APIConnectionError

    def safe_openai_call(client, kwargs, max_retries=3, delay=2):
    """带指数退避重试的OpenAI API调用"""
    for attempt in range(max_retries):
    try:
    return client.chat.completions.create(kwargs)
    except APIConnectionError as e:
    if attempt == max_retries - 1:
    raise # 耗尽重试次数后抛原错误
    time.sleep(delay (2 * attempt)) # 指数退避(2s→4s→8s)
    return None

    替换原_call_api_with_logging中的response赋值逻辑:


    response = safe_openai_call(self.client, kwargs)



    4. 预防措施


  • 最佳实践1:为API调用添加指数退避重试(如上述方案),应对临时网络波动;推荐用tenacity库简化实现(@retry(stop=stop_after_attempt(3), wait=wait_exponential()))。

  • 最佳实践2:调用前用client.models.list()requests.head(API_ENDPOINT)预检查连通性;生产环境可集成网络监控(如Prometheus+Blackbox Exporter)。

  • 工具推荐:用curl/telnet手动验证API端点可达性(如telnet api.openai.com 443)。