import autogenfrom nicegui import ui, contextfrom uuid import uuid4# AutoGen 配置config_list = [ { 'model': 'gpt-4', 'api_key': '' }]llm_config = { 'seed': 42, 'config_list': config_list, 'temperature': 0.2}# 初始化 AutoGen 代理assistant = autogen.AssistantAgent(name='Albert', llm_config=llm_config)user_proxy = autogen.UserProxyAgent(name='user_proxy', human_input_mode="NEVER", max_consecutive_auto_reply=1, is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"), code_execution_config={"work_dir": "web"}, llm_config=llm_config)@ui.page('/')def main(): messages = [] user_id = str(uuid4()) # 为每个用户会话生成唯一ID @ui.refreshable def chat_messages(): for name, text in messages: ui.chat_message(text=text, name=name, sent=name == '您') if context.get_client().has_socket_connection: ui.run_javascript('setTimeout(() => window.scrollTo(0, document.body.scrollHeight), 0)') async def send(): user_message = task_input.value messages.append(('您', user_message)) # 将用户消息添加到消息列表中 chat_messages.refresh() # 刷新聊天消息以显示最新消息 task_input.value = '' # 发送消息后清空输入字段 try: response = await user_proxy.initiate_chat(assistant, message=user_message) if response and 'content' in response[0]: assistant_response = response[0]['content'] messages.append(('Albert', assistant_response)) # 将助手的响应添加到消息中 else: messages.append(('Albert', "助手未提供响应。")) except Exception as e: messages.append(('Albert', f"错误: {e}")) finally: chat_messages.refresh() with ui.scroll_area().classes('w-full h-60 p-3 bg-white overflow-auto'): chat_messages() with ui.footer().style('position: fixed; left: 0; bottom: 0; width: 100%; background: white; padding: 10px; box-shadow: 0 -2px 5px rgba(0,0,0,0.1);'): task_input = ui.input().style('width: calc(100% - 100px);') ui.button('发送', on_click=send).style('width: 90px;')ui.run(title='与 Albert 聊天')
尝试使用这个GUI来覆盖 Autogen。然而,我无法弄清楚响应来自哪里?响应变量似乎没有包含它。当出现异常时,它会在 UI 中打印出来,当它运行良好时,Autogen 会在终端而不是 UI 中打印答案。
回答:
您需要通过 Agent 类的 register_reply
函数传递您的回调函数,以在您的 Web UI 上获取或打印响应。以下是代码的概念:
def print_messages(recipient, messages, sender, config): # 每次代理接收到消息时 # 在这里执行您自己的逻辑 messages.append((messages[-1]['name'], messages[-1]['content'])) return False, Noneassistant.register_reply( [autogen.Agent, None], reply_func=print_messages, config={"callback": None},)
您可能需要查看官方文档