AI AgentsLangChain

How do you add middleware to a LangChain agent?

Question 317 of 324 · Updated

On this page

Direct answer#

Pass middleware instances or decorator-defined middleware to the middleware argument of LangChain's create_agent. Use built-in middleware for common capabilities, and write custom middleware using the AgentMiddleware class or the supported hook decorators when application-specific logic is needed.

Middleware intercepts defined points in the agent execution lifecycle. Node-style hooks run before or after particular stages and may return supported state updates. Wrapper hooks receive a handler representing the next operation and can inspect, modify, delegate, reject or, under carefully controlled circumstances, retry that operation. Choose the hook according to the boundary that must be controlled.

Middleware is not a new agent, a replacement for authorization or a general-purpose background worker. It is an extension of the agent's execution contract. Its ordering, state semantics, handler delegation, error propagation and asynchronous behavior must be tested as part of the complete agent.

Source question #4 (AI Agents #284) introduces the agent execution loop. Questions #17, #19–20, #29–31 (#297, #299–300, #309–311) illustrate specialized middleware uses for errors, tools, trimming, summarization and memory. This lesson establishes middleware registration, hook selection, class and decorator implementations, and composition semantics. Detailed before_model and after_model hooks, state mutation, dynamic prompting, model routing, limits, guardrails and retries are subsequent lessons.

1. Understand where middleware runs#

Consider a fictional read-only support agent. For each user request, the application wants to observe model calls, enforce an approved request policy and collect safe operational metrics without rewriting the agent's core model/tool loop.

A middleware layer can provide these cross-cutting functions at the relevant execution boundary.

Loading diagram…

The diagram shows a simplified normal execution path for a modern graph-backed agent. Interrupts, explicit routing, errors, parallel calls and other configured behavior can change the path. An after-agent hook should not be assumed to execute on every exception, cancellation or interrupted run. Inspect the actual runtime and use appropriate wrapper-level cleanup or host-level resource management.

An agent can make several model calls and several tool calls during one invocation. A hook around a model call runs at that boundary, not necessarily only once per user request. Likewise, a wrapper around a tool call is not a wrapper around every external HTTP request the tool makes internally.

2. Register built-in middleware with create_agent#

Modern LangChain exposes built-in middleware through langchain.agents.middleware. Typical use cases include summarization, human approval, model or tool call limits, retries, fallbacks and redaction. Exact class availability and configuration depend on the installed release.

The following illustrative configuration adds the previously introduced summarization middleware.

PYTHON
from langchain.agents import create_agent from langchain.agents.middleware import SummarizationMiddleware from langgraph.checkpoint.memory import InMemorySaver agent = create_agent( model="openai:gpt-4o-mini", tools=[], system_prompt="Provide fictional read-only support.", checkpointer=InMemorySaver(), middleware=[ SummarizationMiddleware( model="openai:gpt-4o-mini", trigger=("tokens", 4000), keep=("messages", 20), ), ], ) # Host authenticates the caller and authorizes the selected thread first. # agent.invoke({"messages": [{"role": "user", "content": "Hello"}]}, # config={"configurable": {"thread_id": "demo-thread"}})

Verification status: This SDK example is illustrative and unexecuted. Local package inspection on Python 3.13.5 confirmed that langchain, langchain_core and langgraph are not installed. The standalone composition example in section 7 was actually executed. Model names, thresholds and other SDK configuration examples are illustrative rather than verified current compatibility recommendations.

Check the pinned framework's imports, middleware constructor arguments, supported hooks, state contract and provider compatibility before deployment. InMemorySaver is process-local and not a durable production checkpointer. A summarization policy also needs the evidence and retention protections explained in the previous lesson.

The middleware list is part of the deployment configuration. Adding a built-in component does not by itself establish that the entire composed agent is safe or correct. For example, approval middleware needs a compatible interruption and resumption design; a retry component needs an operation-specific replay policy.

