调用百度千帆大模型API时出现unsupported content type
错误,通常是由于请求头中的Content-Type
设置不正确或缺失引起的。百度千帆大模型API通常要求请求头中的Content-Type
为application/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)
关键点:
Content-Type
:确保请求头中的Content-Type
设置为application/json
。
- 请求体:请求体需要是JSON格式,使用
json.dumps()
将Python字典转换为JSON字符串。
- Authorization:在请求头中包含
Authorization
字段,值为Bearer <access_token>
。
如果仍然遇到问题,请检查API文档确认是否有其他特殊要求,或联系百度云技术支持。