python连接chatgpt api 例子
时间: 2023-09-26 18:14:17 浏览: 172
用Python实现ChatGPT接入微信.zip
以下是一个使用Python连接ChatGPT API的例子:
```python
import requests
import json
# ChatGPT API endpoint
url = "https://api.openai.com/v1/engines/davinci-codex/completions"
# API key
api_key = "YOUR_API_KEY"
# Prompt for generating the response
prompt = "Hi, how are you?"
# Request headers
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
# Request data
data = {
"prompt": prompt,
"max_tokens": 50,
"temperature": 0.7
}
# Send POST request to ChatGPT API
response = requests.post(url, headers=headers, data=json.dumps(data))
# Get the response text
response_text = json.loads(response.text)
# Extract the generated text from the response
generated_text = response_text["choices"][0]["text"]
# Print the generated text
print(generated_text)
```
请注意,您需要将`YOUR_API_KEY`替换为您的API密钥。此外,您可能需要调整`max_tokens`和`temperature`参数以控制生成的响应的长度和创造力。
阅读全文