Skip to content

The agent engineering platform.

fix(langchain_v1): keep state to relevant middlewares for tool/model call limits (#33493)

Sydney Runkle8f6851c34970
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.py
index 32d3e9b6af..41538cd266 100644
--- a/libs/langchain_v1/langchain/agents/factory.py
+++ b/libs/langchain_v1/langchain/agents/factory.py
@@ -1031,11 +1031,7 @@ def create_agent( # noqa: PLR0915
if response.structured_response is not None:
state_updates["structured_response"] = response.structured_response
- return {
- "thread_model_call_count": state.get("thread_model_call_count", 0) + 1,
- "run_model_call_count": state.get("run_model_call_count", 0) + 1,
- **state_updates,
- }
+ return state_updates
async def _execute_model_async(request: ModelRequest) -> ModelResponse:
"""Execute model asynchronously and return response.
@@ -1086,11 +1082,7 @@ def create_agent( # noqa: PLR0915
if response.structured_response is not None:
state_updates["structured_response"] = response.structured_response
- return {
- "thread_model_call_count": state.get("thread_model_call_count", 0) + 1,
- "run_model_call_count": state.get("run_model_call_count", 0) + 1,
- **state_updates,
- }
+ return state_updates
# Use sync or async based on model capabilities
graph.add_node("model", RunnableCallable(model_node, amodel_node, trace=False))
diff --git a/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py b/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py
index 63f0be50fd..326e185000 100644
--- a/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py
+++ b/libs/langchain_v1/langchain/agents/middleware/model_call_limit.py
@@ -2,16 +2,33 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Literal
+from typing import TYPE_CHECKING, Annotated, Any, Literal
from langchain_core.messages import AIMessage
+from langgraph.channels.untracked_value import UntrackedValue
+from typing_extensions import NotRequired
-from langchain.agents.middleware.types import AgentMiddleware, AgentState, hook_config
+from langchain.agents.middleware.types import (
+ AgentMiddleware,
+ AgentState,
+ PrivateStateAttr,
+ hook_config,
+)
if TYPE_CHECKING:
from langgraph.runtime import Runtime
+class ModelCallLimitState(AgentState):
+ """State schema for ModelCallLimitMiddleware.
+
+ Extends AgentState with model call tracking fields.
+ """
+
+ thread_model_call_count: NotRequired[Annotated[int, PrivateStateAttr]]
+ run_model_call_count: NotRequired[Annotated[int, UntrackedValue, PrivateStateAttr]]
+
+
def _build_limit_exceeded_message(
thread_count: int,
run_count: int,
@@ -69,7 +86,7 @@ class ModelCallLimitExceededError(Exception):
super().__init__(msg)
-class ModelCallLimitMiddleware(AgentMiddleware):
+class ModelCallLimitMiddleware(AgentMiddleware[ModelCallLimitState, Any]):
"""Middleware that tracks model call counts and enforces limits.
This middleware monitors the number of model calls made during agent execution
@@ -97,6 +114,8 @@ class ModelCallLimitMiddleware(AgentMiddleware):
```
"""
+ state_schema = ModelCallLimitState
+
def __init__(
self,
*,
@@ -135,7 +154,7 @@ class ModelCallLimitMiddleware(AgentMiddleware):
self.exit_behavior = exit_behavior
@hook_config(can_jump_to=["end"])
- def before_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
+ def before_model(self, state: ModelCallLimitState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
"""Check model call limits before making a model call.
Args:
@@ -175,3 +194,18 @@ class ModelCallLimitMiddleware(AgentMiddleware):
return {"jump_to": "end", "messages": [limit_ai_message]}
return None
+
+ def after_model(self, state: ModelCallLimitState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
+ """Increment model call counts after a model call.
+
+ Args:
+ state: The current agent state.
+ runtime: The langgraph runtime.
+
+ Returns:
+ State updates with incremented call counts.
+ """
+ return {
+ "thread_model_call_count": state.get("thread_model_call_count", 0) + 1,
+ "run_model_call_count": state.get("run_model_call_count", 0) + 1,
+ }
diff --git a/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py b/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py
index 52c5d488be..4afe2f97b3 100644
--- a/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py
+++ b/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py
@@ -2,16 +2,37 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Literal
+from typing import TYPE_CHECKING, Annotated, Any, Literal
from langchain_core.messages import AIMessage, AnyMessage, HumanMessage
+from langgraph.channels.untracked_value import UntrackedValue
+from typing_extensions import NotRequired
-from langchain.agents.middleware.types import AgentMiddleware, AgentState, hook_config
+from langchain.agents.middleware.types import (
+ AgentMiddleware,
+ AgentState,
+ PrivateStateAttr,
+ hook_config,
+)
if TYPE_CHECKING:
from langgraph.runtime import Runtime
+class ToolCallLimitState(AgentState):
+ """State schema for ToolCallLimitMiddleware.
+
+ Extends AgentState with tool call tracking fields.
+
+ The count fields are dictionaries mapping tool names to execution counts.
+ This allows multiple middleware instances to track different tools independently.
+ The special key "__all__" is used for tracking all tool calls globally.
+ """
+
+ thread_tool_call_count: NotRequired[Annotated[dict[str, int], PrivateStateAttr]]
+ run_tool_call_count: NotRequired[Annotated[dict[str, int], UntrackedValue, PrivateStateAttr]]
+
+
def _count_tool_calls_in_messages(messages: list[AnyMessage], tool_name: str | None = None) -> int:
"""Count tool calls in a list of messages.
@@ -124,18 +145,18 @@ class ToolCallLimitExceededError(Exception):
super().__init__(msg)
-class ToolCallLimitMiddleware(AgentMiddleware):
+class ToolCallLimitMiddleware(AgentMiddleware[ToolCallLimitState, Any]):
"""Middleware that tracks tool call counts and enforces limits.
This middleware monitors the number of tool calls made during agent execution
and can terminate the agent when specified limits are reached. It supports
both thread-level and run-level call counting with configurable exit behaviors.
- Thread-level: The middleware counts all tool calls in the entire message history
- and persists this count across multiple runs (invocations) of the agent.
+ Thread-level: The middleware tracks the total number of tool calls and persists
+ call count across multiple runs (invocations) of the agent.
- Run-level: The middleware counts tool calls made after the last HumanMessage,
- representing the current run (invocation) of the agent.
+ Run-level: The middleware tracks the number of tool calls made during a single
+ run (invocation) of the agent.
Example:
```python
@@ -157,6 +178,8 @@ class ToolCallLimitMiddleware(AgentMiddleware):
```
"""
+ state_schema = ToolCallLimitState
+
def __init__(
self,
*,
@@ -211,11 +234,11 @@ class ToolCallLimitMiddleware(AgentMiddleware):
return base_name
@hook_config(can_jump_to=["end"])
- def before_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
+ def before_model(self, state: ToolCallLimitState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
"""Check tool call limits before making a model call.
Args:
- state: The current agent state containing messages.
+ state: The current agent state containing tool call counts.
runtime: The langgraph runtime.
Returns:
@@ -226,14 +249,14 @@ class ToolCallLimitMiddleware(AgentMiddleware):
ToolCallLimitExceededError: If limits are exceeded and exit_behavior
is "error".
"""
- messages = state.get("messages", [])
+ # Get the count key for this middleware instance
+ count_key = self.tool_name if self.tool_name else "__all__"
- # Count tool calls in entire thread
- thread_count = _count_tool_calls_in_messages(messages, self.tool_name)
+ thread_counts = state.get("thread_tool_call_count", {})
+ run_counts = state.get("run_tool_call_count", {})
- # Count tool calls in current run (after last HumanMessage)
- run_messages = _get_run_messages(messages)
- run_count = _count_tool_calls_in_messages(run_messages, self.tool_name)
+ thread_count = thread_counts.get(count_key, 0)
+ run_count = run_counts.get(count_key, 0)
# Check if any limits are exceeded
thread_limit_exceeded = self.thread_limit is not None and thread_count >= self.thread_limit
@@ -258,3 +281,53 @@ class ToolCallLimitMiddleware(AgentMiddleware):
return {"jump_to": "end", "messages": [limit_ai_message]}
return None
+
+ def after_model(self, state: ToolCallLimitState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
+ """Increment tool call counts after a model call (when tool calls are made).
+
+ Args:
+ state: The current agent state.
+ runtime: The langgraph runtime.
+
+ Returns:
+ State updates with incremented tool call counts if tool calls were made.
+ """
+ # Get the last AIMessage to check for tool calls
+ messages = state.get("messages", [])
+ if not messages:
+ return None
+
+ # Find the last AIMessage
+ last_ai_message = None
+ for message in reversed(messages):
+ if isinstance(message, AIMessage):
+ last_ai_message = message
+ break
+
+ if not last_ai_message or not last_ai_message.tool_calls:
+ return None
+
+ # Count relevant tool calls (filter by tool_name if specified)
+ tool_call_count = 0
+ for tool_call in last_ai_message.tool_calls:
+ if self.tool_name is None or tool_call["name"] == self.tool_name:
+ tool_call_count += 1
+
+ if tool_call_count == 0:
+ return None
+
+ # Get the count key for this middleware instance
+ count_key = self.tool_name if self.tool_name else "__all__"
+
+ # Get current counts
+ thread_counts = state.get("thread_tool_call_count", {}).copy()
+ run_counts = state.get("run_tool_call_count", {}).copy()
+
+ # Increment counts for this key
+ thread_counts[count_key] = thread_counts.get(count_key, 0) + tool_call_count
+ run_counts[count_key] = run_counts.get(count_key, 0) + tool_call_count
+
+ return {
+ "thread_tool_call_count": thread_counts,
+ "run_tool_call_count": run_counts,
+ }
diff --git a/libs/langchain_v1/langchain/agents/middleware/types.py b/libs/langchain_v1/langchain/agents/middleware/types.py
index ba5c733a46..ecaa65b4db 100644
--- a/libs/langchain_v1/langchain/agents/middleware/types.py
+++ b/libs/langchain_v1/langchain/agents/middleware/types.py
@@ -26,7 +26,6 @@ from typing import TypeAlias
from langchain_core.messages import AIMessage, AnyMessage, BaseMessage, ToolMessage # noqa: TC002
from langgraph.channels.ephemeral_value import EphemeralValue
-from langgraph.channels.untracked_value import UntrackedValue
from langgraph.graph.message import add_messages
from langgraph.types import Command # noqa: TC002
from langgraph.typing import ContextT
@@ -171,8 +170,6 @@ class AgentState(TypedDict, Generic[ResponseT]):
messages: Required[Annotated[list[AnyMessage], add_messages]]
jump_to: NotRequired[Annotated[JumpTo | None, EphemeralValue, PrivateStateAttr]]
structured_response: NotRequired[Annotated[ResponseT, OmitFromInput]]
- thread_model_call_count: NotRequired[Annotated[int, PrivateStateAttr]]
- run_model_call_count: NotRequired[Annotated[int, UntrackedValue, PrivateStateAttr]]
class PublicAgentState(TypedDict, Generic[ResponseT]):
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_tool_call_limit.py b/libs/langchain_v1/tests/unit_tests/agents/test_tool_call_limit.py
index d38849a040..e283aad527 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_tool_call_limit.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_tool_call_limit.py
@@ -149,7 +149,9 @@ def test_middleware_unit_functionality():
"Response",
tool_calls=[{"name": "search", "args": {}, "id": "1"}],
),
- ]
+ ],
+ "thread_tool_call_count": {},
+ "run_tool_call_count": {},
}
result = middleware.before_model(state, runtime) # type: ignore[arg-type]
assert result is None
@@ -172,7 +174,9 @@ def test_middleware_unit_functionality():
"Response 2",
tool_calls=[{"name": "search", "args": {}, "id": "3"}],
),
- ]
+ ],
+ "thread_tool_call_count": {"__all__": 3}, # 2 from first AI message + 1 from second
+ "run_tool_call_count": {"__all__": 1}, # 1 from second AI message (after HumanMessage)
}
result = middleware.before_model(state, runtime) # type: ignore[arg-type]
assert result is not None
@@ -192,7 +196,9 @@ def test_middleware_unit_functionality():
{"name": "calculator", "args": {}, "id": "2"},
],
),
- ]
+ ],
+ "thread_tool_call_count": {"__all__": 2},
+ "run_tool_call_count": {"__all__": 2}, # 2 tool calls in current run
}
result = middleware.before_model(state, runtime) # type: ignore[arg-type]
assert result is not None
@@ -218,7 +224,9 @@ def test_middleware_with_specific_tool():
{"name": "calculator", "args": {}, "id": "2"},
],
),
- ]
+ ],
+ "thread_tool_call_count": {"search": 1}, # 1 search call
+ "run_tool_call_count": {"search": 1}, # 1 search call in current run
}
# Run limit for search is 1, should be exceeded
result = middleware.before_model(state, runtime) # type: ignore[arg-type]
@@ -237,7 +245,9 @@ def test_middleware_with_specific_tool():
{"name": "calculator", "args": {}, "id": "2"},
],
),
- ]
+ ],
+ "thread_tool_call_count": {}, # 0 search calls
+ "run_tool_call_count": {}, # 0 search calls
}
result = middleware.before_model(state, runtime) # type: ignore[arg-type]
assert result is None
@@ -256,7 +266,9 @@ def test_middleware_error_behavior():
AIMessage("R", tool_calls=[{"name": "search", "args": {}, "id": "1"}]),
ToolMessage("Result", tool_call_id="1"),
AIMessage("R", tool_calls=[{"name": "search", "args": {}, "id": "2"}]),
- ]
+ ],
+ "thread_tool_call_count": {"__all__": 2}, # 2 tool calls total
+ "run_tool_call_count": {"__all__": 1}, # 1 tool call in current run
}
with pytest.raises(ToolCallLimitExceededError) as exc_info:
middleware.before_model(state, runtime) # type: ignore[arg-type]
@@ -270,7 +282,9 @@ def test_middleware_error_behavior():
"messages": [
HumanMessage("Question"),
AIMessage("R", tool_calls=[{"name": "search", "args": {}, "id": "1"}]),
- ]
+ ],
+ "thread_tool_call_count": {"__all__": 1},
+ "run_tool_call_count": {"__all__": 1}, # 1 tool call in current run
}
with pytest.raises(ToolCallLimitExceededError) as exc_info:
middleware.before_model(state, runtime) # type: ignore[arg-type]
@@ -397,7 +411,9 @@ def test_exception_error_messages():
AIMessage("R", tool_calls=[{"name": "search", "args": {}, "id": "2"}]),
ToolMessage("Result", tool_call_id="2"),
AIMessage("R", tool_calls=[{"name": "search", "args": {}, "id": "3"}]),
- ]
+ ],
+ "thread_tool_call_count": {"__all__": 3}, # 3 tool calls total
+ "run_tool_call_count": {"__all__": 2}, # 2 tool calls in current run
}
with pytest.raises(ToolCallLimitExceededError) as exc_info:
@@ -423,7 +439,11 @@ def test_exception_error_messages():
ToolMessage("Result", tool_call_id="1"),
ToolMessage("Result", tool_call_id="2"),
AIMessage("R", tool_calls=[{"name": "search", "args": {}, "id": "3"}]),
- ]
+ ],
+ "thread_tool_call_count": {
+ "search": 2
+ }, # 2 search calls total (calculator calls don't count)
+ "run_tool_call_count": {"search": 1}, # 1 search call in current run
}
with pytest.raises(ToolCallLimitExceededError) as exc_info: