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

基于NiceGUI的AutoGen聊天界面问题:终端显回复但UI不展示

解决AutoGen回复无法在NiceGUI UI中显示的问题

1. 核心问题根源

AutoGen默认会把Agent的回复直接打印到终端,不会主动把内容返回给调用者的response变量;而异常信息能显示是因为你已经做了捕获并手动同步到UI,正常流程却没做终端输出到UI的转发。

2. 直接可行的解决方案

给AutoGen的Agent配置自定义输出处理器,把原本打印到终端的内容实时同步到NiceGUI的聊天界面:

from nicegui import ui
from autogen import AssistantAgent, UserProxyAgent, config_list_from_json

# 初始化聊天消息存储和UI组件
chat_messages = []
chat = ui.chat_message()

def update_chat(role, content):
    chat_messages.append({'role': role, 'content': content})
    chat.clear()
    for msg in chat_messages:
        chat.add_message(msg['role'], msg['content'])
    ui.update()  # 强制刷新UI

# 自定义输出处理函数,替代AutoGen默认的print
def capture_autogen_output(message, **kwargs):
    # 提取消息内容和发送者角色
    if hasattr(message, 'content'):
        content = message.content.strip()
        if isinstance(message.sender, AssistantAgent):
            update_chat('assistant', content)
        elif isinstance(message.sender, UserProxyAgent):
            update_chat('user', content)
    else:
        update_chat('system', str(message))

# 加载AutoGen的LLM配置
config_list = config_list_from_json(env_or_file="OAI_CONFIG_LIST")

# 创建Agent时绑定自定义输出处理器
assistant = AssistantAgent(
    name="assistant",
    llm_config={"config_list": config_list},
    system_message="你是专业助手,回答简洁准确。",
    output_handler=capture_autogen_output  # 关键配置
)

user_proxy = UserProxyAgent(
    name="user_proxy",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=5,
    is_termination_msg=lambda x: x.get("content", "").endswith("TERMINATE"),
    output_handler=capture_autogen_output,  # 同样绑定
    code_execution_config={"work_dir": "auto_code"},
)

# 处理用户输入的函数
def send_message():
    user_input = input_box.value.strip()
    if not user_input:
        return
    update_chat('user', user_input)
    input_box.value = ""
    # 触发AutoGen对话,回复会被自定义处理器捕获
    try:
        user_proxy.initiate_chat(assistant, message=user_input)
    except Exception as e:
        update_chat('system', f"出错了:{str(e)}")

# 搭建NiceGUI界面
input_box = ui.input("输入你的问题").on('keydown.enter', send_message)
ui.button("发送", on_click=send_message)

ui.run()

3. 额外优化点

  • 如果需要事后获取完整对话历史,可以直接从Agent的chat_history属性读取:
    # 对话结束后遍历历史
    for msg in user_proxy.chat_history:
        update_chat(msg['role'], msg['content'])
    
  • 确保所有参与对话的Agent都配置了output_handler,避免漏抓某方的回复

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 23:30:59