基于Python和ChatGPT的实时聊天机器人
def send_message(): global chat_history
message_text = message_entry.get()
if not message_text:
return
# 获取前10次的对话记录
last_10_messages = chat_history[-10:]
chat_history.append(f'你: {message_text}
')
# 拼接消息和历史记录
message_with_history = '\n'.join(last_10_messages) + chat_history[-1]
# 检查字符数是否超过4000
if len(message_with_history) > 4000:
overflow = len(message_with_history) - 4000
last_10_messages = [f'......({overflow}个字符被省略)'] + last_10_messages[-9:]
message_with_history = '\n'.join(last_10_messages) + chat_history[-1]
chat_box.config(state=tk.NORMAL)
chat_box.insert(tk.END, chat_history[-1], 'right_align')
chat_box.see(tk.END)
chat_box.config(state=tk.DISABLED)
message_entry.delete(0, tk.END)
# 显示动态等待效果
wait_label.config(text='等待响应中...', fg='gray')
root.update()
# 发送网络请求
response = requests.get('https://chatgpt-chatpt-zggoappkts.cn-beijing.fcapp.run', params={'content': message_with_history})
if response.status_code == 200:
response_text = response.text
chat_history.append(f'chatgpt: {response_text}
\n') chat_box.config(state=tk.NORMAL) chat_box.insert(tk.END, chat_history[-1], 'left_align') chat_box.see(tk.END) chat_box.config(state=tk.DISABLED) wait_label.config(text='')
# 保存消息到本地
with open('chat_history.txt', 'a') as f:
f.write(chat_history[-2])
f.write(chat_history[-1])
else:
messagebox.showerror('错误', f'服务器状态码 {response.status_code}')
wait_label.config(text='')
原文地址: https://www.cveoy.top/t/topic/lIJZ 著作权归作者所有。请勿转载和采集!