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

求助:如何在Gradio中实现Bot回复逐字加载动画(类ChatGPT)

Gradio实现Bot逐字流式回复的修复方案

原代码问题分析

你的代码无法实现逐字回复,主要有以下几个问题:

  • 错误使用gr.Interface而非聊天场景专用的gr.ChatInterface,普通Interface不支持流式更新聊天历史的渲染
  • user函数返回值格式不符合要求,且存在未定义的css变量、无效的interface_size参数
  • 输入框更新的写法错误,Gradio的组件更新应该用gr.update()而非gradio.Interface.update_input

修正后的可运行代码

import time, random
import gradio as gr

def user(user_message, history):
    # 清空输入框,返回更新后的历史
    return gr.update(value=""), history + [[user_message, None]]

def bot(history):
    bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
    history[-1][1] = ""
    # 逐字拼接并流式返回
    for character in bot_message:
        history[-1][1] += character
        time.sleep(0.05)
        yield history
        time.sleep(0.2)

# 使用ChatInterface构建聊天界面
iface = gr.ChatInterface(
    fn=bot,
    fn_user=user,
    chatbot=gr.Chatbot(height=500)
)
iface.queue().launch()

关键改动说明

  • 替换gr.Interface为gr.ChatInterface:这是Gradio针对聊天交互优化的组件,原生支持流式消息更新
  • 修正输入框更新逻辑:使用gr.update()来清空输入框,符合Gradio的组件更新规范
  • 移除无效参数:删除未定义的css和不存在的interface_size参数,避免报错
  • 保留核心流式逻辑:bot函数的生成器写法不变,确保每一个字符添加后都能实时更新界面

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:35:18