LangChain 提供了针对常见用例的预构建 middleware。每个 middleware 都已准备好用于生产环境,并可根据您的特定需求进行配置。
自定义检测器函数签名:
检测器函数必须接受一个字符串(内容)并返回匹配结果:
返回
提供商无关的 Middleware
以下 middleware 适用于任何 LLM 提供商:| Middleware | Description |
|---|---|
| Summarization | Automatically summarize conversation history when approaching token limits. |
| Human-in-the-loop | Pause execution for human approval of tool calls. |
| Model call limit | Limit the number of model calls to prevent excessive costs. |
| Tool call limit | Control tool execution by limiting call counts. |
| Model fallback | Automatically fallback to alternative models when primary fails. |
| PII detection | Detect and handle Personally Identifiable Information (PII). |
| To-do list | Equip agents with task planning and tracking capabilities. |
| LLM tool selector | Use an LLM to select relevant tools before calling main model. |
| Tool retry | Automatically retry failed tool calls with exponential backoff. |
| Model retry | Automatically retry failed model calls with exponential backoff. |
| LLM tool emulator | Emulate tool execution using an LLM for testing purposes. |
| Context editing | Manage conversation context by trimming or clearing tool uses. |
Summarization
当接近 token 限制时自动总结对话历史,在压缩较旧上下文的同时保留最近的消息。总结功能适用于以下场景:- 超过上下文窗口的长时间对话。
- 具有大量历史记录的多轮对话。
- 需要保留完整对话上下文的应用程序。
Configuration options
Configuration options
Model for generating summaries. Can be a model identifier string (e.g.,
'openai:gpt-4o-mini'
) or a
BaseChatModel
instance.
Conditions for triggering summarization. Can be:
- A single condition object (all properties must be met - AND logic)
- An array of condition objects (any condition must be met - OR logic)
-
fraction(number): Fraction of model’s context size (0-1) -
tokens(number): Absolute token count -
messages(number): Message count
How much context to preserve after summarization. Specify exactly one of:
-
fraction(number): Fraction of model’s context size to keep (0-1) -
tokens(number): Absolute token count to keep -
messages(number): Number of recent messages to keep
Custom token counting function. Defaults to character-based counting.
Custom prompt template for summarization. Uses built-in template if not specified. The template should include
{messages}
placeholder where conversation history will be inserted.
Maximum number of tokens to include when generating the summary. Messages will be trimmed to fit this limit before summarization.
Prefix to add to the summary message. If not provided, a default prefix is used.
Deprecated:
Use
trigger: { tokens: value }
instead. Token threshold for triggering summarization.
Deprecated:
Use
keep: { messages: value }
instead. Recent messages to preserve.
Full example
Full example
The summarization middleware monitors message token counts and automatically summarizes older messages when thresholds are reached.
Trigger conditions
control when summarization runs:
- Single condition object (all properties must be met - AND logic)
- Array of conditions (any condition must be met - OR logic)
-
Each condition can use
fraction(of model’s context size),tokens(absolute count), ormessages(message count)
-
fraction- Fraction of model’s context size to keep -
tokens- Absolute token count to keep -
messages- Number of recent messages to keep
Human-in-the-loop
Pause agent execution for human approval, editing, or rejection of tool calls before they execute. Human-in-the-loop is useful for the following:- High-stakes operations requiring human approval (e.g. database writes, financial transactions).
- Compliance workflows where human oversight is mandatory.
- Long-running conversations where human feedback guides the agent.
Watch this
video guide
demonstrating Human-in-the-loop middleware behavior.
Model call limit
限制模型调用次数以防止无限循环或过高成本。模型调用限制适用于以下场景:- 防止失控的智能体发起过多 API 调用。
- 在生产部署中实施成本控制。
- 在特定调用预算内测试智能体行为。
Watch this
video guide
demonstrating Model Call Limit middleware behavior.
Configuration options
Configuration options
Maximum model calls across all runs in a thread. Defaults to no limit.
Maximum model calls per single invocation. Defaults to no limit.
Behavior when limit is reached. Options:
'end'
(graceful termination) or
'error'
(throw exception)
Tool call limit
通过限制工具调用次数来控制智能体执行,可以是全局限制所有工具或针对特定工具。工具调用限制适用于以下场景:- 防止对昂贵外部 API 的过度调用。
- 限制网络搜索或数据库查询。
- 对特定工具的使用实施速率限制。
- 防止智能体陷入无限循环。
Watch this
video guide
demonstrating Tool Call Limit middleware behavior.
Configuration options
Configuration options
要限制的特定工具名称。如果未提供,限制将应用于
所有工具(全局)
。
线程(对话)中所有运行的最大工具调用次数。在具有相同线程 ID 的多次调用之间保持持久。需要检查点管理器来维护状态。
undefined
表示无线程限制。
每次单独调用(一条用户消息 → 响应周期)的最大工具调用次数。每收到新的用户消息时重置。
undefined
表示无运行限制。
注意:
必须至少指定
threadLimit
或
runLimit
其中之一。
达到限制时的行为:
-
'continue'(默认)- 用错误消息阻止超出限制的工具调用,允许其他工具和模型继续执行。模型根据错误消息决定何时结束。 -
'error'- 抛出ToolCallLimitExceededError异常,立即停止执行 -
'end'- 立即停止执行,并为超出限制的工具调用返回 ToolMessage 和 AI 消息。仅在限制单个工具时有效;如果其他工具有待处理的调用则抛出错误。
Full example
Full example
通过以下方式指定限制:
- 线程限制 - 对话中所有运行的最大调用次数(需要检查点管理器)
- 运行限制 - 每次单独调用的最大调用次数(每轮重置)
-
'continue'(默认)- 用错误消息阻止超出限制的调用,智能体继续执行 -
'error'- 立即抛出异常 -
'end'- 使用 ToolMessage + AI 消息停止(仅限单工具场景)
Model fallback
当主模型失败时自动回退到替代模型。模型回退适用于以下场景:- 构建能够处理模型故障的弹性智能体。
- 通过回退到更便宜的模型来优化成本。
- 跨 OpenAI、Anthropic 等提供商的冗余。
Configuration options
Configuration options
该中间件接受可变数量的字符串参数,按顺序表示回退模型:
One or more fallback model strings to try in order when the primary model fails
PII detection
使用可配置策略检测和处理对话中的个人身份信息 (PII)。PII 检测适用于以下场景:- 具有合规要求的医疗和金融应用程序。
- 需要清理日志的客服智能体。
- Any application handling sensitive user data.
Custom PII types
您可以通过提供
detector
参数来创建自定义 PII 类型。这使您能够检测超出内置类型的特定用例模式。
创建自定义检测器的三种方式:
- Regex pattern string - Simple pattern matching
- RegExp object - More control over regex flags
- Custom function - Complex detection logic with validation
PIIMatch
对象数组:
Configuration options
Configuration options
要检测的 PII 类型。可以是内置类型(
email
、
credit_card
、
ip
、
mac_address
、
url
)或自定义类型名称。
如何处理检测到的 PII。选项:
-
'block'- 检测到时抛出错误 -
'redact'- 替换为[REDACTED_TYPE] -
'mask'- 部分掩码(例如,****-****-****-1234) -
'hash'- 替换为确定性哈希值(例如,<email_hash:a1b2c3d4>)
自定义检测器。可以是:
-
RegExp- 用于匹配的正则表达式模式 -
string- 正则表达式模式字符串(例如,"sk-[a-zA-Z0-9]{32}") -
function- 自定义检测器函数(content: string) => PIIMatch[]
在模型调用前检查用户消息
在模型调用后检查 AI 消息
执行后检查工具结果消息
To-do list
为智能体配备任务规划和跟踪能力,用于复杂的多步骤任务。待办事项列表适用于以下场景:- 需要跨多个工具协调的复杂多步骤任务。
- 需要进度可见性的长时间运行操作。
此中间件自动为智能体提供
write_todos
工具和系统提示,以指导有效的任务规划。
观看此
视频指南
演示待办事项列表中间件的行为。
Configuration options
Configuration options
没有可用的配置选项(使用默认值)。
LLM tool selector
使用 LLM 在调用主模型之前智能选择相关工具。LLM 工具选择器适用于以下场景:- 拥有多个工具(10+)的智能体,其中大多数工具与每个查询无关。
- 通过过滤无关工具来减少 token 使用量。
- 提高模型的专注度和准确性。
Configuration options
Configuration options
Model for tool selection. Can be a model identifier string (e.g.,
'openai:gpt-4o-mini'
) or a
BaseChatModel
instance. Defaults to the agent’s main model.
选择模型的指令。如果未指定,则使用内置提示。
要选择的最大工具数量。如果模型选择了更多,则只使用前 maxTools 个。如果未指定则无限制。
无论选择结果如何都始终包含的工具名称。这些不计入 maxTools 限制。
Tool retry
使用可配置的指数退避自动重试失败的工具调用。工具重试适用于以下场景:- 处理外部 API 调用中的瞬时故障。
- 提高依赖网络的工具的可靠性。
- 构建能够优雅处理临时错误的弹性智能体。
toolRetryMiddleware
Configuration options
Configuration options
Maximum number of retry attempts after the initial call (3 total attempts with default). Must be >= 0.
Optional array of tools or tool names to apply retry logic to. Can be a list of
BaseTool
instances or tool name strings. If
undefined
, applies to all tools.
Either an array of error constructors to retry on, or a function that takes an error and returns
true
if it should be retried. Default is to retry on all errors.
Behavior when all retries are exhausted. Options:
-
'continue'(default) - Return aToolMessagewith error details, allowing the LLM to handle the failure and potentially recover -
'error'- Re-raise the exception, stopping agent execution -
Custom function - Function that takes the exception and returns a string for the
ToolMessagecontent, allowing custom error formatting
'raise'
(use
'error'
instead) and
'return_message'
(use
'continue'
代替)。这些已弃用的值仍然有效,但会显示警告。
指数退避的乘数。每次重试等待
initialDelayMs * (backoffFactor ** retryNumber)
毫秒。设置为
0.0
表示固定延迟。必须 >= 0。
首次重试前的初始延迟(毫秒)。必须 >= 0。
重试之间的最大延迟(毫秒),限制指数退避增长。必须 >= 0。
是否为延迟添加随机抖动(
±25%
)以避免惊群效应
Full example
Full example
该中间件使用指数退避自动重试失败的工具调用。
关键配置:
-
maxRetries- 重试尝试次数(默认:2) -
backoffFactor- 指数退避乘数(默认:2.0) -
initialDelayMs- 起始延迟(毫秒)(默认:1000ms) -
maxDelayMs- 延迟增长上限(默认:60000ms) -
jitter- 添加随机变化(默认:true)
-
onFailure: "continue"(默认)- 返回错误消息 -
onFailure: "error"- 重新抛出异常 - 自定义函数 - 返回错误消息的函数
Model retry
使用可配置的指数退避自动重试失败的模型调用。模型重试适用于以下场景:- 处理模型 API 调用中的瞬时故障。
- 提高依赖网络的模型请求的可靠性。
- 构建能够优雅处理临时模型错误的弹性智能体。
modelRetryMiddleware
Configuration options
Configuration options
Maximum number of retry attempts after the initial call (3 total attempts with default). Must be >= 0.
Either an array of error constructors to retry on, or a function that takes an error and returns
true
if it should be retried. Default is to retry on all errors.
Behavior when all retries are exhausted. Options:
-
'continue'(default) - Return anAIMessagewith error details, allowing the agent to potentially handle the failure gracefully -
'error'- Re-raise the exception, stopping agent execution -
Custom function - Function that takes the exception and returns a string for the
AIMessagecontent, allowing custom error formatting
指数退避的乘数。每次重试等待
initialDelayMs * (backoffFactor ** retryNumber)
毫秒。设置为
0.0
表示固定延迟。必须 >= 0。
首次重试前的初始延迟(毫秒)。必须 >= 0。
重试之间的最大延迟(毫秒),限制指数退避增长。必须 >= 0。
是否为延迟添加随机抖动(
±25%
)以避免惊群效应
Full example
Full example
该中间件使用指数退避自动重试失败的模型调用。
LLM tool emulator
使用 LLM 模拟工具执行以进行测试,用 AI 生成的响应替代实际工具调用。LLM 工具模拟器适用于以下场景:- 在不执行真实工具的情况下测试智能体行为。
- 当外部工具不可用或成本较高时开发智能体。
- 在实现实际工具之前原型化智能体工作流。
Configuration options
Configuration options
Full example
Full example
该中间件使用 LLM 为工具调用生成合理的响应,而不是执行实际工具。
Context editing
当达到 token 限制时,通过清除较旧的工具调用输出来管理对话上下文,同时保留最近的结果。这有助于在包含许多工具调用的长对话中保持上下文窗口可管理。上下文编辑适用于以下场景:- 超过 token 限制的包含许多工具调用的长对话
- 通过删除不再相关的旧工具输出来降低 token 成本
- 仅在上下文中保留最近的 N 个工具结果
Configuration options
Configuration options
要应用的
ContextEdit
策略数组
ClearToolUsesEdit
选项:
触发编辑的 token 计数。当对话超过此 token 数量时,将清除较旧的工具输出。
编辑运行时要回收的最小 token 数量。如果设置为 0,则按需清除。
必须保留的最近工具结果数量。这些永远不会被清除。
是否清除 AI 消息上的原始工具调用参数。当设置为
true
时,工具调用参数将被替换为空对象。
要从清除中排除的工具名称列表。这些工具的输出永远不会被清除。
为已清除的工具输出插入的占位符文本。这将替换原始工具消息内容。
Full example
Full example
当达到 token 限制时,该中间件应用上下文编辑策略。最常用的策略是
ClearToolUsesEdit
,它会清除较旧的工具结果,同时保留最近的结果。
工作原理:
- 监控对话中的 token 计数
- 当达到阈值时,清除较旧的工具输出
- 保留最近的 N 个工具结果
- 可选择性地保留工具调用参数以供上下文使用
Provider-specific middleware
这些中间件针对特定的 LLM 提供商进行了优化。请参阅每个提供商的文档以获取完整详情和示例。
在 GitHub 上编辑此页面
或
提交问题
。