求助:如何在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
相关产品推荐
相关产品推荐

