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

如何配置gr.ChatInterface返回多输出(响应+源文档)

如何为gr.ChatInterface添加多输出(响应+源文档)?

我现在用gr.ChatInterface做了一个RAG问答应用,想在返回回答的同时,展示检索用到的文档源。但尝试用outputs参数时报错,因为ChatInterface不支持这个参数。

当前代码:

import gradio as gr

def generate_response(message, history):   
    print(f"\n\n[message] {message}")
    # 调用LLM并生成响应
    return response.answer


demo = gr.ChatInterface(
    fn=generate_response,
    title="RAG app for Q&A",
    description="Ask any question about Stuff",
).queue(default_concurrency_limit=2, max_size=10)

demo.launch(share=True)

报错信息:

Traceback (most recent call last):
  File "/workspaces/aider_repos/app.py", line 20, in <module>
    demo = gr.ChatInterface(
           ^^^^^^^^^^^^^^^^^
TypeError: ChatInterface.__init__() got an unexpected keyword argument 'outputs'

方法一:在回复消息中嵌入源文档

直接把源文档内容附加到回答里,用Markdown格式区分,比如分隔线或列表:

import gradio as gr

def generate_response(message, history):   
    # 模拟LLM生成回答和检索到的文档源
    answer = "这是LLM生成的回答内容"
    sources = [
        "文档1:《XX指南》第3章第2节",
        "文档2:《API参考手册》版本2.0"
    ]
    # 拼接回答和源文档
    full_response = f"{answer}\n\n---\n**参考文档:**\n" + "\n".join([f"- {s}" for s in sources])
    return full_response


demo = gr.ChatInterface(
    fn=generate_response,
    title="RAG app for Q&A",
    description="Ask any question about Stuff",
).queue(default_concurrency_limit=2, max_size=10)

demo.launch(share=True)

方法二:添加独立的额外输出组件(Gradio 4+支持)

如果需要单独区域展示源文档,可使用additional_outputs参数指定额外组件,同时让生成函数返回多个值:

import gradio as gr

def generate_response(message, history):   
    # 模拟LLM生成回答和检索到的文档源
    answer = "这是LLM生成的回答内容"
    sources = "\n".join([
        "文档1:《XX指南》第3章第2节",
        "文档2:《API参考手册》版本2.0"
    ])
    # 返回两个值:回答内容、源文档内容
    return answer, sources


demo = gr.ChatInterface(
    fn=generate_response,
    title="RAG app for Q&A",
    description="Ask any question about Stuff",
    # 指定额外输出组件:只读文本框
    additional_outputs=gr.Textbox(label="参考文档", lines=5, interactive=False)
).queue(default_concurrency_limit=2, max_size=10)

demo.launch(share=True)

注意:additional_outputs是Gradio 4.x版本新增参数,若版本低于4.0,需先升级:pip install --upgrade gradio

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:25:09