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

调用Hugging Face图像转文本API遇400错误求排查

问题根源及解决方案

你的400错误是因为输入数据的结构不符合Hugging Face推理API对Salesforce/blip-image-captioning-large模型的要求,具体问题:

  • 错误使用了复数的images和texts数组格式,该模型API接收的是单个image和text字段
  • 输入的嵌套层级不匹配模型要求

修正后的代码

带文本提示的版本

import base64
import requests
import os

def query(API_TOKEN):
    model = 'Salesforce/blip-image-captioning-large'
    headers = {"Authorization": f"Bearer {API_TOKEN}"}
    image_path = "./demo.jpg"

    if not os.path.isfile(image_path):
        return {"error": "Image file does not exist"}

    with open(image_path, "rb") as image_file:
        try:
            encoded_string = base64.b64encode(image_file.read()).decode()
        except Exception as e:
            return {"error": f"Error encoding image: {str(e)}"}

    # 修正输入结构:使用单个image和text字段,而非数组
    data = {
        "inputs": {
            "image": encoded_string,
            "text": "a photography of"
        }
    }

    try:
        response = requests.post(
            f'https://api-inference.huggingface.co/models/{model}',
            headers=headers,
            json=data
        )
        # 新增状态码检查,方便调试
        if response.status_code != 200:
            return {"error": f"API返回状态码 {response.status_code}: {response.text}"}
    except Exception as e:
        return {"error": f"发送请求失败: {str(e)}"}

    return response.json()

不带文本提示的版本(直接生成图像描述)

如果不需要提示文本,直接传递base64编码字符串作为inputs的值即可:

# ... 前面代码保持不变 ...
data = {
    "inputs": encoded_string
}
# ... 后面代码保持不变 ...

额外调试建议

  • 调用API前打印data结构,确认是否符合模型要求
  • 检查API_TOKEN是否有效,是否拥有该模型的调用权限
  • 验证base64编码的完整性:可以将编码字符串解码后重新保存为图像,确认图像未损坏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 16:28:14