AI AgentsLangChain

How do you modify agent state through middleware?

Question 319 of 324 · Updated

On this page

Direct answer#

Return a partial state update from a LangChain middleware lifecycle hook, rather than directly modifying the state dictionary. Define custom fields using an AgentState schema, register the middleware with create_agent, and let the graph apply the returned updates using its state reducers.

Use this approach when information needs to survive between agent steps, such as a response counter, task phase or validated evidence reference. If you only want to change the next model request, use wrap_model_call with a supported request override instead.

1. Practical example: count model responses#

Imagine a customer support agent that calls a model, uses a tool, and calls the model again to explain the result. You want to record how many model-response stages the agent has processed.

Add a responses_seen field to the agent state. An after_model hook reads the current count and returns an incremented value.

Loading diagram…

The hook returns only the changed field. The existing messages and unrelated state remain available.

2. Implement a custom state schema#

The following helper calculates the update independently of the framework. It also rejects malformed counters rather than silently accepting them.

PYTHON
def response_update(state): count = state.get("responses_seen", 0) if type(count) is not int or count < 0: raise ValueError("invalid counter") return {"responses_seen": count + 1}

Now connect that helper to LangChain middleware:

PYTHON
from typing import NotRequired from langchain.agents import AgentState, create_agent from langchain.agents.middleware import AgentMiddleware from langgraph.runtime import Runtime from langgraph.checkpoint.memory import InMemorySaver class SupportState(AgentState): responses_seen: NotRequired[int] class ResponseCounter(AgentMiddleware): state_schema = SupportState def after_model(self, state: SupportState, runtime: Runtime): return response_update(state) agent = create_agent( model="openai:gpt-4o-mini", tools=[], middleware=[ResponseCounter()], checkpointer=InMemorySaver(), ) result = agent.invoke( {"messages": [{"role": "user", "content": "Hello!"}]}, config={"configurable": {"thread_id": "demo-1"}}, ) print(result["responses_seen"])

For a fresh thread with one ordinary model response, the intended count is 1. A later invocation on the same thread can continue the counter. This measures processed model-response stages, not provider retry attempts or necessarily successful business tasks.

The middleware declares its own state_schema, which compatible modern LangChain versions incorporate into the agent's state contract. You can also define a shared agent-level schema through create_agent(state_schema=...). A supported decorator-based hook with a custom state schema is another option.

Testing: The helper was executed on Python 3.13.5. All eight checks passed: missing-counter initialization, increment, original-state preservation, unrelated-message preservation in a simple dictionary merge, repeated update, and rejection of negative, Boolean and string counters. LangChain and LangGraph were not installed locally, so the SDK integration and actual graph merge were not executed. The expected output is illustrative.

3. Understand reducers before changing state#

A reducer determines how an incoming update combines with the current value. Returning a dictionary does not mean every field uses ordinary dictionary replacement.

FieldTypical update behavior
Scalar counter or task phaseReplace the previous value
List with an additive reducerAppend or combine incoming items
Agent messagesMessage-aware merge, normally using message IDs

For a replacement counter, return the new total. For a counter explicitly configured with an additive reducer, return the increment instead. Mixing these approaches causes incorrect counts.

With the standard message-aware reducer, returning a message with an existing ID can replace the corresponding message. Returning a new message generally appends it. To remove selected messages, use supported RemoveMessage objects with the relevant message IDs; compatible releases also support a remove-all sentinel. Returning an empty list is not generally equivalent to clearing a reducer-managed message channel.

Be careful when replacing or removing messages: preserve required instructions, the current task and complete correlated tool-call/result exchanges.

4. Persistent state or temporary request?#

What you wantUse
Record a task phase for later stepsReturn a state update from a lifecycle hook
Count processed model-response stagesafter_model with a custom state field
Trim history only for the next model callwrap_model_call and request.override
Change the next model's toolsSupported model-request override
Save approved information across threadsScoped store or domain repository

A state update may be checkpointed when a checkpointer is configured. A temporary request override does not automatically update the stored graph state. InMemorySaver is suitable for development; use a compatible durable checkpointer for restart persistence.

5. Common mistakes and best practices#

  • Mutating state directly: Return the intended update through the supported hook contract instead of relying on in-place changes.
  • Conflicting writers: Give a field one clear update owner, or define a reducer suitable for concurrent graph writes. Two parallel read-increment-replace operations can lose an increment.
  • Trusting model-generated values: Validate fields and enforce permissions independently. A state field such as approved does not establish authorization.
  • Assuming exactly-once execution: Interruptions and resumed nodes can cause replay. Reconcile external side effects separately; checkpointing does not make an external write atomic.
  • Mixing sync and async hooks: Provide the supported asynchronous counterpart, such as aafter_model, if the agent uses asynchronous execution.

For production, test the real middleware with a scripted model, multiple model steps, independent threads, concurrent updates and checkpoint restoration. Verify reducer behavior and actual persisted state instead of relying on the helper's dictionary-merge test.

Key takeaway#

Define the state field, read its current value in middleware, return a validated partial update, and let the graph's reducer apply it. Use request overrides when the change should affect only the next model call.

References

  1. 1.
    LangChain custom middlewaredocs.langchain.com
  2. 2.
    LangChain agentsdocs.langchain.com
  3. 3.
    LangChain short-term memorydocs.langchain.com
  4. 4.
    LangGraph persistencedocs.langchain.com

Related questions

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