原标题: ChatGPT的API允许您通过向`https://api.openai.com/v1/chat/completions`发出POST请求来与ChatGPT进行交互。以下是使用Python进行接口调用的示例代码:
导读:
```pythonimport requestsurl = ''headers = {'Authorization': 'Bearer YOUR_API_KEY','Conte...
```python
import requests
url = ''
headers = {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
}
data = {
'model': 'gpt-3.5-turbo',
'messages': [
{'role':'system', "content":"You are a helpful assistant."},
{'role':'user', "content":"Who won the world series in 2020?"},
{'role':'assistant', "content":"The Los Angeles Dodgers won the World Series in 2020."},
{'role':'user', "content":"Where was it played?"}
]
response = requests.post(url, headers=headers, json=data)
result = response.json()
for message in result['choices'][0]['message']['content']:
print(message['role'], ": ", message['content'])
```
此示例演示了一个简单的对话,其中用户和助手之间交替发言,请确保将YOUR_API_KEY替换为您的实际OpenAI API密钥。
在`data`字典中,您可以指定要使用的模型(例如'gpt-3.5-turbo')以及消息列表,消息应包含角色('user'或'assistant')和内容(用户输入或助手回答),返回结果是一个JSON对象,其中包含生成的回复。