`ToolRetryMiddleware`: default settings retry non-idempotent tools on ambiguous transport errors, then ask the model to retry again
Submission checklist
- This is a bug, not a usage question.
- I added a clear and descriptive title that summarizes this issue.
- I used the GitHub search to find a similar question and didn't find it.
- I am sure that this is a bug in LangChain rather than my code.
- The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).
- This is not related to the langchain-community package.
- I posted a self-contained, minimal, reproducible example. A maintainer can copy it and run it AS IS.
Package (Required)
- langchain
- langchain-openai
- langchain-anthropic
- langchain-classic
- langchain-core
- langchain-model-profiles
- langchain-tests
- langchain-text-splitters
- langchain-chroma
- langchain-deepseek
- langchain-exa
- langchain-fireworks
- langchain-groq
- langchain-huggingface
- langchain-mistralai
- langchain-nomic
- langchain-ollama
- langchain-openrouter
- langchain-perplexity
- langchain-qdrant
- langchain-typesafe
- langchain-xai
- Other / not sure / general
Related Issues / PRs
No response
Reproduction Steps / Example Code (Python)
import httpx
from langchain.agents import create_agent
from langchain.agents.middleware import ToolRetryMiddleware
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.tools import tool
CALLS = []
@tool
def charge_card(operation_id: str, amount: str) -> str:
"""Charge a card. Irreversible."""
CALLS.append(operation_id) # the external effect, already committed
raise httpx.ReadTimeout("The read operation timed out") # the response is lost
class ScriptedModel(GenericFakeChatModel):
def bind_tools(self, tools, **kwargs):
return self
model = ScriptedModel(messages=iter([
AIMessage(content="", tool_calls=[{
"name": "charge_card",
"args": {"operation_id": "op-1", "amount": "100.00"},
"id": "call_1", "type": "tool_call",
}]),
AIMessage(content="Finished."),
]))
agent = create_agent(model=model, tools=[charge_card],
middleware=[ToolRetryMiddleware()]) # all defaults
agent.invoke({"messages": [HumanMessage(content="charge the card")]})
print(len(CALLS)) # -> 3Error Message and Stack Trace (if applicable)
Description
With default settings, ToolRetryMiddleware re-invokes a tool after a
httpx.ReadTimeout — a failure that occurs after the request was transmitted
and therefore carries no information about whether the tool's external effect
took place. Three defaults combine to make this the out-of-the-box behaviour for
every tool in the agent:
default_retry_onreturnsTruefor every exception except a non-retryableModelError, so ambiguous transport failures are retryable.tools=Noneapplies the middleware to all tools, so enabling it for a flaky search tool also enrols an effectful one.on_failure="continue"returns a message ending"Please try again."to the model after the retries are exhausted.
The result: one requested tool call, three executions, and then the model is instructed to try a fourth.
For a read-only tool this is the desired behaviour. For a tool that charges a card, sends a message, or creates an order, it produces duplicate irreversible effects while reporting failure to the caller.
Reproduction
langchain 1.4.2, langchain-core 1.6.3, langgraph 1.2.11, httpx 0.28.1.
import httpx
from langchain.agents import create_agent
from langchain.agents.middleware import ToolRetryMiddleware
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.tools import tool
CALLS = []
@tool
def charge_card(operation_id: str, amount: str) -> str:
"""Charge a card. Irreversible."""
CALLS.append(operation_id) # the external effect, already committed
raise httpx.ReadTimeout("The read operation timed out") # the response is lost
class ScriptedModel(GenericFakeChatModel):
def bind_tools(self, tools, **kwargs):
return self
model = ScriptedModel(messages=iter([
AIMessage(content="", tool_calls=[{
"name": "charge_card",
"args": {"operation_id": "op-1", "amount": "100.00"},
"id": "call_1", "type": "tool_call",
}]),
AIMessage(content="Finished."),
]))
agent = create_agent(model=model, tools=[charge_card],
middleware=[ToolRetryMiddleware()]) # all defaults
agent.invoke({"messages": [HumanMessage(content="charge the card")]})
print(len(CALLS)) # -> 3Verified: the snippet above runs standalone on a clean
pip install langchain==1.4.2 httpx and prints 3.
Current behaviour
tool calls requested by the model : 1
tool executions : 3
ToolMessage(status='error') returned to the model:
Tool 'charge_card' failed after 3 attempts with ReadTimeout:
The read operation timed out. Please try again.Expected behaviour
A failure that may have already produced an external effect should not be retried silently by default, and the model should not be told to try again without being told that the effect status is unknown.
Why ReadTimeout is the interesting case
Transport failures divide into two groups that the current default does not distinguish:
- Determinate no-effect —
ConnectionRefusedError, DNS failure: no bytes reached the server, retry is safe. - Ambiguous — read timeout, connection reset mid-request, lost response: the server may have executed, retry is not safe without deduplication.
default_retry_on returns True for both. The class docstring's own example
recommends retry_on=(RequestException, Timeout), which is squarely the second
group.
Suggested changes
Roughly in order of value to cost:
Qualify the exhausted-retry message. Drop
"Please try again.", or replace it with something that states the uncertainty — e.g. "The tool may or may not have completed; its effect status is unknown." This is a one-line change in_format_failure_message(tool_retry.py:243-261) and it removes the instruction that compounds the problem.Let a tool declare itself non-idempotent and exclude such tools from the retry loop unless explicitly listed. This keeps the convenient default for the common case while making the unsafe case opt-in rather than opt-out.
Propagate
tool_call_idto the tool. It is already stable across attempts and read on each one (tool_retry.py:320), but is used only to label the failure message. Passing it through would let a tool or adapter recognise attempts 2 and 3 as replays of attempt 1 — which is what makes a retry safe in the first place.Consider narrowing
default_retry_onso ambiguous transport errors are opted into rather than out of.I tried this and it is not sufficient on its own — worth knowing before anyone implements it.
wrap_tool_callhas only two dispositions:if not should_retry_exception(exc, self.retry_on): # Exception is not retryable, re-raise immediately raiseso making an ambiguous failure non-retryable makes it fatal. In my reproduction the duplicate charge disappeared (3 executions became 1) but the agent run aborted with an unhandled
ReadTimeout.An ambiguous outcome is neither retryable nor the caller's error. It needs a third disposition: stop, and report the uncertainty. Routing it to the existing
_handle_failurerather than re-raising does that:if not should_retry_exception(exc, self.retry_on): if _is_ambiguous_outcome(exc): return self._handle_failure(tool_name, tool_call_id, exc, attempts_made) raiseWith that plus (1), the same reproduction gives one execution, the run completes, and the model receives: "Tool 'charge_card' failed after 1 attempt with ReadTimeout: ... Whether the tool completed its external effect is unknown; do not repeat it without checking."
I am happy to attach the patch and the before/after measurements. My classification of "ambiguous" is by exception type name so it needs no new imports, which is a demonstration rather than a proposed implementation — a registry or an explicit hook would suit the codebase better.
Context
Found while auditing retry behaviour across agent frameworks. The full
reproduction, including a durable ledger showing the three committed effects and
their timing (t+0.00s, t+1.24s, t+3.64s, matching initial_delay=1.0 and
backoff_factor=2.0), is available and I am happy to attach it.
Happy to open a PR for (1) and (3), which look self-contained. Also happy to be told this is working as intended, in which case a note in the docstring warning against enabling it for non-idempotent tools would still help.
System Info
langchain 1.4.2 langchain-core 1.6.3 langgraph 1.2.11 httpx 0.28.1
Social handles (optional)
No response
Source: langchain-ai/langchain