RequirementTypical approach
Standard capability supported by the pinned releaseConfigure reviewed built-in middleware
Simple stateless custom interceptionSupported decorator
Reusable component with configuration or multiple hooksAgentMiddleware subclass
Business authorizationIndependently enforced service boundary, optionally assisted by middleware
Entire HTTP request authenticationHost application boundary, not only agent middleware
Durable asynchronous extraction jobWorker and queue, not an untracked hook

3. Choose node-style or wrapper-style hooks#

Modern AgentMiddleware provides lifecycle hooks and operation wrappers. The following table describes common modern Python interfaces, not a version guarantee.

HookUsual execution boundaryTypical responsibility
before_agentStart of an agent invocationInitialize approved bookkeeping or inspect state
before_modelBefore an individual model stepValidate or prepare supported state
after_modelAfter an individual model stepObserve or validate the model result and supported routing
after_agentEnd of the normal agent pathFinal bookkeeping or validation
wrap_model_callAround the model operationInspect request, override supported fields, delegate and observe response
wrap_tool_callAround an individual tool operationIndependently validate the execution request, delegate or handle a defined error

Node-style hooks commonly receive state and runtime objects. Depending on the hook and release, they can return a supported partial state update, a configured routing directive or None. Wrapper hooks receive a request and a handler and return a value satisfying the wrapper's response contract. Some decorators support declaring permitted routing targets or custom state schemas. Consult the actual installed API instead of inferring return types from ordinary Python decorators.

Use node hooks for lifecycle transitions and wrapper hooks when an operation's request or response must be controlled directly. Do not force a node hook to simulate a wrapper, or mutate state merely to change the next model's request.

The next question examines the before_model and after_model hooks in detail. Here the important design choice is the distinction between lifecycle stages and nested handler execution.

4. Implement decorator-based middleware#

The decorator-based approach is convenient for a small independent concern. For example, a wrapper can measure elapsed wall-clock time around the next model operation without logging message contents.

PYTHON
import logging from time import perf_counter from langchain.agents.middleware import wrap_model_call, ModelRequest, ModelResponse logger = logging.getLogger("demo.agent") @wrap_model_call def measure_model(request: ModelRequest, handler) -> ModelResponse: started = perf_counter() try: return handler(request) finally: logger.info("model_boundary_ms=%.2f", (perf_counter() - started) * 1000)

Register the decorated middleware through create_agent:

PYTHON
from langchain.agents import create_agent agent = create_agent( model="openai:gpt-4o-mini", tools=[], middleware=[measure_model], )

These SDK examples are unexecuted. The timer measures the work inside this wrapper, including any nested middleware and handler behavior. It does not necessarily measure provider network latency alone, and a returned response is not proof of a correct task outcome.

Calling handler(request) delegates to the remainder of the configured chain. Returning the handler's result preserves the expected response contract. The finally block is useful for observing exit on both success and exception. In a real system, telemetry must not mask the original error if its own sink fails; use a protected telemetry path and a reviewed error policy.

If the request needs a temporary change, use the supported request override mechanism in versions that provide it, rather than mutating an arbitrary shared request object. The previous tool-selection and history-trimming lessons show specialized examples of this pattern. An override of model-facing messages should not be confused with durable graph-state mutation.

A wrapper that does not call the handler intentionally short-circuits the operation. This may be useful for a verified rejection or an explicitly approved cached result, but the returned value must conform to the framework's expected contract. A bare string is not universally a valid ModelResponse, and a fake successful tool observation must never stand in for an operation that did not execute.

5. Implement class-based middleware#

A subclass is useful for reusable behavior with configuration, several hooks or explicit ownership of shared dependencies. Keep the configuration immutable or otherwise safe for concurrent use. Store per-run information in the supported state or request-local objects, not on a shared middleware instance unless the semantics are explicitly safe.

PYTHON
from typing import Callable from langchain.agents.middleware import ( AgentMiddleware, ModelRequest, ModelResponse, ) class ModelAuditMiddleware(AgentMiddleware): def __init__(self, emit: Callable[[str], None]): self._emit = emit def wrap_model_call(self, request: ModelRequest, handler) -> ModelResponse: self._emit("model.enter") try: return handler(request) finally: self._emit("model.exit")

The following example composes an instance with a previously defined decorator-based component:

