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

页面刷新时如何更新Gradio聊天历史的显示?

问题解决:Gradio聊天UI刷新后无法加载最新聊天记录

问题根源

你的代码仅在程序启动时从数据库加载一次聊天历史,页面刷新时不会重新执行数据库查询,只会复用启动时的初始历史数据,导致新发送的消息无法在刷新后显示。

解决方案

需要让Gradio在**每次页面加载(包括刷新)**时重新从数据库读取最新的聊天记录,具体修改如下:

  1. 重构loadHistoryFromDB函数,让它返回最新的聊天记录列表,不再依赖全局变量
  2. 在Gradio的Blocks中,使用demo.load()事件,触发历史加载并更新Chatbot组件

修改后的完整代码

import sqlite3
import gradio as gr
import time

sqlite = None

def loadHistoryFromDB():
    global sqlite
    # 每次调用都重新查询数据库,返回最新的历史记录
    sql = "SELECT role, message from chat_history order by created_at_unix ASC Limit 10"
    cur = sqlite.cursor()
    cur.execute(sql)
    rows = cur.fetchall()
    formatted_history = []
    for row in rows:
        formatted_history.append({
            'role': row[0],
            'content': row[1]
        })
    return formatted_history

def chatHandler(message, history, generate_image):
    sql = "INSERT INTO chat_history (role, message, created_at_unix) VALUES (?, ?, ?)"
    current_unix_time = int(time.time())

    response = f"Hello {message}"

    sqlite.execute(sql, ('user', message, current_unix_time))
    time.sleep(3)
    sqlite.execute(sql, ('assistant', response, current_unix_time))
    sqlite.commit()

    yield response

if __name__ == "__main__":
    sqlite = sqlite3.connect("chat_history.db", check_same_thread=False)
    # 确保chat_history表存在(可选,避免首次启动报错)
    sqlite.execute("""
        CREATE TABLE IF NOT EXISTS chat_history (
            role TEXT,
            message TEXT,
            created_at_unix INTEGER
        )
    """)
    sqlite.commit()

    with gr.Blocks() as demo:
        chatbot = gr.Chatbot(type="messages")
        # 页面加载时(包括刷新),调用loadHistoryFromDB更新chatbot内容
        demo.load(lambda: loadHistoryFromDB(), None, chatbot)
        chat = gr.ChatInterface(chatHandler, type="messages", chatbot=chatbot)

    demo.launch()

关键修改说明

  • 移除了全局的formatted_history变量,避免全局状态导致的历史数据不更新问题
  • loadHistoryFromDB每次调用都会重新查询数据库,返回最新的10条记录
  • 通过demo.load(lambda: loadHistoryFromDB(), None, chatbot),让页面每次加载时自动执行历史查询,并将结果更新到Chatbot组件中
  • 添加了CREATE TABLE IF NOT EXISTS语句,避免首次启动时数据库表不存在的报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 05:13:18