Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/oss/langchain/middleware/custom.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -373,30 +373,36 @@ Middleware can extend the agent's state with custom properties.
<Tab title="Decorator">

```python
from langchain.agents import create_agent
from langchain_core.messages import HumanMessage
from langchain.agents.middleware import AgentState, before_model, after_model
from typing_extensions import NotRequired
from typing import Any
from langgraph.runtime import Runtime


class CustomState(AgentState):
model_call_count: NotRequired[int]
user_id: NotRequired[str]


@before_model(state_schema=CustomState, can_jump_to=["end"])
def check_call_limit(state: CustomState, runtime: Runtime) -> dict[str, Any] | None:
count = state.get("model_call_count", 0)
if count > 10:
return {"jump_to": "end"}
return None


@after_model(state_schema=CustomState)
def increment_counter(state: CustomState, runtime: Runtime) -> dict[str, Any] | None:
return {"model_call_count": state.get("model_call_count", 0) + 1}


agent = create_agent(
model="gpt-4o",
middleware=[check_call_limit, increment_counter],
tools=[...],
tools=[],
)

# Invoke with custom state
Expand All @@ -412,14 +418,18 @@ result = agent.invoke({
<Tab title="Class">

```python
from langchain.agents import create_agent
from langchain_core.messages import HumanMessage
from langchain.agents.middleware import AgentState, AgentMiddleware
from typing_extensions import NotRequired
from typing import Any


class CustomState(AgentState):
model_call_count: NotRequired[int]
user_id: NotRequired[str]


class CallCounterMiddleware(AgentMiddleware[CustomState]):
state_schema = CustomState

Expand All @@ -432,10 +442,11 @@ class CallCounterMiddleware(AgentMiddleware[CustomState]):
def after_model(self, state: CustomState, runtime) -> dict[str, Any] | None:
return {"model_call_count": state.get("model_call_count", 0) + 1}


agent = create_agent(
model="gpt-4o",
middleware=[CallCounterMiddleware()],
tools=[...],
tools=[],
)

# Invoke with custom state
Expand Down