import openai
import pyttsx3
openai.api_key = "sk-xxxxxxxxxxxxx" # 你的 OpenAI API Key
class Chat:
def __init__(self, conversation_list=None):
if conversation_list is None:
self.conversation_list = [{'role': 'system', 'content': '你是一个非常友善的助手'}]
else:
self.conversation_list = conversation_list
def show_conversation(self, msg_list):
for msg in msg_list:
if msg['role'] == 'user':
print(f"\U0001f47b: {msg['content']}\n")
else:
print(f"\U0001f47D: {msg['content']}\n")
def ask(self, prompt):
if prompt == '清空':
self.conversation_list = [{'role': 'system', 'content': '已清空对话历史记录'}]
return self.show_conversation(self.conversation_list)
self.conversation_list.append({"role": "user", "content": prompt})
response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=self.conversation_list)
answer = response.choices[0].message['content']
self.conversation_list.append({"role": "assistant", "content": answer})
self.show_conversation(self.conversation_list)
if answer is not None:
engine = pyttsx3.init()
engine.say(answer)
engine.runAndWait()
chatbot = Chat() # 创建一个Chat对象
while True:
askmsg = input() # 获取用户的输入
answer = chatbot.ask(askmsg) # 向Chatbot提问并显示对话历史记录
最后编辑:2023年03月29日
©著作权归作者所有