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字符
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
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='')
在拼接消息和历史记录后,加入判断消息长度是否超过4000字符。如果超过就将最早的历史记录弹出,重新拼接消息和历史记录,直到消息长度小于等于4000字符为止。
原文地址: https://www.cveoy.top/t/topic/lIJ5 著作权归作者所有。请勿转载和采集!