Skip to content

The agent engineering platform.

fix: more robust tool call limit middleware (#33817)

Sydney Runkle1755750ca180
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.py
index cdbb44db0d..c81d3c5d4f 100644
--- a/libs/langchain_v1/langchain/agents/factory.py
+++ b/libs/langchain_v1/langchain/agents/factory.py
@@ -3,7 +3,15 @@
from __future__ import annotations
import itertools
-from typing import TYPE_CHECKING, Annotated, Any, cast, get_args, get_origin, get_type_hints
+from typing import (
+ TYPE_CHECKING,
+ Annotated,
+ Any,
+ cast,
+ get_args,
+ get_origin,
+ get_type_hints,
+)
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage, AnyMessage, SystemMessage, ToolMessage
@@ -15,7 +23,7 @@ from langgraph.prebuilt.tool_node import ToolCallWithContext, ToolNode
from langgraph.runtime import Runtime # noqa: TC002
from langgraph.types import Command, Send
from langgraph.typing import ContextT # noqa: TC002
-from typing_extensions import NotRequired, Required, TypedDict, TypeVar
+from typing_extensions import NotRequired, Required, TypedDict
from langchain.agents.middleware.types import (
AgentMiddleware,
@@ -24,6 +32,8 @@ from langchain.agents.middleware.types import (
ModelRequest,
ModelResponse,
OmitFromSchema,
+ ResponseT,
+ StateT_co,
_InputAgentState,
_OutputAgentState,
)
@@ -53,8 +63,6 @@ if TYPE_CHECKING:
STRUCTURED_OUTPUT_ERROR_TEMPLATE = "Error: {error}\n Please fix your mistakes."
-ResponseT = TypeVar("ResponseT")
-
def _normalize_to_model_response(result: ModelResponse | AIMessage) -> ModelResponse:
"""Normalize middleware return value to ModelResponse."""
@@ -509,7 +517,7 @@ def create_agent( # noqa: PLR0915
tools: Sequence[BaseTool | Callable | dict[str, Any]] | None = None,
*,
system_prompt: str | None = None,
- middleware: Sequence[AgentMiddleware[AgentState[ResponseT], ContextT]] = (),
+ middleware: Sequence[AgentMiddleware[StateT_co, ContextT]] = (),
response_format: ResponseFormat[ResponseT] | type[ResponseT] | None = None,
state_schema: type[AgentState[ResponseT]] | None = None,
context_schema: type[ContextT] | None = None,
@@ -785,7 +793,7 @@ def create_agent( # noqa: PLR0915
async_handlers = [m.awrap_model_call for m in middleware_w_awrap_model_call]
awrap_model_call_handler = _chain_async_model_call_handlers(async_handlers)
- state_schemas = {m.state_schema for m in middleware}
+ state_schemas: set[type] = {m.state_schema for m in middleware}
# Use provided state_schema if available, otherwise use base AgentState
base_state = state_schema if state_schema is not None else AgentState
state_schemas.add(base_state)
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 4dc7b5cf53..72e270cfd5 100644
--- a/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py
+++ b/libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py
@@ -2,24 +2,36 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Annotated, Any, Literal
+from typing import TYPE_CHECKING, Annotated, Any, Generic, Literal
-from langchain_core.messages import AIMessage
+from langchain_core.messages import AIMessage, ToolCall, ToolMessage
from langgraph.channels.untracked_value import UntrackedValue
+from langgraph.typing import ContextT
from typing_extensions import NotRequired
from langchain.agents.middleware.types import (
AgentMiddleware,
AgentState,
PrivateStateAttr,
+ ResponseT,
hook_config,
)
if TYPE_CHECKING:
from langgraph.runtime import Runtime
+ExitBehavior = Literal["continue", "error", "end"]
+"""How to handle execution when tool call limits are exceeded.
-class ToolCallLimitState(AgentState):
+- `"continue"`: Block exceeded tools with error messages, let other tools continue (default)
+- `"error"`: Raise a `ToolCallLimitExceededError` exception
+- `"end"`: Stop execution immediately, injecting a ToolMessage and an AI message
+ for the single tool call that exceeded the limit. Raises `NotImplementedError`
+ if there are other pending tool calls (due to parallel tool calling).
+"""
+
+
+class ToolCallLimitState(AgentState[ResponseT], Generic[ResponseT]):
"""State schema for ToolCallLimitMiddleware.
Extends AgentState with tool call tracking fields.
@@ -33,14 +45,58 @@ class ToolCallLimitState(AgentState):
run_tool_call_count: NotRequired[Annotated[dict[str, int], UntrackedValue, PrivateStateAttr]]
-def _build_tool_limit_exceeded_message(
+def _build_tool_message_content(
+ tool_name: str | None,
+ thread_count: int,
+ run_count: int,
+ thread_limit: int | None,
+ run_limit: int | None,
+) -> str:
+ """Build the error message content for ToolMessage when limit is exceeded.
+
+ This message is sent to the model, so it should not reference thread/run concepts
+ that the model has no notion of.
+
+ Args:
+ tool_name: Tool name being limited (if specific tool), or None for all tools.
+ thread_count: Current thread tool call count.
+ run_count: Current run tool call count.
+ thread_limit: Thread tool call limit (if set).
+ run_limit: Run tool call limit (if set).
+
+ Returns:
+ A concise message. If only run limit is exceeded (not thread limit),
+ returns a simple "limit exceeded" message without instructing model to stop.
+ If thread limit is exceeded, includes instruction not to call again.
+ """
+ # Check if thread limit is exceeded
+ thread_exceeded = thread_limit is not None and thread_count > thread_limit
+ # Check if only run limit is exceeded (not thread limit)
+ only_run_exceeded = run_limit is not None and run_count > run_limit and not thread_exceeded
+
+ if only_run_exceeded:
+ # Run limit exceeded but thread limit not exceeded - simpler message
+ if tool_name:
+ return f"Tool call limit exceeded for '{tool_name}'."
+ return "Tool call limit exceeded."
+
+ # Thread limit exceeded (or both) - include instruction not to call again
+ if tool_name:
+ return f"Tool call limit exceeded. Do not call '{tool_name}' again."
+ return "Tool call limit exceeded. Do not make additional tool calls."
+
+
+def _build_final_ai_message_content(
thread_count: int,
run_count: int,
thread_limit: int | None,
run_limit: int | None,
tool_name: str | None,
) -> str:
- """Build a message indicating which tool call limits were exceeded.
+ """Build the final AI message content for 'end' behavior.
+
+ This message is displayed to the user, so it should include detailed information
+ about which limits were exceeded.
Args:
thread_count: Current thread tool call count.
@@ -52,14 +108,16 @@ def _build_tool_limit_exceeded_message(
Returns:
A formatted message describing which limits were exceeded.
"""
- tool_desc = f"'{tool_name}' tool call" if tool_name else "Tool call"
+ tool_desc = f"'{tool_name}' tool" if tool_name else "Tool"
exceeded_limits = []
- if thread_limit is not None and thread_count >= thread_limit:
- exceeded_limits.append(f"thread limit ({thread_count}/{thread_limit})")
- if run_limit is not None and run_count >= run_limit:
- exceeded_limits.append(f"run limit ({run_count}/{run_limit})")
- return f"{tool_desc} limits exceeded: {', '.join(exceeded_limits)}"
+ if thread_limit is not None and thread_count > thread_limit:
+ exceeded_limits.append(f"thread limit exceeded ({thread_count}/{thread_limit} calls)")
+ if run_limit is not None and run_count > run_limit:
+ exceeded_limits.append(f"run limit exceeded ({run_count}/{run_limit} calls)")
+
+ limits_text = " and ".join(exceeded_limits)
+ return f"{tool_desc} call limit reached: {limits_text}."
class ToolCallLimitExceededError(Exception):
@@ -92,46 +150,70 @@ class ToolCallLimitExceededError(Exception):
self.run_limit = run_limit
self.tool_name = tool_name
- msg = _build_tool_limit_exceeded_message(
+ msg = _build_final_ai_message_content(
thread_count, run_count, thread_limit, run_limit, tool_name
)
super().__init__(msg)
-class ToolCallLimitMiddleware(AgentMiddleware[ToolCallLimitState, Any]):
- """Tracks tool call counts and enforces limits.
+class ToolCallLimitMiddleware(
+ AgentMiddleware[ToolCallLimitState[ResponseT], ContextT],
+ Generic[ResponseT, ContextT],
+):
+ """Track tool call counts and enforces limits during agent execution.
- 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.
+ This middleware monitors the number of tool calls made and can terminate or
+ restrict execution when limits are exceeded. It supports both thread-level
+ (persistent across runs) and run-level (per invocation) call counting.
- Thread-level: The middleware tracks the total number of tool calls and persists
- call count across multiple runs (invocations) of the agent.
+ Configuration:
+ - `exit_behavior`: How to handle when limits are exceeded
+ - `"continue"`: Block exceeded tools, let execution continue (default)
+ - `"error"`: Raise an exception
+ - `"end"`: Stop immediately with a ToolMessage + AI message for the single
+ tool call that exceeded the limit (raises `NotImplementedError` if there
+ are other pending tool calls (due to parallel tool calling).
- Run-level: The middleware tracks the number of tool calls made during a single
- run (invocation) of the agent.
-
- Example:
+ Examples:
+ Continue execution with blocked tools (default):
```python
from langchain.agents.middleware.tool_call_limit import ToolCallLimitMiddleware
from langchain.agents import create_agent
- # Limit all tool calls globally
- global_limiter = ToolCallLimitMiddleware(thread_limit=20, run_limit=10, exit_behavior="end")
-
- # Limit a specific tool
- search_limiter = ToolCallLimitMiddleware(
- tool_name="search", thread_limit=5, run_limit=3, exit_behavior="end"
+ # Block exceeded tools but let other tools and model continue
+ limiter = ToolCallLimitMiddleware(
+ thread_limit=20,
+ run_limit=10,
+ exit_behavior="continue", # default
)
- # Use both in the same agent
- agent = create_agent("openai:gpt-4o", middleware=[global_limiter, search_limiter])
+ agent = create_agent("openai:gpt-4o", middleware=[limiter])
+ ```
+
+ Stop immediately when limit exceeded:
+ ```python
+ # End execution immediately with an AI message
+ limiter = ToolCallLimitMiddleware(run_limit=5, exit_behavior="end")
- result = await agent.invoke({"messages": [HumanMessage("Help me with a task")]})
+ agent = create_agent("openai:gpt-4o", middleware=[limiter])
```
+
+ Raise exception on limit:
+ ```python
+ # Strict limit with exception handling
+ limiter = ToolCallLimitMiddleware(tool_name="search", thread_limit=5, exit_behavior="error")
+
+ agent = create_agent("openai:gpt-4o", middleware=[limiter])
+
+ try:
+ result = await agent.invoke({"messages": [HumanMessage("Task")]})
+ except ToolCallLimitExceededError as e:
+ print(f"Search limit exceeded: {e}")
+ ```
+
"""
- state_schema = ToolCallLimitState
+ state_schema = ToolCallLimitState # type: ignore[assignment]
def __init__(
self,
@@ -139,7 +221,7 @@ class ToolCallLimitMiddleware(AgentMiddleware[ToolCallLimitState, Any]):
tool_name: str | None = None,
thread_limit: int | None = None,
run_limit: int | None = None,
- exit_behavior: Literal["end", "error"] = "end",
+ exit_behavior: ExitBehavior = "continue",
) -> None:
"""Initialize the tool call limit middleware.
@@ -147,17 +229,20 @@ class ToolCallLimitMiddleware(AgentMiddleware[ToolCallLimitState, Any]):
tool_name: Name of the specific tool to limit. If `None`, limits apply
to all tools. Defaults to `None`.
thread_limit: Maximum number of tool calls allowed per thread.
- None means no limit. Defaults to `None`.
+ `None` means no limit. Defaults to `None`.
run_limit: Maximum number of tool calls allowed per run.
- None means no limit. Defaults to `None`.
- exit_behavior: What to do when limits are exceeded.
- - "end": Jump to the end of the agent execution and
- inject an artificial AI message indicating that the limit was exceeded.
- - "error": Raise a ToolCallLimitExceededError
- Defaults to "end".
+ `None` means no limit. Defaults to `None`.
+ exit_behavior: How to handle when limits are exceeded.
+ - `"continue"`: Block exceeded tools with error messages, let other
+ tools continue. Model decides when to end. (default)
+ - `"error"`: Raise a `ToolCallLimitExceededError` exception
+ - `"end"`: Stop execution immediately with a ToolMessage + AI message
+ for the single tool call that exceeded the limit. Raises
+ `NotImplementedError` if there are multiple parallel tool
+ calls to other tools or multiple pending tool calls.
Raises:
- ValueError: If both limits are `None` or if `exit_behavior` is invalid.
+ ValueError: If both limits are `None`.
"""
super().__init__()
@@ -165,10 +250,6 @@ class ToolCallLimitMiddleware(AgentMiddleware[ToolCallLimitState, Any]):
msg = "At least one limit must be specified (thread_limit or run_limit)"
raise ValueError(msg)
- if exit_behavior not in ("end", "error"):
- msg = f"Invalid exit_behavior: {exit_behavior}. Must be 'end' or 'error'"
- raise ValueError(msg)
-
self.tool_name = tool_name
self.thread_limit = thread_limit
self.run_limit = run_limit
@@ -186,64 +267,84 @@ class ToolCallLimitMiddleware(AgentMiddleware[ToolCallLimitState, Any]):
return f"{base_name}[{self.tool_name}]"
return base_name
- @hook_config(can_jump_to=["end"])
- def before_model(self, state: ToolCallLimitState, runtime: Runtime) -> dict[str, Any] | None: # noqa: ARG002
- """Check tool call limits before making a model call.
+ def _would_exceed_limit(self, thread_count: int, run_count: int) -> bool:
+ """Check if incrementing the counts would exceed any configured limit.
Args:
- state: The current agent state containing tool call counts.
- runtime: The langgraph runtime.
+ thread_count: Current thread call count.
+ run_count: Current run call count.
Returns:
- If limits are exceeded and exit_behavior is "end", returns
- a Command to jump to the end with a limit exceeded message. Otherwise returns None.
+ True if either limit would be exceeded by one more call.
+ """
+ return (self.thread_limit is not None and thread_count + 1 > self.thread_limit) or (
+ self.run_limit is not None and run_count + 1 > self.run_limit
+ )
- Raises:
- ToolCallLimitExceededError: If limits are exceeded and exit_behavior
- is "error".
+ def _matches_tool_filter(self, tool_call: ToolCall) -> bool:
+ """Check if a tool call matches this middleware's tool filter.
+
+ Args:
+ tool_call: The tool call to check.
+
+ Returns:
+ True if this middleware should track this tool call.
"""
- # Get the count key for this middleware instance
- count_key = self.tool_name if self.tool_name else "__all__"
+ return self.tool_name is None or tool_call["name"] == self.tool_name
- thread_counts = state.get("thread_tool_call_count", {})
- run_counts = state.get("run_tool_call_count", {})
+ def _separate_tool_calls(
+ self, tool_calls: list[ToolCall], thread_count: int, run_count: int
+ ) -> tuple[list[ToolCall], list[ToolCall], int, int]:
+ """Separate tool calls into allowed and blocked based on limits.
- thread_count = thread_counts.get(count_key, 0)
- run_count = run_counts.get(count_key, 0)
+ Args:
+ tool_calls: List of tool calls to evaluate.
+ thread_count: Current thread call count.
+ run_count: Current run call count.
- # Check if any limits are exceeded
- thread_limit_exceeded = self.thread_limit is not None and thread_count >= self.thread_limit
- run_limit_exceeded = self.run_limit is not None and run_count >= self.run_limit
+ Returns:
+ Tuple of (allowed_calls, blocked_calls, final_thread_count, final_run_count).
+ """
+ allowed_calls: list[ToolCall] = []
+ blocked_calls: list[ToolCall] = []
+ temp_thread_count = thread_count
+ temp_run_count = run_count
- if thread_limit_exceeded or run_limit_exceeded:
- if self.exit_behavior == "error":
- raise ToolCallLimitExceededError(
- thread_count=thread_count,
- run_count=run_count,
- thread_limit=self.thread_limit,
- run_limit=self.run_limit,
- tool_name=self.tool_name,
- )
- if self.exit_behavior == "end":
- # Create a message indicating the limit was exceeded
- limit_message = _build_tool_limit_exceeded_message(
- thread_count, run_count, self.thread_limit, self.run_limit, self.tool_name
- )
- limit_ai_message = AIMessage(content=limit_message)
+ for tool_call in tool_calls:
+ if not self._matches_tool_filter(tool_call):
+ continue
- return {"jump_to": "end", "messages": [limit_ai_message]}
+ if self._would_exceed_limit(temp_thread_count, temp_run_count):
+ blocked_calls.append(tool_call)
+ else:
+ allowed_calls.append(tool_call)
+ temp_thread_count += 1
+ temp_run_count += 1
- return None
+ return allowed_calls, blocked_calls, temp_thread_count, temp_run_count
- 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).
+ @hook_config(can_jump_to=["end"])
+ def after_model(
+ self,
+ state: ToolCallLimitState[ResponseT],
+ runtime: Runtime[ContextT], # noqa: ARG002
+ ) -> dict[str, Any] | None:
+ """Increment tool call counts after a model call and check limits.
Args:
state: The current agent state.
runtime: The langgraph runtime.
Returns:
- State updates with incremented tool call counts if tool calls were made.
+ State updates with incremented tool call counts. If limits are exceeded
+ and exit_behavior is "end", also includes a jump to end with a ToolMessage
+ and AI message for the single exceeded tool call.
+
+ Raises:
+ ToolCallLimitExceededError: If limits are exceeded and exit_behavior
+ is "error".
+ NotImplementedError: If limits are exceeded, exit_behavior is "end",
+ and there are multiple tool calls.
"""
# Get the last AIMessage to check for tool calls
messages = state.get("messages", [])
@@ -260,27 +361,103 @@ class ToolCallLimitMiddleware(AgentMiddleware[ToolCallLimitState, Any]):
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()
+ current_thread_count = thread_counts.get(count_key, 0)
+ current_run_count = run_counts.get(count_key, 0)
+
+ # Separate tool calls into allowed and blocked
+ allowed_calls, blocked_calls, new_thread_count, new_run_count = self._separate_tool_calls(
+ last_ai_message.tool_calls, current_thread_count, current_run_count
+ )
- # 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
+ # Update counts to include ALL tool call attempts (both allowed and blocked)
+ thread_counts[count_key] = new_thread_count + len(blocked_calls)
+ run_counts[count_key] = new_run_count + len(blocked_calls)
+
+ # If no tool calls are blocked, just update counts
+ if not blocked_calls:
+ if allowed_calls:
+ return {
+ "thread_tool_call_count": thread_counts,
+ "run_tool_call_count": run_counts,
+ }
+ return None
+
+ # Get final counts for building messages
+ final_thread_count = thread_counts[count_key]
+ final_run_count = run_counts[count_key]
+
+ # Handle different exit behaviors
+ if self.exit_behavior == "error":
+ raise ToolCallLimitExceededError(
+ thread_count=final_thread_count,
+ run_count=final_run_count,
+ thread_limit=self.thread_limit,
+ run_limit=self.run_limit,
+ tool_name=self.tool_name,
+ )
+
+ # Build tool message content (sent to model - no thread/run details)
+ tool_msg_content = _build_tool_message_content(
+ self.tool_name,
+ final_thread_count,
+ final_run_count,
+ self.thread_limit,
+ self.run_limit,
+ )
+ # Inject artificial error ToolMessages for blocked tool calls
+ artificial_messages: list[ToolMessage | AIMessage] = [
+ ToolMessage(
+ content=tool_msg_content,
+ tool_call_id=tool_call["id"],
+ name=tool_call.get("name"),
+ status="error",
+ )
+ for tool_call in blocked_calls
+ ]
+
+ if self.exit_behavior == "end":
+ # Check if there are tool calls to other tools that would continue executing
+ other_tools = [
+ tc
+ for tc in last_ai_message.tool_calls
+ if self.tool_name is not None and tc["name"] != self.tool_name
+ ]
+
+ if other_tools:
+ tool_names = ", ".join({tc["name"] for tc in other_tools})
+ msg = (
+ f"Cannot end execution with other tool calls pending. "
+ f"Found calls to: {tool_names}. Use 'continue' or 'error' behavior instead."
+ )
+ raise NotImplementedError(msg)
+
+ # Build final AI message content (displayed to user - includes thread/run details)
+ final_msg_content = _build_final_ai_message_content(
+ final_thread_count,
+ final_run_count,
+ self.thread_limit,
+ self.run_limit,
+ self.tool_name,
+ )
+ artificial_messages.append(AIMessage(content=final_msg_content))
+
+ return {
+ "thread_tool_call_count": thread_counts,
+ "run_tool_call_count": run_counts,
+ "jump_to": "end",
+ "messages": artificial_messages,
+ }
+
+ # For exit_behavior="continue", return error messages to block exceeded tools
return {
"thread_tool_call_count": thread_counts,
"run_tool_call_count": run_counts,
+ "messages": artificial_messages,
}
diff --git a/libs/langchain_v1/langchain/agents/middleware/types.py b/libs/langchain_v1/langchain/agents/middleware/types.py
index c9bfa2ee74..cedcc28502 100644
--- a/libs/langchain_v1/langchain/agents/middleware/types.py
+++ b/libs/langchain_v1/langchain/agents/middleware/types.py
@@ -22,7 +22,12 @@ if TYPE_CHECKING:
# Needed as top level import for Pydantic schema generation on AgentState
from typing import TypeAlias
-from langchain_core.messages import AIMessage, AnyMessage, BaseMessage, ToolMessage # noqa: TC002
+from langchain_core.messages import ( # noqa: TC002
+ AIMessage,
+ AnyMessage,
+ BaseMessage,
+ ToolMessage,
+)
from langgraph.channels.ephemeral_value import EphemeralValue
from langgraph.graph.message import add_messages
from langgraph.prebuilt.tool_node import ToolCallRequest, ToolCallWrapper
@@ -44,6 +49,8 @@ __all__ = [
"ModelRequest",
"ModelResponse",
"OmitFromSchema",
+ "ResponseT",
+ "StateT_co",
"ToolCallRequest",
"ToolCallWrapper",
"after_agent",
@@ -186,6 +193,7 @@ class _OutputAgentState(TypedDict, Generic[ResponseT]): # noqa: PYI049
StateT = TypeVar("StateT", bound=AgentState, default=AgentState)
+StateT_co = TypeVar("StateT_co", bound=AgentState, default=AgentState, covariant=True)
StateT_contra = TypeVar("StateT_contra", bound=AgentState, contravariant=True)
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_parallel_tool_call_limits.py b/libs/langchain_v1/tests/unit_tests/agents/test_parallel_tool_call_limits.py
new file mode 100644
index 0000000000..141dcc9ac8
--- /dev/null
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_parallel_tool_call_limits.py
@@ -0,0 +1,192 @@
+"""Tests for parallel tool call handling in ToolCallLimitMiddleware."""
+
+import pytest
+from langchain_core.messages import AIMessage, HumanMessage, ToolCall, ToolMessage
+from langchain_core.tools import tool
+from langgraph.checkpoint.memory import InMemorySaver
+
+from langchain.agents.factory import create_agent
+from langchain.agents.middleware.tool_call_limit import ToolCallLimitMiddleware
+from tests.unit_tests.agents.model import FakeToolCallingModel
+
+
+def test_parallel_tool_calls_with_limit_continue_mode():
+ """Test parallel tool calls with a limit of 1 in 'continue' mode.
+
+ When the model proposes 3 tool calls with a limit of 1:
+ - The first call should execute successfully
+ - The 2nd and 3rd calls should be blocked with error ToolMessages
+ - Execution should continue (no jump_to)
+ """
+
+ @tool
+ def search(query: str) -> str:
+ """Search for information."""
+ return f"Results: {query}"
+
+ # Model proposes 3 parallel search calls in a single AIMessage
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [
+ ToolCall(name="search", args={"query": "q1"}, id="1"),
+ ToolCall(name="search", args={"query": "q2"}, id="2"),
+ ToolCall(name="search", args={"query": "q3"}, id="3"),
+ ],
+ [], # Model stops after seeing the errors
+ ]
+ )
+
+ limiter = ToolCallLimitMiddleware(thread_limit=1, exit_behavior="continue")
+ agent = create_agent(
+ model=model, tools=[search], middleware=[limiter], checkpointer=InMemorySaver()
+ )
+
+ result = agent.invoke(
+ {"messages": [HumanMessage("Test")]}, {"configurable": {"thread_id": "test"}}
+ )
+ messages = result["messages"]
+
+ # Verify tool message counts
+ tool_messages = [msg for msg in messages if isinstance(msg, ToolMessage)]
+ successful_tool_messages = [msg for msg in tool_messages if msg.status != "error"]
+ error_tool_messages = [msg for msg in tool_messages if msg.status == "error"]
+
+ assert len(successful_tool_messages) == 1, "Should have 1 successful tool message (q1)"
+ assert len(error_tool_messages) == 2, "Should have 2 blocked tool messages (q2, q3)"
+
+ # Verify the successful call is q1
+ assert "q1" in successful_tool_messages[0].content
+
+ # Verify error messages explain the limit
+ for error_msg in error_tool_messages:
+ assert "limit" in error_msg.content.lower()
+
+ # Verify execution continued (no early termination)
+ ai_messages = [msg for msg in messages if isinstance(msg, AIMessage)]
+ # Should have: initial AI message with 3 tool calls, then final AI message (no tool calls)
+ assert len(ai_messages) >= 2
+
+
+def test_parallel_tool_calls_with_limit_end_mode():
+ """Test parallel tool calls with a limit of 1 in 'end' mode.
+
+ When the model proposes 3 tool calls with a limit of 1:
+ - The first call would be allowed (within limit)
+ - The 2nd and 3rd calls exceed the limit and get blocked with error ToolMessages
+ - Execution stops immediately (jump_to: end) so NO tools actually execute
+ - An AI message explains why execution stopped
+ """
+
+ @tool
+ def search(query: str) -> str:
+ """Search for information."""
+ return f"Results: {query}"
+
+ # Model proposes 3 parallel search calls
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [
+ ToolCall(name="search", args={"query": "q1"}, id="1"),
+ ToolCall(name="search", args={"query": "q2"}, id="2"),
+ ToolCall(name="search", args={"query": "q3"}, id="3"),
+ ],
+ [],
+ ]
+ )
+
+ limiter = ToolCallLimitMiddleware(thread_limit=1, exit_behavior="end")
+ agent = create_agent(
+ model=model, tools=[search], middleware=[limiter], checkpointer=InMemorySaver()
+ )
+
+ result = agent.invoke(
+ {"messages": [HumanMessage("Test")]}, {"configurable": {"thread_id": "test"}}
+ )
+ messages = result["messages"]
+
+ # Verify tool message counts
+ # With "end" behavior, when we jump to end, NO tools execute (not even allowed ones)
+ # We only get error ToolMessages for the 2 blocked calls
+ tool_messages = [msg for msg in messages if isinstance(msg, ToolMessage)]
+ successful_tool_messages = [msg for msg in tool_messages if msg.status != "error"]
+ error_tool_messages = [msg for msg in tool_messages if msg.status == "error"]
+
+ assert len(successful_tool_messages) == 0, "No tools execute when we jump to end"
+ assert len(error_tool_messages) == 2, "Should have 2 blocked tool messages (q2, q3)"
+
+ # Verify error tool messages (sent to model - include "Do not" instruction)
+ for error_msg in error_tool_messages:
+ assert "Tool call limit exceeded" in error_msg.content
+ assert "Do not" in error_msg.content
+
+ # Verify AI message explaining why execution stopped (displayed to user - includes thread/run details)
+ ai_limit_messages = [
+ msg
+ for msg in messages
+ if isinstance(msg, AIMessage) and "limit" in msg.content.lower() and not msg.tool_calls
+ ]
+ assert len(ai_limit_messages) == 1, "Should have exactly one AI message explaining the limit"
+
+ ai_msg_content = ai_limit_messages[0].content.lower()
+ assert "thread limit exceeded" in ai_msg_content or "run limit exceeded" in ai_msg_content, (
+ "AI message should include thread/run limit details for the user"
+ )
+
+
+def test_parallel_mixed_tool_calls_with_specific_tool_limit():
+ """Test parallel calls to different tools when limiting a specific tool.
+
+ When limiting 'search' to 1 call, and model proposes 3 search + 2 calculator calls:
+ - First search call should execute
+ - Other 2 search calls should be blocked
+ - All calculator calls should execute (not limited)
+ """
+
+ @tool
+ def search(query: str) -> str:
+ """Search for information."""
+ return f"Search: {query}"
+
+ @tool
+ def calculator(expression: str) -> str:
+ """Calculate an expression."""
+ return f"Calc: {expression}"
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [
+ ToolCall(name="search", args={"query": "q1"}, id="1"),
+ ToolCall(name="calculator", args={"expression": "1+1"}, id="2"),
+ ToolCall(name="search", args={"query": "q2"}, id="3"),
+ ToolCall(name="calculator", args={"expression": "2+2"}, id="4"),
+ ToolCall(name="search", args={"query": "q3"}, id="5"),
+ ],
+ [],
+ ]
+ )
+
+ search_limiter = ToolCallLimitMiddleware(
+ tool_name="search", thread_limit=1, exit_behavior="continue"
+ )
+ agent = create_agent(
+ model=model,
+ tools=[search, calculator],
+ middleware=[search_limiter],
+ checkpointer=InMemorySaver(),
+ )
+
+ result = agent.invoke(
+ {"messages": [HumanMessage("Test")]}, {"configurable": {"thread_id": "test"}}
+ )
+ messages = result["messages"]
+
+ tool_messages = [msg for msg in messages if isinstance(msg, ToolMessage)]
+ search_success = [m for m in tool_messages if "Search:" in m.content]
+ search_blocked = [
+ m for m in tool_messages if "limit" in m.content.lower() and "search" in m.content.lower()
+ ]
+ calc_success = [m for m in tool_messages if "Calc:" in m.content]
+
+ assert len(search_success) == 1, "Should have 1 successful search call"
+ assert len(search_blocked) == 2, "Should have 2 blocked search calls"
+ assert len(calc_success) == 2, "All calculator calls should succeed (not limited)"
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 8498926a30..094d07f11f 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
@@ -19,15 +19,11 @@ def test_middleware_initialization_validation():
with pytest.raises(ValueError, match="At least one limit must be specified"):
ToolCallLimitMiddleware()
- # Test invalid exit behavior
- with pytest.raises(ValueError, match="Invalid exit_behavior"):
- ToolCallLimitMiddleware(thread_limit=5, exit_behavior="invalid") # type: ignore[arg-type]
-
- # Test valid initialization
+ # Test valid initialization with both limits
middleware = ToolCallLimitMiddleware(thread_limit=5, run_limit=3)
assert middleware.thread_limit == 5
assert middleware.run_limit == 3
- assert middleware.exit_behavior == "end"
+ assert middleware.exit_behavior == "continue"
assert middleware.tool_name is None
# Test with tool name
@@ -36,6 +32,11 @@ def test_middleware_initialization_validation():
assert middleware.thread_limit == 5
assert middleware.run_limit is None
+ # Test exit behaviors
+ for behavior in ["error", "end", "continue"]:
+ middleware = ToolCallLimitMiddleware(thread_limit=5, exit_behavior=behavior)
+ assert middleware.exit_behavior == behavior
+
def test_middleware_name_property():
"""Test that the name property includes tool name when specified."""
@@ -56,89 +57,96 @@ def test_middleware_name_property():
def test_middleware_unit_functionality():
- """Test that the middleware works as expected in isolation."""
- # Test with end behavior - global tool limit
- middleware = ToolCallLimitMiddleware(thread_limit=3, run_limit=2)
+ """Test that the middleware works as expected in isolation.
- # Mock runtime (not used in current implementation)
+ Tests basic count tracking, thread limit, run limit, and limit-not-exceeded cases.
+ """
+ middleware = ToolCallLimitMiddleware(thread_limit=3, run_limit=2, exit_behavior="end")
runtime = None
- # Test when limits are not exceeded
+ # Test when limits are not exceeded - counts should increment normally
state = {
"messages": [
HumanMessage("Question"),
- AIMessage(
- "Response",
- tool_calls=[{"name": "search", "args": {}, "id": "1"}],
- ),
+ AIMessage("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
+ result = middleware.after_model(state, runtime) # type: ignore[arg-type]
+ assert result is not None
+ assert result["thread_tool_call_count"] == {"__all__": 1}
+ assert result["run_tool_call_count"] == {"__all__": 1}
+ assert "jump_to" not in result
- # Test when thread limit is exceeded
+ # Test thread limit exceeded
state = {
"messages": [
- HumanMessage("Question 1"),
- AIMessage(
- "Response 1",
- tool_calls=[
- {"name": "search", "args": {}, "id": "1"},
- {"name": "calculator", "args": {}, "id": "2"},
- ],
- ),
- ToolMessage("Result 1", tool_call_id="1"),
- ToolMessage("Result 2", tool_call_id="2"),
HumanMessage("Question 2"),
- AIMessage(
- "Response 2",
- tool_calls=[{"name": "search", "args": {}, "id": "3"}],
- ),
+ AIMessage("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)
+ "thread_tool_call_count": {"__all__": 3},
+ "run_tool_call_count": {"__all__": 3},
}
- result = middleware.before_model(state, runtime) # type: ignore[arg-type]
+ result = middleware.after_model(state, runtime) # type: ignore[arg-type]
assert result is not None
assert result["jump_to"] == "end"
- assert "messages" in result
- assert len(result["messages"]) == 1
- assert "thread limit (3/3)" in result["messages"][0].content
-
- # Test when run limit is exceeded
+ # Check the ToolMessage (sent to model - no thread/run details)
+ tool_msg = result["messages"][0]
+ assert isinstance(tool_msg, ToolMessage)
+ assert tool_msg.status == "error"
+ assert "Tool call limit exceeded" in tool_msg.content
+ # When thread limit exceeded, should include "Do not" instruction
+ assert "Do not" in tool_msg.content, (
+ "Tool message should include 'Do not' instruction when thread limit exceeded"
+ )
+ # Check the final AI message (displayed to user - includes thread/run details)
+ final_ai_msg = result["messages"][-1]
+ assert isinstance(final_ai_msg, AIMessage)
+ assert "limit" in final_ai_msg.content.lower()
+ assert "thread limit exceeded" in final_ai_msg.content.lower()
+ assert result["thread_tool_call_count"] == {"__all__": 4}
+
+ # Test run limit exceeded (thread count must be >= run count)
state = {
"messages": [
HumanMessage("Question"),
- AIMessage(
- "Response",
- tool_calls=[
- {"name": "search", "args": {}, "id": "1"},
- {"name": "calculator", "args": {}, "id": "2"},
- ],
- ),
+ AIMessage("Response", tool_calls=[{"name": "search", "args": {}, "id": "1"}]),
],
"thread_tool_call_count": {"__all__": 2},
- "run_tool_call_count": {"__all__": 2}, # 2 tool calls in current run
+ "run_tool_call_count": {"__all__": 2},
}
- result = middleware.before_model(state, runtime) # type: ignore[arg-type]
+ result = middleware.after_model(state, runtime) # type: ignore[arg-type]
assert result is not None
assert result["jump_to"] == "end"
- assert "run limit (2/2)" in result["messages"][0].content
+ # Check the final AI message includes run limit details
+ final_ai_msg = result["messages"][-1]
+ assert "run limit exceeded" in final_ai_msg.content
+ assert "3/2 calls" in final_ai_msg.content
+ # Check the tool message (sent to model) - when only run limit exceeded,
+ # should not include "Do not" instruction since run is ending anyway
+ tool_msg = result["messages"][0]
+ assert isinstance(tool_msg, ToolMessage)
+ assert "Tool call limit exceeded" in tool_msg.content
+ assert "Do not" not in tool_msg.content, (
+ "Tool message should not include 'Do not' instruction when only run limit exceeded"
+ )
-def test_middleware_with_specific_tool():
- """Test middleware that limits a specific tool."""
- # Limit only the "search" tool
- middleware = ToolCallLimitMiddleware(tool_name="search", thread_limit=2, run_limit=1)
+def test_middleware_end_behavior_with_unrelated_parallel_tool_calls():
+ """Test that 'end' behavior raises NotImplementedError when there are parallel calls to unrelated tools.
+ When limiting a specific tool with "end" behavior and the model proposes parallel calls
+ to BOTH the limited tool AND other tools, we can't handle this scenario (we'd be stopping
+ execution while other tools should run).
+ """
+ # Limit search tool specifically
+ middleware = ToolCallLimitMiddleware(tool_name="search", thread_limit=1, exit_behavior="end")
runtime = None
- # Test with search tool calls
+ # Test with search + calculator calls when search exceeds limit
state = {
"messages": [
- HumanMessage("Question"),
AIMessage(
"Response",
tool_calls=[
@@ -147,91 +155,85 @@ def test_middleware_with_specific_tool():
],
),
],
- "thread_tool_call_count": {"search": 1}, # 1 search call
- "run_tool_call_count": {"search": 1}, # 1 search call in current run
+ "thread_tool_call_count": {"search": 1},
+ "run_tool_call_count": {"search": 1},
}
- # Run limit for search is 1, should be exceeded
- result = middleware.before_model(state, runtime) # type: ignore[arg-type]
- assert result is not None
- assert "'search' tool call" in result["messages"][0].content
- assert "run limit (1/1)" in result["messages"][0].content
- # Test with only calculator calls (should not trigger limit)
- state = {
- "messages": [
- HumanMessage("Question"),
- AIMessage(
- "Response",
- tool_calls=[
- {"name": "calculator", "args": {}, "id": "1"},
- {"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
+ with pytest.raises(
+ NotImplementedError, match="Cannot end execution with other tool calls pending"
+ ):
+ middleware.after_model(state, runtime) # type: ignore[arg-type]
-def test_middleware_error_behavior():
- """Test middleware with error exit behavior."""
- middleware = ToolCallLimitMiddleware(thread_limit=2, run_limit=1, exit_behavior="error")
-
+def test_middleware_with_specific_tool():
+ """Test middleware that limits a specific tool while ignoring others."""
+ middleware = ToolCallLimitMiddleware(
+ tool_name="search", thread_limit=2, run_limit=1, exit_behavior="end"
+ )
runtime = None
- # Test exception when thread limit exceeded
+ # Test search tool exceeding run limit
state = {
"messages": [
- HumanMessage("Q"),
- AIMessage("R", tool_calls=[{"name": "search", "args": {}, "id": "1"}]),
- ToolMessage("Result", tool_call_id="1"),
- AIMessage("R", tool_calls=[{"name": "search", "args": {}, "id": "2"}]),
+ AIMessage("Response 2", tool_calls=[{"name": "search", "args": {}, "id": "3"}]),
],
- "thread_tool_call_count": {"__all__": 2}, # 2 tool calls total
- "run_tool_call_count": {"__all__": 1}, # 1 tool call in current run
+ "thread_tool_call_count": {"search": 1},
+ "run_tool_call_count": {"search": 1},
}
- with pytest.raises(ToolCallLimitExceededError) as exc_info:
- middleware.before_model(state, runtime) # type: ignore[arg-type]
-
- assert "thread limit (2/2)" in str(exc_info.value)
- assert exc_info.value.thread_count == 2
- assert exc_info.value.thread_limit == 2
+ result = middleware.after_model(state, runtime) # type: ignore[arg-type]
+ assert result is not None
+ assert result["jump_to"] == "end"
+ assert "search" in result["messages"][0].content.lower()
- # Test exception when run limit exceeded
+ # Test calculator tool - should be ignored by search-specific middleware
state = {
"messages": [
- HumanMessage("Question"),
- AIMessage("R", tool_calls=[{"name": "search", "args": {}, "id": "1"}]),
+ AIMessage("Response", tool_calls=[{"name": "calculator", "args": {}, "id": "1"}] * 10),
],
- "thread_tool_call_count": {"__all__": 1},
- "run_tool_call_count": {"__all__": 1}, # 1 tool call in current run
+ "thread_tool_call_count": {},
+ "run_tool_call_count": {},
}
+ result = middleware.after_model(state, runtime) # type: ignore[arg-type]
+ assert result is None, "Calculator calls shouldn't be counted by search-specific middleware"
+
+
+def test_middleware_error_behavior():
+ """Test that middleware raises ToolCallLimitExceededError when configured with exit_behavior='error'."""
+ middleware = ToolCallLimitMiddleware(thread_limit=2, exit_behavior="error")
+ runtime = None
+
+ state = {
+ "messages": [AIMessage("Response", tool_calls=[{"name": "search", "args": {}, "id": "1"}])],
+ "thread_tool_call_count": {"__all__": 2},
+ "run_tool_call_count": {"__all__": 2},
+ }
+
with pytest.raises(ToolCallLimitExceededError) as exc_info:
- middleware.before_model(state, runtime) # type: ignore[arg-type]
+ middleware.after_model(state, runtime) # type: ignore[arg-type]
- assert "run limit (1/1)" in str(exc_info.value)
+ error = exc_info.value
+ assert error.thread_count == 3
+ assert error.thread_limit == 2
+ assert error.tool_name is None
def test_multiple_middleware_instances():
- """Test using multiple ToolCallLimitMiddleware instances in the same agent."""
+ """Test that multiple middleware instances can coexist and track independently."""
@tool
def search(query: str) -> str:
"""Search for information."""
- return f"Results for: {query}"
+ return f"Results for {query}"
@tool
def calculator(expression: str) -> str:
"""Calculate an expression."""
return f"Result: {expression}"
- # Create model that makes multiple tool calls
model = FakeToolCallingModel(
tool_calls=[
[
- ToolCall(name="search", args={"query": "test1"}, id="1"),
+ ToolCall(name="search", args={"query": "test"}, id="1"),
ToolCall(name="calculator", args={"expression": "1+1"}, id="2"),
],
[
@@ -245,132 +247,262 @@ def test_multiple_middleware_instances():
]
)
- # Global limit: max 5 tool calls per thread
- # Search-specific limit: max 2 search calls per thread
- global_limiter = ToolCallLimitMiddleware(thread_limit=5)
- search_limiter = ToolCallLimitMiddleware(tool_name="search", thread_limit=2)
+ # Create two middleware instances - one for each tool
+ search_limiter = ToolCallLimitMiddleware(
+ tool_name="search", thread_limit=2, exit_behavior="end"
+ )
+ calc_limiter = ToolCallLimitMiddleware(
+ tool_name="calculator", thread_limit=2, exit_behavior="end"
+ )
agent = create_agent(
model=model,
tools=[search, calculator],
- middleware=[global_limiter, search_limiter],
+ middleware=[search_limiter, calc_limiter],
checkpointer=InMemorySaver(),
)
- # First invocation: 2 search calls, 2 calculator calls (4 total)
- # Should succeed - within both limits
result = agent.invoke(
- {"messages": [HumanMessage("First question")]},
+ {"messages": [HumanMessage("Question")]},
{"configurable": {"thread_id": "test_thread"}},
)
- assert len(result["messages"]) > 0
- # Second invocation would add 1 more search call (total 3), exceeding search limit
- # Should hit the search-specific limit
- result = agent.invoke(
- {"messages": [HumanMessage("Second question")]},
+ # The agent should stop after the second iteration
+ # because search will hit its limit (3 calls > 2 limit)
+ ai_limit_messages = [
+ msg
+ for msg in result["messages"]
+ if isinstance(msg, AIMessage) and "limit" in msg.content.lower()
+ ]
+ assert len(ai_limit_messages) > 0, "Should have AI message explaining limit was exceeded"
+
+
+def test_run_limit_with_multiple_human_messages():
+ """Test that run limits reset between invocations.
+
+ Verifies that when using run_limit, the count resets for each new user message,
+ allowing execution to continue across multiple invocations in the same thread.
+ """
+
+ @tool
+ def search(query: str) -> str:
+ """Search for information."""
+ return f"Results for {query}"
+
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "test1"}, id="1")],
+ [ToolCall(name="search", args={"query": "test2"}, id="2")],
+ [],
+ ]
+ )
+
+ middleware = ToolCallLimitMiddleware(run_limit=1, exit_behavior="end")
+ agent = create_agent(
+ model=model, tools=[search], middleware=[middleware], checkpointer=InMemorySaver()
+ )
+
+ # First invocation: test1 executes successfully, test2 exceeds limit
+ result1 = agent.invoke(
+ {"messages": [HumanMessage("Question 1")]},
+ {"configurable": {"thread_id": "test_thread"}},
+ )
+ tool_messages = [msg for msg in result1["messages"] if isinstance(msg, ToolMessage)]
+ successful_tool_msgs = [msg for msg in tool_messages if msg.status != "error"]
+ error_tool_msgs = [msg for msg in tool_messages if msg.status == "error"]
+ ai_limit_msgs = [
+ msg
+ for msg in result1["messages"]
+ if isinstance(msg, AIMessage) and "limit" in msg.content.lower() and not msg.tool_calls
+ ]
+
+ assert len(successful_tool_msgs) == 1, "Should have 1 successful tool execution (test1)"
+ assert len(error_tool_msgs) == 1, "Should have 1 artificial error ToolMessage (test2)"
+ assert len(ai_limit_msgs) == 1, "Should have AI limit message after test2 proposed"
+
+ # Second invocation: run limit should reset, allowing continued execution
+ result2 = agent.invoke(
+ {"messages": [HumanMessage("Question 2")]},
{"configurable": {"thread_id": "test_thread"}},
)
- # Check that the limit was hit
- last_message = result["messages"][-1]
- assert isinstance(last_message, AIMessage)
- assert "'search' tool call" in last_message.content
- assert "thread limit" in last_message.content
+ assert len(result2["messages"]) > len(result1["messages"]), (
+ "Second invocation should add new messages, proving run limit reset"
+ )
-def test_run_limit_with_multiple_human_messages():
- """Test that run limit correctly resets after each HumanMessage."""
+def test_exception_error_messages():
+ """Test that error messages include expected information."""
+ # Test for specific tool
+ with pytest.raises(ToolCallLimitExceededError) as exc_info:
+ raise ToolCallLimitExceededError(
+ thread_count=5, run_count=3, thread_limit=4, run_limit=2, tool_name="search"
+ )
+ msg = str(exc_info.value)
+ assert "search" in msg.lower()
+ assert "5/4" in msg or "thread" in msg.lower()
+
+ # Test for all tools
+ with pytest.raises(ToolCallLimitExceededError) as exc_info:
+ raise ToolCallLimitExceededError(
+ thread_count=10, run_count=5, thread_limit=8, run_limit=None, tool_name=None
+ )
+ msg = str(exc_info.value)
+ assert "10/8" in msg or "thread" in msg.lower()
+
+
+def test_limit_reached_but_not_exceeded():
+ """Test that limits are only triggered when exceeded (>), not when reached (==)."""
+ middleware = ToolCallLimitMiddleware(thread_limit=3, run_limit=2, exit_behavior="end")
+ runtime = None
+
+ # Test when limit is reached exactly (count = limit) - should not trigger
+ state = {
+ "messages": [AIMessage("Response", tool_calls=[{"name": "search", "args": {}, "id": "1"}])],
+ "thread_tool_call_count": {"__all__": 2}, # After +1 will be exactly 3
+ "run_tool_call_count": {"__all__": 1},
+ }
+ result = middleware.after_model(state, runtime) # type: ignore[arg-type]
+ assert result is not None
+ assert "jump_to" not in result
+ assert result["thread_tool_call_count"]["__all__"] == 3
+
+ # Test when limit is exceeded (count > limit) - should trigger
+ state = {
+ "messages": [AIMessage("Response", tool_calls=[{"name": "search", "args": {}, "id": "1"}])],
+ "thread_tool_call_count": {"__all__": 3}, # After +1 will be 4 > 3
+ "run_tool_call_count": {"__all__": 1},
+ }
+ result = middleware.after_model(state, runtime) # type: ignore[arg-type]
+ assert result is not None
+ assert "jump_to" in result
+ assert result["jump_to"] == "end"
+
+
+def test_exit_behavior_continue():
+ """Test that exit_behavior='continue' blocks only the exceeded tool, not others.
+
+ Verifies that when a specific tool hits its limit, it gets blocked with error messages
+ while other tools continue to execute normally.
+ """
@tool
def search(query: str) -> str:
"""Search for information."""
- return f"Results for: {query}"
+ return f"Search: {query}"
+
+ @tool
+ def calculator(expression: str) -> str:
+ """Calculate an expression."""
+ return f"Calc: {expression}"
- # Model makes 2 tool calls, then 1 tool call, then no tool calls
model = FakeToolCallingModel(
tool_calls=[
[
- ToolCall(name="search", args={"query": "test1"}, id="1"),
- ToolCall(name="search", args={"query": "test2"}, id="2"),
+ ToolCall(name="search", args={"query": "q1"}, id="1"),
+ ToolCall(name="calculator", args={"expression": "1+1"}, id="2"),
+ ],
+ [
+ ToolCall(name="search", args={"query": "q2"}, id="3"),
+ ToolCall(name="calculator", args={"expression": "2+2"}, id="4"),
+ ],
+ [
+ ToolCall(name="search", args={"query": "q3"}, id="5"), # Should be blocked
+ ToolCall(name="calculator", args={"expression": "3+3"}, id="6"), # Should work
],
- [ToolCall(name="search", args={"query": "test3"}, id="3")],
[],
]
)
- # Run limit of 2 tool calls per run
- middleware = ToolCallLimitMiddleware(run_limit=2)
+ # Limit search to 2 calls, but allow other tools to continue
+ search_limiter = ToolCallLimitMiddleware(
+ tool_name="search", thread_limit=2, exit_behavior="continue"
+ )
agent = create_agent(
- model=model, tools=[search], middleware=[middleware], checkpointer=InMemorySaver()
+ model=model,
+ tools=[search, calculator],
+ middleware=[search_limiter],
+ checkpointer=InMemorySaver(),
)
- thread_config = {"configurable": {"thread_id": "test_thread"}}
+ result = agent.invoke(
+ {"messages": [HumanMessage("Question")]},
+ {"configurable": {"thread_id": "test_thread"}},
+ )
- # First run: 2 tool calls, should hit run limit
- result = agent.invoke({"messages": [HumanMessage("Question 1")]}, thread_config)
- last_message = result["messages"][-1]
- assert "run limit (2/2)" in last_message.content
+ tool_messages = [msg for msg in result["messages"] if isinstance(msg, ToolMessage)]
- # Second run: starts fresh, should also hit run limit after 2 calls
- result = agent.invoke({"messages": [HumanMessage("Question 2")]}, thread_config)
- last_message = result["messages"][-1]
- # This should also hit the limit because run count resets
- assert "run limit (2/2)" in last_message.content
+ # Verify search has 2 successful + 1 blocked, calculator has all 3 successful
+ successful_search_msgs = [msg for msg in tool_messages if "Search:" in msg.content]
+ blocked_search_msgs = [
+ msg
+ for msg in tool_messages
+ if "limit" in msg.content.lower() and "search" in msg.content.lower()
+ ]
+ successful_calc_msgs = [msg for msg in tool_messages if "Calc:" in msg.content]
+ assert len(successful_search_msgs) == 2, "Should have 2 successful search calls"
+ assert len(blocked_search_msgs) == 1, "Should have 1 blocked search call with limit error"
+ assert len(successful_calc_msgs) == 3, "All calculator calls should succeed"
-def test_exception_error_messages():
- """Test that exceptions provide clear error messages."""
- # Test global tool limit
- middleware = ToolCallLimitMiddleware(thread_limit=3, run_limit=2, exit_behavior="error")
- state = {
- "messages": [
- HumanMessage("Q"),
- AIMessage("R", tool_calls=[{"name": "search", "args": {}, "id": "1"}]),
- ToolMessage("Result", tool_call_id="1"),
- 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
- }
+def test_end_behavior_creates_artificial_messages():
+ """Test that 'end' behavior creates an AI message explaining why execution stopped.
- with pytest.raises(ToolCallLimitExceededError) as exc_info:
- middleware.before_model(state, None) # type: ignore[arg-type]
+ Verifies that when limit is exceeded with exit_behavior='end', the middleware:
+ 1. Injects an artificial error ToolMessage for the blocked tool call
+ 2. Adds an AI message explaining the limit to the user
+ 3. Jumps to end, stopping execution
+ """
- error_msg = str(exc_info.value)
- assert "Tool call limits exceeded" in error_msg
- assert "thread limit (3/3)" in error_msg
+ @tool
+ def search(query: str) -> str:
+ """Search for information."""
+ return f"Results: {query}"
- # Test specific tool limit
- middleware = ToolCallLimitMiddleware(tool_name="search", thread_limit=2, exit_behavior="error")
+ model = FakeToolCallingModel(
+ tool_calls=[
+ [ToolCall(name="search", args={"query": "q1"}, id="1")],
+ [ToolCall(name="search", args={"query": "q2"}, id="2")],
+ [ToolCall(name="search", args={"query": "q3"}, id="3")], # Exceeds limit
+ [],
+ ]
+ )
- state = {
- "messages": [
- HumanMessage("Q"),
- AIMessage(
- "R",
- tool_calls=[
- {"name": "search", "args": {}, "id": "1"},
- {"name": "calculator", "args": {}, "id": "2"},
- ],
- ),
- 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
- }
+ limiter = ToolCallLimitMiddleware(thread_limit=2, exit_behavior="end")
+ agent = create_agent(
+ model=model, tools=[search], middleware=[limiter], checkpointer=InMemorySaver()
+ )
- with pytest.raises(ToolCallLimitExceededError) as exc_info:
- middleware.before_model(state, None) # type: ignore[arg-type]
+ result = agent.invoke(
+ {"messages": [HumanMessage("Test")]}, {"configurable": {"thread_id": "test"}}
+ )
- error_msg = str(exc_info.value)
- assert "'search' tool call limits exceeded" in error_msg
- assert "thread limit (2/2)" in error_msg
+ # Verify AI message explaining the limit (displayed to user - includes thread/run details)
+ ai_limit_messages = [
+ msg
+ for msg in result["messages"]
+ if isinstance(msg, AIMessage) and "limit" in msg.content.lower() and not msg.tool_calls
+ ]
+ assert len(ai_limit_messages) == 1, "Should have exactly one AI message explaining the limit"
+
+ ai_msg_content = ai_limit_messages[0].content.lower()
+ assert "thread limit exceeded" in ai_msg_content or "run limit exceeded" in ai_msg_content, (
+ "AI message should include thread/run limit details for the user"
+ )
+
+ # Verify tool message counts
+ tool_messages = [msg for msg in result["messages"] if isinstance(msg, ToolMessage)]
+ successful_tool_msgs = [msg for msg in tool_messages if msg.status != "error"]
+ error_tool_msgs = [msg for msg in tool_messages if msg.status == "error"]
+
+ assert len(successful_tool_msgs) == 2, "Should have 2 successful tool messages (q1, q2)"
+ assert len(error_tool_msgs) == 1, "Should have 1 artificial error tool message (q3)"
+
+ # Verify the error tool message (sent to model - no thread/run details, includes instruction)
+ error_msg_content = error_tool_msgs[0].content
+ assert "Tool call limit exceeded" in error_msg_content
+ assert "Do not" in error_msg_content, (
+ "Tool message should instruct model not to call tool again"
+ )