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

如何实现Gradio ChatInterface Bot连续回复及解决history打印问题

解决Gradio ChatInterface连续回复与Colab打印history问题

一、实现Bot连续发送两条回复

要让Chatbot组件连续输出两条Bot回复,需将响应函数改为生成器函数,通过yield逐个返回消息(可添加延迟让两条消息分开显示)。

示例代码:

import gradio as gr
import time
import random

def random_response(message, history):
    # 返回第一条回复
    yield "这是Bot的第一条回复"
    # 可选:添加延迟模拟思考过程
    time.sleep(1)
    # 返回第二条回复
    yield f"这是Bot的第二条回复,你刚才说的是:{message}"

demo = gr.ChatInterface(random_response)
demo.launch()

说明:生成器函数会逐步返回内容,Gradio会自动将每条yield的内容作为独立Bot消息显示,无需用户再次触发交互。

二、解决Colab中print(history)无输出的问题

Colab环境中,Gradio后台的print输出默认不会显示在单元格标准输出面板,可通过以下三种方式解决:

方法1:用Gradio内置组件在界面显示内容

在响应函数中通过gr.Info将history内容展示在界面,同时保留print:

import gradio as gr
import time
import random

def random_response(message, history):
    print("当前对话历史:", history)
    # 在界面顶部弹出提示框显示history
    gr.Info(f"对话历史:{history}")
    
    yield "这是Bot的第一条回复"
    time.sleep(1)
    yield f"这是Bot的第二条回复,你刚才说的是:{message}"

demo = gr.ChatInterface(random_response)
demo.launch()

方法2:启用Gradio Debug模式

启动时添加debug=True,所有print输出会显示在Colab单元格日志中:

demo.launch(debug=True)

启用后,Colab单元格的「输出」面板会展示Gradio所有后台日志,包括print(history)的内容。

方法3:将history写入文件查看

若需持久化保存,可将history写入Colab本地文件:

def random_response(message, history):
    with open("chat_history.txt", "a", encoding="utf-8") as f:
        f.write(f"对话历史:{history}\n")
    print("当前对话历史已写入文件")
    
    yield "这是Bot的第一条回复"
    time.sleep(1)
    yield f"这是Bot的第二条回复,你刚才说的是:{message}"

执行后,在Colab左侧「文件」面板找到chat_history.txt,打开即可查看内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 01:19:54