如何正确调用GPT-3 API?解决调用时的400错误请求问题
解决GPT-3 API调用400 Bad Request错误
错误原因及修复点:
- API端点错误:你使用的
/v1/engines/gpt-3/jobs是批量任务接口,text-davinci-002需调用补全接口/v1/completions。 - Authorization头格式错误:API密钥前必须添加
Bearer前缀,正确格式为"Authorization": "Bearer sk-apikey"。 - 请求数据传递优化:使用
requests.post时,直接用json参数传递字典即可,无需手动json.dumps(),框架会自动处理序列化。
修正后的代码:
import requests url = "https://api.openai.com/v1/completions" headers = { "Content-Type": "application/json", "Authorization": "Bearer sk-apikey" } data = { "model": "text-davinci-002", "prompt": "Correct this to standard English : Who are you", "max_tokens": 60 } response = requests.post(url, headers=headers, json=data) # 可打印响应内容排查后续问题 print(response.json())
内容的提问来源于stack exchange,提问作者Kaptan Singh
相关产品推荐
相关产品推荐

