19  Middleware

Chapter 13 ended on create_agent: the loop written for you, and middleware as the level that re-opens the seams in it — the places where you can inspect or change a model call or a tool call before it happens. This chapter opens those seams. First the payoff — one line that puts a human approval gate on a destructive tool — then the mechanism, then a middleware built by hand.

Middleware hangs functions on the seams of the agent loop — before and after the model call, around the model call, around each tool call. Those seams are the node boundaries you wired yourself in Part I.

19.1 What we’re building

Chapter 13’s create_agent doc-bot, with two additions bolted on from the outside, no graph surgery: the shipped HumanInTheLoopMiddleware guarding a destructive delete_index tool, and a hand-built CallLimitMiddleware that caps how many times the model may be called — Chapter 6’s fuse, rebuilt as a hook.

%%{init: {'securityLevel': 'loose', 'flowchart': {'diagramPadding': 24}, 'themeCSS': 'foreignObject{overflow:visible}span.bot{display:flex;justify-content:flex-start;align-items:flex-start;width:100%;height:0;overflow:visible;line-height:0}span.bot img{display:block!important;width:18px!important;height:18px!important;padding:2px;background:#fff;border-radius:50%;box-shadow:0 0 0 1px #999}span.bot.r img{margin:0;transform:translate(-24px,-24px)}span.bot.d{justify-content:center}span.bot.d img{margin-top:-50%;transform:translateY(-24px)}'}}%%
flowchart LR
    START(["START"]) --> bm["before_model"] --> model("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>model") --> am["after_model"]
    am -->|tool calls| tools("tools")
    tools --> bm
    am -->|answer| END(["END"])
    style bm stroke-dasharray: 5 3
    style am stroke-dasharray: 5 3

The dashed boxes are the seams. create_agent compiles to the same StateGraph you met in Chapter 13 — model node, ToolNode, a conditional edge, a back-edge — and each middleware hook becomes a step on one of those edges, or a wrapper around one of those nodes.

19.2 One line of protection

The doc-bot grows a second tool. One is harmless, one is not:

@tool
def search_docs(query: str) -> str:
    """Search the local documentation for configuration answers."""
    return "No relevant document found. Try a different phrasing."


@tool
def delete_index(name: str) -> str:
    """Delete a document index permanently. Destructive."""
    return f"index '{name}' deleted"

Chapter 13’s Gotcha said it plainly: hand the model a bag of tools and you no longer decide when they run. For delete_index, “the model felt like it” is not good enough. In Chapter 9 we built the answer as a graph node: an interrupt() before the dangerous step, a Command(resume=...) to continue. HumanInTheLoopMiddleware is that pattern, packaged:

agent = create_agent(
    llm,
    [search_docs, delete_index],
1    middleware=[HumanInTheLoopMiddleware(interrupt_on={"delete_index": True})],
2    checkpointer=InMemorySaver(),
)
1
Per-tool policy: delete_index pauses for review; search_docs (not named) runs without one.
2
An interrupt still needs somewhere to park the run — the checkpointer is Chapter 8’s, unchanged.

Every name this chapter adds comes from one module, langchain.agents.middleware, so the top of the file grows one more import, next to Chapter 13’s create_agent:

from langchain.agents import create_agent
from langchain.agents.middleware import (
    AgentMiddleware,            # the base class you subclass
    AgentState,                 # the agent's built-in state, to extend
    HumanInTheLoopMiddleware,
    hook_config,
)

llm is Chapter 12’s ChatOpenAI pointed at your local server, and cfg below is Chapter 8’s {"configurable": {"thread_id": …}}. Neither changes here.

Ask the agent to delete an index and the run does not delete anything. It pauses, exactly as Chapter 9’s graph did, and the interrupt payload carries what the model wanted to do:

result = agent.invoke(
    {"messages": [("user", "Delete the index called stale-docs-v1.")]},
    config=cfg,
)
1req = result["__interrupt__"][0].value["action_requests"][0]
1
The payload is structured: action_requests lists each pending tool call (name and args), review_configs lists the decisions the reviewer may take — approve, edit, reject, respond.

The resume value is structured the same way, one decision per pending call:

agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), config=cfg)

Running the file plays both endings — an approval, then the same request on a fresh thread with a rejection:

===== 1. HumanInTheLoopMiddleware (model: qwen/qwen3.8-27b) =====
[paused]   the agent wants: delete_index({'name': 'stale-docs-v1'})
[approved] The index `stale-docs-v1` has been deleted.
[rejected] The deletion was rejected because the index `stale-docs-v1` is still serving traffic.

A rejection is not an exception: the decision’s message goes back to the model as the tool’s response, and the model composes a civil answer around it. The reviewer talked to the model, not to the user.

19.3 The hooks

Where did that pause actually happen? HumanInTheLoopMiddleware overrides one method: after_model — the moment the model has emitted its tool calls but nothing has executed them. That is the same “filled-out request form, nobody has acted on it yet” gap that Chapter 13’s hand-written loop exposed between reading ai.tool_calls and calling tool.invoke.

