帮我写一个api调用chatgbt的代码
时间: 2023-05-31 20:01:58 浏览: 62
以下是使用Python编写的调用ChatGPT的API的示例代码:
```
import requests
def get_response(prompt):
url = "https://api.openai.com/v1/engines/davinci-codex/completions"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY"
}
data = {
"prompt": prompt,
"max_tokens": 50,
"temperature": 0.7,
"n": 1,
"stop": "\n"
}
response = requests.post(url, headers=headers, json=data)
response_json = response.json()
return response_json["choices"][0]["text"].strip()
# Example usage
prompt = "What is the meaning of life?"
response = get_response(prompt)
print(response)
```
在以上代码中,`get_response`函数接受一个字符串参数`prompt`,并返回一个字符串作为ChatGPT对提示的响应。在函数中,我们首先设置了API的URL和请求头,然后将要求传递给API的数据以JSON格式组织,并使用POST方法将请求发送到API。我们使用`requests`库执行HTTP请求和处理响应。最后,我们将响应JSON解析为Python对象,并返回响应中的文本。
请注意,您需要将`YOUR_API_KEY`替换为您自己的API密钥,以使用此代码。