PYTHON
import logging from langchain.agents import create_agent audit = ModelAuditMiddleware(logging.getLogger("demo.audit").info) agent = create_agent( model="openai:gpt-4o-mini", tools=[], middleware=[audit, measure_model], )

This example is illustrative and unexecuted. Its callback must be trusted and appropriate for the runtime. An actual telemetry sink may need non-blocking or failure-isolated operation. Class-based middleware can also declare supported state schemas, tool contributions and other hooks according to the installed release. Do not assume arbitrary instance attributes become checkpointed state.

A class is not inherently safer than a decorator. It can be less safe if it stores the latest user ID, token count or tool result on self and then shares the same middleware instance among concurrent agent requests. Treat instance configuration as reusable; keep request state scoped to the request.

State, context and request are different#

ObjectMeaningTypical lifecycle
Agent stateThread-scoped working data and messagesUpdated through graph state contract
Runtime contextHost-provided invocation dependencies and identityScoped to invocation
StoreApproved persistent records outside a threadSeparate repository lifecycle
ModelRequestEffective next model operationTemporary request override
Middleware instanceReusable configured componentOften shared across requests

A middleware hook may need access to several of these objects. Only use supported APIs for the hook in question. In particular, do not put a database client, credential or other live service handle into checkpointed AgentState merely to make it accessible to a middleware component. Reconstruct approved dependencies from trusted runtime context.

6. Understand execution ordering and composition#

The sequence in the middleware list matters. In common modern LangChain middleware composition, before-style hooks run in listed order, after-style hooks run in reverse order, and the first wrapper is outermost. Verify the exact behavior for the installed version, including conditional routing, state merges and interrupts; do not assume all hook types share one ordering rule.

For a wrapper-only chain containing A then B, a single successful delegation can be represented as follows:

Loading diagram…

A wrapper is different from two unrelated callbacks: it owns a nested invocation and its return path. If A rejects the request before delegating, B and the model are not reached. If B retries its handler, the model may be invoked more than once while A is entered only once.

This ordering affects policy. For example, a host may want a per-attempt authorization check inside an outer retry wrapper. An outer authorization wrapper that runs once is not enough if the retry can continue after authorization changes. Independently recheck the business operation at the actual execution boundary.

Similarly, a timer outside a retry wrapper measures total elapsed operation time, including retries. A timer inside the retry wrapper measures individual attempts. Both may be useful but must be labeled accurately.

Order exampleConsequence
Request budget check outside model callCan reject before model operation
Logging outside sensitive-data projectionRisk of observing raw input if logging is not minimized
Per-attempt validation inside retryEach delegated attempt rechecked
Final output validation outside fallbackValidation can inspect fallback result too
Cache hit outside a security checkPotential bypass if cached delivery is not independently authorized

These are design examples, not automatic SDK guarantees. Write an explicit composition specification describing which components may short-circuit, which may delegate more than once, and which owns state updates. Validate the final effective request, not only the initial one. A later component may add tools or modify a prompt after an earlier component calculated its budget.

7. Tested Python: wrapper composition, errors and async cancellation#

The following standard-library implementation models nested wrappers independently of LangChain. It uses immutable request fixtures, explicit handler delegation and a simple permission flag supplied by trusted test code. It demonstrates synchronous composition, request-copy normalization, rejection, bounded read retries, error propagation, concurrent async requests and cancellation cleanup.

The exact program was run locally before publication.

