人机协作HITL实现:当AI Agent向你求助时
2026/5/7 9:40:59 网站建设 项目流程

摘要:再强大的AI也有盲区——验证码、主观判断、物理操作。browser-use webui内置了完善的人机协作(Human-in-the-Loop)机制。本文深入解析ask_for_assistantAction的实现,讲解如何让Agent在关键时刻"举手提问"。


一、为什么Agent需要向人类求助?

Agent求助场景

认证壁垒

短信验证码

图形验证码

二次验证

信息缺口

账号密码

主观偏好

实时决策

能力边界

物理操作

复杂CAPTCHA

人类判断

异常处理

页面结构突变

反爬拦截

支付确认


二、核心实现:ask_for_assistant Action

# src/controller/custom_controller.pyclassCustomController(Controller):def__init__(self,...,ask_assistant_callback=None):super().__init__(...)self.ask_assistant_callback=ask_assistant_callbackdef_register_custom_actions(self):@self.registry.action("When executing tasks, prioritize autonomous completion. ""However, if you encounter a definitive blocker that prevents ""you from proceeding independently – such as needing credentials, ""requiring subjective human judgment, encountering complex CAPTCHAs, ""or facing limitations in your capabilities – you must request human assistance.")asyncdefask_for_assistant(query:str,browser:BrowserContext):""" Agent向人类求助的核心Action :param query: Agent描述遇到的问题 :param browser: 当前浏览器上下文(可用于截图展示) """ifself.ask_assistant_callback:# 判断回调是同步还是异步ifinspect.iscoroutinefunction(self.ask_assistant_callback):user_response=awaitself.ask_assistant_callback(query,browser)else:user_response=self.ask_assistant_callback(query,browser)msg=f"AI提问:{query}\n用户回复:{user_response['response']}"logger.info(msg)returnActionResult(extracted_content=msg,include_in_memory=True)else:returnActionResult(extracted_content="人类无法帮助你,请尝试其他方式。",include_in_memory=True)

三、WebUI层的事件同步

3.1 等待用户回复

# src/webui/components/browser_use_agent_tab.pyasyncdef_ask_assistant_callback(webui_manager,query,browser_context):"""Agent求助时的UI回调函数"""logger.info("Agent需要协助,等待用户输入...")# 在Chatbot中显示求助信息webui_manager.bu_chat_history.append({"role":"assistant","content":f"**需要帮助:**{query}\n请在下方输入框填写信息后点击提交。"})# 创建异步事件,Agent将在此挂起等待webui_manager.bu_response_event=asyncio.Event()webui_manager.bu_user_help_response=Nonetry:# 等待用户提交(最多1小时)awaitasyncio.wait_for(webui_manager.bu_response_event.wait(),timeout=3600.0)exceptasyncio.TimeoutError:logger.warning("用户帮助请求超时")return{"response":"超时: 用户未响应"}# 获取用户回复并清理事件response=webui_manager.bu_user_help_response webui_manager.bu_response_event=Nonereturn{"response":response}

3.2 用户提交回复

asyncdefhandle_submit(webui_manager,components):user_input_comp=webui_manager.get_component_by_id("browser_use_agent.user_input")user_input_value=components.get(user_input_comp,"").strip()# 场景1:Agent正在等待帮助ifwebui_manager.bu_response_eventandnotwebui_manager.bu_response_event.is_set():logger.info(f"用户提交帮助信息:{user_input_value}")webui_manager.bu_user_help_response=user_input_valueor"用户未提供文字回复"webui_manager.bu_response_event.set()# 唤醒Agent!yield{user_input_comp:gr.update(value="",interactive=False),run_button:gr.update(value="⏳ Running...",interactive=False),}

四、交互时序图

人类用户Gradio UIBrowserUseAgent人类用户Gradio UIBrowserUseAgentAgent挂起等待(asyncio.Event.wait)遇到验证码ask_for_assistant("请帮我输入验证码")在Chatbot显示求助激活输入框输入验证码"123456"点击Submitevent.set()返回{"response": "123456"}继续执行填写验证码并提交

五、最佳实践

5.1 Prompt工程:让Agent知道何时求助

ask_for_assistant的Action描述经过精心设计:

When executing tasks, prioritize autonomous completion. However, if you encounter a definitive blocker: - needing credentials you don't possess - requiring subjective human judgment - needing a physical action performed - encountering complex CAPTCHAs - facing limitations in your capabilities You MUST request human assistance.

要点:明确列举求助场景,避免Agent过度依赖人类(什么都问)或过度自信(硬闯验证码)。

5.2 超时策略

场景建议超时理由
验证码输入5分钟用户需要查看手机/邮箱
主观判断10分钟可能需要查阅资料
账号密码2分钟应已准备就绪

六、总结

人机协作不是Agent的"失败",而是能力边界的诚实声明。browser-use webui的HITL实现展现了三个工程智慧:

  1. 非阻塞等待asyncio.Event让Agent暂停而不卡死
  2. 状态透明:求助信息实时显示在Chatbot中,用户随时知晓Agent状态
  3. 超时保护:避免Agent永久等待,无人值守时也能自动退出

核心哲学:最好的AI Agent不是替代人类,而是在需要时恰当地邀请人类参与。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询