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

如何将用户提问与GPT API响应变量接入Gradio Chatbot组件?

解决Gradio Chatbot滚动显示及对话逻辑问题

代码中的核心问题

  1. bot函数错误依赖未正确传递的全局user_message变量,应该从聊天历史中提取最新用户提问
  2. 每次响应都重复加载index.json,大幅降低性能
  3. 存在冗余的全局变量定义和未使用的question_answer_NEW函数
  4. 对话历史更新逻辑存在漏洞,导致响应无法正确显示

修正后的完整代码

import gradio as gr
import time
from llama_index import GPTSimpleVectorIndex
import os

# 提前加载索引,避免重复读取文件
os.environ["OPENAI_API_KEY"] = 'sk-...'  # 替换为你的API密钥
index = GPTSimpleVectorIndex.load_from_disk('index.json')

with gr.Blocks() as demo:
    chatbot = gr.Chatbot(height=600)  # 设置固定高度,确保内容溢出时自动滚动
    msg = gr.Textbox(placeholder="请输入你的问题...")
    clear = gr.Button("清空对话")

    def user_input_handler(user_message, history):
        # 清空输入框,将用户提问添加到聊天历史(响应位置先留空)
        return "", history + [[user_message, None]]

    def bot_response_handler(history):
        # 从聊天历史中获取最新的用户提问
        latest_question = history[-1][0]
        # 查询索引生成响应
        bot_message = index.query(latest_question, response_mode="compact").response.strip()
        # 更新聊天历史中的响应内容
        history[-1][1] = bot_message
        # 模拟延迟优化交互体验
        time.sleep(1)
        return history

    # 绑定事件流程:提交输入→处理用户输入→生成机器人响应
    msg.submit(user_input_handler, [msg, chatbot], [msg, chatbot], queue=False).then(
        bot_response_handler, chatbot, chatbot
    )
    # 绑定清空对话事件
    clear.click(lambda: None, None, chatbot, queue=False)

if __name__ == "__main__":
    demo.launch()

关键修改说明

  • 提前加载索引:将index.json的加载移到全局作用域,避免每次响应重复读取文件,提升运行效率
  • 修复对话逻辑:bot_response_handler从聊天历史的最后一条数据中获取用户提问,不再依赖不稳定的全局变量
  • 优化滚动显示:给Chatbot设置height属性,确保内容超过高度阈值时自动触发滚动
  • 清理冗余代码:移除未使用的函数和不必要的全局变量,简化代码结构
  • 规范事件绑定:确保用户输入与机器人响应的流程衔接正确,保证对话内容正常显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:07:46