PYTHON
from dataclasses import dataclass, replace from functools import partial import asyncio, sys, importlib.util @dataclass(frozen=True) class Request: subject: str allowed: bool text: str class Denied(Exception): pass class Transient(Exception): pass def compose(wrappers, terminal): for wrapper in reversed(wrappers): terminal = partial(wrapper, handler=terminal) return terminal def audit(name, events): def wrap(request, *, handler): events.append((name, 'enter', request.subject)) try: return handler(request) finally: events.append((name, 'exit', request.subject)) return wrap def gate(request, *, handler): if not request.allowed: raise Denied('not allowed') return handler(request) def normalize(request, *, handler): return handler(replace(request, text=request.text.strip())) def run_tests(): events=[]; seen=[] def terminal(request): seen.append(request) return request.text.upper() r=Request('alice',True,' hello ') chain=compose([audit('outer',events),gate,normalize,audit('inner',events)], terminal) assert chain(r)=='HELLO' assert events==[('outer','enter','alice'),('inner','enter','alice'),('inner','exit','alice'),('outer','exit','alice')] assert seen==[replace(r,text='hello')] and r.text==' hello ' events.clear(); seen.clear() try: chain(replace(r,allowed=False)) except Denied: pass else: raise AssertionError('gate bypass') assert seen==[] assert events==[('outer','enter','alice'),('outer','exit','alice')] events.clear() err=RuntimeError('unexpected') def broken(request): raise err try: compose([audit('outer',events),audit('inner',events)],broken)(r) except RuntimeError as exc: assert exc is err else: raise AssertionError('error swallowed') assert events==[('outer','enter','alice'),('inner','enter','alice'),('inner','exit','alice'),('outer','exit','alice')] attempts=[] def retry_read(request, *, handler): for i in range(2): try: return handler(request) except Transient: if i==1: raise def flaky(request): attempts.append(request.subject) if len(attempts)==1: raise Transient('read failed') return 'ok' assert compose([gate,retry_read],flaky)(r)=='ok' assert attempts==['alice','alice'] attempts.clear() def always_fail(request): attempts.append(request.subject); raise Transient('read failed') try: compose([gate,retry_read],always_fail)(r) except Transient: pass else: raise AssertionError('retry swallowed error') assert len(attempts)==2 assert compose([],terminal)(r)==' HELLO ' async def async_tests(): events=[] async def trace(request, *, handler): events.append(('enter',request.subject)) try: return await handler(request) finally: events.append(('exit',request.subject)) async def terminal(request): await asyncio.sleep(0) return request.subject chain=compose([trace],terminal) assert await asyncio.gather(chain(Request('a',True,'')),chain(Request('b',True,'')))==['a','b'] assert sorted(events)==[('enter','a'),('enter','b'),('exit','a'),('exit','b')] entered=asyncio.Event(); never=asyncio.Event() async def blocked(request): entered.set(); await never.wait() task=asyncio.create_task(compose([trace],blocked)(Request('c',True,''))) await entered.wait(); task.cancel() try: await task except asyncio.CancelledError: pass else: raise AssertionError('cancellation swallowed') assert events[-2:]==[('enter','c'),('exit','c')] run_tests(); asyncio.run(async_tests()) print('16 check groups passed') print(sys.version.split()[0], {p:importlib.util.find_spec(p) is not None for p in ['langchain','langchain_core','langgraph']})

Actual local execution output:

16 check groups passed
3.13.5 {'langchain': False, 'langchain_core': False, 'langgraph': False}

The program completed all assertions and expected-exception branches. The printed count is a grouped test label, not a framework-generated test count.

Fixture or check groupObserved behavior
Normal synchronous requestTerminal returns HELLO
Nested audit wrappersOuter enter, inner enter, inner exit, outer exit
Request normalizationNew request reaches terminal, original remains unchanged
Unauthorized requestDenied exception propagates
Denied terminal invocationTerminal not reached
Denied nested middlewareInner wrapper not reached; outer cleanup runs
Unexpected terminal exceptionOriginal RuntimeError object preserved
Exception cleanupBoth exit events recorded
Transient read retrySecond attempt succeeds
Retry countExactly two attempts
Exhausted retryOriginal Transient exception category propagates
Exhausted attempt countExactly two attempts
Empty chainOriginal terminal behavior preserved
Concurrent async callsResults correspond to their own subjects
Async audit eventsEach subject has its enter and exit events
CancellationCancelledError propagates and cleanup event is recorded

What the execution proves#

For the successful chain, outer is invoked first. The gate permits the request, normalize creates a new frozen Request, inner delegates to the terminal, and the wrappers exit in reverse order. When the gate rejects, neither normalize nor the inner wrapper reaches the terminal. The outer finally block still runs.

