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
auth_url = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={api_key}&client_secret={secret_key}'
auth_response = requests.get(auth_url)
access_token = auth_response.json().get('access_token')
# 构建请求URL
request_url = f'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token={access_token}'
# 构建请求体
payload = {
"messages": [
{"role": "user", "content": "你好,请问你是谁?"}
]
}
# 设置请求头
headers = {
'Content-Type': 'application/json'
}
# 发送POST请求
response = requests.post(request_url, headers=headers, data=json.dumps(payload))
# 打印响应结果
print(response.json())
关键点:
- Content-Type: 确保请求头中的
Content-Type 设置为 application/json。
- 请求体: 确保请求体是有效的JSON格式。
- Access Token: 获取并正确传递
access_token。
如果仍然遇到问题,请检查:
- 请求体的JSON格式是否正确。
- 请求URL是否正确。
- 你的API Key和Secret Key是否有效。