Python ChatGPT 聊天机器人:实现历史记录保存和加载

本代码使用 Python 的 Tkinter 库和 ChatGPT API 创建一个简单的聊天机器人界面,并实现历史记录保存和加载功能,方便用户进行持续的对话。

代码如下:

import tkinter as tk
from tkinter import messagebox
import requests
from tkinter import ttk

chat_history = []

def send_message():
    global chat_history
    
    message_text = message_entry.get()
    if not message_text:
        return
    
    # 获取前10次的对话记录
    last_10_messages = chat_history[-20:]
    
    # 如果最后一条消息是用户自己发送的,则不添加到 chat_history 中
    if not last_10_messages or not last_10_messages[-1].startswith('你:'):
        chat_history.append(f'你: {message_text}\n')
    
    # 拼接消息和历史记录
    message_with_history = '\n'.join(last_10_messages) + chat_history[-1]
    
    # 判断消息长度是否超过4000字符
    while len(message_with_history.encode('utf-8')) > 4000:
        last_10_messages.pop(0)
        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
        print(response_text)
        chat_history.append(f'chatgpt: {response_text}\n\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='')
        

def load_chat_history():
    try:
        with open('chat_history.txt', 'r') as f:
            chat_history.extend(f.readlines())
            chat_box.config(state=tk.NORMAL)
            for message in chat_history:
                if message.startswith('你:'):
                    chat_box.insert(tk.END, message, 'right_align')
                elif message.startswith('chatgpt:'):
                    chat_box.insert(tk.END, message, 'left_align')
            chat_box.see(tk.END)
            chat_box.config(state=tk.DISABLED)
    except FileNotFoundError:
        pass
    
    root.update()  # 强制刷新聊天界面

root = tk.Tk()
root.title('Chatgpt by 果然多cc果卷')

# 添加样式
style = ttk.Style()
style.configure('right_align.TLabel', anchor='e')
style.configure('left_align.TLabel', anchor='w')
style.configure('center_align.TLabel', justify='center')

# Material Design 颜色定义(蓝色)
primary_color = '#2196f3'
light_primary_color = '#6ec6ff'
dark_primary_color = '#0069c0'
text_primary_color = '#ffffff'
accent_color = '#4caf50'

# 创建聊天界面
chat_frame = tk.Frame(root, bg=primary_color)
chat_frame.pack(pady=(15, 0), fill='both', expand=True)

chat_box = tk.Text(chat_frame, height=20, width=50, state=tk.DISABLED, font=('Arial', 12), bg='white', fg='black', highlightbackground='#c5c5c5', highlightthickness=1)
chat_box.pack(side=tk.LEFT, padx=(0, 10), pady=(0, 5), fill='both', expand=True)

scrollbar = tk.Scrollbar(chat_frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

message_entry = tk.Entry(root, width=50, font=('Arial', 12), relief='flat')
message_entry.pack(padx=10, pady=10, ipady=8, fill='x')

send_button = tk.Button(root, text='发送', command=send_message, font=('Arial', 12), bg=accent_color, fg=text_primary_color, bd=0, padx=20, pady=10)
send_button.pack(side=tk.BOTTOM, padx=10, pady=(0, 10))

wait_label = tk.Label(root, text='', font=('Arial', 12), fg=primary_color)
wait_label.pack(pady=(0, 10))

chat_box.tag_configure('right_align', foreground=light_primary_color, font=('Arial', 12, 'bold'))
chat_box.tag_configure('left_align', foreground=dark_primary_color, font=('Arial', 12, 'bold'))
chat_box.tag_configure('center_align', font=('Arial', 12))

chat_box.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=chat_box.yview)

load_chat_history()  # 加载聊天历史记录

# 设置窗口背景颜色和大小
root.configure(bg=primary_color)
root.geometry('400x550')
root.resizable(False, False)
root.bind('<Return>', lambda event: send_button.invoke())

root.mainloop()

代码说明:

  1. 导入库: 导入 tkintermessageboxrequeststtk 库。
  2. 创建聊天历史记录列表: 创建一个名为 chat_history 的列表,用于存储用户与聊天机器人的对话历史记录。
  3. 发送消息函数:
    • 获取用户输入的文本。
    • 将用户输入添加到 chat_history 列表中。
    • 将历史记录和当前用户输入拼接成一个字符串,并发送给 ChatGPT API。
    • 接收 ChatGPT API 的响应,并将其添加到 chat_history 列表中。
    • 将聊天历史记录显示在聊天框中。
  4. 加载聊天历史记录函数:
    • chat_history.txt 文件中读取历史记录,并将它们添加到 chat_history 列表中。
    • 将历史记录显示在聊天框中。
  5. 创建 Tkinter 窗口: 创建一个 Tkinter 窗口,并设置标题、背景颜色和大小。
  6. 创建聊天界面: 创建一个 chat_frame 框架,用于放置聊天框和滚动条。
  7. 创建聊天框: 创建一个 chat_box 文本框,用于显示聊天历史记录。
  8. 创建滚动条: 创建一个 scrollbar 滚动条,用于滚动聊天框。
  9. 创建输入框: 创建一个 message_entry 输入框,用于用户输入文本。
  10. 创建发送按钮: 创建一个 send_button 按钮,用于发送用户输入的文本。
  11. 绑定回车键: 将回车键绑定到 send_button 按钮,以便用户可以通过回车键发送消息。
  12. 运行主循环: 使用 root.mainloop() 运行 Tkinter 主循环,使窗口保持活动状态。

注意:

  • 代码中使用 'https://chatgpt-chatpt-zggoappkts.cn-beijing.fcapp.run' 作为 ChatGPT API 的地址,请根据您的实际情况进行修改。
  • 代码中使用 'chat_history.txt' 作为保存聊天历史记录的文件名,请根据您的实际情况进行修改。

运行代码:

运行代码后,您将看到一个聊天机器人界面。您可以输入文本并点击“发送”按钮,或按回车键发送消息。聊天机器人的响应将显示在聊天框中。

历史记录加载:

  • 当您重新打开程序时,程序会自动从 chat_history.txt 文件中加载之前的聊天历史记录。

其他功能:

  • 您可以根据需要添加其他功能,例如:
    • 退出程序功能
    • 清除聊天历史记录功能
    • 使用不同的 ChatGPT API
    • 自定义界面样式

代码优化:

  • 可以使用 asyncio 库来异步发送网络请求,提高程序响应速度。
  • 可以使用 threading 库来创建一个线程,用于在后台保存聊天历史记录。
  • 可以使用 tkinter.ttk 模块来创建更现代的界面。

总结:

本代码提供了一个简单但实用的 ChatGPT 聊天机器人界面,并实现了历史记录保存和加载功能,方便用户进行持续的对话。您可以根据需要对代码进行修改和扩展,以创建更强大和实用的聊天机器人。

Python ChatGPT 聊天机器人:实现历史记录保存和加载

原文地址: https://www.cveoy.top/t/topic/lIKk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录