
Haystack v2.20 Experimental Agents API 详解工具调用 Agent 与 Human-in-the-Loop 确认策略【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack本文以 Haystack 2.20 版本的haystack-experimental包中 Agents API 文档为主体系统讲解实验性Agent组件的构造参数、run/run_async运行语义、序列化接口以及配套的 human-in-the-loopHITL确认策略模块breakpoint 工具函数、HITLBreakpointException、BreakpointConfirmationStrategy。读完本文你可以掌握如何配置一个带工具调用循环的 Agent 组件如何通过confirmation_strategies对工具执行施加人工确认并借助当前主仓库中对应的源码实现理解其底层调用链与版本演进关系。一、模块定位haystack-experimental 中的 Agents API该文档对应haystack_experimental.components.agents.agent模块其核心是一个实现工具调用 Agent的 Haystack 组件具备 provider 无关provider-agnostic的聊天模型支持。文档中对该类的关键描述包括该组件扩展了 Haystack 核心的 Agent 组件增加了**人工确认策略human-in-the-loop confirmation strategies**的支持组件会持续处理消息并执行工具直到满足某个退出条件exit condition。退出条件既可以由一条直接的文本回复触发也可以由调用某个被指定工具触发且支持同时指定多个退出条件当 Agent 不配置任何工具时它的行为退化为一个ChatGenerator产生一次响应后即退出。需要注意适用前提这是v2.20 时期haystack-experimental独立包的 API 文档Agent位于haystack_experimental.components.agents命名空间下与主包haystack中的Agent是两个不同的导入路径。在当前仓库的主干源码中Agent已演进为位于 haystack/components/agents/agent.py 的核心组件HITL 相关原语则位于 haystack/hooks/human_in_the_loop/ 目录本文在第四节结合主干源码说明二者的对应关系。二、Agent 组件构造参数完整说明2.1 用法示例文档给出的标准用法示例展示了如何为不同工具绑定不同的确认策略from haystack.components.generators.chat import OpenAIChatGenerator from haystack.dataclasses import ChatMessage from haystack.tools.tool import Tool from haystack_experimental.components.agents import Agent from haystack_experimental.components.agents.human_in_the_loop import ( HumanInTheLoopStrategy, AlwaysAskPolicy, NeverAskPolicy, SimpleConsoleUI, ) calculator_tool Tool(namecalculator, descriptionA tool for performing mathematical calculations., ...) search_tool Tool(namesearch, descriptionA tool for searching the web., ...) agent Agent( chat_generatorOpenAIChatGenerator(), tools[calculator_tool, search_tool], confirmation_strategies{ calculator_tool.name: HumanInTheLoopStrategy( confirmation_policyNeverAskPolicy(), confirmation_uiSimpleConsoleUI() ), search_tool.name: HumanInTheLoopStrategy( confirmation_policyAlwaysAskPolicy(), confirmation_uiSimpleConsoleUI() ), }, ) # Run the agent result agent.run( messages[ChatMessage.from_user(Find information about Haystack)] ) assert messages in result # Contains conversation history从示例可以读出三点设计意图confirmation_strategies是一个以工具名为键的字典可以为每个工具单独指定何时询问的策略与通过什么界面询问的 UINeverAskPolicy表示该工具直接放行AlwaysAskPolicy表示每次都向用户确认返回值是一个包含messages键的字典承载完整的对话历史。2.2Agent.__init__参数表def __init__(*, chat_generator: ChatGenerator, tools: ToolsType | None None, system_prompt: str | None None, exit_conditions: list[str] | None None, state_schema: dict[str, Any] | None None, max_agent_steps: int 100, streaming_callback: StreamingCallbackT | None None, raise_on_tool_invocation_failure: bool False, confirmation_strategies: dict[str, ConfirmationStrategy] | None None, tool_invoker_kwargs: dict[str, Any] | None None, chat_message_store: ChatMessageStore | None None, memory_store: MemoryStore | None None) - None所有参数均为关键字参数*之后的强制 keyword-only逐项说明如下参数类型 / 默认值说明chat_generatorChatGenerator必填Agent 使用的聊天生成器实例。必须支持 tools否则抛出TypeError。toolsToolsType \| None默认NoneAgent 可使用的工具列表或一个Toolset。system_promptstr \| None默认NoneAgent 的系统提示词。exit_conditionslist[str] \| None默认None等价于[text]让 Agent 返回的条件列表text表示当模型生成不含工具调用的消息时返回工具名表示该工具执行完毕后 Agent 即返回。非法取值抛出ValueError。state_schemadict[str, Any] \| None默认None工具所用的运行时状态State的模式定义决定了run时可通过**kwargs传入的额外数据键。max_agent_stepsint默认100Agent 运行步数上限。超出后 Agent 停止并返回当前状态。streaming_callbackStreamingCallbackT \| None默认NoneLLM 流式响应时的回调同一回调也可配置为在工具被调用时输出工具结果。raise_on_tool_invocation_failurebool默认False工具调用失败时是否抛出异常。设为False时异常会被转成一条聊天消息传回 LLM由模型自行处理这是让 Agent 具备错误自愈能力的关键开关。confirmation_strategiesdict[str, ConfirmationStrategy] \| None默认None以工具名为键的确认策略映射是 experimental 版本 Agent 相比核心 Agent 的主要扩展点。tool_invoker_kwargsdict[str, Any] \| None默认None透传给ToolInvoker的额外关键字参数。chat_message_storeChatMessageStore \| None默认NoneAgent 用来存取聊天消息历史的存储后端。memory_storeMemoryStore \| None默认NoneAgent 用来存取记忆memories的存储后端。异常约定chat_generator的run方法不支持tools参数时抛TypeErrorexit_conditions非法时抛ValueError。2.3Agent.run运行语义与全部参数def run(messages: list[ChatMessage], streaming_callback: StreamingCallbackT | None None, *, generation_kwargs: dict[str, Any] | None None, break_point: AgentBreakpoint | None None, snapshot: AgentSnapshot | None None, system_prompt: str | None None, tools: ToolsType | list[str] | None None, confirmation_strategy_context: dict[str, Any] | None None, chat_message_store_kwargs: dict[str, Any] | None None, memory_store_kwargs: dict[str, Any] | None None, **kwargs: Any) - dict[str, Any]run的行为是处理消息并执行工具直到满足退出条件。参数中几个与 HITL、断点续跑直接相关的要点值得展开break_point一个AgentBreakpoint可以是面向chat_generator的Breakpoint也可以是面向tool_invoker的ToolBreakpoint。触发断点时会抛出BreakpointException。snapshot一个字典包含先前保存的 Agent 执行快照携带了从断点处重启执行所需的全部信息。它与break_point配合构成了暂停—确认—恢复的完整机制也是BreakpointConfirmationStrategy依赖的基础。tools运行期参数可选的 Tool 对象列表、Toolset或工具名列表用于覆盖本次运行使用的工具传工具名时从 Agent 初始化时配置的工具中选取。confirmation_strategy_context请求级资源的传递通道。在 Web/服务器环境下可以放入每个请求独立的对象例如 WebSocket 连接、异步队列、Redis pub/sub 客户端供确认策略实现非阻塞的用户交互。chat_message_store_kwargs透传给ChatMessageStore的参数例如chat_history_id与last_k用于按会话 ID 和最近 N 条检索聊天历史。memory_store_kwargs透传给MemoryStore的参数包含user_id按用户 ID 检索/写入记忆run_id按运行 ID 检索/写入记忆agent_id按 Agent ID 检索/写入记忆search_criteriasearch_memories方法的 kwargs 字典其中filters过滤条件、query检索查询传入后将忽略传给 Agent 的用户查询用于记忆检索、top_k返回条数、include_memory_metadata是否在ChatMessage中附带记忆元数据。**kwargs传给 Agentstate_schema使用的 State 的额外数据键名必须与state_schema定义一致。返回字典固定包含两个键并附加 schema 键messagesAgent 本次运行中交换的所有消息列表、last_message最后一条消息以及state_schema中定义的所有额外键。异常约定run()调用前组件未预热warm up时抛RuntimeError触发断点时抛BreakpointException。2.4Agent.run_asyncrun_async与run签名一一对应messages、streaming_callback、generation_kwargs、break_point、snapshot、system_prompt、tools、confirmation_strategy_context、chat_message_store_kwargs、memory_store_kwargs、**kwargs文档明确说明它是run的异步版本遵循相同逻辑但在可行处使用异步操作——例如当ChatGenerator提供run_async方法时直接调用它。其streaming_callback也相应为异步回调。返回值与异常约定与run完全一致未预热抛RuntimeError断点触发抛BreakpointException。2.5 序列化to_dict与from_dictdef to_dict() - dict[str, Any] # 序列化为字典 classmethod def from_dict(cls, data: dict[str, Any]) - Agent # 从字典反序列化这两个方法使Agent包括其绑定的chat_generator、tools与confirmation_strategies可以随 Pipeline 一起序列化/反序列化从而把带确认策略的 Agent 配置完整地持久化到管道文件中。三、HITL 模块breakpoint 辅助函数、异常与断点确认策略文档的后半部分覆盖haystack_experimental.components.agents.human_in_the_loop包下的三个子模块它们共同支撑非即时交互场景下的人工确认。3.1breakpoint从快照提取工具调用信息def get_tool_calls_and_descriptions_from_snapshot( agent_snapshot: AgentSnapshot, breakpoint_tool_only: bool True ) - tuple[list[dict], dict[str, str]]该函数从一个AgentSnapshot中提取工具调用列表和工具描述字典。breakpoint_tool_onlyTrue时只处理触发断点的那一次工具调用并重建其参数设为False时返回全部工具调用。文档指出其典型场景是把相关工具调用及其描述呈现给人类在执行前获取确认——这正是BreakpointConfirmationStrategy抛出的快照文件与用户端审查流程之间的衔接点。3.2errorsHITLBreakpointExceptionclass HITLBreakpointException: def __init__(message: str, tool_name: str, snapshot_file_path: str, tool_call_id: str | None None) - None当工具执行被某个ConfirmationStrategy例如BreakpointConfirmationStrategy暂停时抛出。构造参数message异常消息tool_name被暂停工具的名称snapshot_file_path已保存的 pipeline 快照的文件路径恢复执行时通过run(snapshot...)使用tool_call_id可选的工具调用唯一标识用于把用户的确认决定与具体某次工具调用关联追踪。3.3strategiesBreakpointConfirmationStrategyclass BreakpointConfirmationStrategy: def __init__(snapshot_file_path: str) - Nonesnapshot_file_path是快照应当保存到的目录路径。该策略的定位是当无法与用户即时交互时使用。其工作流程为某次工具执行需要确认时策略抛出HITLBreakpointExceptionAgent 捕获该异常并把当前状态包含工具调用细节序列化为快照文件用户端可能是另一个进程、另一次交互读取快照审阅并确认工具执行确认后的流程携带snapshot调用Agent.run/Agent.run_async从断点处恢复。其run/run_async签名一致def run(self, *, tool_name: str, tool_description: str, tool_params: dict[str, Any], tool_call_id: str | None None, confirmation_strategy_context: dict[str, Any] | None None) - ToolExecutionDecision文档对其语义的表述非常明确该方法是不返回的——它总是抛出HITLBreakpointException以表示需要用户确认confirmation_strategy_context参数仅为接口兼容而保留、本策略并不使用。run_async是run的异步版本内部调用同步run()行为与异常约定相同。策略同样提供to_dict/from_dict保证作为confirmation_strategies的值时可以被 Pipeline 序列化机制处理。四、结合主干源码的实现印证HITL 原语如何落地v2.20 文档中的AlwaysAskPolicy、NeverAskPolicy、SimpleConsoleUI等类型在当前仓库主干中已由haystack.hooks.human_in_the_loop包提供统一实现可以借源码印证文档中的策略语义。4.1 确认策略ConfirmationPolicy在 haystack/hooks/human_in_the_loop/policies.py 中定义了文档示例用到的策略家族AlwaysAskPolicy第 11 行、NeverAskPolicy第 26 行以及AskOncePolicy第 41 行询问一次后记住结果。策略的核心接口是should_ask(tool_name, tool_description, tool_params)策略在被询问后还会通过update_after_confirmation接收用户的确认结果以做学习/更新。4.2 确认 UI 与阻塞式策略在 haystack/hooks/human_in_the_loop/user_interfaces.py 中定义了RichConsoleUI第 22 行与文档示例中的SimpleConsoleUI第 124 行它们实现向用户展示工具名、描述与参数并收集决定的界面抽象。在 haystack/hooks/human_in_the_loop/strategies.py 中BlockingConfirmationStrategy第 31 行展示了文档中HumanInTheLoopStrategy一类即时确认策略的执行逻辑先调用self.confirmation_policy.should_ask(...)判断是否需要询问不需要则直接返回放行的ToolExecutionDecisionexecuteTrue需要询问则调用self.confirmation_ui.get_user_confirmation(...)随后把 UI 结果回传给策略做update_after_confirmation用户拒绝时按reject_template默认文案 Tool execution for {tool_name} was rejected by the user.构造反馈消息返回executeFalse的决定修改参数时则按modify_template回填用户修正后的final_tool_params。同文件中的_run_confirmation_strategies第 408 行与_apply_tool_execution_decisions第 544 行则负责在 Agent 的工具调用循环中批量执行各工具的策略并把决定落回工具调用_serialize_confirmation_strategies/_deserialize_confirmation_strategies第 666、686 行保证了策略字典随组件一起被序列化——这与文档中Agent.to_dict/Agent.from_dict的行为相对应。4.3 主干 Agent 的运行状态管理主干的Agent实现见 haystack/components/agents/agent.pyAgent类定义于第 225 行。从源码结构看其运行状态被显式划分为三类_RUN_METADATA_STATE_KEYS第 77 行自动维护step_count、token_usage、tool_call_counts、exit_reason等运行元数据_INTERNAL_STATE_KEYS第 93 行管理continue_run、stop_run、tools、hook_context、context_tokens等内部控制状态第 88 行注释指出tools键供 hook 检查当前步骤可用工具例如 HITL 确认用户数据则来自state_schema。同时源码中保留了文档所述的核心语义_EXIT_REASON_TEXT text第 70 行对应exit_conditions中的text条件max_agent_steps超限时以max_agent_steps作为退出原因第 73 行。相关的测试集中在 test/components/agents/ 目录可作为行为验证的入口。从源码结构看可以推断BreakpointConfirmationStrategy这类抛出HITLBreakpointException保存快照的非阻塞策略在主干演进中被重构进了hooks机制与 Agent 的断点/快照体系AgentBreakpoint、AgentSnapshot类型定义见 haystack/dataclasses/breakpoints.py其暂停—快照—确认—恢复的语义与 v2.20 文档描述保持一致只是类型归属和导入路径发生了变化。五、小结与实践要点无工具即生成器不配置tools时 Agent 退化为单轮ChatGenerator这使其可以直接充当 Pipeline 中的一次性生成节点。退出条件是显式契约exit_conditions默认[text]加入工具名即可实现调用某工具后必须收尾的流程控制max_agent_steps默认 100兜底防止无限循环。失败策略二选一raise_on_tool_invocation_failureFalse默认会把工具异常转成聊天消息交回 LLM 自纠适合需要鲁棒性的生产流程设为True则快速失败适合调试。HITL 两种形态即时交互用策略 UIAlwaysAskPolicy/NeverAskPolicy等可结合SimpleConsoleUI/RichConsoleUI无法即时交互时用BreakpointConfirmationStrategy靠HITLBreakpointException 快照文件 run(snapshot...)完成暂停—人工审查—恢复闭环tool_call_id保证决定与具体调用可关联。版本注意本文主体基于 v2.20 的haystack-experimentalAPI导入路径为haystack_experimental.components.agents使用当前主干haystack包时Agent与 HITL 原语的导入路径为haystack.components.agents与haystack.hooks.human_in_the_loop参数语义可参照 haystack/components/agents/agent.py 的最新实现核对。【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考