前言

本篇进入第三部分「LangChain 薄壳与积木」。英文暗线仍是 Agent Runtime → Harness;这里要拆的「薄壳」,就是 LangChain 的 create_agent——看它到底薄在哪、厚在哪。

在这里插入图片描述

一、先把它放回四层坐标里

第 2 篇里,我用 create_agent 一口气跑通了第一个 Agent(智能体);第 3、4 篇,我又手写了 StateGraph 和工具调用循环。现在回头看会有一个很自然的疑问:create_agent 和手写的 StateGraph,到底是什么关系?

答案是:create_agent 就是一个 StateGraph 工厂函数——它自己不发明任何新的运行时能力,只是把你在第 3、4 篇手写的「model 节点 + tools 节点 + 条件回环」这套固定套路,按 LangGraph 的规则装配成一个编译好的图,再在外面套一层 middleware 钩子。

把它放回本系列的四层坐标(依赖自底向上):

langchain-core(积木:messages / tools / models / bind_tools)   ← 最底层
        ↑
LangGraph(运行时:图 / 状态 / Checkpoint / 流式 / HITL)
        ↑
create_agent + middleware(LangChain 薄壳)                     ← 本篇拆这一层
        ↑
deepagents / create_deep_agent(Deep Agents 套件)

注意方向:「积木」在 LangGraph 之下,「薄壳」在 LangGraph 之上。create_agent 里用到的消息、工具、模型绑定,全都来自 langchain-core(积木);它做的只是「把这些积木摆进 LangGraph 的图里」。官方按产品分 3 类——Runtime(运行时,LangGraph)、Framework(框架,LangChain)、Harness(套件,官方名 Deep Agents SDK);但 LangChain 那一半其实要再拆成「积木(下)+ 薄壳(上)」两块,依赖上才数得出 4 层。

这也解释了为什么 create_agent 的源码主体约 1000 行,却仍被称作「薄壳」:那 1000 行大部分在应付 middleware、结构化输出、模型能力探测这些外围扩展,真正装配「model↔tools 回环」的核心只有几十行——第 4 篇你已经手写过一遍了。

二、签名与主干:它把 LangGraph 装配成了什么

先看签名(本文基于 langchain 1.4.4 / langgraph 1.2.14 / langchain-core 1.6.9 / langchain-deepseek 1.1.1,泛型参数有省略):

def create_agent(
    model: str | BaseChatModel,
    tools: Sequence[BaseTool | Callable[..., Any] | dict[str, Any]] | None = None,
    *,
    system_prompt: str | SystemMessage | None = None,
    middleware: Sequence[AgentMiddleware] = (),
    response_format: ResponseFormat | type | dict[str, Any] | None = None,
    state_schema: type[AgentState] | None = None,
    context_schema: type | 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,
    name: str | None = None,
    cache: BaseCache | None = None,
    transformers: Sequence[TransformerFactory] | None = None,
) -> CompiledStateGraph:
    ...

model 可以传字符串(如 "openai:gpt-5.5")或模型实例;tools 可以是 BaseTool、普通函数或 dict;返回值是一个编译好的 CompiledStateGraph——这就是「工厂函数」的直接证据:你拿到手的是一个图,不是一个 Agent 类。

顺着源码走主干,装配过程一共就这几步:

  1. 字符串转模型:if isinstance(model, str): model = init_chat_model(model)。

  2. 系统提示转消息:system_prompt 是字符串就包成 SystemMessage。

  3. 空工具归一:tools is None → [](没有工具时,图就只有一个 model 节点,没有回环)。

  4. 拼 ToolNode:把 tools(含 middleware 注入的工具)交给 ToolNode。

  5. 定状态 Schema:base_state = state_schema if state_schema is not None else AgentState,再和 middleware 声明的状态字段合并,解出 state_schema / input_schema / output_schema。

  6. 建图、加节点:

    graph = StateGraph(state_schema=resolved_state_schema, input_schema=input_schema, output_schema=output_schema, context_schema=context_schema)
    graph.add_node("model", RunnableCallable(model_node, amodel_node, trace=False))
    if tool_node is not None:
        graph.add_node("tools", tool_node)
    

    「model」节点是 RunnableCallable 包着同步 / 异步两个实现(resolved_state_schema 是第 5 步合并解析后的结果,不是用户原始入参);middleware 若注册了钩子,会生成 {名字}.before_agent、{名字}.before_model、{名字}.after_model、{名字}.after_agent 四个节点(注意官方没有 before_tool / after_tool,只有 wrap_tool_call)。

  7. 连边、回环:START → model,然后 model 按「最后一条 AIMessage 有没有 tool_calls」条件分叉——有就进 tools,没有就 END;tools 再回到 model。这就是工具调用循环。严格说,真实实现里 model→tools 是 Send("tools", [tool_call]) 对多工具并行 fan-out,tools→model 也是条件边(只在无 return_direct、无结构化输出工具时退化为无条件);单工具最简场景就退化成我下面手写的那张图。

  8. 兜底 + 编译:末尾 graph.compile(...).with_config({"recursion_limit": 9_999, "metadata": {"ls_integration": "langchain_create_agent"}})。

