python调用chatgpt api
import os
import openai
import requests
import json
class GPT():
def askgpt(self,question):
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + "你的API密钥"
}
data = {
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": question}],
"temperature": 0.7
}
response = requests.post(url, headers=headers, data=json.dumps(data))
response = response.json()
text=response['choices'][0]['message']['content']
return text
这样就封装了一个askgpt()方法,传入问题返回chatgpt的回答