The composition algorithm builds a nested chain using functools.partial, with one wrapper per supplied component. Construction takes linear work in the number of wrappers. A normal one-delegation execution traverses that chain once, but a retrying wrapper can invoke its downstream chain repeatedly. The total work therefore depends on the number of actual handler invocations, not just the middleware list length.

The retry fixture deliberately uses a read-only synthetic operation and a bounded two-attempt retry. It does not implement timeouts, backoff, service idempotency, exception classification for real networks or current authorization checks on each attempt. The permission flag is trusted synthetic fixture data, not authentication. The immutable request's subject does not establish resource ownership. Real authorization needs an independent service.

The async tasks execute cooperatively in a single event loop. They test request separation and cleanup under cancellation, not parallel multi-worker performance or distributed isolation. The event list is a teaching fixture. Production telemetry must have a protected sink and avoid unbounded growth or raw user content. The program is not a reimplementation of AgentMiddleware or its node-hook dispatch semantics; it verifies only the wrapper composition contract it explicitly defines.

8. Synchronous and asynchronous middleware#

Modern class-based middleware implementations commonly expose synchronous and asynchronous variants of supported hooks, such as wrap_model_call and awrap_model_call. Verify the installed release and whether a decorator-defined async function registers the intended asynchronous hook. Do not assume a sync-only wrapper will automatically work safely in an asynchronous agent invocation.

An illustrative class-based async wrapper looks like this:

PYTHON
from time import perf_counter from langchain.agents.middleware import AgentMiddleware class AsyncTimingMiddleware(AgentMiddleware): async def awrap_model_call(self, request, handler): start = perf_counter() try: return await handler(request) finally: # Illustrative local observation only; use safe telemetry in production. elapsed_ms = (perf_counter() - start) * 1000 print("async_model_boundary_ms", round(elapsed_ms, 2))

This snippet is unexecuted SDK code. Register it only with a compatible asynchronous deployment, and supply the synchronous variant if the same component must support both paths. A normal synchronous handler must not be awaited unless the framework explicitly adapts it to an awaitable.

An async hook does not make blocking work non-blocking. A synchronous network call, long CPU-bound calculation or blocking telemetry sink inside it can still stall the event loop. Use approved async clients and appropriate execution facilities for blocking work; enforce resource bounds and understand cancellation behavior.

Do not catch BaseException or cancellation merely to convert every failure into a friendly successful result. Cancellation often communicates that the caller, runtime or deadline has stopped waiting. Cleanup should run, but the operation's actual external outcome may still need reconciliation. A cancelled coroutine does not prove a remote request or thread-pool operation stopped.

If a tool is performing a consequential external action, an exception or timeout may represent an unknown commit outcome. Never blindly retry that action from generic middleware. The dedicated retry and fallback lesson covers the detailed recovery policy.

9. Security, failure semantics and safe defaults#

A useful middleware composition must preserve the difference between a normal result, an expected domain rejection, a transient failure, an unexpected programming error and an uncertain external effect.

Loading diagram…

In production, separate a model's tool-selection behavior from actual tool authorization. Model-call middleware can hide tools, but a sensitive domain service must still enforce current permissions on the operation itself. Tool-call wrappers can add a defensive execution boundary; they must not trust identity or approval fields emitted by the model.

A model response can be rejected without claiming a business operation succeeded. If an expected tool error becomes a ToolMessage, follow the actual call-correlation and error-result contract. Do not fabricate a tool-call ID or silently skip required observations.

For sensitive processing, ensure all middleware that observes raw inputs is authorized to do so. A redaction layer applied after a logging layer cannot retroactively prevent disclosure. Protect tracing, callbacks, metrics and error diagnostics. The dedicated redaction lesson covers transformations in detail.

Set independent run limits and deadlines. A wrapper can accidentally create multiple handler invocations, a fallback can trigger additional model calls, and a tool can have internal retries. A count of middleware invocations alone is not an accurate measure of model or service operations.

