python请求chatgpt
import requests
def chat_with_gpt(prompt, model="gpt-3.5-turbo", api_key=""):
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
data = {
"model": model,
"prompt": prompt,
"temperature": 0.7,
"max_tokens": 100
}
response = requests.post("https://api.openai.com/v1/engines/gpt-3.5-turbo/completions",
headers=headers, json=data, verify=False)
if response.status_code == 200:
return response.json()['choices'][0]['text'].strip()
else:
return f"Error: {response.status_code}"
# 使用示例
prompt = "你好,我是ChatGPT,请问有什么可以帮助你的?"
response = chat_with_gpt(prompt, api_key="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")
print(response)