flask程序中如何与你对接?
时间: 2024-04-11 15:32:39 浏览: 14
要在Flask程序中与我对接,你可以使用OpenAI的ChatGPT API。首先,你需要在OpenAI上创建一个帐户并获取API密钥。然后,你可以使用Python的requests库向API发送HTTP请求来与我进行对话。
以下是一个简单的示例代码:
```python
import requests
def interact_with_chatgpt(message):
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY"
}
data = {
"model": "gpt-3.5-turbo",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": message}
]
}
response = requests.post(url, headers=headers, json=data)
response_data = response.json()
reply = response_data['choices'][0]['message']['content']
return reply
# 在Flask中使用时,可以将用户的输入作为参数传递给interact_with_chatgpt函数
# 然后将返回的回复作为响应返回给用户
@app.route('/chat', methods=['POST'])
def chat():
user_message = request.form['message']
reply = interact_with_chatgpt(user_message)
return jsonify({'reply': reply})
```
请确保替换示例代码中的"YOUR_API_KEY"为你自己的API密钥。此外,这只是一个简单的示例,你可以根据自己的需求进行更多的定制和错误处理。