Python ChatGPT API 示例代码:使用 Requests 库
以下是一个使用 Python 语言和 requests 库访问 ChatGPT 的示例代码:
import requests
url = 'https://api.openai.com/v1/chat/gpt3'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
}
data = {
'prompt': 'Hello',
'temperature': 0.7,
'max_tokens': 50,
'stop': '\n'
}
response = requests.post(url, headers=headers, json=data)
if response.ok:
response_json = response.json()
print(response_json['choices'][0]['text'])
else:
print('Error:', response.status_code, response.reason)
其中,YOUR_API_KEY 需要替换为你自己的 OpenAI API 密钥。此代码将向 ChatGPT 发送一个 'Hello' 的提示,然后返回一个基于给定温度和最大标记数的响应。响应的 'choices' 列表将包含一个文本字符串,表示 GPT-3 生成的响应。
原文地址: https://www.cveoy.top/t/topic/niMF 著作权归作者所有。请勿转载和采集!