_from_response(err.response) from None openai.BadRequestError: Error code: 400 -...

2025年12月18日 12:49 状态: processing

🚨 错误信息

root@dsw-1551458-76f897b777-n9qpn:/mnt/workspace# pyhton ocr_recognize.py bash: pyhton: 未找到命令 root@dsw-1551458-76f897b777-n9qpn:/mnt/workspace# python ocr_recognize.py Traceback (most recent call last): File "/mnt/workspace/ocr_recognize.py", line 12, in <module> response = client.chat.completions.create( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/openai/_utils/_utils.py", line 286, in wrapper return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/openai/resources/chat/completions/completions.py", line 1192, in create return self._post( ^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/openai/_base_client.py", line 1259, in post return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/openai/_base_client.py", line 1047, in request raise self._make_status_error_from_response(err.response) from None openai.BadRequestError: Error code: 400 - {'error': {'message': 'Invalid param: {"detail":"Failed to load image: Unsupported URL format: ***.jpg"}', 'type': 'rix_api_error', 'param': 'fae9587a-5bfb-4519-980d-52cd14c69b2e', 'code': 'param_error'}} root@dsw-1551458-76f897b777-n9qpn:/mnt/workspace#

🤖 AI解决方案

正在分析报错信息...

1. 错误翻译

原文:Invalid param: {"detail":"Failed to load image: Unsupported URL format: ***.jpg"}
译文:参数无效:{"detail":"无法加载图像:不支持的URL格式:***.jpg"}

2. 原因分析

根本原因:OpenAI API 无法加载指定URL格式的图片文件。

具体分析

  • 报错发生在调用 client.chat.completions.create() 时,这是向OpenAI API发送请求的函数

  • 错误类型为 BadRequestError,状态码400,表示客户端请求参数有问题

  • API返回的具体错误信息指出URL格式不受支持,可能是:

  • 1. URL协议不正确(如使用文件路径而非HTTP/HTTPS URL)
    2. URL格式不符合API要求
    3. 图片文件无法通过URL访问

    3. 解决方案

    方案A:如果使用本地文件路径

    import base64
    from openai import OpenAI
    
    # 初始化客户端
    client = OpenAI(api_key="你的API密钥")
    
    # 读取本地图片并转换为base64
    def encode_image(image_path):
        with open(image_path, "rb") as image_file:
            return base64.b64encode(image_file.read()).decode('utf-8')
    
    # 使用base64编码的图片
    base64_image = encode_image("your_image.jpg")
    
    response = client.chat.completions.create(
        model="gpt-4-vision-preview",  # 或最新的视觉模型
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "这是什么图片?"},
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/jpeg;base64,{base64_image}"
                        }
                    }
                ]
            }
        ],
        max_tokens=300,
    )

    方案B:如果使用网络URL

    from openai import OpenAI
    
    client = OpenAI(api_key="你的API密钥")
    
    # 确保URL格式正确且可公开访问
    image_url = "https://example.com/your_image.jpg"  # 必须是完整的HTTP/HTTPS URL
    
    response = client.chat.completions.create(
        model="gpt-4-vision-preview",
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "这是什么图片?"},
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": image_url
                        }
                    }
                ]
            }
        ],
        max_tokens=300,
    )

    4. ️ 预防措施

    最佳实践:

  • 验证URL格式:使用OpenAI API处理图片时,确保URL是完整的HTTP/HTTPS链接(如 https://example.com/image.jpg)或正确的base64 data URL格式
  • 先测试可访问性:在代码中发送请求前,先用浏览器或curl命令测试图片URL是否能正常访问
  • 推荐工具:

  • 使用Python的 requests 库测试URL可访问性:
  import requests
  response = requests.head(image_url)
  if response.status_code == 200:
      print("URL可访问")
  

---
提示:如果您使用的是本地文件,请采用方案A的base64编码方法;如果使用网络图片,请确保URL格式正确且可公开访问。