直接登ChatGPT老被封,分享一个自己写的Python3版本的ChatGPT使用代码,支持以下功能:
1、多轮对话
2、历史对话保存
import requests
def chat_with_gpt(messages):
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer 自己的chatgpt-api-token"
}
data = {
"model": "gpt-3.5-turbo",
"messages": messages
}
response = requests.post(url, headers=headers, json=data)
response_data = response.json()
# 提取助手的回复
assistant_reply = response_data['choices'][0]['message']['content']
return assistant_reply
# 进行多轮对话
def conduct_dialogue():
# 初始化对话历史,可以包含系统角色的消息来设定助手的行为
dialogue_history = [
{"role": "system", "content": "You are a helpful assistant."},
]
while True:
# 用户输入,stop或bye可以结束多轮对话,输入end结束单次输入
print("User:")
user_input = ""
while True:
line = input()
if line == "/end":
break
if line == "exit":
user_input = line
break
else:
user_input += line + "\n"
# 输入exit结束程序运行
if user_input == "exit":
break
# 输出至屏幕并追加到文件
with open("dialogue_history.txt", "a", encoding="utf-8") as f:
print(user_input, file=f)
print(user_input)
# 添加用户的消息到对话历史中
dialogue_history.append({"role": "user", "content": user_input})
# 调用ChatGPT API进行对话
assistant_reply = chat_with_gpt(dialogue_history)
# 输出至屏幕并追加到文件
with open("dialogue_history.txt", "a", encoding="utf-8") as f:
print("Assistant:", assistant_reply, file=f)
print("Assistant:", assistant_reply)
# 添加助手的回复到对话历史中
dialogue_history.append({"role": "assistant", "content": assistant_reply})
# 执行对话
conduct_dialogue()
--
FROM 103.102.203.*