The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(router): anchor stall detection on the newest tool call
moe-berri939039f4927b
diff --git a/litellm/router_strategy/complexity_router/README.md b/litellm/router_strategy/complexity_router/README.mdindex a7ed9e9dc21..ad84d4499d2 100644--- a/litellm/router_strategy/complexity_router/README.md+++ b/litellm/router_strategy/complexity_router/README.md@@ -270,14 +270,20 @@ model_list:REASONING: o1-preview```-Detection looks at the assistant's own tool calls, not the human's messages: of the last-`stall_escalation_window` tool calls, if `stall_escalation_repeat_threshold` or more are-identical (same tool, same arguments) or came back as errors, the task counts as stalled and the-classified tier is bumped one step by the same `_escalate_tier` ladder `escalation_keywords`-uses, capped at the highest configured tier. It reads both tool-call shapes: Anthropic Messages+Detection looks at the assistant's own tool calls, not the human's messages. The task counts as+stalled when the NEWEST tool call is still part of a stuck pattern: it repeats, or it errored, at+least `stall_escalation_repeat_threshold` times across the last `stall_escalation_window` calls.+The tier is then bumped one step by the same `_escalate_tier` ladder `escalation_keywords` uses,+capped at the highest configured tier. It reads both tool-call shapes: Anthropic Messages`tool_use`/`tool_result` blocks (including `is_error`) and chat-completions `tool_calls`/`tool`messages (which carry no standard error flag, so those calls are judged on repetition alone).+Anchoring on the newest call is what keeps a recovered task from being escalated on stale+evidence. A model that tried the same command three times and then moved on still has those+three calls sitting in the window for a few turns, and counting whichever pattern is most common+in the window would escalate a request that is already making progress again. Anchoring still+leaves room between the matches, so a retry loop broken up by an unrelated lookup counts.+There is no state to expire or leak: detection reruns on every classified turn from thatrequest's own message list, so the bump lasts only as long as the recent tool calls still lookstuck and lifts on its own the moment they don't. This also means it reads the wholediff --git a/litellm/router_strategy/complexity_router/config.py b/litellm/router_strategy/complexity_router/config.pyindex 508c4ec8c91..46b5dd4a0f0 100644--- a/litellm/router_strategy/complexity_router/config.py+++ b/litellm/router_strategy/complexity_router/config.py@@ -813,16 +813,17 @@ class ComplexityRouterConfig(BaseModel):default=False,description=("Escalate mid-task to the next-higher configured tier when the assistant's own recent "- "tool calls look stuck: stall_escalation_repeat_threshold or more of the last "- "stall_escalation_window tool calls are identical repeats (same tool, same arguments) "- "or came back as errors. One tier at most, on the same ladder escalation_keywords bumps "- "along, and never above the highest configured tier. Detection re-runs on every "- "classified turn from the tool calls visible in that request, so it needs no state and "- "nothing survives past the task: once the recent tool calls stop looking stuck, the "- "next classified turn routes normally again. Mutually exclusive with session_affinity "- "and classification_mode='user_turn', which both replay a held routing decision instead "- "of classifying most turns, so this would never see the tool calls to look at. Off by "- "default."+ "tool calls look stuck: the newest tool call repeats, or errors, at least "+ "stall_escalation_repeat_threshold times across the last stall_escalation_window "+ "calls. Both tests are anchored on the newest call, so a task that tried the same "+ "thing a few times and then moved on is not escalated on the strength of those older "+ "calls alone, while a retry loop broken up by an unrelated lookup still counts. One "+ "tier at most, on the same ladder escalation_keywords bumps along, and never above "+ "the highest configured tier. Detection re-runs on every classified turn from the "+ "tool calls visible in that request, so it needs no state and nothing survives past "+ "the task. Mutually exclusive with session_affinity and classification_mode="+ "'user_turn', which both replay a held routing decision instead of classifying most "+ "turns, so this would never see the tool calls to look at. Off by default."),)stall_escalation_window: int = Field(@@ -839,9 +840,9 @@ class ComplexityRouterConfig(BaseModel):default=3,ge=2,description=(- "How many of the last stall_escalation_window tool calls must be identical repeats, or "- "error results, before the task counts as stalled. Must not exceed "- "stall_escalation_window, or the condition could never be reached."+ "How many of the last stall_escalation_window tool calls must repeat the newest call, "+ "or must have errored alongside it, before the task counts as stalled. Must not "+ "exceed stall_escalation_window, or the condition could never be reached."),)diff --git a/litellm/router_strategy/complexity_router/stall_detector.py b/litellm/router_strategy/complexity_router/stall_detector.pyindex 450f8b6a653..690603f05d5 100644--- a/litellm/router_strategy/complexity_router/stall_detector.py+++ b/litellm/router_strategy/complexity_router/stall_detector.py@@ -1,27 +1,21 @@"""Mid-task stall detection for the Complexity Router.-Looks at the assistant's own recent tool calls -- visible on every request an agentic-client resends, since each turn carries the whole conversation so far -- for a tight loop-of identical calls or repeated tool errors. No LLM call, no state: the same fixed-size-window is rescanned on every classified turn, so a stall reads the same way whether it-started one turn ago or ten, and stops reading as a stall the moment the recent calls-change.--Assistant tool calls appear in two shapes depending on the API surface, and this module-reads both without translating one into the other:-- Anthropic Messages: assistant `content` blocks of type "tool_use" (id, name, input),- answered by a later user-turn `content` block of type "tool_result" (tool_use_id,- is_error).-- Chat completions: assistant `tool_calls` entries (id, function.name, function.arguments- as a JSON string), answered by a later `role: "tool"` message. Chat completions has no- standard error flag on that message, so those calls are judged on repetition alone.+Reads the assistant's own recent tool calls, which every agentic client resends on each+turn, and reports whether the task currently looks stuck. No LLM call and no stored state:+the same window is rescanned per classified turn, so the verdict follows the conversation+rather than latching.++Tool calls arrive in two shapes and are read in place rather than translated:+- Anthropic Messages: assistant `tool_use` content blocks, answered by a user-turn+ `tool_result` block carrying `is_error`+- Chat completions: assistant `tool_calls` entries, answered by a `role: "tool"` message,+ which has no standard error flag, so those calls are judged on repetition alone"""from __future__ import annotationsimport json-from collections import Counterfrom collections.abc import Iterator, Mapping, Sequencefrom itertools import islicefrom typing import Final, NamedTuple@@ -32,8 +26,7 @@ _ARGUMENTS_PARSE_FAILED: Final = object()class _ToolCallEvent(NamedTuple):signature: tuple[str, str]is_error: bool | None- """None when the surface carries no structured error signal for this call. Never- treated as an error: a call this module cannot judge must not count toward the tally."""+ """None where the surface reports no error status, and never counted as an error."""def _json_arguments(raw: str) -> object:@@ -44,9 +37,8 @@ def _json_arguments(raw: str) -> object:def _tool_call_signature(name: str, raw_arguments: object) -> tuple[str, str]:- """A (name, canonical-arguments) pair that compares equal across both surfaces'- argument shapes: a dict (Anthropic `input`) and a JSON-encoded string (chat- completions `function.arguments`) representing the same call must match."""+ """Canonicalized so the same call compares equal across both surfaces, which carry+ arguments as a dict and as a JSON string respectively."""parsed: Final = _json_arguments(raw_arguments) if isinstance(raw_arguments, str) else raw_argumentsarguments: Final = raw_arguments if parsed is _ARGUMENTS_PARSE_FAILED else parsedtry:@@ -56,8 +48,6 @@ def _tool_call_signature(name: str, raw_arguments: object) -> tuple[str, str]:def _iter_tool_result_error_pairs(messages: Sequence[Mapping[str, object]]) -> Iterator[tuple[str, bool]]:- """(call id, whether that call's result was an error), read only where the surface- reports one: an Anthropic Messages `tool_result` content block's `is_error`."""for msg in messages:content = msg.get("content")if msg.get("role") != "user" or not isinstance(content, list):@@ -70,8 +60,6 @@ def _iter_tool_result_error_pairs(messages: Sequence[Mapping[str, object]]) -> Idef _iter_tool_call_events_newest_first(messages: Sequence[Mapping[str, object]]) -> Iterator[_ToolCallEvent]:- """Every tool call the assistant made, newest first, paired with its result's error- status where the surface reports one."""error_by_call_id: Final = dict(_iter_tool_result_error_pairs(messages))for msg in reversed(messages):if msg.get("role") != "assistant":@@ -107,20 +95,24 @@ def detect_stalled_task(window: int,repeat_threshold: int,) -> bool:- """Whether the assistant's recent tool-call activity looks stuck: repeat_threshold or- more of the last `window` tool calls share an identical signature, or resolved to an- error on a surface that reports one.-- Reads the whole message list rather than only the turns since the newest human ask,- so a follow-up like "try again" does not discard the evidence that came before it.+ """Whether the newest tool call is still part of a stuck pattern: it repeats, or it+ errored, at least repeat_threshold times across the last `window` calls.++ Both tests are anchored on the newest call rather than counting whichever pattern is+ most common in the window. A task that tried the same thing three times and then moved+ on has those three calls in the window for a while yet, and counting them alone would+ escalate a request that already recovered. Anchoring also leaves room between the+ matches, so a retry loop broken up by an unrelated lookup still reads as stuck."""if not messages or repeat_threshold <= 0:return Falserecent: Final = tuple(islice(_iter_tool_call_events_newest_first(messages), window))if len(recent) < repeat_threshold:return False- _, most_common_count = Counter(event.signature for event in recent).most_common(1)[0]- if most_common_count >= repeat_threshold:+ newest: Final = recent[0]+ repeats: Final = sum(1 for event in recent if event.signature == newest.signature)+ if repeats >= repeat_threshold:return True- error_count: Final = sum(1 for event in recent if event.is_error)- return error_count >= repeat_threshold+ if not newest.is_error:+ return False+ return sum(1 for event in recent if event.is_error) >= repeat_thresholddiff --git a/tests/test_litellm/router_strategy/test_stall_detector.py b/tests/test_litellm/router_strategy/test_stall_detector.pyindex 8f39969a8ec..34067cc3626 100644--- a/tests/test_litellm/router_strategy/test_stall_detector.py+++ b/tests/test_litellm/router_strategy/test_stall_detector.py@@ -109,6 +109,39 @@ class TestDetectStalledTask:]assert detect_stalled_task(messages, window=6, repeat_threshold=3) is True+ def test_a_recovered_task_is_not_stalled_while_its_old_failures_sit_in_the_window(self):+ """The three identical failures stay in the window for a few turns after the model+ breaks out of them, and counting them on their own would escalate a request that is+ already making progress again."""+ messages = [+ *_anthropic_call("t1", "bash", {"cmd": "pytest"}, is_error=True),+ *_anthropic_call("t2", "bash", {"cmd": "pytest"}, is_error=True),+ *_anthropic_call("t3", "bash", {"cmd": "pytest"}, is_error=True),+ *_anthropic_call("t4", "read_file", {"path": "conftest.py"}, is_error=False),+ *_anthropic_call("t5", "edit_file", {"path": "conftest.py"}, is_error=False),+ ]+ assert detect_stalled_task(messages, window=6, repeat_threshold=3) is False++ def test_a_retry_loop_broken_up_by_an_unrelated_call_still_counts(self):+ """Anchoring on the newest call must not require the repeats to be adjacent: a model+ re-running the same failing command around a lookup in between is still stuck."""+ messages = [+ *_anthropic_call("t1", "bash", {"cmd": "pytest"}, is_error=True),+ *_anthropic_call("t2", "read_file", {"path": "conftest.py"}, is_error=False),+ *_anthropic_call("t3", "bash", {"cmd": "pytest"}, is_error=True),+ *_anthropic_call("t4", "bash", {"cmd": "pytest"}, is_error=True),+ ]+ assert detect_stalled_task(messages, window=6, repeat_threshold=3) is True++ def test_errors_only_count_while_the_newest_call_is_still_failing(self):+ messages = [+ *_anthropic_call("t1", "bash", {"cmd": "pytest a"}, is_error=True),+ *_anthropic_call("t2", "bash", {"cmd": "pytest b"}, is_error=True),+ *_anthropic_call("t3", "bash", {"cmd": "pytest c"}, is_error=True),+ *_anthropic_call("t4", "bash", {"cmd": "pytest d"}, is_error=False),+ ]+ assert detect_stalled_task(messages, window=6, repeat_threshold=3) is False+def test_no_messages_is_not_stalled(self):assert detect_stalled_task(None, window=6, repeat_threshold=3) is Falseassert detect_stalled_task([], window=6, repeat_threshold=3) is Falsediff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 09dfbd841c8..ce19330a511 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -34898,13 +34898,13 @@ export interface components {simple_keywords?: string[] | null;/*** Stall Escalation Enabled- * @description Escalate mid-task to the next-higher configured tier when the assistant's own recent tool calls look stuck: stall_escalation_repeat_threshold or more of the last stall_escalation_window tool calls are identical repeats (same tool, same arguments) or came back as errors. One tier at most, on the same ladder escalation_keywords bumps along, and never above the highest configured tier. Detection re-runs on every classified turn from the tool calls visible in that request, so it needs no state and nothing survives past the task: once the recent tool calls stop looking stuck, the next classified turn routes normally again. Mutually exclusive with session_affinity and classification_mode='user_turn', which both replay a held routing decision instead of classifying most turns, so this would never see the tool calls to look at. Off by default.+ * @description Escalate mid-task to the next-higher configured tier when the assistant's own recent tool calls look stuck: the newest tool call repeats, or errors, at least stall_escalation_repeat_threshold times across the last stall_escalation_window calls. Both tests are anchored on the newest call, so a task that tried the same thing a few times and then moved on is not escalated on the strength of those older calls alone, while a retry loop broken up by an unrelated lookup still counts. One tier at most, on the same ladder escalation_keywords bumps along, and never above the highest configured tier. Detection re-runs on every classified turn from the tool calls visible in that request, so it needs no state and nothing survives past the task. Mutually exclusive with session_affinity and classification_mode='user_turn', which both replay a held routing decision instead of classifying most turns, so this would never see the tool calls to look at. Off by default.* @default false*/stall_escalation_enabled: boolean;/*** Stall Escalation Repeat Threshold- * @description How many of the last stall_escalation_window tool calls must be identical repeats, or error results, before the task counts as stalled. Must not exceed stall_escalation_window, or the condition could never be reached.+ * @description How many of the last stall_escalation_window tool calls must repeat the newest call, or must have errored alongside it, before the task counts as stalled. Must not exceed stall_escalation_window, or the condition could never be reached.* @default 3*/stall_escalation_repeat_threshold: number;