A middleware is a class with up to six hooks, each optional:

The hook surface of AgentMiddleware. Each has an async twin (abefore_model, …).
Hook Fires In the hand-built graphs, this was
before_agent / after_agent once per run, at the ends code around graph.invoke(...)
before_model each loop turn, before the model the edge into the model node
after_model each loop turn, model’s output in hand, tools not yet run the edge from model to ToolNode
wrap_model_call around the model call the model node’s body
wrap_tool_call around each tool execution ToolNode’s body

Stack several middleware and they nest like decorators: before_* hooks run in list order, after_* hooks in reverse, so the first middleware in the list is the outermost wrapper.

before_*/after_* hooks read the state and return an update — a node’s contract (Chapter 3). wrap_* hooks take a different shape: they receive the call itself plus a handler to forward to, and the do-nothing version is the one line that hands it straight on.

def wrap_model_call(self, request, handler):
    return handler(request)          # the call you were given, run unchanged

def wrap_tool_call(self, request, handler):
    return handler(request)

Everything a wrap_* hook can do lives around that one line: work before it, work after it, calling it more than once, or not calling it at all. That is enough to retry the call, time it, or swap the model. The shipped ModelRetryMiddleware, ToolRetryMiddleware, and ModelFallbackMiddleware — three names Chapter 21 comes to in Part III — are each a single wrap_model_call or wrap_tool_call. And a middleware can declare extra state fields through state_schema — Chapter 14’s move, which the next section uses.

19.4 A middleware by hand

Chapter 6 put a fuse on a loop with recursion_limit, counted in supersteps. The harness equivalent is a cap on model calls — the expensive, billable thing — and building it takes the two ingredients above: a counter in the state, and a check on the seam before the model runs.

class CallCounterState(AgentState):
1    model_calls: NotRequired[int]


class CallLimitMiddleware(AgentMiddleware):
    state_schema = CallCounterState

    def __init__(self, limit: int):
        super().__init__()
        self.limit = limit

2    @hook_config(can_jump_to=["end"])
    def before_model(self, state, runtime) -> dict[str, Any] | None:
        if state.get("model_calls", 0) >= self.limit:
3            return {"jump_to": "end",
                    "messages": [AIMessage(f"Stopped: model call limit of {self.limit} reached.")]}
        return None

    def after_model(self, state, runtime) -> dict[str, Any] | None:
4        return {"model_calls": state.get("model_calls", 0) + 1}
1
The middleware brings its own channel: AgentState plus one field, declared through state_schema. The agent’s state grows the way Chapter 14 composed schemas.
2
A hook that may reroute has to declare its exits — this is add_conditional_edges’ path_map (Chapter 5), resurfacing at the harness level.
3
The verdict is an update, not an exception: jump to the end and leave a plain-language AIMessage as the final word.
4
The counter is ordinary state arithmetic, one bump per model call.

Point the agent at a docs search that never succeeds, tell it to keep trying, and the fuse does its job:

===== 2. A hand-built CallLimitMiddleware, limit=3 =====
model calls made: 3
final message:    Stopped: model call limit of 3 reached.

The shipped ModelCallLimitMiddleware is this exact design with more knobs — a per-thread limit next to the per-run one, and an exit_behavior="error" that raises instead of ending. Read its source after building this one and it will look familiar, down to the {"jump_to": "end"}.

One scope caveat before you reach for the hand-built version, though: model_calls is ordinary persistent state, not a per-run counter. This demo runs with fresh state each invoke (no checkpointer), so it reads like per-run. Put the same middleware on an agent with a checkpointer and keep invoking the same thread_id and the count carries over — a limit=2 will block the third model call of that conversation, whichever invoke it lands in. A true per-invoke limit has to reset the field at the start of a run (or track a run-local baseline); that is one of the knobs the shipped middleware adds.

WarningGotcha: middleware configures the harness, not the graph

A middleware hook can only stand on the seams create_agent exposes: around the model, around the tools, at the ends of the run. It cannot add a second retrieval node, a parallel fan-out, or a subgraph — there is no hook for “a topology I’d rather have.” The dividing line for production work: to observe or guard the loop, reach for middleware and keep the one-liner; to change the shape of the flow, drop down a level and write the graph, as every chapter since Chapter 3 has. The five-levels table in Section 13.7 is the map; middleware is rung five, not a replacement for rungs one through four.

19.5 What the built-ins cover

Before writing a middleware, check the shelf; langchain.agents.middleware ships the common production guards, and each is a thin use of the same hooks:

  • Limits: ModelCallLimitMiddleware, ToolCallLimitMiddleware — the fuse, per run or per thread.
  • Resilience: ModelRetryMiddleware, ToolRetryMiddleware, ModelFallbackMiddleware — Chapter 21’s RetryPolicy and fallback route, relocated to the harness.
  • Approval: HumanInTheLoopMiddleware — Chapter 9’s gate.
  • Context: SummarizationMiddleware — Chapter 17’s fold-the-history move, as a before_model hook.

The class map in Appendix B lists the rest. The pattern to notice: every one of them is a capability this book first built as graph pieces. The harness did not invent new powers; it packaged the ones you already have.

19.6 The same shape elsewhere

If you have built HTTP services, you have written this class before under another name: an Express middleware is (req, res, next), a handler wrapped in a handler, and the order you register them is the order they nest, first registered outermost — which is the hook table’s rule here too.

The tell is the handler argument, which makes this Decorator rather than anything simpler: a layer that receives the next layer can decide whether to call it, how many times, and what to do with what comes back. Express’s next() is that argument; AgentMiddleware carries the same choice per hook, and the hooks that have no handler are the simpler shape, a callback before or after.

What does not carry over is that the seams are fixed. A filter chain lets you insert a layer anywhere in a pipeline you own; here the six hook points are the ones create_agent wired, which is the whole content of the Gotcha above.

19.7 What we learned

  • Middleware is the sanctioned way into create_agent’s loop. Hook objects ride middleware=[...]; the one-liner stays a one-liner.
  • Six hooks, two shapes. before_*/after_* read state and return an update, like a node; wrap_* receive the call and a handler, like a decorated node body. Async twins throughout.
  • Hooks stand where your edges were. after_model is the gap between “the model asked” and “the tool ran”; that is why one line of HumanInTheLoopMiddleware equals Chapter 9’s hand-built gate.
  • A middleware can extend the state. state_schema adds channels the same way Chapter 14 composed them; @hook_config(can_jump_to=...) declares reroutes the way path_map did.
  • Guard with middleware, reshape with graphs. A hook becomes a node — but only on the seams create_agent already wired; no hook adds a node of your own design or an edge of your own choosing. When the topology must change, drop down the five-levels ladder.

That is every seam the doc-bot has: nodes and edges you wired, and hooks hung on the ones create_agent wired for you. The next chapter is about proving they still hold when nobody is watching.

New pieces in this chapter

Piece Usage
AgentMiddleware Base class; override any of the six hooks. class CallLimitMiddleware(AgentMiddleware): ..., then create_agent(model, tools, middleware=[...])
HumanInTheLoopMiddleware Approval gate on named tools. HumanInTheLoopMiddleware(interrupt_on={"delete_index": True}); resume with Command(resume={"decisions": [{"type": "approve"}]})
state_schema Class attribute declaring the middleware’s extra state fields. state_schema = CallCounterState
hook_config(can_jump_to=…) Decorator letting a before_model/after_model hook reroute; the hook returns {"jump_to": "end"}

Code in this chapter

File What it runs
code/ch17_middleware.py Middleware on the create_agent harness: hooks before and after the model call, around tools, and a call limit of your own.

Challenge

🥉 Bronze — reject with a reason

Run the file’s HITL demo, but answer with each of the other decision types the payload advertises: reject with a different message; edit (an edited_action with a changed index name — the edit is the approval, and the edited call runs); and respond (skip the tool entirely and supply its output yourself). Confirm from the final transcript who saw your message: the model reads it, and the user reads whatever the model makes of it.

office hours The review_configs in the interrupt payload list every decision shape the middleware accepts.

🥈 Silver — a timing middleware

Write TimingMiddleware with the two wrap_* hooks: time every model call and every tool call, collect (kind, name, ms) rows in a list on self, and print a table after the run.

Ask it something that makes the agent reach for a tool, then read the table you printed: rows of both kinds have to be there — one per model call, one per tool call — standing in the order the run made them.

Hints: this is the same idea Chapter 24 builds later as a traced() wrapper — you are meeting it here first, from the hook side. That chapter is not a prerequisite: collect (kind, name, ms) around each call the way a decorator would wrap a node, but from inside the wrap_* hooks instead.

office hours Worked solution with tests: code/answers/ch17_timing_middleware.py.

🥇 Gold — rebuild the summarizer

SummarizationMiddleware is Chapter 17’s summarize-then-prune in a before_model hook. Rebuild a minimal version: when the history tops eight messages, replace all but the last four with one summary HumanMessage (use RemoveMessage, Chapter 17). Then run the shipped one with the same threshold and compare what each kept.

One thing to get right when you configure the shipped one, because the older parameter names are still what most examples online use: on 1.x they take a (kind, value) pair, and the old spellings raise a DeprecationWarning rather than an error, so a run that looks fine may be running on a fallback path.

SummarizationMiddleware’s renamed parameters.
Deprecated Use instead
max_tokens_before_summary=N trigger=("tokens", N)
messages_to_keep=N keep=("messages", N)

Budget for the wait. Filling an eight-message history takes several turns, you run it twice — your version and the shipped one — and every turn is a model call, so this is minutes on a local model with nothing on screen unless you put it there. Print the turn number and the message count before each call, so a long run looks like progress on screen.

office hours Start from the file’s CallLimitMiddleware: the shape is identical, only the update differs.