Documentation Index Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
Use this file to discover all available pages before exploring further.
智能体将语言模型与 工具 结合,创建能够推理任务、决定使用哪些工具并迭代寻求解决方案的系统。
createAgent() 提供了一个生产就绪的智能体实现。
LLM 智能体通过循环运行工具来实现目标 。
智能体会一直运行直到满足停止条件——即当模型输出最终结果或达到迭代限制时。
createAgent() 使用 LangGraph 构建基于图 的智能体运行时。图由节点(步骤)和边(连接)组成,定义了智能体如何处理信息。智能体在此图中移动,执行节点如模型节点(调用模型)、工具节点(执行工具)或中间件。了解更多关于 Graph API 。
核心组件
model 是智能体的推理引擎。它可以通过多种方式指定,支持静态和动态模型选择。
静态模型
静态模型在创建智能体时配置一次,并在整个执行过程中保持不变。这是最常见且直接的方法。
要从 模型标识符字符串 初始化静态模型:
import { createAgent } from "langchain" ;
const agent = createAgent ( {
model : "openai:gpt-5" ,
tools : []
} ) ;
模型标识符字符串使用 provider:model 格式(例如 "openai:gpt-5")。您可能希望对模型配置有更多控制,在这种情况下,您可以直接使用 provider 包初始化模型实例:
import { createAgent } from "langchain" ;
import { ChatOpenAI } from "@langchain/openai" ;
const model = new ChatOpenAI ( {
model : "gpt-4.1" ,
temperature : 0.1 ,
maxTokens : 1000 ,
timeout : 30
} ) ;
const agent = createAgent ( {
model ,
tools : []
} ) ;
模型实例让您完全控制配置。当您需要在特定参数上设置值,如 temperature、max_tokens、timeouts,或配置 API 密钥、base_url 和其他 provider 特定设置时使用它们。参考 API reference 查看您的模型上可用的参数和方法。
动态模型
动态模型根据当前的 runtime 和 state 进行选择。这启用了复杂的路由逻辑和成本优化。
要使用动态模型,请使用 wrapModelCall 创建中间件来修改请求中的模型:
import { ChatOpenAI } from "@langchain/openai" ;
import { createAgent , createMiddleware } from "langchain" ;
const basicModel = new ChatOpenAI ( { model : "gpt-4.1-mini" } ) ;
const advancedModel = new ChatOpenAI ( { model : "gpt-4.1" } ) ;
const dynamicModelSelection = createMiddleware ( {
name : "DynamicModelSelection" ,
wrapModelCall : ( request , handler ) => {
// Choose model based on conversation complexity
const messageCount = request . messages . length ;
return handler ( {
... request ,
model : messageCount > 10 ? advancedModel : basicModel ,
} ) ;
},
} ) ;
const agent = createAgent ( {
model : "gpt-4.1-mini" , // Base model (used when messageCount ≤ 10)
tools ,
middleware : [dynamicModelSelection] ,
} ) ;
有关中间件和高级模式的更多详细信息,请参阅 middleware 文档 。
工具赋予智能体采取行动的能力。智能体超越了简单的仅模型工具绑定,通过促进以下内容:
按顺序进行多次工具调用(由单个提示触发)
在适当时并行调用工具
根据先前结果动态选择工具
工具重试逻辑和错误处理
跨工具调用的状态持久化
更多信息,请参阅 Tools 。
静态工具
静态工具在创建智能体时定义,并在整个执行过程中保持不变。这是最常见且直接的方法。
要定义带有静态工具的智能体,请将工具列表传递给智能体。
import * as z from "zod" ;
import { createAgent , tool } from "langchain" ;
const search = tool (
({ query }) => `Results for: ${ query } ` ,
{
name : "search" ,
description : "Search for information" ,
schema : z . object ( {
query : z . string () . describe ( "The query to search for" ) ,
} ) ,
}
) ;
const getWeather = tool (
({ location }) => `Weather in ${ location } : Sunny, 72°F` ,
{
name : "get_weather" ,
description : "Get weather information for a location" ,
schema : z . object ( {
location : z . string () . describe ( "The location to get weather for" ) ,
} ) ,
}
) ;
const agent = createAgent ( {
model : "gpt-4.1" ,
tools : [search , getWeather] ,
} ) ;
如果提供空工具列表,智能体将仅包含一个没有工具调用能力的 LLM 节点。
动态工具
使用动态工具,智能体可用的工具集在运行时进行修改,而不是全部预先定义。并非所有工具都适用于每种情况。工具过多可能会使模型不堪重负(过载上下文)并增加错误;工具过少则限制能力。动态工具选择使得能够根据认证状态、用户权限、功能标志或对话阶段调整可用工具集。
有两种方法取决于工具是否提前已知:
当所有可能的工具在智能体创建时已知时,您可以预先注册它们,并根据状态、权限或上下文动态过滤向模型暴露的工具。 仅在达到某些对话里程碑后启用高级工具: import { createMiddleware , tool } from "langchain" ;
import { createDeepAgent } from "deepagents" ;
const stateBasedTools = createMiddleware ( {
name : "StateBasedTools" ,
wrapModelCall : ( request , handler ) => {
// Read from State: check authentication and conversation length
const state = request . state as typeof request . state & {
authenticated ?: boolean ;
};
const isAuthenticated = state . authenticated ?? false ;
const messageCount = state . messages . length ;
let filteredTools = request . tools ;
// Only enable sensitive tools after authentication
if ( ! isAuthenticated) {
filteredTools = request . tools . filter (
( t : any ) => typeof t . name === "string" && t . name . startsWith ( "public_" ) ,
) ;
} else if (messageCount < 5 ) {
filteredTools = request . tools . filter (
( t : any ) => typeof t . name === "string" && t . name !== "advanced_search" ,
) ;
}
return handler ( { ... request , tools : filteredTools } ) ;
},
} ) ;
const agent = await createDeepAgent ( {
model : "claude-sonnet-4-20250514" ,
tools : tools ,
middleware : [stateBasedTools] as any ,
} ) ;
根据 Store 中的用户偏好或功能标志过滤工具: import { createMiddleware } from "langchain" ;
import { createDeepAgent } from "deepagents" ;
import * as z from "zod" ;
import { InMemoryStore } from "@langchain/langgraph" ;
const contextSchema = z . object ( {
userId : z . string () ,
} ) ;
const storeBasedTools = createMiddleware ( {
name : "StoreBasedTools" ,
contextSchema ,
wrapModelCall : async ( request , handler ) => {
const userId =
(request . runtime ?. context as { userId ?: string } | undefined ) ?. userId ??
"user-123" ;
// Read from Store: get user's enabled features
const runtimeStore = request . runtime ?. store as InMemoryStore | undefined ;
const rawFlags = ( await runtimeStore ?. get (
[ "features" ] ,
userId as string ,
)) as unknown ;
const featureFlags = rawFlags as FeatureFlags | undefined ;
let filteredTools = request . tools ;
if (featureFlags) {
const enabledFeatures = featureFlags . enabledTools || [] ;
filteredTools = request . tools . filter ( ( t ) =>
enabledFeatures . includes (t . name as string )
) ;
}
return handler ( { ... request , tools : filteredTools } ) ;
},
} ) ;
const agent = await createDeepAgent ( {
model : "claude-sonnet-4-20250514" ,
backend : backendFactory ,
store ,
checkpointer ,
tools ,
middleware : [storeBasedTools] as any ,
} ) ;
根据运行时上下文中的用户权限过滤工具: import * as z from "zod" ;
import { createMiddleware } from "langchain" ;
import { createDeepAgent } from "deepagents" ;
const contextSchema = z . object ( {
userRole : z . string () ,
} ) ;
const contextBasedTools = createMiddleware ( {
name : "ContextBasedTools" ,
contextSchema ,
wrapModelCall : ( request , handler ) => {
// Read from Runtime Context: get user role
const userRole = request . runtime . context . userRole ;
let filteredTools = request . tools ;
if (userRole === "admin" ) {
// Admins get all tools
} else if (userRole === "editor" ) {
filteredTools = request . tools . filter ( ( t ) => t . name !== "delete_data" ) ;
} else {
filteredTools = request . tools . filter (
( t ) => (t . name as string ) . startsWith ( "read_" ) ,
) ;
}
return handler ( { ... request , tools : filteredTools } ) ;
},
} ) ;
const agent = await createDeepAgent ( {
model : "claude-sonnet-4-20250514" ,
store ,
checkpointer ,
tools ,
middleware : [contextBasedTools] as any ,
} ) ;
这种方法最适合以下情况:
所有可能的工具在编译/启动时已知
您希望根据权限、功能标志或对话状态进行过滤
工具是静态的,但其可用性是动态的
有关更多示例,请参阅 Dynamically selecting tools 。 当工具在运行时被发现或创建时(例如,从 MCP 服务器加载、根据用户数据生成或从远程注册表获取),您需要同时注册工具并动态处理其执行。 这需要两个中间件钩子:
wrap_model_call - 将动态工具添加到请求中
wrap_tool_call - 处理动态添加的工具的执行
import { createAgent , createMiddleware , tool } from "langchain" ;
import * as z from "zod" ;
// A tool that will be added dynamically at runtime
const calculateTip = tool (
({ billAmount , tipPercentage = 20 }) => {
const tip = billAmount * (tipPercentage / 100 ) ;
return `Tip: $ ${ tip . toFixed ( 2 ) } , Total: $ ${ ( billAmount + tip ) . toFixed ( 2 ) } ` ;
},
{
name : "calculate_tip" ,
description : "Calculate the tip amount for a bill" ,
schema : z . object ( {
billAmount : z . number () . describe ( "The bill amount" ) ,
tipPercentage : z . number () . default ( 20 ) . describe ( "Tip percentage" ) ,
} ) ,
}
) ;
const dynamicToolMiddleware = createMiddleware ( {
name : "DynamicToolMiddleware" ,
wrapModelCall : ( request , handler ) => {
// Add dynamic tool to the request
// This could be loaded from an MCP server, database, etc.
return handler ( {
... request ,
tools : [ ... request . tools , calculateTip] ,
} ) ;
},
wrapToolCall : ( request , handler ) => {
// Handle execution of the dynamic tool
if (request . toolCall . name === "calculate_tip" ) {
return handler ( { ... request , tool : calculateTip } ) ;
}
return handler (request) ;
},
} ) ;
const agent = createAgent ( {
model : "gpt-4o" ,
tools : [getWeather] , // Only static tools registered here
middleware : [dynamicToolMiddleware] ,
} ) ;
// The agent can now use both getWeather AND calculateTip
const result = await agent . invoke ( {
messages : [ { role : "user" , content : "Calculate a 20% tip on $85" } ] ,
} ) ;
这种方法最适合以下情况:
工具在运行时被发现(例如,来自 MCP 服务器)
工具根据用户数据或配置动态生成
您正在集成外部工具注册表
wrap_tool_call 钩子是必需的,用于运行时注册的工具,因为智能体需要知道如何执行原始工具列表中不存在的工具。如果没有它,智能体将不知道如何调用动态添加的工具。
工具错误处理
要自定义工具错误的处理方式,请在自定义中间件中使用 wrapToolCall 钩子:
import { createAgent , createMiddleware , ToolMessage } from "langchain" ;
const handleToolErrors = createMiddleware ( {
name : "HandleToolErrors" ,
wrapToolCall : async ( request , handler ) => {
try {
return await handler (request) ;
} catch (error) {
// Return a custom error message to the model
return new ToolMessage ( {
content : `Tool error: Please check your input and try again. ( ${ error } )` ,
tool_call_id : request . toolCall . id ! ,
} ) ;
}
},
} ) ;
const agent = createAgent ( {
model : "gpt-4.1" ,
tools : [
/* ... */
] ,
middleware : [handleToolErrors] ,
} ) ;
当工具失败时,智能体将返回带有自定义错误消息的 ToolMessage 。
ReAct 循环中的工具使用
智能体遵循 ReAct(“推理 + 行动”)模式,在简短的推理步骤(带有针对性的工具调用)和将 resulting observations 反馈到后续决策之间交替,直到能够提供最终答案。
提示: 识别当前最流行的无线耳机并验证库存。================================ Human Message =================================
Find the most popular wireless headphones right now and check if they're in stock
推理 :“流行度是时间敏感的,我需要使用提供的搜索工具。”
行动 :调用 search_products("wireless headphones")
================================== Ai Message ==================================
Tool Calls:
search_products (call_abc123)
Call ID: call_abc123
Args:
query: wireless headphones
================================= Tool Message =================================
Found 5 products matching "wireless headphones". Top 5 results: WH-1000XM5, ...
推理 :“在回答之前,我需要确认排名最高项目的库存情况。”
行动 :调用 check_inventory("WH-1000XM5")
================================== Ai Message ==================================
Tool Calls:
check_inventory (call_def456)
Call ID: call_def456
Args:
product_id: WH-1000XM5
================================= Tool Message =================================
Product WH-1000XM5: 10 units in stock
推理 :“我已经有了最流行的型号及其库存状态。我现在可以回答用户的问题了。”
行动 :生成最终答案
================================== Ai Message ==================================
I found wireless headphones (model WH-1000XM5) with 10 units in stock...
系统提示词
您可以通过提供提示词来塑造智能体处理任务的方式。systemPrompt 参数可以作为字符串提供:
const agent = createAgent ( {
model ,
tools ,
systemPrompt : "You are a helpful assistant. Be concise and accurate." ,
} ) ;
当未提供 systemPrompt 时,智能体将直接从消息中推断其任务。
systemPrompt 参数接受 string 或 SystemMessage。使用 SystemMessage 可以让您对提示词结构有更多的控制,这对于 provider 特定功能如 Anthropic 的提示词缓存 很有用:
import { createAgent } from "langchain" ;
import { SystemMessage , HumanMessage } from "@langchain/core/messages" ;
const literaryAgent = createAgent ( {
model : "anthropic:claude-sonnet-4-5" ,
systemPrompt : new SystemMessage ( {
content : [
{
type : "text" ,
text : "You are an AI assistant tasked with analyzing literary works." ,
},
{
type : "text" ,
text : "<the entire contents of 'Pride and Prejudice'>" ,
cache_control : { type : "ephemeral" }
}
]
} )
} ) ;
const result = await literaryAgent . invoke ( {
messages : [ new HumanMessage ( "Analyze the major themes in 'Pride and Prejudice'." )]
} ) ;
具有 { type: "ephemeral" } 的 cache_control 字段告诉 Anthropic 缓存该内容块,减少重复请求的延迟和成本,这些请求使用相同的系统提示词。
动态系统提示词
对于需要根据运行时上下文或智能体状态修改系统提示词的更高级用例,您可以使用 middleware 。
import * as z from "zod" ;
import { createAgent , dynamicSystemPromptMiddleware } from "langchain" ;
const contextSchema = z . object ( {
userRole : z . enum ([ "expert" , "beginner" ]) ,
} ) ;
const agent = createAgent ( {
model : "gpt-4.1" ,
tools : [ /* ... */ ] ,
contextSchema ,
middleware : [
dynamicSystemPromptMiddleware < z . infer < typeof contextSchema >> ( ( state , runtime ) => {
const userRole = runtime . context . userRole || "user" ;
const basePrompt = "You are a helpful assistant." ;
if (userRole === "expert" ) {
return ` ${ basePrompt } Provide detailed technical responses.` ;
} else if (userRole === "beginner" ) {
return ` ${ basePrompt } Explain concepts simply and avoid jargon.` ;
}
return basePrompt ;
} ) ,
] ,
} ) ;
// The system prompt will be set dynamically based on context
const result = await agent . invoke (
{ messages : [ { role : "user" , content : "Explain machine learning" } ] },
{ context : { userRole : "expert" } }
) ;
为智能体设置可选的 name。这是在 多智能体系统 中将智能体作为子图添加时用作节点标识符:
const agent = createAgent ( {
model ,
tools ,
name : "research_assistant" ,
} ) ;
优先使用 snake_case 作为智能体名称(例如 research_assistant 而不是 Research Assistant)。某些模型提供商会拒绝包含空格或特殊字符的名称并报错。仅使用字母数字字符、下划线和连字符可确保在所有提供商之间的兼容性。这也适用于 工具名称 。
您可以通过传递更新到其 State 来调用智能体。所有智能体在其状态中都包含 消息序列 ;要调用智能体,请传递新消息:
await agent . invoke ( {
messages : [ { role : "user" , content : "What's the weather in San Francisco?" } ] ,
} )
有关从智能体流式传输步骤和/或令牌,请参阅 streaming 指南。
否则,智能体遵循 LangGraph Graph API 并支持所有相关方法,如 stream 和 invoke。
高级概念
结构化输出
在某些情况下,您可能希望智能体以特定格式返回输出。LangChain 提供了一种简单通用的方法来做到这一点,使用 responseFormat 参数。
import * as z from "zod" ;
import { createAgent } from "langchain" ;
const ContactInfo = z . object ( {
name : z . string () ,
email : z . string () ,
phone : z . string () ,
} ) ;
const agent = createAgent ( {
model : "gpt-4.1" ,
responseFormat : ContactInfo ,
} ) ;
const result = await agent . invoke ( {
messages : [
{
role : "user" ,
content : "Extract contact info from: John Doe, john@example.com, (555) 123-4567" ,
},
] ,
} ) ;
console . log (result . structuredResponse) ;
// {
// name: 'John Doe',
// email: 'john@example.com',
// phone: '(555) 123-4567'
// }
智能体通过消息状态自动维护对话历史。您还可以配置智能体使用自定义状态架构在对话期间记住额外信息。
存储在状态中的信息可以被视为智能体的 短期记忆 :
import { z } from "zod/v4" ;
import { StateSchema , MessagesValue } from "@langchain/langgraph" ;
import { createAgent } from "langchain" ;
const CustomAgentState = new StateSchema ( {
messages : MessagesValue ,
userPreferences : z . record (z . string () , z . string ()) ,
} ) ;
const customAgent = createAgent ( {
model : "gpt-4.1" ,
tools : [] ,
stateSchema : CustomAgentState ,
} ) ;
流式传输
我们已经看到如何使用 invoke 调用智能体以获得最终响应。如果智能体执行多个步骤,这可能需要一段时间。为了显示中间进度,我们可以流式传输发生的消息。
const stream = await agent . stream (
{
messages : [ {
role : "user" ,
content : "Search for AI news and summarize the findings"
} ] ,
},
{ streamMode : "values" }
) ;
for await ( const chunk of stream) {
// Each chunk contains the full state at that point
const latestMessage = chunk . messages . at ( - 1 ) ;
if (latestMessage ?. content) {
console . log ( `Agent: ${ latestMessage . content } ` ) ;
} else if (latestMessage ?. tool_calls) {
const toolCallNames = latestMessage . tool_calls . map ( ( tc ) => tc . name) ;
console . log ( `Calling tools: ${ toolCallNames . join ( ", " ) } ` ) ;
}
}
中间件
Middleware 为在不同执行阶段自定义智能体行为提供了强大的可扩展性。您可以使用中间件来:
在调用模型之前处理状态(例如,消息修剪、上下文注入)
修改或验证模型的响应(例如,护栏、内容过滤)
使用自定义逻辑处理工具执行错误
根据状态或上下文实现动态模型选择
添加自定义日志记录、监控或分析
中间件无缝集成到智能体的执行中,允许您在关键点拦截和修改数据流,而无需更改核心智能体逻辑。
有关全面的中间件文档,包括 beforeModel、afterModel 和 wrapToolCall 等钩子,请参阅 Middleware 。