一个关键观察:在「无 middleware、无 response_format、无结构化输出」的最简情况下,整张图就是两个节点(model、tools)加三条边。剩下那一千行,全是在给这两个节点套外套。下面用手写版把它证出来。

三、手写一个「自己的 create_agent」

把上面 8 步里的最简路径抽出来,手写一个 my_create_agent,只保留 model、tools、system_prompt 三个参数:

import sys
from datetime import datetime
from typing import Annotated, TypedDict

from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langchain_core.tools import tool
from langchain_deepseek import ChatDeepSeek
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode

sys.stdout.reconfigure(encoding="utf-8")


class AgentState(TypedDict):
    """Agent 状态:messages 用 add_messages 归约,累积所有对话。"""

    messages: Annotated[list, add_messages]


@tool
def get_current_time() -> str:
    """返回当前本地时间,格式 YYYY-MM-DD HH:MM:SS。"""
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")


def my_create_agent(model, tools, system_prompt: str):
    """手写的 create_agent 最小等价物:model 节点 + tools 节点 + 条件回环。

    对应真实 create_agent 在「无 middleware / 无 response_format / 无结构化输出」
    时的装配路径:StateGraph(AgentState) → add_node("model") → add_node("tools")
    → START→model → model 按 tool_calls 条件分叉 → tools→model 回环 → compile。
    """

    def call_model(state: AgentState):
        # system_prompt 转 SystemMessage 后放到消息最前面,等价 create_agent 的做法
        messages = [SystemMessage(content=system_prompt), *state["messages"]]
        bound = model.bind_tools(tools)
        return {"messages": [bound.invoke(messages)]}

    def route_after_model(state: AgentState):
        last = state["messages"][-1]
        if isinstance(last, AIMessage) and last.tool_calls:
            return "tools"
        return END

    graph = StateGraph(AgentState)
    graph.add_node("model", call_model)
    graph.add_node("tools", ToolNode(tools))
    graph.add_edge(START, "model")
    graph.add_conditional_edges("model", route_after_model, {"tools": "tools", END: END})
    graph.add_edge("tools", "model")
    # 等价 create_agent 末尾的 recursion_limit 兜底:放在运行时 config,不是 compile 参数
    return graph.compile().with_config({"recursion_limit": 9_999})


def main() -> None:
    llm = ChatDeepSeek(model="deepseek-chat")
    app = my_create_agent(llm, [get_current_time], "你是助手,用户问时间就调用工具。")
    out = app.invoke({"messages": [HumanMessage(content="现在几点了?")]})
    for m in out["messages"]:
        print(f"[{m.type}] {m.content}\n")


if __name__ == "__main__":
    main()

真源:code/09-create_agent源码拆解/my_create_agent.py

对应关系一眼能看懂:call_model 里的 bind_tools + 前置 SystemMessage,就是源码 _get_bound_model + _execute_model_sync 的极简版;route_after_model 就是 _make_model_to_tools_edge 的条件判断;ToolNode(tools) 是源码第 4 步的原样调用。

两个细节都来自真源码:

  • system_prompt 放在消息最前面,而不是单独传一个 system= 参数——这样它和后续消息一起进 messages 状态。
  • recursion_limit 是运行时 config,不是 compile() 参数。我第一版写成 graph.compile(recursion_limit=9_999),直接 TypeError。正确姿势是 compile().with_config({"recursion_limit": 9_999}),或调用时 invoke(..., config={"recursion_limit": N})。这是高频踩坑点。

四、对照实验:手写版 == 官方版

光说「等价」不算数,直接把两张图的结构打出来比一比:

import sys

from langchain.agents import create_agent
from langchain_deepseek import ChatDeepSeek

from my_create_agent import get_current_time, my_create_agent

sys.stdout.reconfigure(encoding="utf-8")


def describe(app):
    """把编译图的结构抽成可打印的 dict:节点名 + 边。"""
    g = app.get_graph()
    nodes = sorted(g.nodes.keys())
    edges = sorted((e.source, e.target) for e in g.edges)
    return {"nodes": nodes, "edges": edges}


def main() -> None:
    llm = ChatDeepSeek(model="deepseek-chat")
    real = create_agent(model=llm, tools=[get_current_time], system_prompt="你是助手。")
    mine = my_create_agent(llm, [get_current_time], "你是助手。")

    print("真实 create_agent  :", describe(real))
    print("手写 my_create_agent:", describe(mine))


if __name__ == "__main__":
    main()

真源:code/09-create_agent源码拆解/compare_create_agent.py

两个文件放同一目录(compare_create_agent.py 靠 from my_create_agent import ... 引用前者),在该目录下直接 python compare_create_agent.py 即可。

运行输出:

真实 create_agent  : {'nodes': ['__end__', '__start__', 'model', 'tools'], 'edges': [('__start__', 'model'), ('model', '__end__'), ('model', 'tools'), ('tools', 'model')]}
手写 my_create_agent: {'nodes': ['__end__', '__start__', 'model', 'tools'], 'edges': [('__start__', 'model'), ('model', '__end__'), ('model', 'tools'), ('tools', 'model')]}

