You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GPT-4o-mini调用OpenAI API时image_url类型报错的问题排查

错误原因及修正方案

核心原因

你的请求payload中图像内容的格式不符合OpenAI API要求,具体问题:

  • 在定义图像类型的content对象时,你用image作为嵌套URL信息的键,但OpenAI Chat Completions API规定,图像类型内容必须用image_url这个键来包裹URL,而非image。
  • 虽然gpt-4o-mini模型确实支持图像输入,但格式错误导致API无法识别该内容类型,从而返回"Invalid content type"的错误。

修正后的代码片段

将payload中图像内容部分修改为:

{
    "type": "image_url",
    "image_url": {
        "url": f"data:image/png;base64,{encoded_image}"
    }
}

完整修正后的函数:

def analyze_screenshot_base64(encoded_image):
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {openai.api_key}"
    }

    payload = {
        "model": "gpt-4o-mini",
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "Develop a trading setup (LONG or SHORT) with a CRV of at least 5 based on this chart. Include entry price, stop loss, and take profit levels."
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/png;base64,{encoded_image}"
                        }
                    }
                ]
            }
        ],
        "max_tokens": 300
    }

    response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
    return response.json()

内容的提问来源于stack exchange,提问作者Ploetzeneder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 23:17:06