Hands-On Guide to LangChain v1 Middleware for AI Agents
A Juejin tutorial uses two runnable scripts to demonstrate the six lifecycle hooks in LangChain v1 middleware, including agent, model, and tool execution stages. It covers custom state injection, state-patch returns, model-call short-circuiting, dynamic tool attachment, Command-based tool results, middleware ordering, and practical pitfalls such as undefined counters and skipped cleanup hooks.
The examples give LangChain and LangGraph developers a concrete pattern for separating logging, policy checks, request rewriting, retries, caching, and dynamic tools from an AI agent's main business flow.
LangChain v1 中间件实战:不碰主流程,也能给 Agent 装上"外挂"
面向正在用 LangChain / LangGraph 做 Agent 的后端和 AI 开发同学,读完你能独立写出日志、埋点、限流、敏感词拦截、动态工具这类"横切逻辑"。
前言
一句话:Agent 的业务逻辑不该被日志、计数、敏感词、权限这些杂事污染,中间件就是那个"不侵入主流程的插槽"。
本文用两个可运行的小脚本,把 LangChain v1 的 6 个生命周期钩子、状态注入、短路跳转、动态挂工具全部跑通,并附上我们真实踩到的坑。
知识点清单
createAgent的四个核心配置:model/tools/systemPrompt/middleware- 6 个生命周期钩子的执行时机与执行次数
stateSchema:中间件如何给 Agent 增加自定义状态,并让invoke()把状态返回给你- 钩子返回值 = 状态补丁(不是副作用)
wrapModelCall:改写请求、重试、缓存、短路beforeModel+canJumpTo+jumpTo:在模型调用前"掐断"整个流程- 中间件自带工具:顶层
tools: []也能让 Agent 拥有工具 wrapToolCall返回Command:同时改消息和改状态- 洋葱模型的注册顺序:谁在最外层