两行一模一样。__start__ / __end__ 是 LangGraph 的内置起止哨兵节点,剩下就是 model、tools 两个节点和三条边(model→tools 是条件边,model→__end__ 是「没有工具调用了就结束」那条,tools→model 是回环)。create_agent 装配出来的,就是你手写的这张图——这是「薄壳」最硬核的证据。

五、跑起来:复刻第 2 篇的最小 Agent

用 get_current_time(工具本身是纯标准库,不联网;但模型推理仍需 DEEPSEEK_API_KEY)复刻第 2 篇那种「一个工具的最小 Agent」:

$ python my_create_agent.py
[human] 现在几点了?

[ai] I'll check the current time for you.

[tool] 2026-11-01 15:49:10

[ai] 现在是 **2026年11月1日 15:49:10**。

流程和第 2 篇完全一致:用户发问 → model 节点判定「要调工具」,返回一个带 tool_calls 的 AIMessage(content 不保证为空,模型可能先附一句文字前言)→ 条件边进 tools → ToolNode 执行 get_current_time,产出 ToolMessage → 回环到 model → 模型拿着时间组织出最终回答。只是这一次,这张图是你自己手写的,不再是黑盒。

模型密钥照旧从系统环境变量读取(ChatDeepSeek 走 os.getenv("DEEPSEEK_API_KEY")),不写死、不引 dotenv——这是全系列的约定。

六、弃用 API 清单:这些旧写法别再用了

拆 create_agent 绕不开 LangGraph 1.0 的一次大清理。下面这张表是读老教程时的必查清单(langgraph 1.2.14 / langchain 1.4.4 实测):

旧写法1.0 正确替代
create_react_agent(langgraph.prebuilt)langchain.agents.create_agent
langgraph.prebuilt.AgentStatelangchain.agents.AgentState
langgraph.prebuilt.ValidationNode迁移到 LangChain
MessageGraphStateGraph(messages key)
AgentExecutor(0.x)create_agent

实测有几个坑值得单独点名:

  • langgraph.prebuilt.AgentState 已从顶层导出移除——from langgraph.prebuilt import AgentState 直接 ImportError(弃用别名仍残留在 chat_agent_executor 子模块),统一改从 langchain.agents.AgentState 导入。新版 AgentState 只有三个字段:messages(Required[Annotated[list[AnyMessage], add_messages]])、jump_to、structured_response。
  • langchain.agents.create_react_agent 从来不存在——老教程里那个 create_react_agent 在 langgraph.prebuilt,现在还活着但已标记弃用。
  • AgentExecutor(0.x)才是真·硬移除(import 直接 ImportError,全目录已无此符号);MessageGraph、ValidationNode 仍在但同样弃用。

一句话记住:新的都去 langchain.agents,图能力都去 langgraph.graph,见到 react / Executor / 旧 AgentState 一律绕开。

七、工程化:看懂工厂函数,然后自己改装配

拆完源码,落到三个工程判断上:

1. 什么时候直接用 create_agent,什么时候手写 StateGraph。 标准单 Agent 工具循环,用 create_agent 就好,别手写——它替你处理了 middleware、结构化输出、模型能力探测这些脏活。但当你的拓扑不是「model↔tools 一个回环」,而是 supervisor / 子图 / 自定义路由(见第 8 篇),create_agent 固定装配的骨架就不够了,这时下沉到 StateGraph 手写才是对的。判断标准不是「哪个高级」,而是「你的控制流是不是还是那个标准回环」。

2. 看懂工厂函数,就能自己改装配。 create_agent 的价值不在「藏住复杂度」,而在「给你一个可读的装配模板」。你要加一步(比如 model 之后、tools 之前插一个审计节点),不用推倒重来——照它的装配抄一遍,改一条边就行。这个「抄装配、改一步」的能力,会在讲 Deep Agents 源码拆解的那篇继续放大(create_deep_agent 就是 create_agent + 一套内置 middleware 栈)。

3. 认准 langchain-core 积木的位置。 本篇用到的 SystemMessage / AIMessage / ToolMessage、@tool、bind_tools,全是 langchain-core(积木)的东西;create_agent 一行图运行时都没写,它只是「把积木按 LangGraph 规则摆进 StateGraph」。分清「积木在 LangGraph 之下、薄壳在 LangGraph 之上」,你才知道改装配时该去哪个包找原料——积木去 langchain_core,图去 langgraph,装配模板看 langchain.agents.create_agent。

最后留一句反直觉的结论:你从第 2 篇起就在用 create_agent,但直到手写复刻出它、并看到两张图完全一致,才算真正「会用」它——因为薄壳的正确用法,是随时能把它拆开、改一处、再装回去。

参考文献

[1] LangChain Agents 官方文档:https://docs.langchain.com/oss/python/langchain/agents
[2] LangGraph 官方文档:https://docs.langchain.com/oss/python/langgraph/overview


在这里插入图片描述

🎯 更多专栏系列文章可以查看博客主页📑 👍 若文章对你有所触动,恳请点赞 ⭐ 关注 ⭐ 收藏

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