Api接口调用百度千帆大模型提示unsupported content type错误。

Api接口调用百度千帆大模型提示unsupported content type错误。

5 回复

确保请求头中的Content-Type设置正确,如application/json。


请检查请求头中的Content-Type,确保设置为application/json

调用百度千帆大模型API时出现“unsupported content type”错误,通常是因为请求头中的Content-Type设置不正确。请确保请求头中包含Content-Type: application/json,并且请求体是有效的JSON格式。例如:

{
  "prompt": "你的输入内容",
  "max_tokens": 50
}

检查并修正请求头和请求体后,再次尝试调用API。

确保请求头中Content-Type设置正确,如application/json。

调用百度千帆大模型API时出现unsupported content type错误,通常是由于请求头中的Content-Type设置不正确或缺失引起的。百度千帆大模型API通常要求请求头中的Content-Typeapplication/json,因为请求体是以JSON格式发送的。

以下是一个示例代码,展示如何正确设置请求头并调用API:

import requests
import json

# 替换为你的API Key和Secret Key
api_key = "your_api_key"
secret_key = "your_secret_key"

# 获取Access Token
def get_access_token(api_key, secret_key):
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        "grant_type": "client_credentials",
        "client_id": api_key,
        "client_secret": secret_key
    }
    response = requests.post(url, params=params)
    return response.json().get("access_token")

# 调用千帆大模型API
def call_qianfan_api(access_token, prompt):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {access_token}"
    }
    data = {
        "messages": [
            {
                "role": "user",
                "content": prompt
            }
        ]
    }
    response = requests.post(url, headers=headers, data=json.dumps(data))
    return response.json()

# 示例调用
access_token = get_access_token(api_key, secret_key)
prompt = "你好,请介绍一下你自己。"
response = call_qianfan_api(access_token, prompt)
print(response)

关键点:

  1. Content-Type:确保请求头中的Content-Type设置为application/json
  2. 请求体:请求体需要是JSON格式,使用json.dumps()将Python字典转换为JSON字符串。
  3. Authorization:在请求头中包含Authorization字段,值为Bearer <access_token>

如果仍然遇到问题,请检查API文档确认是否有其他特殊要求,或联系百度云技术支持。

回到顶部