Skip to content

The agent engineering platform.

chore(langchain_v1): rename on_tool_call to wrap_tool_call (#33366)

Eugene Yurtsev87df179ca973
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.py
index 0a0f53fbf3..860342d939 100644
--- a/libs/langchain_v1/langchain/agents/factory.py
+++ b/libs/langchain_v1/langchain/agents/factory.py
@@ -545,16 +545,16 @@ def create_agent( # noqa: PLR0915
structured_output_tools[structured_tool_info.tool.name] = structured_tool_info
middleware_tools = [t for m in middleware for t in getattr(m, "tools", [])]
- # Collect middleware with on_tool_call hooks
- middleware_w_on_tool_call = [
- m for m in middleware if m.__class__.on_tool_call is not AgentMiddleware.on_tool_call
+ # Collect middleware with wrap_tool_call hooks
+ middleware_w_wrap_tool_call = [
+ m for m in middleware if m.__class__.wrap_tool_call is not AgentMiddleware.wrap_tool_call
]
- # Chain all on_tool_call handlers into a single composed handler
- on_tool_call_handler = None
- if middleware_w_on_tool_call:
- handlers = [m.on_tool_call for m in middleware_w_on_tool_call]
- on_tool_call_handler = _chain_tool_call_handlers(handlers)
+ # Chain all wrap_tool_call handlers into a single composed handler
+ wrap_tool_call_handler = None
+ if middleware_w_wrap_tool_call:
+ handlers = [m.wrap_tool_call for m in middleware_w_wrap_tool_call]
+ wrap_tool_call_handler = _chain_tool_call_handlers(handlers)
# Setup tools
tool_node: ToolNode | None = None
@@ -567,7 +567,7 @@ def create_agent( # noqa: PLR0915
# Only create ToolNode if we have client-side tools
tool_node = (
- ToolNode(tools=available_tools, on_tool_call=on_tool_call_handler)
+ ToolNode(tools=available_tools, on_tool_call=wrap_tool_call_handler)
if available_tools
else None
)
diff --git a/libs/langchain_v1/langchain/agents/middleware/types.py b/libs/langchain_v1/langchain/agents/middleware/types.py
index 7a9f2ca4e0..d55796c13d 100644
--- a/libs/langchain_v1/langchain/agents/middleware/types.py
+++ b/libs/langchain_v1/langchain/agents/middleware/types.py
@@ -54,6 +54,7 @@ __all__ = [
"hook_config",
"modify_model_request",
"on_model_call",
+ "wrap_tool_call",
]
JumpTo = Literal["tools", "model", "end"]
@@ -278,7 +279,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):
) -> dict[str, Any] | None:
"""Async logic to run after the agent execution completes."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -302,18 +303,18 @@ class AgentMiddleware(Generic[StateT, ContextT]):
Examples:
Passthrough (execute once):
- def on_tool_call(self, request, handler):
+ def wrap_tool_call(self, request, handler):
return handler(request)
Modify request before execution:
- def on_tool_call(self, request, handler):
+ def wrap_tool_call(self, request, handler):
request.tool_call["args"]["value"] *= 2
return handler(request)
Retry on error (call handler multiple times):
- def on_tool_call(self, request, handler):
+ def wrap_tool_call(self, request, handler):
for attempt in range(3):
try:
result = handler(request)
@@ -326,7 +327,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):
Conditional retry based on response:
- def on_tool_call(self, request, handler):
+ def wrap_tool_call(self, request, handler):
for attempt in range(3):
result = handler(request)
if isinstance(result, ToolMessage) and result.status != "error":
@@ -337,7 +338,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):
Access state and runtime:
- def on_tool_call(self, request, handler):
+ def wrap_tool_call(self, request, handler):
# Access state from request
messages = request.state.get("messages", [])
# Access runtime from request
@@ -389,6 +390,21 @@ class _CallableReturningModelResponse(Protocol[StateT_contra, ContextT]): # typ
...
+class _CallableReturningToolResponse(Protocol):
+ """Callable for tool call interception with handler callback.
+
+ Receives handler callback to execute tool and returns final ToolMessage or Command.
+ """
+
+ def __call__(
+ self,
+ request: ToolCallRequest,
+ handler: Callable[[ToolCallRequest], ToolMessage | Command],
+ ) -> ToolMessage | Command:
+ """Intercept tool execution via handler callback."""
+ ...
+
+
CallableT = TypeVar("CallableT", bound=Callable[..., Any])
@@ -1367,3 +1383,115 @@ def on_model_call(
if func is not None:
return decorator(func)
return decorator
+
+
+@overload
+def wrap_tool_call(
+ func: _CallableReturningToolResponse,
+) -> AgentMiddleware: ...
+
+
+@overload
+def wrap_tool_call(
+ func: None = None,
+ *,
+ tools: list[BaseTool] | None = None,
+ name: str | None = None,
+) -> Callable[
+ [_CallableReturningToolResponse],
+ AgentMiddleware,
+]: ...
+
+
+def wrap_tool_call(
+ func: _CallableReturningToolResponse | None = None,
+ *,
+ tools: list[BaseTool] | None = None,
+ name: str | None = None,
+) -> (
+ Callable[
+ [_CallableReturningToolResponse],
+ AgentMiddleware,
+ ]
+ | AgentMiddleware
+):
+ """Create middleware with wrap_tool_call hook from a function.
+
+ Converts a function with handler callback into middleware that can intercept
+ tool calls, implement retry logic, monitor execution, and modify responses.
+
+ Args:
+ func: Function accepting (request, handler) that calls
+ handler(request) to execute the tool and returns final ToolMessage or Command.
+ tools: Additional tools to register with this middleware.
+ name: Middleware class name. Defaults to function name.
+
+ Returns:
+ AgentMiddleware instance if func provided, otherwise a decorator.
+
+ Examples:
+ Basic passthrough:
+ ```python
+ @wrap_tool_call
+ def passthrough(request, handler):
+ return handler(request)
+ ```
+
+ Retry logic:
+ ```python
+ @wrap_tool_call
+ def retry_on_error(request, handler):
+ max_retries = 3
+ for attempt in range(max_retries):
+ try:
+ return handler(request)
+ except Exception:
+ if attempt == max_retries - 1:
+ raise
+ ```
+
+ Modify request:
+ ```python
+ @wrap_tool_call
+ def modify_args(request, handler):
+ request.tool_call["args"]["value"] *= 2
+ return handler(request)
+ ```
+
+ Short-circuit with cached result:
+ ```python
+ @wrap_tool_call
+ def with_cache(request, handler):
+ if cached := get_cache(request):
+ return ToolMessage(content=cached, tool_call_id=request.tool_call["id"])
+ result = handler(request)
+ save_cache(request, result)
+ return result
+ ```
+ """
+
+ def decorator(
+ func: _CallableReturningToolResponse,
+ ) -> AgentMiddleware:
+ def wrapped(
+ self: AgentMiddleware, # noqa: ARG001
+ request: ToolCallRequest,
+ handler: Callable[[ToolCallRequest], ToolMessage | Command],
+ ) -> ToolMessage | Command:
+ return func(request, handler)
+
+ middleware_name = name or cast("str", getattr(func, "__name__", "WrapToolCallMiddleware"))
+
+ return type(
+ middleware_name,
+ (AgentMiddleware,),
+ {
+ "state_schema": AgentState,
+ "tools": tools or [],
+ "wrap_tool_call": wrapped,
+ },
+ )()
+
+ if func is not None:
+ return decorator(func)
+ return decorator
diff --git a/libs/langchain_v1/langchain/tools/tool_node.py b/libs/langchain_v1/langchain/tools/tool_node.py
index 4eed09b650..c8b40576a2 100644
--- a/libs/langchain_v1/langchain/tools/tool_node.py
+++ b/libs/langchain_v1/langchain/tools/tool_node.py
@@ -105,7 +105,7 @@ TOOL_INVOCATION_ERROR_TEMPLATE = (
@dataclass()
class ToolCallRequest:
- """Tool execution request passed to on_tool_call handlers.
+ """Tool execution request passed to tool call interceptors.
Attributes:
tool_call: Tool call dict with name, args, and id from model output.
@@ -139,7 +139,7 @@ is independent and stateless.
Note:
When implementing middleware for ``create_agent``, use
- ``AgentMiddleware.on_tool_call`` which provides properly typed
+ ``AgentMiddleware.wrap_tool_call`` which provides properly typed
state parameter for better type safety.
Examples:
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_on_tool_call_middleware.py b/libs/langchain_v1/tests/unit_tests/agents/test_on_tool_call_middleware.py
index bbe22082ef..bdd01ed700 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_on_tool_call_middleware.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_on_tool_call_middleware.py
@@ -1,4 +1,4 @@
-"""Unit tests for on_tool_call middleware integration."""
+"""Unit tests for wrap_tool_call middleware integration."""
from collections.abc import Callable
@@ -40,7 +40,7 @@ def test_simple_logging_middleware() -> None:
class LoggingMiddleware(AgentMiddleware):
"""Middleware that logs tool calls."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -81,7 +81,7 @@ def test_request_modification_middleware() -> None:
class ModifyArgsMiddleware(AgentMiddleware):
"""Middleware that modifies tool arguments."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -123,7 +123,7 @@ def test_response_inspection_middleware() -> None:
class ResponseInspectionMiddleware(AgentMiddleware):
"""Middleware that inspects responses."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -173,7 +173,7 @@ def test_conditional_retry_middleware() -> None:
class ConditionalRetryMiddleware(AgentMiddleware):
"""Middleware that retries based on response content."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -232,7 +232,7 @@ def test_multiple_middleware_composition() -> None:
class OuterMiddleware(AgentMiddleware):
"""Outer middleware."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -245,7 +245,7 @@ def test_multiple_middleware_composition() -> None:
class InnerMiddleware(AgentMiddleware):
"""Inner middleware."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -287,7 +287,7 @@ def test_middleware_with_multiple_tool_calls() -> None:
class LoggingMiddleware(AgentMiddleware):
"""Middleware that logs tool calls."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -333,7 +333,7 @@ def test_middleware_access_to_state() -> None:
class StateInspectionMiddleware(AgentMiddleware):
"""Middleware that inspects state."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -413,7 +413,7 @@ def test_generator_composition_immediate_outer_return() -> None:
class ImmediateReturnMiddleware(AgentMiddleware):
"""Outer middleware that intercepts and modifies response."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -433,7 +433,7 @@ def test_generator_composition_immediate_outer_return() -> None:
class InnerMiddleware(AgentMiddleware):
"""Inner middleware."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -477,7 +477,7 @@ def test_generator_composition_short_circuit() -> None:
class OuterMiddleware(AgentMiddleware):
"""Outer middleware."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -498,7 +498,7 @@ def test_generator_composition_short_circuit() -> None:
class InnerShortCircuitMiddleware(AgentMiddleware):
"""Inner middleware that short-circuits without calling actual tool."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -545,7 +545,7 @@ def test_generator_composition_nested_retries() -> None:
class OuterRetryMiddleware(AgentMiddleware):
"""Outer middleware with retry logic."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -563,7 +563,7 @@ def test_generator_composition_nested_retries() -> None:
class InnerRetryMiddleware(AgentMiddleware):
"""Inner middleware with retry logic."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -622,7 +622,7 @@ def test_generator_composition_three_levels() -> None:
class OuterMiddleware(AgentMiddleware):
"""Outermost middleware."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -635,7 +635,7 @@ def test_generator_composition_three_levels() -> None:
class MiddleMiddleware(AgentMiddleware):
"""Middle middleware."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -648,7 +648,7 @@ def test_generator_composition_three_levels() -> None:
class InnerMiddleware(AgentMiddleware):
"""Innermost middleware."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -698,7 +698,7 @@ def test_generator_composition_return_value_extraction() -> None:
class ModifyingMiddleware(AgentMiddleware):
"""Middleware that modifies the final result."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -750,7 +750,7 @@ def test_generator_composition_with_mixed_passthrough_and_intercepting() -> None
class FirstPassthroughMiddleware(AgentMiddleware):
"""First middleware that passes through."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -763,7 +763,7 @@ def test_generator_composition_with_mixed_passthrough_and_intercepting() -> None
class SecondInterceptingMiddleware(AgentMiddleware):
"""Second middleware that intercepts and returns custom result."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
@@ -781,7 +781,7 @@ def test_generator_composition_with_mixed_passthrough_and_intercepting() -> None
class ThirdPassthroughMiddleware(AgentMiddleware):
"""Third middleware that passes through."""
- def on_tool_call(
+ def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
diff --git a/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py b/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py
index c2d4fb5855..f683e7909d 100644
--- a/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py
+++ b/libs/langchain_v1/tests/unit_tests/tools/test_on_tool_call.py
@@ -1,4 +1,4 @@
-"""Unit tests for on_tool_call handler in ToolNode."""
+"""Unit tests for tool call interceptor in ToolNode."""
from collections.abc import Callable