Keep middleware configuration versioned. Review additions and ordering changes as behavior changes, not purely refactoring. Pin SDK and provider dependencies and verify compatibility before adopting a new middleware feature. When a component has an optional safe fallback, define it explicitly; security-critical policy failures should not silently fail open.

10. Test the actual middleware stack in production-like environments#

The deterministic teaching program above demonstrates composition logic but does not establish SDK hook dispatch. In a pinned LangChain environment, create scripted model and tool fixtures and inspect the actual execution trace and provider request. Use controlled, synthetic data.

TestAcceptance condition
Registration with create_agentIntended middleware component active
Class and decorator combinationBoth components execute at their expected boundaries
Before and after lifecycle hooksActual order and invocation counts match the pinned contract
Nested model wrappersFirst listed wrapper outermost if confirmed by SDK
Nested tool wrappersCorrect per-call execution and response correlation
Request overrideIntended provider-bound request changed; authoritative state unaffected unless explicitly updated
Explicit state updateSupported reducer and persistence semantics verified
Short-circuitDownstream operation not executed; correct response or rejection
Handler called twiceAllowed only under explicit reviewed operation policy
Unexpected exceptionNo fabricated success; cleanup and propagation correct
Async invocationCorrect async hook path, no blocking or missing await
Concurrent subjectsNo shared mutable identity or request state
CancellationResources cleaned up; external uncertain outcome reconciled
Interrupt and resumeMiddleware behavior matches documented graph semantics
Logging and telemetryNo unintended sensitive-data disclosure
SDK upgradeHook API, composition order, result contracts and regression fixtures reverified

Use actual trace events and independent terminal counters to detect accidental double delegation. Validate both ordinary successful behavior and negative scenarios. A chain that blocks all requests is not a correct policy. Similarly, a chain that returns the expected final text but invokes a sensitive tool twice is not acceptable.

Track model calls, tool calls, wrapper entry counts, retry attempts, rejection categories, exceptions, cancellation outcomes and operation latency. Distinguish end-to-end latency from individual attempt timing. Use safe request correlations and configuration revisions rather than unrestricted raw message logging.

For example, a hypothetical outer timer observes 900 ms for an operation that includes a failed 250 ms attempt, a 100 ms backoff and a successful 550 ms attempt. An inner timer might record 250 and 550 ms for the separate attempts. These illustrative numbers explain the measurement boundary; they are not measured LangChain performance.

A release should verify the final composed agent configuration, not merely individual middleware unit tests. Interactions between summarization, dynamic routing, tool filtering, approval and retries can introduce failures that isolated components do not expose.

Interview-ready answer#

I add middleware through the middleware list passed to create_agent. I use built-in middleware for supported common patterns and decorator-defined hooks for small custom concerns, or an AgentMiddleware subclass for reusable configured components. I distinguish node lifecycle hooks from wrapper hooks that delegate through a handler. I explicitly control ordering, short-circuiting, state changes, request overrides and error propagation. I keep per-run state and trusted identity separate from shared middleware configuration, support the correct sync or async path, and enforce authorization independently of model instructions. Finally, I test the actual composed stack, including ordering, duplicate execution, failure, cancellation and provider-bound requests.

Official documentation research leads and verification status#

Authorized offline research exception applied. These official documentation URLs are research leads, not live-accessed citations. The exact standalone program was run locally on Python 3.13.5 and completed all assertions and expected-exception branches, printing 16 check groups passed. The local package inspection confirmed langchain, langchain_core and langgraph were absent. All framework snippets remain illustrative and unexecuted; actual SDK hook ordering, lifecycle dispatch, provider calls, graph persistence, distributed concurrency and live documentation were not verified. No real service, customer data or model invocation was used. Mermaid diagrams use triple-backtick fences; actual rendering and public website display were not tested.

References

  1. 1.
  2. 2.
  3. 3.
    LangChain custom middlewaredocs.langchain.com
  4. 4.
    LangChain agentsdocs.langchain.com
  5. 5.
    LangChain runtimedocs.langchain.com
  6. 6.
    LangChain API referencereference.langchain.com
  7. 7.
    Python asyncio tasksdocs.python.org
  8. 8.
    Python functoolsdocs.python.org

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps