You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gradio.Chatbot聊天记录新标签页消失问题求助

解决Gradio Chatbot新标签页聊天历史不显示的问题

问题原因

你当前的代码在Gradio应用启动时仅读取一次data.yaml来初始化Chatbot的历史记录,之后新打开的标签页会复用启动时的初始历史,而不会读取文件中最新的对话内容。另外,send_message函数依赖闭包中的data变量,多会话场景下容易出现数据不一致的问题。

修复方案

调整代码,让每个新会话加载时都主动读取data.yaml的最新内容,同时在消息提交时确保操作的是最新的文件数据:

import yaml
import time
import gradio as gr

def load_history():
    # 每次会话加载时读取最新的聊天记录
    with open('data.yaml', 'r') as file:
        data = yaml.load(file, Loader=yaml.FullLoader)
    return [(item.get("human1"), item.get("human2")) for item in data]

def send_message(msg, history):
    time.sleep(1)
    
    # 先读取最新的数据,避免并发覆盖
    with open('data.yaml', 'r') as file:
        data = yaml.load(file, Loader=yaml.FullLoader)
    
    data.append({"human1": msg, "human2": None})
    with open('data.yaml', 'w') as file:
        yaml.dump(data, file)
    
    # 返回更新后的完整历史,确保和文件同步
    updated_history = load_history()
    return "", updated_history

with gr.Blocks() as demo:
    history = gr.Chatbot()
    msg = gr.Textbox()
    
    # 会话加载时初始化历史记录
    demo.load(load_history, outputs=history)
    msg.submit(send_message, [msg, history], [msg, history])

demo.launch()

关键改动说明

  • 新增load_history函数:专门负责从data.yaml读取并格式化聊天历史,每次新会话打开时都会调用该函数初始化Chatbot。
  • 修改send_message函数:每次提交消息时先读取最新的文件数据,避免多会话场景下的变量不一致问题,最后返回从文件重新读取的完整历史,确保Chatbot显示的内容和文件完全同步。
  • 使用demo.load()替代静态初始化:让每个新会话都能获取到最新的聊天记录,而不是应用启动时的旧数据。

内容的提问来源于stack exchange,提问作者Procrastinator

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:43:01