The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
feat(langchain_v1): tool retry middleware (#33503)
Eugene Yurtsev8734c05f64e8
diff --git a/libs/langchain_v1/langchain/agents/middleware/__init__.py b/libs/langchain_v1/langchain/agents/middleware/__init__.pyindex 5b40667126..b06a5feb74 100644--- a/libs/langchain_v1/langchain/agents/middleware/__init__.py+++ b/libs/langchain_v1/langchain/agents/middleware/__init__.py@@ -21,6 +21,7 @@ from .summarization import SummarizationMiddlewarefrom .todo import TodoListMiddlewarefrom .tool_call_limit import ToolCallLimitMiddlewarefrom .tool_emulator import LLMToolEmulator+from .tool_retry import ToolRetryMiddlewarefrom .tool_selection import LLMToolSelectorMiddlewarefrom .types import (AgentMiddleware,@@ -55,6 +56,7 @@ __all__ = ["SummarizationMiddleware","TodoListMiddleware","ToolCallLimitMiddleware",+ "ToolRetryMiddleware","after_agent","after_model","before_agent",diff --git a/libs/langchain_v1/langchain/agents/middleware/tool_retry.py b/libs/langchain_v1/langchain/agents/middleware/tool_retry.pynew file mode 100644index 0000000000..146cf75625--- /dev/null+++ b/libs/langchain_v1/langchain/agents/middleware/tool_retry.py@@ -0,0 +1,384 @@+"""Tool retry middleware for agents."""++from __future__ import annotations++import asyncio+import random+import time+from typing import TYPE_CHECKING, Literal++from langchain_core.messages import ToolMessage++from langchain.agents.middleware.types import AgentMiddleware++if TYPE_CHECKING:+ from collections.abc import Awaitable, Callable++ from langgraph.types import Command++ from langchain.tools import BaseTool+ from langchain.tools.tool_node import ToolCallRequest+++class ToolRetryMiddleware(AgentMiddleware):+ """Middleware that automatically retries failed tool calls with configurable backoff.++ Supports retrying on specific exceptions and exponential backoff.++ Examples:+ Basic usage with default settings (2 retries, exponential backoff):+ ```python+ from langchain.agents import create_agent+ from langchain.agents.middleware import ToolRetryMiddleware++ agent = create_agent(model, tools=[search_tool], middleware=[ToolRetryMiddleware()])+ ```++ Retry specific exceptions only:+ ```python+ from requests.exceptions import RequestException, Timeout++ retry = ToolRetryMiddleware(+ max_retries=4,+ retry_on=(RequestException, Timeout),+ backoff_factor=1.5,+ )+ ```++ Custom exception filtering:+ ```python+ from requests.exceptions import HTTPError+++ def should_retry(exc: Exception) -> bool:+ # Only retry on 5xx errors+ if isinstance(exc, HTTPError):+ return 500 <= exc.status_code < 600+ return False+++ retry = ToolRetryMiddleware(+ max_retries=3,+ retry_on=should_retry,+ )+ ```++ Apply to specific tools with custom error handling:+ ```python+ def format_error(exc: Exception) -> str:+ return "Database temporarily unavailable. Please try again later."+++ retry = ToolRetryMiddleware(+ max_retries=4,+ tools=["search_database"],+ on_failure=format_error,+ )+ ```++ Apply to specific tools using BaseTool instances:+ ```python+ from langchain_core.tools import tool+++ @tool+ def search_database(query: str) -> str:+ '''Search the database.'''+ return results+++ retry = ToolRetryMiddleware(+ max_retries=4,+ tools=[search_database], # Pass BaseTool instance+ )+ ```++ Constant backoff (no exponential growth):+ ```python+ retry = ToolRetryMiddleware(+ max_retries=5,+ backoff_factor=0.0, # No exponential growth+ initial_delay=2.0, # Always wait 2 seconds+ )+ ```++ Raise exception on failure:+ ```python+ retry = ToolRetryMiddleware(+ max_retries=2,+ on_failure="raise", # Re-raise exception instead of returning message+ )+ ```+ """++ def __init__(+ self,+ *,+ max_retries: int = 2,+ tools: list[BaseTool | str] | None = None,+ retry_on: tuple[type[Exception], ...] | Callable[[Exception], bool] = (Exception,),+ on_failure: (+ Literal["raise", "return_message"] | Callable[[Exception], str]+ ) = "return_message",+ backoff_factor: float = 2.0,+ initial_delay: float = 1.0,+ max_delay: float = 60.0,+ jitter: bool = True,+ ) -> None:+ """Initialize ToolRetryMiddleware.++ Args:+ max_retries: Maximum number of retry attempts after the initial call.+ Default is 2 retries (3 total attempts). Must be >= 0.+ tools: Optional list of tools or tool names to apply retry logic to.+ Can be a list of `BaseTool` instances or tool name strings.+ If `None`, applies to all tools. Default is `None`.+ retry_on: Either a tuple of exception types to retry on, or a callable+ that takes an exception and returns `True` if it should be retried.+ Default is to retry on all exceptions.+ on_failure: Behavior when all retries are exhausted. Options:+ - `"return_message"` (default): Return a ToolMessage with error details,+ allowing the LLM to handle the failure and potentially recover.+ - `"raise"`: Re-raise the exception, stopping agent execution.+ - Custom callable: Function that takes the exception and returns a string+ for the ToolMessage content, allowing custom error formatting.+ backoff_factor: Multiplier for exponential backoff. Each retry waits+ `initial_delay * (backoff_factor ** retry_number)` seconds.+ Set to 0.0 for constant delay. Default is 2.0.+ initial_delay: Initial delay in seconds before first retry. Default is 1.0.+ max_delay: Maximum delay in seconds between retries. Caps exponential+ backoff growth. Default is 60.0.+ jitter: Whether to add random jitter (±25%) to delay to avoid thundering herd.+ Default is `True`.++ Raises:+ ValueError: If max_retries < 0 or delays are negative.+ """+ super().__init__()++ # Validate parameters+ if max_retries < 0:+ msg = "max_retries must be >= 0"+ raise ValueError(msg)+ if initial_delay < 0:+ msg = "initial_delay must be >= 0"+ raise ValueError(msg)+ if max_delay < 0:+ msg = "max_delay must be >= 0"+ raise ValueError(msg)+ if backoff_factor < 0:+ msg = "backoff_factor must be >= 0"+ raise ValueError(msg)++ self.max_retries = max_retries++ # Extract tool names from BaseTool instances or strings+ self._tool_filter: list[str] | None+ if tools is not None:+ self._tool_filter = [tool.name if not isinstance(tool, str) else tool for tool in tools]+ else:+ self._tool_filter = None++ self.tools = [] # No additional tools registered by this middleware+ self.retry_on = retry_on+ self.on_failure = on_failure+ self.backoff_factor = backoff_factor+ self.initial_delay = initial_delay+ self.max_delay = max_delay+ self.jitter = jitter++ def _should_retry_tool(self, tool_name: str) -> bool:+ """Check if retry logic should apply to this tool.++ Args:+ tool_name: Name of the tool being called.++ Returns:+ `True` if retry logic should apply, `False` otherwise.+ """+ if self._tool_filter is None:+ return True+ return tool_name in self._tool_filter++ def _should_retry_exception(self, exc: Exception) -> bool:+ """Check if the exception should trigger a retry.++ Args:+ exc: The exception that occurred.++ Returns:+ `True` if the exception should be retried, `False` otherwise.+ """+ if callable(self.retry_on):+ return self.retry_on(exc)+ return isinstance(exc, self.retry_on)++ def _calculate_delay(self, retry_number: int) -> float:+ """Calculate delay for the given retry attempt.++ Args:+ retry_number: The retry attempt number (0-indexed).++ Returns:+ Delay in seconds before next retry.+ """+ if self.backoff_factor == 0.0:+ delay = self.initial_delay+ else:+ delay = self.initial_delay * (self.backoff_factor**retry_number)++ # Cap at max_delay+ delay = min(delay, self.max_delay)++ if self.jitter and delay > 0:+ jitter_amount = delay * 0.25+ delay = delay + random.uniform(-jitter_amount, jitter_amount) # noqa: S311+ # Ensure delay is not negative after jitter+ delay = max(0, delay)++ return delay++ def _format_failure_message(self, tool_name: str, exc: Exception, attempts_made: int) -> str:+ """Format the failure message when retries are exhausted.++ Args:+ tool_name: Name of the tool that failed.+ exc: The exception that caused the failure.+ attempts_made: Number of attempts actually made.++ Returns:+ Formatted error message string.+ """+ exc_type = type(exc).__name__+ attempt_word = "attempt" if attempts_made == 1 else "attempts"+ return f"Tool '{tool_name}' failed after {attempts_made} {attempt_word} with {exc_type}"++ def _handle_failure(+ self, tool_name: str, tool_call_id: str | None, exc: Exception, attempts_made: int+ ) -> ToolMessage:+ """Handle failure when all retries are exhausted.++ Args:+ tool_name: Name of the tool that failed.+ tool_call_id: ID of the tool call (may be None).+ exc: The exception that caused the failure.+ attempts_made: Number of attempts actually made.++ Returns:+ ToolMessage with error details.++ Raises:+ Exception: If on_failure is "raise", re-raises the exception.+ """+ if self.on_failure == "raise":+ raise exc++ if callable(self.on_failure):+ content = self.on_failure(exc)+ else:+ content = self._format_failure_message(tool_name, exc, attempts_made)++ return ToolMessage(+ content=content,+ tool_call_id=tool_call_id,+ name=tool_name,+ status="error",+ )++ def wrap_tool_call(+ self,+ request: ToolCallRequest,+ handler: Callable[[ToolCallRequest], ToolMessage | Command],+ ) -> ToolMessage | Command:+ """Intercept tool execution and retry on failure.++ Args:+ request: Tool call request with call dict, BaseTool, state, and runtime.+ handler: Callable to execute the tool (can be called multiple times).++ Returns:+ ToolMessage or Command (the final result).+ """+ tool_name = request.tool.name++ # Check if retry should apply to this tool+ if not self._should_retry_tool(tool_name):+ return handler(request)++ tool_call_id = request.tool_call["id"]++ # Initial attempt + retries+ for attempt in range(self.max_retries + 1):+ try:+ return handler(request)+ except Exception as exc: # noqa: BLE001+ attempts_made = attempt + 1 # attempt is 0-indexed++ # Check if we should retry this exception+ if not self._should_retry_exception(exc):+ # Exception is not retryable, handle failure immediately+ return self._handle_failure(tool_name, tool_call_id, exc, attempts_made)++ # Check if we have more retries left+ if attempt < self.max_retries:+ # Calculate and apply backoff delay+ delay = self._calculate_delay(attempt)+ if delay > 0:+ time.sleep(delay)+ # Continue to next retry+ else:+ # No more retries, handle failure+ return self._handle_failure(tool_name, tool_call_id, exc, attempts_made)++ # Unreachable: loop always returns via handler success or _handle_failure+ msg = "Unexpected: retry loop completed without returning"+ raise RuntimeError(msg)++ async def awrap_tool_call(+ self,+ request: ToolCallRequest,+ handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]],+ ) -> ToolMessage | Command:+ """Intercept and control async tool execution with retry logic.++ Args:+ request: Tool call request with call dict, BaseTool, state, and runtime.+ handler: Async callable to execute the tool and returns ToolMessage or Command.++ Returns:+ ToolMessage or Command (the final result).+ """+ tool_name = request.tool.name++ # Check if retry should apply to this tool+ if not self._should_retry_tool(tool_name):+ return await handler(request)++ tool_call_id = request.tool_call["id"]++ # Initial attempt + retries+ for attempt in range(self.max_retries + 1):+ try:+ return await handler(request)+ except Exception as exc: # noqa: BLE001+ attempts_made = attempt + 1 # attempt is 0-indexed++ # Check if we should retry this exception+ if not self._should_retry_exception(exc):+ # Exception is not retryable, handle failure immediately+ return self._handle_failure(tool_name, tool_call_id, exc, attempts_made)++ # Check if we have more retries left+ if attempt < self.max_retries:+ # Calculate and apply backoff delay+ delay = self._calculate_delay(attempt)+ if delay > 0:+ await asyncio.sleep(delay)+ # Continue to next retry+ else:+ # No more retries, handle failure+ return self._handle_failure(tool_name, tool_call_id, exc, attempts_made)++ # Unreachable: loop always returns via handler success or _handle_failure+ msg = "Unexpected: retry loop completed without returning"+ raise RuntimeError(msg)diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/test_tool_retry.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/test_tool_retry.pynew file mode 100644index 0000000000..88faa0deb1--- /dev/null+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/test_tool_retry.py@@ -0,0 +1,895 @@+"""Tests for ToolRetryMiddleware functionality."""++import asyncio+import time+from collections.abc import Callable++import pytest+from langchain_core.messages import 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_retry import ToolRetryMiddleware+from tests.unit_tests.agents.test_middleware_agent import FakeToolCallingModel+++@tool+def working_tool(input: str) -> str:+ """Tool that always succeeds."""+ return f"Success: {input}"+++@tool+def failing_tool(input: str) -> str:+ """Tool that always fails."""+ msg = f"Failed: {input}"+ raise ValueError(msg)+++class TemporaryFailureTool:+ """Tool that fails a certain number of times before succeeding."""++ def __init__(self, fail_count: int):+ """Initialize with the number of times to fail.++ Args:+ fail_count: Number of times to fail before succeeding.+ """+ self.fail_count = fail_count+ self.attempt = 0++ def __call__(self, input: str) -> str:+ """Execute the tool.++ Args:+ input: Input string.++ Returns:+ Success message if attempt >= fail_count.++ Raises:+ ValueError: If attempt < fail_count.+ """+ self.attempt += 1+ if self.attempt <= self.fail_count:+ msg = f"Temporary failure {self.attempt}"+ raise ValueError(msg)+ return f"Success after {self.attempt} attempts: {input}"+++def test_tool_retry_initialization_defaults() -> None:+ """Test ToolRetryMiddlewareinitialization with default values."""+ retry = ToolRetryMiddleware()++ assert retry.max_retries == 2+ assert retry._tool_filter is None+ assert retry.tools == []+ assert retry.on_failure == "return_message"+ assert retry.backoff_factor == 2.0+ assert retry.initial_delay == 1.0+ assert retry.max_delay == 60.0+ assert retry.jitter is True+++def test_tool_retry_initialization_custom() -> None:+ """Test ToolRetryMiddlewareinitialization with custom values."""+ retry = ToolRetryMiddleware(+ max_retries=5,+ tools=["tool1", "tool2"],+ retry_on=(ValueError, RuntimeError),+ on_failure="raise",+ backoff_factor=1.5,+ initial_delay=0.5,+ max_delay=30.0,+ jitter=False,+ )++ assert retry.max_retries == 5+ assert retry._tool_filter == ["tool1", "tool2"]+ assert retry.tools == []+ assert retry.retry_on == (ValueError, RuntimeError)+ assert retry.on_failure == "raise"+ assert retry.backoff_factor == 1.5+ assert retry.initial_delay == 0.5+ assert retry.max_delay == 30.0+ assert retry.jitter is False+++def test_tool_retry_initialization_with_base_tools() -> None:+ """Test ToolRetryMiddleware initialization with BaseTool instances."""+ retry = ToolRetryMiddleware(+ max_retries=3,+ tools=[working_tool, failing_tool], # Pass BaseTool instances+ )++ assert retry.max_retries == 3+ # Should extract names from BaseTool instances+ assert retry._tool_filter == ["working_tool", "failing_tool"]+ assert retry.tools == []+++def test_tool_retry_initialization_with_mixed_tools() -> None:+ """Test ToolRetryMiddleware initialization with mixed tool types."""+ retry = ToolRetryMiddleware(+ max_retries=2,+ tools=[working_tool, "failing_tool"], # Mix of BaseTool and string+ )++ assert retry.max_retries == 2+ # Should handle both BaseTool instances and strings+ assert retry._tool_filter == ["working_tool", "failing_tool"]+ assert retry.tools == []+++def test_tool_retry_invalid_max_retries() -> None:+ """Test ToolRetryMiddlewareraises error for invalid max_retries."""+ with pytest.raises(ValueError, match="max_retries must be >= 0"):+ ToolRetryMiddleware(max_retries=-1)+++def test_tool_retry_invalid_initial_delay() -> None:+ """Test ToolRetryMiddlewareraises error for invalid initial_delay."""+ with pytest.raises(ValueError, match="initial_delay must be >= 0"):+ ToolRetryMiddleware(initial_delay=-1.0)+++def test_tool_retry_invalid_max_delay() -> None:+ """Test ToolRetryMiddlewareraises error for invalid max_delay."""+ with pytest.raises(ValueError, match="max_delay must be >= 0"):+ ToolRetryMiddleware(max_delay=-1.0)+++def test_tool_retry_invalid_backoff_factor() -> None:+ """Test ToolRetryMiddlewareraises error for invalid backoff_factor."""+ with pytest.raises(ValueError, match="backoff_factor must be >= 0"):+ ToolRetryMiddleware(backoff_factor=-1.0)+++def test_tool_retry_working_tool_no_retry_needed() -> None:+ """Test ToolRetryMiddlewarewith a working tool (no retry needed)."""+ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="working_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(max_retries=2, initial_delay=0.01, jitter=False)++ agent = create_agent(+ model=model,+ tools=[working_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ result = agent.invoke(+ {"messages": [HumanMessage("Use working tool")]},+ {"configurable": {"thread_id": "test"}},+ )++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1+ assert "Success: test" in tool_messages[0].content+ assert tool_messages[0].status != "error"+++def test_tool_retry_failing_tool_returns_message() -> None:+ """Test ToolRetryMiddlewarewith failing tool returns error message."""+ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(+ max_retries=2,+ initial_delay=0.01,+ jitter=False,+ on_failure="return_message",+ )++ agent = create_agent(+ model=model,+ tools=[failing_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ result = agent.invoke(+ {"messages": [HumanMessage("Use failing tool")]},+ {"configurable": {"thread_id": "test"}},+ )++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1+ # Should contain error message with tool name and attempts+ assert "failing_tool" in tool_messages[0].content+ assert "3 attempts" in tool_messages[0].content+ assert "ValueError" in tool_messages[0].content+ assert tool_messages[0].status == "error"+++def test_tool_retry_failing_tool_raises() -> None:+ """Test ToolRetryMiddlewarewith on_failure='raise' re-raises exception."""+ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(+ max_retries=2,+ initial_delay=0.01,+ jitter=False,+ on_failure="raise",+ )++ agent = create_agent(+ model=model,+ tools=[failing_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ # Should raise the ValueError from the tool+ with pytest.raises(ValueError, match="Failed: test"):+ agent.invoke(+ {"messages": [HumanMessage("Use failing tool")]},+ {"configurable": {"thread_id": "test"}},+ )+++def test_tool_retry_custom_failure_formatter() -> None:+ """Test ToolRetryMiddlewarewith custom failure message formatter."""++ def custom_formatter(exc: Exception) -> str:+ return f"Custom error: {type(exc).__name__}"++ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(+ max_retries=1,+ initial_delay=0.01,+ jitter=False,+ on_failure=custom_formatter,+ )++ agent = create_agent(+ model=model,+ tools=[failing_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ result = agent.invoke(+ {"messages": [HumanMessage("Use failing tool")]},+ {"configurable": {"thread_id": "test"}},+ )++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1+ assert "Custom error: ValueError" in tool_messages[0].content+++def test_tool_retry_succeeds_after_retries() -> None:+ """Test ToolRetryMiddlewaresucceeds after temporary failures."""+ temp_fail = TemporaryFailureTool(fail_count=2)++ @tool+ def temp_failing_tool(input: str) -> str:+ """Tool that fails temporarily."""+ return temp_fail(input)++ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(+ max_retries=3,+ initial_delay=0.01,+ jitter=False,+ )++ agent = create_agent(+ model=model,+ tools=[temp_failing_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ result = agent.invoke(+ {"messages": [HumanMessage("Use temp failing tool")]},+ {"configurable": {"thread_id": "test"}},+ )++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1+ # Should succeed on 3rd attempt+ assert "Success after 3 attempts" in tool_messages[0].content+ assert tool_messages[0].status != "error"+++def test_tool_retry_specific_tools_only() -> None:+ """Test ToolRetryMiddlewareonly applies to specific tools."""+ model = FakeToolCallingModel(+ tool_calls=[+ [+ ToolCall(name="failing_tool", args={"input": "test1"}, id="1"),+ ToolCall(name="working_tool", args={"input": "test2"}, id="2"),+ ],+ [],+ ]+ )++ # Only retry failing_tool+ retry = ToolRetryMiddleware(+ max_retries=2,+ tools=["failing_tool"],+ initial_delay=0.01,+ jitter=False,+ on_failure="return_message",+ )++ agent = create_agent(+ model=model,+ tools=[failing_tool, working_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ result = agent.invoke(+ {"messages": [HumanMessage("Use both tools")]},+ {"configurable": {"thread_id": "test"}},+ )++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 2++ # failing_tool should have error message+ failing_msg = next(m for m in tool_messages if m.name == "failing_tool")+ assert failing_msg.status == "error"+ assert "3 attempts" in failing_msg.content++ # working_tool should succeed normally (no retry applied)+ working_msg = next(m for m in tool_messages if m.name == "working_tool")+ assert "Success: test2" in working_msg.content+ assert working_msg.status != "error"+++def test_tool_retry_specific_tools_with_base_tool() -> None:+ """Test ToolRetryMiddleware accepts BaseTool instances for filtering."""+ model = FakeToolCallingModel(+ tool_calls=[+ [+ ToolCall(name="failing_tool", args={"input": "test1"}, id="1"),+ ToolCall(name="working_tool", args={"input": "test2"}, id="2"),+ ],+ [],+ ]+ )++ # Only retry failing_tool, passed as BaseTool instance+ retry = ToolRetryMiddleware(+ max_retries=2,+ tools=[failing_tool], # Pass BaseTool instance+ initial_delay=0.01,+ jitter=False,+ on_failure="return_message",+ )++ agent = create_agent(+ model=model,+ tools=[failing_tool, working_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ result = agent.invoke(+ {"messages": [HumanMessage("Use both tools")]},+ {"configurable": {"thread_id": "test"}},+ )++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 2++ # failing_tool should have error message (with retries)+ failing_msg = next(m for m in tool_messages if m.name == "failing_tool")+ assert failing_msg.status == "error"+ assert "3 attempts" in failing_msg.content++ # working_tool should succeed normally (no retry applied)+ working_msg = next(m for m in tool_messages if m.name == "working_tool")+ assert "Success: test2" in working_msg.content+ assert working_msg.status != "error"+++def test_tool_retry_specific_exceptions() -> None:+ """Test ToolRetryMiddlewareonly retries specific exception types."""++ @tool+ def value_error_tool(input: str) -> str:+ """Tool that raises ValueError."""+ msg = f"ValueError: {input}"+ raise ValueError(msg)++ @tool+ def runtime_error_tool(input: str) -> str:+ """Tool that raises RuntimeError."""+ msg = f"RuntimeError: {input}"+ raise RuntimeError(msg)++ model = FakeToolCallingModel(+ tool_calls=[+ [+ ToolCall(name="value_error_tool", args={"input": "test1"}, id="1"),+ ToolCall(name="runtime_error_tool", args={"input": "test2"}, id="2"),+ ],+ [],+ ]+ )++ # Only retry ValueError+ retry = ToolRetryMiddleware(+ max_retries=2,+ retry_on=(ValueError,),+ initial_delay=0.01,+ jitter=False,+ on_failure="return_message",+ )++ agent = create_agent(+ model=model,+ tools=[value_error_tool, runtime_error_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ result = agent.invoke(+ {"messages": [HumanMessage("Use both tools")]},+ {"configurable": {"thread_id": "test"}},+ )++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 2++ # ValueError should be retried (3 attempts)+ value_error_msg = next(m for m in tool_messages if m.name == "value_error_tool")+ assert "3 attempts" in value_error_msg.content++ # RuntimeError should fail immediately (1 attempt only)+ runtime_error_msg = next(m for m in tool_messages if m.name == "runtime_error_tool")+ assert "1 attempt" in runtime_error_msg.content+++def test_tool_retry_custom_exception_filter() -> None:+ """Test ToolRetryMiddlewarewith custom exception filter function."""++ class CustomError(Exception):+ """Custom exception with retry_me attribute."""++ def __init__(self, message: str, retry_me: bool):+ """Initialize custom error.++ Args:+ message: Error message.+ retry_me: Whether this error should be retried.+ """+ super().__init__(message)+ self.retry_me = retry_me++ attempt_count = {"value": 0}++ @tool+ def custom_error_tool(input: str) -> str:+ """Tool that raises CustomError."""+ attempt_count["value"] += 1+ if attempt_count["value"] == 1:+ raise CustomError("Retryable error", retry_me=True)+ raise CustomError("Non-retryable error", retry_me=False)++ def should_retry(exc: Exception) -> bool:+ return isinstance(exc, CustomError) and exc.retry_me++ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="custom_error_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(+ max_retries=3,+ retry_on=should_retry,+ initial_delay=0.01,+ jitter=False,+ on_failure="return_message",+ )++ agent = create_agent(+ model=model,+ tools=[custom_error_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ result = agent.invoke(+ {"messages": [HumanMessage("Use custom error tool")]},+ {"configurable": {"thread_id": "test"}},+ )++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1++ # Should retry once (attempt 1 with retry_me=True), then fail on attempt 2 (retry_me=False)+ assert attempt_count["value"] == 2+ assert "2 attempts" in tool_messages[0].content+++def test_tool_retry_backoff_timing() -> None:+ """Test ToolRetryMiddlewareapplies correct backoff delays."""+ temp_fail = TemporaryFailureTool(fail_count=3)++ @tool+ def temp_failing_tool(input: str) -> str:+ """Tool that fails temporarily."""+ return temp_fail(input)++ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(+ max_retries=3,+ initial_delay=0.1,+ backoff_factor=2.0,+ jitter=False,+ )++ agent = create_agent(+ model=model,+ tools=[temp_failing_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ start_time = time.time()+ result = agent.invoke(+ {"messages": [HumanMessage("Use temp failing tool")]},+ {"configurable": {"thread_id": "test"}},+ )+ elapsed = time.time() - start_time++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1++ # Expected delays: 0.1 + 0.2 + 0.4 = 0.7 seconds+ # Allow some margin for execution time+ assert elapsed >= 0.6, f"Expected at least 0.6s, got {elapsed}s"+++def test_tool_retry_constant_backoff() -> None:+ """Test ToolRetryMiddlewarewith constant backoff (backoff_factor=0)."""+ temp_fail = TemporaryFailureTool(fail_count=2)++ @tool+ def temp_failing_tool(input: str) -> str:+ """Tool that fails temporarily."""+ return temp_fail(input)++ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(+ max_retries=2,+ initial_delay=0.1,+ backoff_factor=0.0, # Constant backoff+ jitter=False,+ )++ agent = create_agent(+ model=model,+ tools=[temp_failing_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ start_time = time.time()+ result = agent.invoke(+ {"messages": [HumanMessage("Use temp failing tool")]},+ {"configurable": {"thread_id": "test"}},+ )+ elapsed = time.time() - start_time++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1++ # Expected delays: 0.1 + 0.1 = 0.2 seconds (constant)+ assert elapsed >= 0.15, f"Expected at least 0.15s, got {elapsed}s"+ assert elapsed < 0.5, f"Expected less than 0.5s (exponential would be longer), got {elapsed}s"+++def test_tool_retry_max_delay_cap() -> None:+ """Test ToolRetryMiddlewarecaps delay at max_delay."""+ retry = ToolRetryMiddleware(+ max_retries=5,+ initial_delay=1.0,+ backoff_factor=10.0, # Very aggressive backoff+ max_delay=2.0, # Cap at 2 seconds+ jitter=False,+ )++ # Test delay calculation+ delay_0 = retry._calculate_delay(0) # 1.0+ delay_1 = retry._calculate_delay(1) # 10.0 -> capped to 2.0+ delay_2 = retry._calculate_delay(2) # 100.0 -> capped to 2.0++ assert delay_0 == 1.0+ assert delay_1 == 2.0+ assert delay_2 == 2.0+++def test_tool_retry_jitter_variation() -> None:+ """Test ToolRetryMiddlewareadds jitter to delays."""+ retry = ToolRetryMiddleware(+ max_retries=1,+ initial_delay=1.0,+ backoff_factor=1.0,+ jitter=True,+ )++ # Generate multiple delays and ensure they vary+ delays = [retry._calculate_delay(0) for _ in range(10)]++ # All delays should be within ±25% of 1.0 (i.e., between 0.75 and 1.25)+ for delay in delays:+ assert 0.75 <= delay <= 1.25++ # Delays should vary (not all the same)+ assert len(set(delays)) > 1+++async def test_tool_retry_async_working_tool() -> None:+ """Test ToolRetryMiddlewarewith async execution and working tool."""+ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="working_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(max_retries=2, initial_delay=0.01, jitter=False)++ agent = create_agent(+ model=model,+ tools=[working_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ result = await agent.ainvoke(+ {"messages": [HumanMessage("Use working tool")]},+ {"configurable": {"thread_id": "test"}},+ )++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1+ assert "Success: test" in tool_messages[0].content+++async def test_tool_retry_async_failing_tool() -> None:+ """Test ToolRetryMiddlewarewith async execution and failing tool."""+ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(+ max_retries=2,+ initial_delay=0.01,+ jitter=False,+ on_failure="return_message",+ )++ agent = create_agent(+ model=model,+ tools=[failing_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ result = await agent.ainvoke(+ {"messages": [HumanMessage("Use failing tool")]},+ {"configurable": {"thread_id": "test"}},+ )++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1+ assert "failing_tool" in tool_messages[0].content+ assert "3 attempts" in tool_messages[0].content+ assert tool_messages[0].status == "error"+++async def test_tool_retry_async_succeeds_after_retries() -> None:+ """Test ToolRetryMiddlewareasync execution succeeds after temporary failures."""+ temp_fail = TemporaryFailureTool(fail_count=2)++ @tool+ def temp_failing_tool(input: str) -> str:+ """Tool that fails temporarily."""+ return temp_fail(input)++ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(+ max_retries=3,+ initial_delay=0.01,+ jitter=False,+ )++ agent = create_agent(+ model=model,+ tools=[temp_failing_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ result = await agent.ainvoke(+ {"messages": [HumanMessage("Use temp failing tool")]},+ {"configurable": {"thread_id": "test"}},+ )++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1+ assert "Success after 3 attempts" in tool_messages[0].content+++async def test_tool_retry_async_backoff_timing() -> None:+ """Test ToolRetryMiddlewareasync applies correct backoff delays."""+ temp_fail = TemporaryFailureTool(fail_count=3)++ @tool+ def temp_failing_tool(input: str) -> str:+ """Tool that fails temporarily."""+ return temp_fail(input)++ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="temp_failing_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(+ max_retries=3,+ initial_delay=0.1,+ backoff_factor=2.0,+ jitter=False,+ )++ agent = create_agent(+ model=model,+ tools=[temp_failing_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ start_time = time.time()+ result = await agent.ainvoke(+ {"messages": [HumanMessage("Use temp failing tool")]},+ {"configurable": {"thread_id": "test"}},+ )+ elapsed = time.time() - start_time++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1++ # Expected delays: 0.1 + 0.2 + 0.4 = 0.7 seconds+ assert elapsed >= 0.6, f"Expected at least 0.6s, got {elapsed}s"+++def test_tool_retry_zero_retries() -> None:+ """Test ToolRetryMiddlewarewith max_retries=0 (no retries)."""+ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="failing_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(+ max_retries=0, # No retries+ on_failure="return_message",+ )++ agent = create_agent(+ model=model,+ tools=[failing_tool],+ middleware=[retry],+ checkpointer=InMemorySaver(),+ )++ result = agent.invoke(+ {"messages": [HumanMessage("Use failing tool")]},+ {"configurable": {"thread_id": "test"}},+ )++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1+ # Should fail after 1 attempt (no retries)+ assert "1 attempt" in tool_messages[0].content+ assert tool_messages[0].status == "error"+++def test_tool_retry_multiple_middleware_composition() -> None:+ """Test ToolRetryMiddlewarecomposes correctly with other middleware."""+ call_log = []++ # Custom middleware that logs calls+ from langchain.agents.middleware.types import wrap_tool_call++ @wrap_tool_call+ def logging_middleware(+ request: "ToolCallRequest", handler: Callable+ ) -> "ToolMessage | Command":+ call_log.append(f"before_{request.tool.name}")+ response = handler(request)+ call_log.append(f"after_{request.tool.name}")+ return response++ model = FakeToolCallingModel(+ tool_calls=[+ [ToolCall(name="working_tool", args={"input": "test"}, id="1")],+ [],+ ]+ )++ retry = ToolRetryMiddleware(max_retries=2, initial_delay=0.01, jitter=False)++ agent = create_agent(+ model=model,+ tools=[working_tool],+ middleware=[logging_middleware, retry],+ checkpointer=InMemorySaver(),+ )++ result = agent.invoke(+ {"messages": [HumanMessage("Use working tool")]},+ {"configurable": {"thread_id": "test"}},+ )++ # Both middleware should be called+ assert call_log == ["before_working_tool", "after_working_tool"]++ tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]+ assert len(tool_messages) == 1+ assert "Success: test" in tool_messages[0].content