LangChain 助手
- 作者仓库星标 0
- 作者更新于 实时读取
- 作者仓库 skills-registry
- 领域
- AI 智能
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 88 / 100 · 社区维护
- 作者 / 版本 / 许可
- @tomevault-io · 未声明 license
- Token 消耗评级
- 中等消耗
- 接入复杂程度
- 需简单配置
- 是否需要外部 API Key
- 不需要
- 兼容的系统
- macOS · Linux · Windows
- 底层运行要求
- Node.js · Python
- 文件与系统权限
-
- 只读
- 允许写入 / 修改
- Shell 执行
- 网络行为
- 仅限本地
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: langchain-agents-middleware
description: Use when building or productionising any agent — adding retries, fallbacks, summarization, human…
category: AI 智能
runtime: Node.js / Python
---
# langchain-agents-middleware 输出预览
## PART A: 任务判断
- 适用问题:提示词、Agent 工作流、模型评估或自动化推理。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“The model / Lifecycle hooks (for custom middleware) / Built-in middlewares (provider-agnostic)”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于提示词、Agent 工作流、模型评估或自动化推理,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“The model / Lifecycle hooks (for custom middleware) / Built-in middlewares (provider-agnostic)”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、写入/修改文件、执行终端命令、主要在本地完成、通常不需要额外 API Key 给出执行前确认项。
## Running Rules
- 读取文件、写入/修改文件、执行终端命令;主要在本地完成;通常不需要额外 API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文没有稳定的斜杠命令要求。安装验证后通常全局生效,直接在对话里点名这个 Skill 并描述任务即可。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、写入/修改文件、执行终端命令。
先用一个小任务确认它会围绕“The model / Lifecycle hooks (for custom middleware) / Built-in middlewares (provider-agnostic)”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
name: langchain-agents-middleware
description: Use when building or productionising any agent — adding retries, fallbacks, summarization, human…
category: AI 智能
source: tomevault-io/skills-registry
---
# langchain-agents-middleware
## 什么时候使用
- 把 AI / Agent方向的常用动作沉淀成 Agent 可调用的技能 适合处理AI Agent、提示词、模型评估与自动化推理,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛回答。 把任务拆成可执行、可检查…
- 面向提示词、Agent 工作流、模型评估或自动化推理,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「The model / Lifecycle hooks (for custom middleware) / Built-in middlewares (provider-agnostic)」组织步骤,不把推断写成作者事实。
- 读取文件、写入/修改文件、执行终端命令;主要在本地完成;通常不需要额外 API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "langchain-agents-middleware" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> The model / Lifecycle hooks (for custom middleware) / Built-in middlewares (provider-agnostic)
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> Node.js / Python | 读取文件、写入/修改文件、执行终端命令 | 主要在本地完成
安全层 -> 通常不需要额外 API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} Agentic Middleware
Middleware is how you compose cross-cutting agent behavior in LangChain v1+. It plugs into create_agent(...) (and is the underlying implementation of DeepAgents). For any production agent, the question is "which middlewares" — not "do I need middleware".
The model
from langchain.agents import create_agent
from langchain.agents.middleware import (
SummarizationMiddleware,
ModelRetryMiddleware,
ModelFallbackMiddleware,
ModelCallLimitMiddleware,
ToolRetryMiddleware,
PIIMiddleware,
)
agent = create_agent(
model="claude-sonnet-4-6",
tools=[...],
middleware=[
ModelRetryMiddleware(max_retries=3, backoff_factor=2.0, initial_delay=1.0),
ModelFallbackMiddleware("openai:gpt-4o-mini"),
ModelCallLimitMiddleware(run_limit=50),
ToolRetryMiddleware(max_retries=3, backoff_factor=2.0),
SummarizationMiddleware(model="claude-haiku-4-5", trigger=("tokens", 4000), keep=("messages", 20)),
PIIMiddleware("email", strategy="redact", apply_to_input=True),
],
)
create_agent returns a compiled LangGraph. All Runnable semantics apply: .invoke, .ainvoke, .stream, .astream, langgraph dev, langgraph build, etc.
Lifecycle hooks (for custom middleware)
Every middleware can override one or more of these:
| Hook | Fires | Return |
|---|---|---|
before_agent(state, runtime) |
Once, before the loop starts | dict to merge into state, or None |
before_model(state, runtime) |
Before each model call | dict to merge into state, or None |
wrap_model_call(request, handler) |
Wraps the model call | call handler(request) → ModelResponse; return it (possibly modified) |
after_model(state, runtime) |
After each model response | dict to merge into state, or None |
wrap_tool_call(request, handler) |
Wraps each tool call | call handler(request) → ToolMessage | Command; return it (possibly modified) |
after_agent(state, runtime) |
Once, after the loop ends | dict to merge into state, or None |
Node-style hooks (before_* / after_*) run sequentially. Wrap-style hooks compose like Python decorators — first middleware in the list is the outermost wrapper.
Built-in middlewares (provider-agnostic)
Import from langchain.agents.middleware:
| Middleware | Purpose | Constructor |
|---|---|---|
SummarizationMiddleware |
Auto-summarize long conversations to stay under token limits | (model, trigger=("tokens", N), keep=("messages", N)) |
HumanInTheLoopMiddleware |
Pause for human approve/edit/reject on sensitive tool calls | (interrupt_on={"tool_name": {"allowed_decisions": [...]}}) — requires a checkpointer |
ModelCallLimitMiddleware |
Cap model calls per run / per thread (cost containment, infinite-loop guard) | (thread_limit, run_limit, exit_behavior="end") |
ToolCallLimitMiddleware |
Cap tool calls globally or per-tool | (thread_limit, run_limit) or (tool_name, thread_limit, run_limit) |
ModelRetryMiddleware |
Retry transient model failures with exponential backoff | (max_retries, backoff_factor, initial_delay) |
ToolRetryMiddleware |
Retry transient tool failures with exponential backoff | same args |
ModelFallbackMiddleware |
Fall back to alternative models on primary failure | ("model-1", "model-2", ...) |
LLMToolSelectorMiddleware |
Use a small LLM to pick which tools to expose to the main model | (model, max_tools, always_include=[...]) |
PIIMiddleware |
Detect & redact / mask / block PII | ("email"|"credit_card"|..., strategy="redact"|"mask"|"block", apply_to_input=True) |
ContextEditingMiddleware |
Drop old tool outputs from context to free tokens | (edits=[ClearToolUsesEdit(trigger, keep)]) |
TodoListMiddleware |
Adds the write_todos planning tool to the agent |
() |
LLMToolEmulator |
Replace tool execution with LLM-generated outputs (testing) | () — never use in production |
ShellToolMiddleware |
Persistent shell session as a tool, with execution policy | (workspace_root, execution_policy) |
FilesystemFileSearchMiddleware |
Glob + Grep tools over a filesystem | (root_path, use_ripgrep=True) |
DeepAgents-specific (import from deepagents.middleware):
| Middleware | Purpose |
|---|---|
FilesystemMiddleware |
Virtual or backed filesystem for the agent (read/write/edit/ls/glob/grep) |
SubAgentMiddleware |
Adds the task tool with named sub-agents |
create_deep_agent(...) is a thin wrapper over create_agent(...) that pre-installs FilesystemMiddleware + SubAgentMiddleware + TodoListMiddleware. You can compose additional middlewares on top.
Production middleware stack (start here)
For any production agent, this is the default stack to copy and tune:
middleware=[
# Cost containment (set BEFORE retries — limits the multiplier)
ModelCallLimitMiddleware(run_limit=50),
ToolCallLimitMiddleware(run_limit=200),
# Resilience to transient failures
ModelRetryMiddleware(max_retries=3, backoff_factor=2.0, initial_delay=1.0),
ToolRetryMiddleware(max_retries=3, backoff_factor=2.0, initial_delay=1.0),
# Provider-level resilience
ModelFallbackMiddleware("openai:gpt-4o-mini"),
# Long-conversation hygiene
SummarizationMiddleware(model="claude-haiku-4-5", trigger=("tokens", 8000), keep=("messages", 20)),
# Privacy (only if user input may contain PII)
PIIMiddleware("email", strategy="redact", apply_to_input=True),
PIIMiddleware("credit_card", strategy="mask", apply_to_input=True),
]
Add HumanInTheLoopMiddleware for any tool that touches money, sends external messages, or makes irreversible changes. Requires a checkpointer (InMemorySaver for dev, PostgresSaver for production — see the deploy skill).
Custom middleware
Inherit from AgentMiddleware:
from typing import Any, Callable
from langchain.agents.middleware import (
AgentMiddleware, AgentState, ModelRequest, ModelResponse,
)
from langchain.tools.tool_node import ToolCallRequest
from langchain.messages import ToolMessage
from langgraph.types import Command
class TokenBudgetMiddleware(AgentMiddleware):
"""Hard-cap total tokens across the run. Halts the agent when exceeded."""
def __init__(self, budget: int) -> None:
self.budget = budget
def wrap_model_call(
self,
request: ModelRequest,
handler: Callable[[ModelRequest], ModelResponse],
) -> ModelResponse:
used = request.state.get("tokens_used", 0)
if used >= self.budget:
# short-circuit: return a synthetic "stop" response without calling the model
return ModelResponse(
messages=[{"role": "assistant", "content": "Token budget exceeded."}],
command=Command(goto="__end__"),
)
response = handler(request)
# ... extract token count from response.usage and add to state
return response
If you need extra fields in state, declare them on a subclass of AgentState and set state_schema = MyState on the middleware class.
Hard rules
- Order matters. Limits before retries (so retries don't burn through your budget). Privacy redaction before logging. Summarization should run before the model call, not after.
- HumanInTheLoopMiddleware needs a checkpointer. Without one, interrupts have nothing to resume from.
LLMToolEmulatoris a testing-only middleware. Never ship it.- Retries cost money. A
max_retries=3withbackoff_factor=2means up to 4 calls per failure. SetModelCallLimitMiddlewareBEFORE retries to cap the worst-case cost. - Don't roll your own retry/fallback/limit. The built-ins handle the edge cases (jitter, retryable error classification, streaming-aware wrapping). Custom middleware is for app-specific concerns.
Skills to load alongside this one
langchain-agents-deploy— productionisation: durable execution, checkpointers, deployment.langchain-agents-observability— tracing what middleware actually does at runtime.langchain-agents-langgraph-code— when to drop down to rawStateGraph(rare, but real cases exist).
Source: cwijayasundara/agent_cli_langchain — distributed by TomeVault.
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核