1. 前言前面几章我们讲了 Tools、Tool Calling、Agent Loop。现在进入新版 LangChain Agent 的入口create_agent。它是新式 Agent 的总装厂。你把 model、tools、system_prompt、middleware 交给它它返回的不是普通对象而是一张 CompiledStateGraph。这意味着两件事第一Agent 的运行过程本质上是图执行第二模型调用、工具调用、状态更新、中间件拦截全部被放进图里统一调度。2. 先看参数不要背按职责分组create_agent 的参数看起来多其实只有四类核心组件、状态记忆、人工控制、工程治理。3. 最小代码三行搭起一个 Agent最小形态只需要模型和工具。system_prompt 用来定规则。其他能力后面再加。from langchain.agents import create_agentagent create_agent(modelopenai:gpt-5.5,tools[search_tool, query_order_tool],system_prompt你是一个企业助手回答必须简洁、准确、可追溯。,)result agent.invoke({messages: [{role: user, content: 帮我查一下订单 123456}]})这段代码表面很短。源码里面做了很多事初始化模型、转换工具、构造状态、创建节点、连边、编译图。4. 源码主线create_agent 先装配再编译源码不要一行一行死扣。先抓主线。它不是运行 Agent而是先生成一张 Agent Graph。5. 源码第一步处理 model 和 system_prompt源码先判断 model 是字符串还是模型实例。字符串会走 init_chat_model。实例直接用。接着处理 system_prompt。字符串会被转成 SystemMessage。调用模型时它会被放到 messages 前面。# 伪代码对应 factory.py 的初始化思路if isinstance(model, str):model init_chat_model(model)if system_prompt is not None:system_message SystemMessage(contentsystem_prompt)else:system_message None系统提示词不是普通文本。它进入源码后会变成 SystemMessage作为模型调用的最高优先级上下文。6. 源码第二步处理 response_formatresponse_format 负责结构化输出。你可以传 Pydantic、TypedDict、JSON Schema也可以显式传 ToolStrategy 或 ProviderStrategy。源码的核心动作是如果你直接传 Schema先包成 AutoStrategy。后面再根据模型能力决定走 ProviderStrategy 还是 ToolStrategy。# 伪代码结构化输出的核心逻辑if response_format is None:initial_response_format Noneelif isinstance(response_format, (ToolStrategy, ProviderStrategy, AutoStrategy)):initial_response_format response_formatelse:initial_response_format AutoStrategy(schemaresponse_format)ProviderStrategy 更像“模型服务商原生保证”。ToolStrategy 更像“通过工具调用让模型返回结构化结果”。7. 源码第三步收集工具创建 ToolNodetools 不是直接塞给模型就完事。源码会拆分工具类型。普通工具和中间件注册的工具通常需要本地执行会进入 ToolNode。dict 格式的 provider 内置工具可能由模型提供商处理。结构化输出工具会根据 response_format 动态加入。# 伪代码工具装配思路middleware_tools [tool for m in middleware for tool in m.tools]regular_tools [t for t in tools if not isinstance(t, dict)]built_in_tools [t for t in tools if isinstance(t, dict)]available_tools middleware_tools regular_toolstool_node ToolNode(toolsavailable_tools) if available_tools else NoneToolNode 是工具执行中心。模型只负责“要不要调工具、调哪个工具、传什么参数”。真正执行工具的是 ToolNode。8. 源码第四步收集中间件 Hookmiddleware 是 create_agent 变强的地方。源码会检查每个中间件是否重写了 before_agent、before_model、after_model、after_agent、wrap_model_call、wrap_tool_call。before/after 类型会变成图节点。wrap 类型会变成调用链包住模型调用或工具调用。# 伪代码中间件收集思路middleware_w_before_model [m for m in middleware if m.before_model 被重写]middleware_w_after_model [m for m in middleware if m.after_model 被重写]middleware_w_wrap_model [m for m in middleware if m.wrap_model_call 被重写]middleware_w_wrap_tool [m for m in middleware if m.wrap_tool_call 被重写]wrap_model_call_handler chain(wrap_model_call_hooks)wrap_tool_call_wrapper chain(wrap_tool_call_hooks)9. 源码第五步创建 StateGraphAgent 运行时必须有状态。最核心的状态就是 messages。源码会把 AgentState、middleware 的 state_schema、你传入的 state_schema 合并得到最终的状态结构。然后用这个状态结构创建 StateGraph。# 伪代码状态图创建思路base_state state_schema if state_schema is not None else AgentStatestate_schemas [middleware.state_schema..., base_state]resolved_state_schema, input_schema, output_schema resolve_schemas(state_schemas)graph StateGraph(state_schemaresolved_state_schema,input_schemainput_schema,output_schemaoutput_schema,context_schemacontext_schema,)这里的 context_schema 不是聊天历史。它是运行时上下文比如 user_id、tenant_id、feature_flag、权限信息。10. 源码第六步定义 model_nodemodel_node 是 Agent Loop 的心脏。每次循环都会走这里。它做五件事构造 ModelRequest绑定工具拼 system_message调用模型处理模型输出。# 伪代码model_node 的核心流程request ModelRequest(modelmodel,toolsdefault_tools,system_messagesystem_message,response_formatinitial_response_format,messagesstate[messages],runtimeruntime,)bound_model, effective_response_format get_bound_model(request)output bound_model.invoke([system_message, *messages])handled handle_model_output(output, effective_response_format)return Command(update{messages: handled[messages]})model_node 不只是调用模型。它还决定工具如何绑定、结构化输出如何解析、结果如何写回状态。11. 源码第七步加节点、连边、编译图节点有 model、tools以及中间件节点。边决定流程怎么走。最关键的条件边是如果 AIMessage 有 tool_calls就去 tools如果没有就结束。tools 执行完会把 ToolMessage 放回 messages再回到 model。# 伪代码图结构主线graph.add_node(model, model_node)if tool_node:graph.add_node(tools, tool_node)graph.add_edge(START, entry_node)graph.add_conditional_edges(model, model_to_tools_or_end)graph.add_conditional_edges(tools, tools_to_model_or_end)return graph.compile(checkpointercheckpointer,storestore,interrupt_beforeinterrupt_before,interrupt_afterinterrupt_after,debugdebug,)12. invoke、stream、thread_id运行时怎么用create_agent 返回的是可执行图。你可以 invoke 拿最终结果也可以 stream 看中间过程。多轮对话要配 checkpointer并在 config 里传 thread_id。thread_id 决定这轮会话的状态保存在哪里。from langgraph.checkpoint.memory import InMemorySaverfrom langchain.agents import create_agentagent create_agent(modelopenai:gpt-5.5,tools[query_order],checkpointerInMemorySaver(),)config {configurable: {thread_id: user-1001-session-01}}agent.invoke({messages: [{role: user, content: 我的订单到哪了}]},configconfig,)# 同一个 thread_id下一轮可以接上上一轮状态agent.invoke({messages: [{role: user, content: 那能改地址吗}]},configconfig,)13. 把源码压缩成一条线源码很长但主线可以压缩成下面这条线。14. 企业落地封装 AgentFactory不要散落 create_agent真实项目里不建议在每个业务接口里直接 create_agent。这样模型、工具、Prompt、权限、日志都会散。更好的方式是做一个 AgentFactory。业务方只传场景和上下文。AgentFactory 统一选择模型、加载工具、注入中间件、配置 checkpointer 和 trace。15. 总结• create_agent 是新版 LangChain Agent 的核心入口。• 它返回的是 CompiledStateGraph不是普通 Python 对象。• model、tools、system_prompt、middleware、response_format 都会在源码里被装配进图。• Agent Loop 的关键判断很简单有 tool_calls 就去工具没有 tool_calls 就结束。• 中间件是企业级能力的插槽日志、鉴权、重试、脱敏、人工确认都应该放进去。• 生产项目要封装 AgentFactory统一管理模型、工具、Prompt、状态、观测和安全策略。最后记住一句create_agent 不是让模型变聪明而是把模型变成一个可执行、可拦截、可持久化、可观测的 Agent Graph。内容来源create_agentLangChain 新版 Agent 的核心入口功能变化与行业影响解析_热闻岛