文档索引 在以下地址获取完整的文档索引:https://docs.langchain.org.cn/llms.txt
在进一步探索之前,请使用此文件发现所有可用页面。
LangChain 和 Deep Agents 为常见用例提供预置中间件。每个中间件都是生产就绪的,并且可以根据您的特定需求进行配置。
与供应商无关的中间件
以下中间件可与任何 LLM 提供商配合使用
中间件 描述 总结 当接近 token 限制时,自动总结对话历史。 人工干预 暂停执行,等待人工批准工具调用。 模型调用限制 限制模型调用次数,以防止产生过高费用。 工具调用限制 通过限制调用次数来控制工具的执行。 模型回退 (Fallback) 当主模型失败时,自动回退到备选模型。 PII 检测 检测并处理个人身份信息 (PII)。 待办事项列表 为智能体配备任务规划和跟踪功能。 LLM 工具选择器 在调用主模型之前,使用 LLM 选择相关的工具。 工具重试 使用指数退避算法自动重试失败的工具调用。 模型重试 使用指数退避算法自动重试失败的模型调用。 LLM 工具模拟器 出于测试目的,使用 LLM 模拟工具执行。 上下文编辑 通过修剪或清除工具使用记录来管理对话上下文。 文件系统 为智能体提供用于存储上下文和长期记忆的文件系统。 子智能体 (Subagent) 中间件 增加创建子智能体的能力。
当接近 token 限制时自动总结对话历史,在压缩旧上下文的同时保留最近的消息。总结功能适用于以下场景:
超出上下文窗口的长期对话。
包含大量历史记录的多轮对话。
需要保留完整对话脉络的应用场景。
import { createAgent , summarizationMiddleware } from "langchain" ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [weatherTool , calculatorTool] ,
middleware : [
summarizationMiddleware ( {
model : "gpt-5.4-mini" ,
trigger : { tokens : 4000 },
keep : { messages : 20 },
} ) ,
] ,
} ) ;
如果使用 langchain@1.1.0,用于 trigger 和 keep 的 fraction 条件(如下所示)依赖于聊天模型的配置文件数据 。如果数据不可用,请使用其他条件或手动指定。 const customProfile : ModelProfile = {
maxInputTokens : 100_000 ,
// ...
}
model = await initChatModel ( "..." , {
profile : customProfile ,
} ) ;
用于生成摘要的模型。可以是模型标识符字符串(例如 'openai:gpt-5.4-mini')或 BaseChatModel 实例。
触发总结的条件。可以是:
单个条件对象(必须满足所有属性 - 逻辑“与”)
条件对象数组(满足任一条件即可 - 逻辑“或”)
每个条件可以包括:
fraction (number): 模型上下文大小的比例 (0-1)
tokens (number): 绝对 token 数量
messages (number): 消息数量
每个条件必须至少指定一个属性。如果未提供,则不会自动触发总结。 总结后要保留多少上下文。请指定以下其中之一:
fraction (number): 要保留的模型上下文大小比例 (0-1)
tokens (number): 要保留的绝对 token 数量
messages (number): 要保留的最近消息数量
自定义 token 计数函数。默认为基于字符的计数。
自定义总结提示模板。如果未指定,则使用内置模板。模板应包含 {messages} 占位符,对话历史将插入该位置。
生成摘要时包含的最大 token 数量。消息在总结前将被修剪以符合此限制。
要添加到摘要消息的前缀。如果未提供,则使用默认前缀。
已弃用: 请改用 trigger: { tokens: value }。触发总结的 token 阈值。
已弃用: 请改用 keep: { messages: value }。要保留的最近消息数。
总结中间件会监控消息的 token 计数,并在达到阈值时自动总结旧消息。 触发条件 (Trigger conditions) 控制总结何时运行:
单个条件对象(必须满足指定项)
条件数组(满足任一条件即可 - 逻辑“或”)
每个条件可以使用 fraction(模型上下文大小的比例)、tokens(绝对计数)或 messages(消息计数)
保留条件 (Keep condition) 控制要保留多少上下文(仅指定一个)
fraction - 要保留的模型上下文大小比例
tokens - 要保留的绝对 token 数量
messages - 要保留的最近消息数量
import { createAgent , summarizationMiddleware } from "langchain" ;
// Single condition
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [weatherTool , calculatorTool] ,
middleware : [
summarizationMiddleware ( {
model : "gpt-5.4-mini" ,
trigger : { tokens : 4000 , messages : 10 },
keep : { messages : 20 },
} ) ,
] ,
} ) ;
// Multiple conditions
const agent2 = createAgent ( {
model : "gpt-5.4" ,
tools : [weatherTool , calculatorTool] ,
middleware : [
summarizationMiddleware ( {
model : "gpt-5.4-mini" ,
trigger : [
{ tokens : 3000 , messages : 6 },
] ,
keep : { messages : 20 },
} ) ,
] ,
} ) ;
// Using fractional limits
const agent3 = createAgent ( {
model : "gpt-5.4" ,
tools : [weatherTool , calculatorTool] ,
middleware : [
summarizationMiddleware ( {
model : "gpt-5.4-mini" ,
trigger : { fraction : 0.8 },
keep : { fraction : 0.3 },
} ) ,
] ,
} ) ;
人工干预
在工具执行前暂停智能体执行,以便人工批准、编辑或拒绝工具调用。人机回环 (Human-in-the-loop) 适用于以下场景:
需要人工批准的高风险操作(例如数据库写入、金融交易)。
必须进行人工监督的合规性工作流。
通过人工反馈引导智能体的长期对话。
import { createAgent , humanInTheLoopMiddleware } from "langchain" ;
function readEmailTool ( emailId : string ) : string {
/** Mock function to read an email by its ID. */
return `Email content for ID: ${ emailId } ` ;
}
function sendEmailTool ( recipient : string , subject : string , body : string ) : string {
/** Mock function to send an email. */
return `Email sent to ${ recipient } with subject ' ${ subject } '` ;
}
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [readEmailTool , sendEmailTool] ,
middleware : [
humanInTheLoopMiddleware ( {
interruptOn : {
sendEmailTool : {
allowedDecisions : [ "approve" , "edit" , "reject" ] ,
},
readEmailTool : false ,
}
} )
]
} ) ;
模型调用限制
限制模型调用次数,以防止无限循环或费用过高。模型调用限制适用于以下场景:
防止失控的智能体进行过多的 API 调用。
在生产部署中实施成本控制。
在特定的调用预算内测试智能体行为。
import { createAgent , modelCallLimitMiddleware } from "langchain" ;
import { MemorySaver } from "@langchain/langgraph" ;
const agent = createAgent ( {
model : "gpt-5.4" ,
checkpointer : new MemorySaver () , // Required for thread limiting
tools : [] ,
middleware : [
modelCallLimitMiddleware ( {
threadLimit : 10 ,
runLimit : 5 ,
exitBehavior : "end" ,
} ) ,
] ,
} ) ;
达到限制时的行为。选项:'end'(正常终止)或 'error'(抛出异常)
通过限制工具调用次数(全局所有工具或特定工具)来控制智能体的执行。工具调用限制适用于以下场景:
防止对昂贵的外部 API 进行过度调用。
限制网页搜索或数据库查询。
对特定工具的使用实施速率限制。
防止智能体陷入失控循环。
import { createAgent , toolCallLimitMiddleware } from "langchain" ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [searchTool , databaseTool] ,
middleware : [
toolCallLimitMiddleware ( { threadLimit : 20 , runLimit : 10 } ) ,
toolCallLimitMiddleware ( {
toolName : "search" ,
threadLimit : 5 ,
runLimit : 3 ,
} ) ,
] ,
} ) ;
要限制的特定工具名称。如果未提供,限制将应用于全局所有工具 。
一个线程(对话)中所有运行的最大工具调用次数。在具有相同线程 ID 的多次调用中保持持久。需要检查点记录器来维持状态。undefined 表示没有线程限制。
单次调用(一次用户消息 → 响应周期)的最大工具调用次数。每次新用户消息都会重置。undefined 表示没有单次运行限制。 注意: 必须指定 threadLimit 或 runLimit 中的至少一个。
达到限制时的行为
'continue'(默认)- 使用错误消息阻止超出的工具调用,允许其他工具和模型继续运行。模型将根据错误消息决定何时结束。
'error' - 抛出 ToolCallLimitExceededError 异常,立即停止执行
'end' - 立即停止执行,并为超出的工具调用返回一个 ToolMessage 和 AI 消息。仅在限制单个工具时有效;如果其他工具有待处理的调用,则抛出错误。
指定限制方式:
线程限制 (Thread limit) - 一次对话中所有运行的最大调用次数(需要检查点记录器)
运行限制 (Run limit) - 单次调用的最大调用次数(每轮重置)
退出行为
'continue'(默认)- 阻止超出的调用并提示错误消息,智能体继续运行
'error' - 立即引发异常
'end' - 以 ToolMessage + AI 消息停止(仅限单工具场景)
import { createAgent , toolCallLimitMiddleware } from "langchain" ;
const globalLimiter = toolCallLimitMiddleware ( { threadLimit : 20 , runLimit : 10 } ) ;
const searchLimiter = toolCallLimitMiddleware ( { toolName : "search" , threadLimit : 5 , runLimit : 3 } ) ;
const databaseLimiter = toolCallLimitMiddleware ( { toolName : "query_database" , threadLimit : 10 } ) ;
const strictLimiter = toolCallLimitMiddleware ( { toolName : "scrape_webpage" , runLimit : 2 , exitBehavior : "error" } ) ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [searchTool , databaseTool , scraperTool] ,
middleware : [globalLimiter , searchLimiter , databaseLimiter , strictLimiter] ,
} ) ;
模型回退 (Fallback)
当主模型失败时,自动回退到备选模型。模型回退适用于以下场景:
构建能够处理模型故障的有韧性的智能体。
通过回退到更便宜的模型来进行成本优化。
实现 OpenAI、Anthropic 等供应商之间的冗余。
import { createAgent , modelFallbackMiddleware } from "langchain" ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [] ,
middleware : [
modelFallbackMiddleware (
"gpt-5.4-mini" ,
"claude-3-5-sonnet-20241022"
) ,
] ,
} ) ;
该中间件接受可变数量的字符串参数,按顺序表示回退模型 当主模型失败时,按顺序尝试的一个或多个回退模型字符串 modelFallbackMiddleware (
"first-fallback-model" ,
"second-fallback-model" ,
// ... more models
)
PII 检测
使用可配置策略检测并处理对话中的个人身份信息 (PII)。PII 检测适用于以下场景:
具有合规性要求的医疗保健和金融应用。
需要对日志进行脱敏处理的客户服务智能体。
任何处理敏感用户数据的应用。
import { createAgent , piiMiddleware } from "langchain" ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [] ,
middleware : [
piiMiddleware ( "email" , { strategy : "redact" , applyToInput : true } ) ,
piiMiddleware ( "credit_card" , { strategy : "mask" , applyToInput : true } ) ,
] ,
} ) ;
自定义 PII 类型
您可以通过提供 detector 参数来创建自定义 PII 类型。这允许您检测内置类型以外的特定于您的用例的模式。 创建自定义检测器的三种方式:
正则模式字符串 - 简单的模式匹配
RegExp 对象 - 更多对正则标志的控制
自定义函数 - 带有验证逻辑的复杂检测逻辑
import { createAgent , piiMiddleware , type PIIMatch } from "langchain" ;
// Method 1: Regex pattern string
const agent1 = createAgent ( {
model : "gpt-5.4" ,
tools : [] ,
middleware : [
piiMiddleware ( "api_key" , {
detector : "sk-[a-zA-Z0-9]{32}" ,
strategy : "block" ,
} ) ,
] ,
} ) ;
// Method 2: RegExp object
const agent2 = createAgent ( {
model : "gpt-5.4" ,
tools : [] ,
middleware : [
piiMiddleware ( "phone_number" , {
detector : /\+ ? \d {1,3} [ \s. - ] ? \d {3,4} [ \s. - ] ? \d {4} / ,
strategy : "mask" ,
} ) ,
] ,
} ) ;
// Method 3: Custom detector function
function detectSSN ( content : string ) : PIIMatch[] {
const matches : PIIMatch[] = [] ;
const pattern = /\d {3} - \d {2} - \d {4} / g ;
let match : RegExpExecArray | null ;
while ((match = pattern . exec (content)) !== null ) {
const ssn = match[ 0 ] ;
// Validate: first 3 digits shouldn't be 000, 666, or 900-999
const firstThree = parseInt (ssn . substring ( 0 , 3 ) , 10 ) ;
if (firstThree !== 0 && firstThree !== 666 && ! (firstThree >= 900 && firstThree <= 999 )) {
matches . push ( {
text : ssn ,
start : match . index ?? 0 ,
end : (match . index ?? 0 ) + ssn . length ,
} ) ;
}
}
return matches ;
}
const agent3 = createAgent ( {
model : "gpt-5.4" ,
tools : [] ,
middleware : [
piiMiddleware ( "ssn" , {
detector : detectSSN ,
strategy : "hash" ,
} ) ,
] ,
} ) ;
自定义检测器函数签名: 检测器函数必须接受一个字符串(内容)并返回匹配结果: 返回一个 PIIMatch 对象数组: interface PIIMatch {
text : string ; // The matched text
start : number ; // Start index in content
end : number ; // End index in content
}
function detector ( content : string ) : PIIMatch[] {
return [
{ text : "matched_text" , start : 0 , end : 12 },
// ... more matches
] ;
}
对于自定义检测器:
对于简单模式,使用正则字符串
需要标志(例如不区分大小写的匹配)时,使用 RegExp 对象
当您需要模式匹配之外的验证逻辑时,使用自定义函数
自定义函数让您完全控制检测逻辑,并可以实现复杂的验证规则
要检测的 PII 类型。可以是内置类型(email, credit_card, ip, mac_address, url)或自定义类型名称。
如何处理检测到的 PII。选项:
'block' - 检测到时抛出错误
'redact' - 替换为 [REDACTED_TYPE] (脱敏)
'mask' - 部分遮掩(例如:****-****-****-1234)
'hash' - 替换为确定性哈希(例如:<email_hash:a1b2c3d4>)
detector
RegExp | string | function
自定义检测器。可以是:
RegExp - 用于匹配的正则对象
string - 正则模式字符串(例如:"sk-[a-zA-Z0-9]{32}")
function - 自定义检测器函数 (content: string) => PIIMatch[]
如果未提供,则使用该 PII 类型的内置检测器。
待办事项列表
为智能体配备任务规划和跟踪功能,以处理复杂的多步骤任务。待办事项列表适用于以下场景:
需要跨多个工具协作的复杂多步骤任务。
进度可见性很重要的长期运行操作。
该中间件会自动为智能体提供 write_todos 工具和系统提示,以引导有效的任务规划。
import { createAgent , todoListMiddleware } from "langchain" ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [readFile , writeFile , runTests] ,
middleware : [ todoListMiddleware ()] ,
} ) ;
没有可用的配置选项(使用默认值)。
在调用主模型之前,使用 LLM 智能地选择相关的工具。LLM 工具选择器适用于以下场景:
拥有大量工具(10+)且大多数工具与单个查询无关的智能体。
通过过滤无关工具来减少 token 使用量。
提高模型的专注度和准确性。
该中间件使用结构化输出询问 LLM 哪些工具与当前查询最相关。结构化输出模式定义了可用的工具名称和描述。模型提供商通常会在后台将此结构化输出信息添加到系统提示中。
import { createAgent , llmToolSelectorMiddleware } from "langchain" ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [tool1 , tool2 , tool3 , tool4 , tool5 , ... ] ,
middleware : [
llmToolSelectorMiddleware ( {
model : "gpt-5.4-mini" ,
maxTools : 3 ,
alwaysInclude : [ "search" ] ,
} ) ,
] ,
} ) ;
用于工具选择的模型。可以是模型标识符字符串(例如 'openai:gpt-5.4-mini')或 BaseChatModel 实例。如果未指定,默认为智能体的主模型。
要选择的最大工具数量。如果模型选择了更多,则仅使用前 maxTools 个。如果未指定则无限制。
无论选择结果如何,始终包含的工具名称。这些不计入 maxTools 限制。
使用可配置的指数退避算法自动重试失败的工具调用。工具重试适用于以下场景:
处理外部 API 调用中的瞬时故障。
提高依赖网络的工具的可靠性。
构建能够优雅处理临时错误的具有韧性的智能体。
API 参考: toolRetryMiddleware
import { createAgent , toolRetryMiddleware } from "langchain" ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [searchTool , databaseTool] ,
middleware : [
toolRetryMiddleware ( {
maxRetries : 3 ,
backoffFactor : 2.0 ,
initialDelayMs : 1000 ,
} ) ,
] ,
} ) ;
初始调用后的最大重试次数(默认总共 3 次尝试)。必须 >= 0。
tools
(ClientTool | ServerTool | string)[]
应用重试逻辑的可选工具或工具名称数组。可以是 BaseTool 实例列表或工具名称字符串。如果为 undefined,则应用于所有工具。
retryOn
((error: Error) => boolean) | (new (...args: any[]) => Error)[]
默认值: "() => true"
可以是需要重试的错误构造函数数组,也可以是一个接收错误并返回 true(表示应重试)的函数。默认为重试所有错误。
onFailure
'error' | 'continue' | ((error: Error) => string)
默认值: "continue"
所有重试次数用尽后的行为。选项:
'continue'(默认)- 返回包含错误详情的 ToolMessage,允许 LLM 处理失败并可能恢复
'error' - 重新引发异常,停止智能体执行
自定义函数 - 接收异常并返回用于 ToolMessage 内容的字符串,允许自定义错误格式
已弃用的值: 'raise'(请改用 'error')和 'return_message'(请改用 'continue')。这些已弃用的值仍然有效,但会显示警告。指数退避乘数。每次重试等待 initialDelayMs * (backoffFactor ** retryNumber) 毫秒。设置为 0.0 则为恒定延迟。必须 >= 0。
重试之间的最大延迟(毫秒)(限制指数退避的增长)。必须 >= 0。
是否为延迟添加随机抖动 (±25%),以避免惊群效应
中间件使用指数退避算法自动重试失败的工具调用。 关键配置:
maxRetries - 重试次数(默认:2)
backoffFactor - 指数退避乘数(默认:2.0)
initialDelayMs - 起始延迟毫秒数(默认:1000ms)
maxDelayMs - 延迟增长上限(默认:60000ms)
jitter - 添加随机波动(默认:true)
失败处理
onFailure: "continue"(默认)- 返回错误消息
onFailure: "error" - 重新引发异常
自定义函数 - 返回错误消息的函数
import { createAgent , toolRetryMiddleware } from "langchain" ;
import { tool } from "@langchain/core/tools" ;
import { z } from "zod" ;
// Basic usage with default settings (2 retries, exponential backoff)
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [searchTool , databaseTool] ,
middleware : [ toolRetryMiddleware ()] ,
} ) ;
// Retry specific exceptions only
const retry = toolRetryMiddleware ( {
maxRetries : 4 ,
retryOn : [TimeoutError , NetworkError] ,
backoffFactor : 1.5 ,
} ) ;
// Custom exception filtering
function shouldRetry ( error : Error ) : boolean {
// Only retry on 5xx errors
if (error . name === "HTTPError" && "statusCode" in error) {
const statusCode = (error as any ) . statusCode ;
return 500 <= statusCode && statusCode < 600 ;
}
return false ;
}
const retryWithFilter = toolRetryMiddleware ( {
maxRetries : 3 ,
retryOn : shouldRetry ,
} ) ;
// Apply to specific tools with custom error handling
const formatError = ( error : Error ) =>
"Database temporarily unavailable. Please try again later." ;
const retrySpecificTools = toolRetryMiddleware ( {
maxRetries : 4 ,
tools : [ "search_database" ] ,
onFailure : formatError ,
} ) ;
// Apply to specific tools using BaseTool instances
const searchDatabase = tool (
async ({ query }) => {
// Search implementation
return results ;
},
{
name : "search_database" ,
description : "Search the database" ,
schema : z . object ( { query : z . string () } ) ,
}
) ;
const retryWithToolInstance = toolRetryMiddleware ( {
maxRetries : 4 ,
tools : [searchDatabase] , // Pass BaseTool instance
} ) ;
// Constant backoff (no exponential growth)
const constantBackoff = toolRetryMiddleware ( {
maxRetries : 5 ,
backoffFactor : 0.0 , // No exponential growth
initialDelayMs : 2000 , // Always wait 2 seconds
} ) ;
// Raise exception on failure
const strictRetry = toolRetryMiddleware ( {
maxRetries : 2 ,
onFailure : "error" , // Re-raise exception instead of returning message
} ) ;
模型重试
使用可配置的指数退避算法自动重试失败的模型调用。模型重试适用于以下场景:
处理模型 API 调用中的瞬时故障。
提高依赖网络的模型请求的可靠性。
构建能够优雅处理临时模型错误的具有韧性的智能体。
API 参考: modelRetryMiddleware
import { createAgent , modelRetryMiddleware } from "langchain" ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [searchTool , databaseTool] ,
middleware : [
modelRetryMiddleware ( {
maxRetries : 3 ,
backoffFactor : 2.0 ,
initialDelayMs : 1000 ,
} ) ,
] ,
} ) ;
初始调用后的最大重试次数(默认总共 3 次尝试)。必须 >= 0。
retryOn
((error: Error) => boolean) | (new (...args: any[]) => Error)[]
默认值: "() => true"
可以是需要重试的错误构造函数数组,也可以是一个接收错误并返回 true(表示应重试)的函数。默认为重试所有错误。
onFailure
'error' | 'continue' | ((error: Error) => string)
默认值: "continue"
所有重试次数用尽后的行为。选项:
'continue'(默认)- 返回包含错误详情的 AIMessage,允许智能体可能优雅地处理失败
'error' - 重新引发异常,停止智能体执行
自定义函数 - 接收异常并返回用于 AIMessage 内容的字符串,允许自定义错误格式
指数退避乘数。每次重试等待 initialDelayMs * (backoffFactor ** retryNumber) 毫秒。设置为 0.0 则为恒定延迟。必须 >= 0。
重试之间的最大延迟(毫秒)(限制指数退避的增长)。必须 >= 0。
是否为延迟添加随机抖动 (±25%),以避免惊群效应
该中间件使用指数退避算法自动重试失败的模型调用。 import { createAgent , modelRetryMiddleware } from "langchain" ;
// Basic usage with default settings (2 retries, exponential backoff)
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [searchTool] ,
middleware : [ modelRetryMiddleware ()] ,
} ) ;
class TimeoutError extends Error {
// ...
}
class NetworkError extends Error {
// ...
}
// Retry specific exceptions only
const retry = modelRetryMiddleware ( {
maxRetries : 4 ,
retryOn : [TimeoutError , NetworkError] ,
backoffFactor : 1.5 ,
} ) ;
// Custom exception filtering
function shouldRetry ( error : Error ) : boolean {
// Only retry on rate limit errors
if (error . name === "RateLimitError" ) {
return true ;
}
// Or check for specific HTTP status codes
if (error . name === "HTTPError" && "statusCode" in error) {
const statusCode = (error as any ) . statusCode ;
return statusCode === 429 || statusCode === 503 ;
}
return false ;
}
const retryWithFilter = modelRetryMiddleware ( {
maxRetries : 3 ,
retryOn : shouldRetry ,
} ) ;
// Return error message instead of raising
const retryContinue = modelRetryMiddleware ( {
maxRetries : 4 ,
onFailure : "continue" , // Return AIMessage with error instead of throwing
} ) ;
// Custom error message formatting
const formatError = ( error : Error ) =>
`Model call failed: ${ error . message } . Please try again later.` ;
const retryWithFormatter = modelRetryMiddleware ( {
maxRetries : 4 ,
onFailure : formatError ,
} ) ;
// Constant backoff (no exponential growth)
const constantBackoff = modelRetryMiddleware ( {
maxRetries : 5 ,
backoffFactor : 0.0 , // No exponential growth
initialDelayMs : 2000 , // Always wait 2 seconds
} ) ;
// Raise exception on failure
const strictRetry = modelRetryMiddleware ( {
maxRetries : 2 ,
onFailure : "error" , // Re-raise exception instead of returning message
} ) ;
出于测试目的,使用 LLM 模拟工具执行,将实际的工具调用替换为 AI 生成的响应。LLM 工具模拟器适用于以下场景:
在不执行真实工具的情况下测试智能体行为。
在外部工具不可用或昂贵时开发智能体。
在实现实际工具之前对智能体工作流进行原型设计。
import { createAgent , toolEmulatorMiddleware } from "langchain" ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [getWeather , searchDatabase , sendEmail] ,
middleware : [
toolEmulatorMiddleware () , // Emulate all tools
] ,
} ) ;
tools
(string | ClientTool | ServerTool)[]
要模拟的工具名称(字符串)或工具实例列表。如果为 undefined(默认),将模拟所有工具。如果是空数组 [],则不模拟任何工具。如果是带有工具名称/实例的数组,则仅模拟这些工具。
用于生成模拟工具响应的模型。可以是模型标识符字符串(例如 'google_genai:gemini-3.1-pro-preview')或 BaseChatModel 实例。如果未指定,默认使用智能体的模型。
该中间件使用 LLM 为工具调用生成合理的响应,而不是执行实际工具。 import { createAgent , toolEmulatorMiddleware , tool } from "langchain" ;
import * as z from "zod" ;
const getWeather = tool (
async ({ location }) => `Weather in ${ location } ` ,
{
name : "get_weather" ,
description : "Get the current weather for a location" ,
schema : z . object ( { location : z . string () } ) ,
}
) ;
const sendEmail = tool (
async ({ to , subject , body }) => "Email sent" ,
{
name : "send_email" ,
description : "Send an email" ,
schema : z . object ( {
to : z . string () ,
subject : z . string () ,
body : z . string () ,
} ) ,
}
) ;
// Emulate all tools (default behavior)
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [getWeather , sendEmail] ,
middleware : [ toolEmulatorMiddleware ()] ,
} ) ;
// Emulate specific tools by name
const agent2 = createAgent ( {
model : "gpt-5.4" ,
tools : [getWeather , sendEmail] ,
middleware : [
toolEmulatorMiddleware ( {
tools : [ "get_weather" ] ,
} ) ,
] ,
} ) ;
// Emulate specific tools by passing tool instances
const agent3 = createAgent ( {
model : "gpt-5.4" ,
tools : [getWeather , sendEmail] ,
middleware : [
toolEmulatorMiddleware ( {
tools : [getWeather] ,
} ) ,
] ,
} ) ;
// Use custom model for emulation
const agent5 = createAgent ( {
model : "gpt-5.4" ,
tools : [getWeather , sendEmail] ,
middleware : [
toolEmulatorMiddleware ( {
model : "claude-sonnet-4-6" ,
} ) ,
] ,
} ) ;
上下文编辑
在达到 token 限制时,通过清除旧的工具调用输出来管理对话上下文,同时保留最近的结果。这有助于在包含大量工具调用的长对话中保持上下文窗口的可控性。上下文编辑适用于以下场景:
包含大量工具调用且超过 token 限制的长对话
通过删除不再相关的旧工具输出来降低 token 成本
在上下文中仅保留最近的 N 个工具结果
import { createAgent , contextEditingMiddleware , ClearToolUsesEdit } from "langchain" ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [] ,
middleware : [
contextEditingMiddleware ( {
edits : [
new ClearToolUsesEdit ( {
triggerTokens : 100000 ,
keep : 3 ,
} ) ,
] ,
} ) ,
] ,
} ) ;
edits
ContextEdit[]
默认值: "[new ClearToolUsesEdit()]"
ClearToolUsesEdit 选项触发编辑的 token 计数。当对话超过此 token 计数时,旧的工具输出将被清除。
运行编辑时至少回收的 token 数量。如果设置为 0,则根据需要清除。
必须保留的最近工具结果的数量。这些将永远不会被清除。
是否清除 AI 消息上原始的工具调用参数。当为 true 时,工具调用参数将被替换为空对象。
要排除在清除范围之外的工具名称列表。这些工具的输出将永远不会被清除。
为清除的工具输出插入的占位符文本。这会替换原始的工具消息内容。
当达到 token 限制时,该中间件会应用上下文编辑策略。最常见的策略是 ClearToolUsesEdit,它会清除旧的工具结果,同时保留最近的结果。 工作原理:
监控对话中的 token 数量
当达到阈值时,清除较早的工具输出
保留最近的 N 个工具结果
可选地保留工具调用参数以作为背景上下文
import { createAgent , contextEditingMiddleware , ClearToolUsesEdit } from "langchain" ;
const agent = createAgent ( {
model : "gpt-5.4" ,
tools : [searchTool , calculatorTool , databaseTool] ,
middleware : [
contextEditingMiddleware ( {
edits : [
new ClearToolUsesEdit ( {
triggerTokens : 2000 ,
keep : 3 ,
clearToolInputs : false ,
excludeTools : [] ,
placeholder : "[cleared]" ,
} ) ,
] ,
} ) ,
] ,
} ) ;
文件系统中间件
上下文工程是构建有效智能体的主要挑战。当使用返回可变长度结果的工具(例如 web_search 和 RAG)时,这一点尤其困难,因为长工具结果会迅速填满您的上下文窗口。 来自 Deep Agents 的 FilesystemMiddleware 提供了四个用于与短期和长期记忆交互的工具:
ls: 列出文件系统中的文件
read_file: 读取整个文件或文件中的特定行数
write_file: 向文件系统写入新文件
edit_file: 编辑文件系统中的现有文件
import { createAgent } from "langchain" ;
import { createFilesystemMiddleware } from "deepagents" ;
// FilesystemMiddleware is included by default in createDeepAgent
// You can customize it if building a custom agent
const agent = createAgent ( {
model : "claude-sonnet-4-6" ,
middleware : [
createFilesystemMiddleware ( {
backend : undefined , // Optional: custom backend (defaults to StateBackend)
systemPrompt : "Write to the filesystem when..." , // Optional custom system prompt override
customToolDescriptions : {
ls : "Use the ls tool when..." ,
read_file : "Use the read_file tool to..." ,
}, // Optional: Custom descriptions for filesystem tools
} ) ,
] ,
} ) ;
短期 vs. 长期文件系统
默认情况下,这些工具会写入图状态(graph state)中的本地“文件系统”。要跨线程启用持久存储,请配置一个 CompositeBackend,将特定路径(如 /memories/)路由到 StoreBackend。
import { createAgent } from "langchain" ;
import { createFilesystemMiddleware , CompositeBackend , StateBackend , StoreBackend } from "deepagents" ;
import { InMemoryStore } from "@langchain/langgraph-checkpoint" ;
const store = new InMemoryStore () ;
const agent = createAgent ( {
model : "claude-sonnet-4-6" ,
store ,
middleware : [
createFilesystemMiddleware ( {
backend : new CompositeBackend (
new StateBackend () ,
{ "/memories/" : new StoreBackend () }
) ,
systemPrompt : "Write to the filesystem when..." , // Optional custom system prompt override
customToolDescriptions : {
ls : "Use the ls tool when..." ,
read_file : "Use the read_file tool to..." ,
}, // Optional: Custom descriptions for filesystem tools
} ) ,
] ,
} ) ;
当您为 /memories/ 配置了带有 StoreBackend 的 CompositeBackend 时,任何带有 /memories/ 前缀的文件都会保存到持久存储中,并在不同线程之间存续。没有此前缀的文件保留在临时状态存储中。
子智能体
将任务移交给子智能体可以隔离上下文,使主(主管)智能体的上下文窗口保持整洁,同时仍能深入完成任务。 来自 Deep Agents 的子智能体中间件允许您通过 task 工具提供子智能体。 import { tool } from "langchain" ;
import { createAgent } from "langchain" ;
import { createSubAgentMiddleware } from "deepagents" ;
import { z } from "zod" ;
const getWeather = tool (
async ({ city } : { city : string }) => {
return `The weather in ${ city } is sunny.` ;
},
{
name : "get_weather" ,
description : "Get the weather in a city." ,
schema : z . object ( {
city : z . string () ,
} ) ,
},
) ;
const agent = createAgent ( {
model : "claude-sonnet-4-6" ,
middleware : [
createSubAgentMiddleware ( {
defaultModel : "claude-sonnet-4-6" ,
defaultTools : [] ,
subagents : [
{
name : "weather" ,
description : "This subagent can get weather in cities." ,
systemPrompt : "Use the get_weather tool to get the weather in a city." ,
tools : [getWeather] ,
model : "gpt-5.4" ,
middleware : [] ,
},
] ,
} ) ,
] ,
} ) ;
子智能体由名称 、描述 、系统提示 和工具 定义。您还可以为子智能体提供自定义模型 或额外的中间件 。当您想给子智能体一个额外的状态键来与主智能体共享时,这特别有用。 对于更复杂的用例,您还可以提供自己预置的 LangGraph 图作为子智能体。 import { tool , createAgent } from "langchain" ;
import { createSubAgentMiddleware , type SubAgent } from "deepagents" ;
import { z } from "zod" ;
const getWeather = tool (
async ({ city } : { city : string }) => {
return `The weather in ${ city } is sunny.` ;
},
{
name : "get_weather" ,
description : "Get the weather in a city." ,
schema : z . object ( {
city : z . string () ,
} ) ,
},
) ;
const weatherSubagent : SubAgent = {
name : "weather" ,
description : "This subagent can get weather in cities." ,
systemPrompt : "Use the get_weather tool to get the weather in a city." ,
tools : [getWeather] ,
model : "gpt-5.4" ,
middleware : [] ,
};
const agent = createAgent ( {
model : "claude-sonnet-4-6" ,
middleware : [
createSubAgentMiddleware ( {
defaultModel : "claude-sonnet-4-6" ,
defaultTools : [] ,
subagents : [weatherSubagent] ,
} ) ,
] ,
} ) ;
除了任何用户定义的子智能体外,主智能体随时都可以访问一个 general-purpose(通用)子智能体。该子智能体拥有与主智能体相同的指令及其可访问的所有工具。general-purpose 子智能体的主要目的是上下文隔离——主智能体可以将复杂的任务委托给该子智能体,并获得简明的答案,而不会受到中间工具调用的干扰。
特定提供商中间件
这些中间件针对特定的 LLM 提供商进行了优化。有关完整详细信息和示例,请参阅各提供商的文档。
Anthropic 适用于 Claude 模型的提示缓存、bash 工具、文本编辑器、记忆和文件搜索中间件。
将这些文档 连接到 Claude、VSCode 等,以获得实时答案。