Skip to content

第16章 预构建 Agent 组件

16.1 引言

前面的章节深入剖析了 LangGraph 的底层基础设施——StateGraph、Channel、Pregel 调度、Checkpoint、Send、Runtime、Store。这些原语提供了极大的灵活性,但直接使用它们构建一个完整的 Agent 需要编写大量的样板代码:定义状态 schema、创建 ToolNode、编写条件边路由、处理错误和重试。

langgraph.prebuilt 模块正是为了解决这个问题。它在底层原语之上提供了一组经过实战验证的高层组件:create_react_agent 工厂函数可以一行代码创建完整的 ReAct Agent;ToolNode 封装了工具执行的并行化、错误处理和状态注入;tools_condition 提供了标准的条件路由;ValidationNode 支持工具调用的 schema 验证;InjectedStateInjectedStore 让工具可以直接访问图状态和持久化存储。

本章将从这些组件的源码出发,分析它们如何将底层能力组合成开发者友好的高层 API,同时保持完整的可扩展性。

本章要点

  1. create_react_agent 工厂函数——从参数到编译图的完整构建流程
  2. ToolNode 实现——并行执行、错误处理、状态注入、Command 支持
  3. tools_condition 路由——标准的 Agent 循环条件判断
  4. ValidationNode——工具调用的 Pydantic schema 验证
  5. InjectedStateInjectedStoreToolRuntime——工具级别的依赖注入

16.2 create_react_agent 工厂函数

16.2.1 签名概览

create_react_agent 定义在 langgraph/prebuilt/chat_agent_executor.py 中,是构建 ReAct Agent 的一站式入口:

python
def create_react_agent(
    model: str | LanguageModelLike | Callable,
    tools: Sequence[BaseTool | Callable | dict] | ToolNode,
    *,
    prompt: Prompt | None = None,
    response_format: StructuredResponseSchema | None = None,
    pre_model_hook: RunnableLike | None = None,
    post_model_hook: RunnableLike | None = None,
    state_schema: StateSchemaType | None = None,
    context_schema: type[Any] | None = None,
    checkpointer: Checkpointer | None = None,
    store: BaseStore | None = None,
    interrupt_before: list[str] | None = None,
    interrupt_after: list[str] | None = None,
    debug: bool = False,
    version: Literal["v1", "v2"] = "v2",
    name: str | None = None,
) -> CompiledStateGraph:

16.2.2 构建流程

基于 VitePress 构建