AI AgentsLangChain
How do before_model and after_model middleware hooks work?
Question 318 of 324 · Updated
On this page
- Direct answer
- 1. Where the hooks run
- 2. Understand AgentState and Runtime
- State versus temporary request
- 3. Decorator-based lifecycle hooks
- 4. Class-based hooks
- 5. Ordering and repeated model iterations
- 6. Conditional routing and jump_to
- 7. Tested Python: lifecycle simulation
- Interpretation and limitations
- 8. Synchronous and asynchronous lifecycle hooks
- 9. Interruption, error propagation and validation
- 10. Production evaluation
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
before_model and after_model are node-style lifecycle hooks that run around each model step in a LangChain agent's execution graph. The former observes the current AgentState before the model operation; the latter observes the state after the model response has been incorporated, before the ordinary next routing decision. They can return supported partial state updates and, where configured, a jump_to routing directive. Register decorator-based hooks or AgentMiddleware subclasses through the middleware list of create_agent.
They are different from wrap_model_call: a wrapper receives a request and a handler, whereas a node hook participates in graph execution and state transitions. Use the node hooks when a decision depends on the current graph state, not when you need to measure or intercept the exact network attempt.
This lesson follows LangChain source #37 (AI Agents #317), which introduced middleware registration and composition. Source #4 (#284) explains the agent loop; #29 (#309) explains request-only history trimming. Here the distinct objective is per-model-step lifecycle execution, routing and validation. The next lessons cover state mutation, dynamic prompts, limits and guardrails in depth.
1. Where the hooks run#
A single invocation can use the model more than once. A model might propose a tool call, receive a tool result, and then produce a final response. Both model steps ordinarily have their own before_model and after_model boundaries.
This is the conceptual normal path, not a guarantee that every hook executes on every exception, retry, jump or interrupt. In particular, after_model is not Python's finally block. A failed model operation might never produce a response to incorporate. A middleware wrapper can perform cleanup around an operation, and a host can manage resources across an invocation, independently of the after_model node.
| Boundary | What it can normally observe | What not to assume |
|---|---|---|
| before_agent | Initial invocation state | It repeats before every model step |
| before_model | Current messages and working state | It runs for every provider retry |
| wrap_model_call | Effective model request and handler | Request overrides persist into state |
| after_model | State including the model response | A proposed tool has already executed |
| after_agent | Normal final path | It runs after every failure or cancellation |
A model-call wrapper may delegate twice because it implements a fallback or a bounded retry. That can produce multiple underlying attempts inside one graph model step. Counting before_model invocations is therefore not exact provider-call or token accounting. Count actual provider operations at their boundary when that distinction matters.
2. Understand AgentState and Runtime#
A typical modern hook receives an AgentState and a Runtime. AgentState includes the messages channel and may include custom typed fields configured in the agent's supported schema. Runtime provides invocation-scoped context and, where configured, other runtime facilities. The precise imports and generic typing are release-dependent.
The state can include the latest user request, prior assistant responses, tool observations, and an explicit task phase. A hook must not assume the final message is always a HumanMessage. On a later model iteration, the last message may be a ToolMessage or a supported sequence of tool observations.
The runtime context is supplied by the trusted application at invocation. Use it for approved identity and service dependencies rather than storing credentials or live clients in checkpointed messages. The model cannot establish authorization by writing an assistant message saying it has permission.
Node hooks commonly return None for no state update, or a supported dictionary of updates. Treat that dictionary as a partial update to the graph, not a full replacement for its state. The graph's reducers determine the resulting value. For example, a message-aware reducer may merge by ID rather than replace the entire message sequence. The next source question explores reducer semantics and state changes more deeply.
State versus temporary request#
A before_model hook returning an update can change the state observed by later graph nodes. A wrap_model_call using request.override can change the effective model request without intending a durable state mutation. Do not return a shortened history as a state update merely because the next model request must be smaller. Use the mechanism appropriate to the actual persistence contract.
3. Decorator-based lifecycle hooks#
The following example is a minimal illustrative modern LangChain configuration. It observes lifecycle events without copying private conversation content into telemetry.
PYTHONimport logging from langchain.agents import AgentState, create_agent from langchain.agents.middleware import before_model, after_model from langgraph.runtime import Runtime log = logging.getLogger("demo.lifecycle") @before_model def observe_input(state: AgentState, runtime: Runtime): log.info("before_model message_count=%d", len(state["messages"])) return None @after_model def observe_output(state: AgentState, runtime: Runtime): log.info("after_model message_count=%d", len(state["messages"])) return None agent = create_agent( model="openai:gpt-4o-mini", tools=[], middleware=[observe_input, observe_output], system_prompt="Provide fictional read-only support.", )
SDK verification limitation: Python 3.13.5 is available locally, but langchain, langchain_core and langgraph are not installed. The SDK snippets are illustrative and unexecuted. The separate lifecycle simulation in section 7 was actually executed; all 12 scenario groups passed. Under the authorized offline research exception, documentation URLs are research leads, not live-verified references. Confirm the exact hook signatures, decorator forms, state behavior and model configuration against a pinned release.
The example logs message counts only. It does not inspect the full transcript or guarantee that the output has been accepted by business logic. In production, protect telemetry against failures that could mask the original exception, avoid retaining sensitive payloads and account for the cost of observability.
A decorator is suitable for a focused independent concern. A class-based component is often more convenient when several hooks share immutable configuration.
4. Class-based hooks#
The AgentMiddleware subclass can implement multiple lifecycle hooks. Here the example records the boundary labels and checks that a supported model response is present before treating the model stage as observed.
PYTHONfrom langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langchain_core.messages import AIMessage from langgraph.runtime import Runtime class ObserveModelLifecycle(AgentMiddleware): def before_model(self, state: AgentState, runtime: Runtime): log.info("model stage entered") return None def after_model(self, state: AgentState, runtime: Runtime): if not state["messages"] or not isinstance(state["messages"][-1], AIMessage): raise ValueError("Unexpected model-stage message") log.info("model response observed") return None
Register ObserveModelLifecycle() in the middleware list when testing this alternative configuration. This snippet assumes a normal chat-model response represented by AIMessage. Verify the actual supported model and middleware response contracts, especially custom structured-output integrations and error routes. This is an illustrative stage invariant, not a general guardrail or factual validation system.
Do not maintain self.current_user or self.last_response on a reused middleware instance. Different invocations can overlap. Use the state and trusted runtime supplied to each hook. Keep static configuration immutable, and make injected dependencies safe for the intended execution model.
5. Ordering and repeated model iterations#
Modern LangChain middleware normally runs before-style hooks in the configured list order and after-style hooks in reverse order. This can be conceptualized as A before B before the model, followed by B after A. Verify the exact ordering of the installed release, including explicit jumps and conditional routes; lifecycle nodes are not the same as nested Python wrapper functions.
This sequence shows conceptual control flow, not literal method calls between middleware objects. The graph runtime schedules the hooks. In the ordinary two-step fixture, A and B each run before and after two model steps, and the tool executes once. A rejected before_model can stop the model from being called at all. A jump after_model can change the next route. Later hooks may be skipped depending on the graph's supported routing semantics.
Consider a metric counting model-step admissions. If before_model increments a counter but the model subsequently fails, that count may represent admitted steps rather than successful responses. If an after_model hook counts accepted AI responses, it measures a different quantity. Keep those counters named and interpreted correctly.
6. Conditional routing and jump_to#
Some modern LangChain node hooks support returning jump_to together with state updates. Declare permitted destinations using the supported API, for example before_model(can_jump_to=["end"]) in compatible versions. Typical destination labels in modern versions include model, tools and end, but their availability, appropriate hook types and control flow are version-dependent. Do not send arbitrary model-generated node names.
For a narrow demonstration, assume the trusted host supplies a read-only invocation context with a prevalidated allow_model flag. If the current turn has not begun a tool exchange and the last message is a HumanMessage, the hook can end with a controlled explanation when model access is unavailable.
PYTHONfrom dataclasses import dataclass from langchain.agents import AgentState, create_agent from langchain.agents.middleware import before_model from langchain_core.messages import AIMessage, HumanMessage from langgraph.runtime import Runtime @dataclass(frozen=True) class InvocationContext: allow_model: bool @before_model(can_jump_to=["end"]) def admit_model_step(state: AgentState, runtime: Runtime[InvocationContext]): if runtime.context.allow_model: return None messages = state["messages"] if messages and isinstance(messages[-1], HumanMessage): # Host must also establish that no tool exchange is pending. return { "messages": [AIMessage(content="Model access is unavailable for this request.")], "jump_to": "end", } raise PermissionError("Model step unavailable in current execution state") agent = create_agent( model="openai:gpt-4o-mini", tools=[], middleware=[admit_model_step], context_schema=InvocationContext, ) # Pass context=InvocationContext(allow_model=...) from trusted host code.
The SDK code is unexecuted. It intentionally uses a tool-free illustrative agent; the host owns the flag and must never accept it from model-generated content. Verify the actual routing directive and the resulting final state. The returned AIMessage is an application-authored refusal rather than a generated model answer. If an application returns a structured response or requires other completion fields, a simple message plus jump_to may not fulfill its contract.
Do not end a tool-enabled graph with an unresolved AI tool-call proposal and then resume as if the conversation were complete. A tool result must correspond to an actual operation, and a proposal must not be silently transformed into a success. A real after_model gate that rejects proposed tools must use the supported protocol-aware handling path, preserve the relevant state and avoid dangling calls.
A route is control flow, not an access grant. Even if a hook directs execution to tools, the tool and domain service must independently authorize the requested operation. Avoid routing loops: a jump back to a model step must have a bounded policy and a reason for expected progress.
7. Tested Python: lifecycle simulation#
The following independent standard-library simulation implements a small, explicit contract: before hooks run in list order, after hooks run in reverse order, permitted route values are next and end, and ordinary model outcomes are answer or tool. It demonstrates repeated model steps, early exit, exception propagation and a bounded loop. A separate asynchronous fixture tests request-local updates and cancellation cleanup.
It is not LangGraph, does not implement actual message reducers, and does not claim to reproduce the SDK's jump_to behavior. All 12 scenario groups were genuinely executed before publication.
PYTHONfrom dataclasses import dataclass, replace import asyncio, importlib.util, sys @dataclass(frozen=True) class State: calls: int = 0 result: str = '' class Halt(Exception): pass class Paused(Exception): pass def run(state, before, after, model, tool, limit=3): for _ in range(limit): for hook in before: state, route = hook(state) if route == 'end': return state if route != 'next': raise ValueError('invalid before route') state = replace(state, calls=state.calls+1, result=model(state)) for hook in reversed(after): state, route = hook(state) if route == 'end': return state if route != 'next': raise ValueError('invalid after route') if state.result == 'answer': return state if state.result != 'tool': raise ValueError('invalid result') tool(state) raise Halt('iteration limit') def fixture(outputs, *, cap=3, stop=False): events=[]; it=iter(outputs) def before_a(s): events.append('before_a') return s, 'end' if s.calls>=cap else 'next' def before_b(s): events.append('before_b'); return s,'next' def after_a(s): events.append('after_a'); return s,'next' def after_b(s): events.append('after_b'); return s,'end' if stop else 'next' def model(s): events.append('model'); return next(it) def tool(s): events.append('tool') return events, lambda: run(State(),[before_a,before_b],[after_a,after_b],model,tool) def reject(exc, f): try: f() except exc: return raise AssertionError('expected exception') cycle=['before_a','before_b','model','after_b','after_a'] e,f=fixture(['answer']); assert f()==State(1,'answer') and e==cycle e,f=fixture(['tool','answer']); assert f()==State(2,'answer') and e==cycle+['tool']+cycle e,f=fixture([],cap=0); assert f()==State() and e==['before_a'] e,f=fixture(['tool'],stop=True); assert f()==State(1,'tool') and e==cycle[:-1] e,f=fixture(['tool'],cap=1); assert f()==State(1,'tool') and e==cycle+['tool','before_a'] e,f=fixture(['invalid']); reject(ValueError,f); assert e==cycle calls=[] def broken(s): calls.append('model'); raise RuntimeError('failure') reject(RuntimeError,lambda:run(State(),[],[lambda s:(calls.append('after') or s,'next')],broken,lambda s:None)); assert calls==['model'] def pause(s): raise Paused('pause') reject(Paused,lambda:run(State(),[pause],[],broken,lambda s:None)); assert calls==['model'] reject(ValueError,lambda:run(State(),[lambda s:(s,'tools')],[],broken,lambda s:None)); assert calls==['model'] reject(Halt,lambda:run(State(),[],[],lambda s:'tool',lambda s:None,limit=0)) async def async_test(): async def hook(s): await asyncio.sleep(0) return replace(s,calls=s.calls+1) assert await asyncio.gather(hook(State(1)),hook(State(5)))==[State(2),State(6)] entered=asyncio.Event(); cleaned=[] async def blocked(): try: entered.set(); await asyncio.Event().wait() finally: cleaned.append(True) task=asyncio.create_task(blocked()); await entered.wait(); task.cancel() try: await task except asyncio.CancelledError: pass else: raise AssertionError('cancellation swallowed') assert cleaned==[True] asyncio.run(async_test()) print('12 scenario 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:
12 scenario groups passed
3.13.5 {'langchain': False, 'langchain_core': False, 'langgraph': False}| Scenario group | Verified outcome |
|---|---|
| Ordinary final answer | Before A, before B, model, after B, after A |
| Tool then answer | Two complete hook cycles, one simulated tool event |
| Pre-model admission stops | No model or downstream hook |
| After-model early end | Stops before remaining after hook and tool |
| One-step admission cap | A later model iteration is prevented |
| Unsupported model outcome | Controlled ValueError |
| Model exception | Original failure propagates; after hook not entered |
| Simulated pause | Stops before model |
| Unsupported route | Rejected |
| Zero iteration budget | Halt raised without model execution |
| Concurrent async state operations | Independent immutable results |
| Async cancellation | CancelledError propagates and finally cleanup runs |
Interpretation and limitations#
The teaching runtime calls before hooks in order, applies a simulated model response, invokes after hooks in reverse order and then selects the next branch. It has an outer iteration cap and a separate before-hook admission cap. These are intentionally simple policies rather than LangGraph recursion limits or middleware call limits.
The model receives the pre-increment State; calls counts modeled completed model-return steps. If the model raises, no new State is returned. The toy tool only records an event, so it does not update result or create a ToolMessage. In particular the after-model early-exit fixture returns result='tool' without executing a tool. That is a stopped simulation, not a valid resumable production transcript or a successful completed task. The test verifies control-flow termination only.
Paused is an ordinary synthetic exception; it does not test LangGraph interrupt, checkpointing, restart or Command resume. The zero-budget fixture tests an immediate bound, not a long-running loop or actual token accounting. The asynchronous checks test two standalone coroutines and cancellation cleanup, not the entire asynchronous agent lifecycle. No model, external service, actual authorization or tool messages were used.
8. Synchronous and asynchronous lifecycle hooks#
Class-based middleware can commonly implement abefore_model and aafter_model for the asynchronous path. Confirm whether your pinned release requires separate sync and async implementations, and how decorators recognize async functions.
PYTHONfrom langchain.agents.middleware import AgentMiddleware class AsyncLifecycle(AgentMiddleware): async def abefore_model(self, state, runtime): # Use an approved non-blocking service if I/O is needed. return None async def aafter_model(self, state, runtime): return None
This SDK example is unexecuted. A no-op hook is only a skeleton, not a meaningful validation or timing component. Use the correct agent invocation interface, such as ainvoke where supported, and test the installed runtime actually dispatches the intended method. If a policy is required on both sync and async paths, ensure both enforce equivalent invariants.
Do not block the event loop with synchronous network I/O or expensive computation inside an async hook. Respect deadlines and cancellation. If a remote operation may have started, cancellation does not prove it stopped or rolled back. Use operation-specific reconciliation for uncertain outcomes.
9. Interruption, error propagation and validation#
An interrupt can pause graph execution while awaiting an external decision. In compatible LangGraph deployments, a checkpointer and supported interrupt/resume contract allow continuation. The interrupted node may execute again from its beginning upon resume. Consequently, code before an interrupt must be safe to replay. Do not treat an audit write, notification or external mutation in a node hook as exactly-once merely because it precedes the model.
Keep interruption distinct from an exception and from a terminal jump. A jump_to end normally chooses a termination route; it does not create a resumable approval checkpoint by itself. A model error may propagate without an after_model response. A tool proposal can exist without its execution result. A cancelled invocation may leave an uncertain external effect.
| Event | Appropriate invariant |
|---|---|
| before_model validation fails | Do not invoke the model on the prohibited path |
| Model fails before response | Do not fabricate an after-model result |
| after_model rejects response | Do not execute an unauthorized proposed action |
| Hook intentionally interrupts | Resume only through supported authorized protocol |
| Unexpected exception | Preserve failure; avoid claiming success |
| Cancellation | Clean up resources and reconcile uncertain effects |
| Replayed node | No unintended duplicate external operation |
Check whether a particular routing directive skips other middleware nodes in your installed graph. Do not rely on a later validation hook to enforce a policy if an earlier hook can bypass it. Independent action authorization and final output acceptance remain necessary. Detailed guardrail and retry lessons follow.
10. Production evaluation#
Use a pinned LangChain and LangGraph environment with scripted model responses and synthetic tools. Record event order, actual terminal invocations and graph state. Test the actual graph rather than relying only on a pure lifecycle simulation.
| Integration test | Acceptance condition |
|---|---|
| One final model response | Correct before and after sequence |
| Tool-enabled multi-step turn | Hooks repeat around each intended model step |
| Multiple lifecycle components | Installed ordering established |
| Explicit permitted route | Correct destination and output contract |
| Unsupported route | Controlled failure, no unsafe default |
| Partial state update | Expected reducer and checkpoint effects |
| Model wrapper retries | Hook counts distinguished from actual attempts |
| Pre-model stop | No underlying provider call |
| Rejected tool proposal | No unauthorized domain execution; valid message protocol |
| Model or hook exception | Original failure and intended state handling |
| Async invocation | Correct hook implementation used |
| Interrupted and resumed node | Correct recovery and no unintended replay side effects |
| Concurrent threads | No shared mutable state contamination |
| Model/SDK upgrade | Trace, routing and state contracts reverified |
Track hook entry and completion counts, actual model and tool calls, route decisions, validation failures, unexpected exceptions, interruption/resumption counts and latency. Avoid raw private messages in routine telemetry. Verify a positive authorized path as well as rejection paths; an agent that terminates every request is not a successful implementation.
Interview-ready answer#
I use before_model and after_model as per-model-step graph lifecycle hooks, configured with decorators or an AgentMiddleware subclass. They receive the current state and runtime and may return supported partial state updates. Before hooks generally run in configured order and after hooks in reverse order. They repeat across model-tool iterations, but are not guaranteed to surround each provider retry or execute after a failure. Where supported, I declare allowed jump_to destinations and use controlled routing without breaking message or tool-call consistency. I keep trusted context separate from model output, test async and interruption behavior, and independently enforce execution permissions.
Official documentation research leads and verification status#
- LangChain custom middleware
- LangChain middleware overview
- LangChain agents
- LangChain runtime
- LangGraph interrupts
- LangGraph persistence
- LangChain API reference
- Python asyncio tasks
Authorized offline research exception applied. Official documentation URLs are unverified research leads. The exact standalone program was executed locally on Python 3.13.5; all 12 scenario groups passed. Package inspection confirmed langchain, langchain_core and langgraph were absent. SDK hook dispatch, actual jump_to routing, checkpoint resumption, tool-message consistency, provider calls, distributed execution, live documentation and public website rendering remain unverified. Mermaid diagrams use triple-backtick fences; rendering was not tested.
References
- 1.LangChain custom middlewaredocs.langchain.com
- 2.LangChain middleware overviewdocs.langchain.com
- 3.LangChain agentsdocs.langchain.com
- 4.LangChain runtimedocs.langchain.com
- 5.LangGraph interruptsdocs.langchain.com
- 6.LangGraph persistencedocs.langchain.com
- 7.LangChain API referencereference.langchain.com
- 8.Python asyncio tasksdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps