Skip to content

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]

fix: validate max_agentic_loops wherever it is set

mateo-berri19e077ab5102
diff --git a/litellm/integrations/websearch_interception/ARCHITECTURE.md b/litellm/integrations/websearch_interception/ARCHITECTURE.md
index b1485b9b680..4ea7a7ae527 100644
--- a/litellm/integrations/websearch_interception/ARCHITECTURE.md
+++ b/litellm/integrations/websearch_interception/ARCHITECTURE.md
@@ -235,6 +235,11 @@ model_list:
Clients cannot set it. `max_agentic_loops` is on the proxy's untrusted-field list, so a request body that
carries it is ignored and one request can never drive an unbounded number of upstream model calls.
+Both places are validated at config load, and a value that is not an integer of at least 1 stops the proxy
+from starting rather than surfacing later. The per-deployment one is checked while the model list is read,
+not on `LiteLLM_Params`, because the proxy builds its router with `ignore_invalid_deployments=True` and a
+validator down there would drop the deployment silently instead of refusing to start.
+
When the ceiling is reached on a non-streaming `/v1/messages` request, the turn ends there and the client gets
the last response back with the internal `litellm_web_search` tool call removed and `stop_reason: end_turn`.
The client never declared that tool, so leaving the block in would hand it a tool call it has no way to answer.
diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py
index 760824f820f..13a16947fb4 100644
--- a/litellm/integrations/websearch_interception/handler.py
+++ b/litellm/integrations/websearch_interception/handler.py
@@ -31,6 +31,9 @@ from litellm.integrations.websearch_interception.tools import (
from litellm.integrations.websearch_interception.transformation import (
WebSearchTransformation,
)
+from litellm.litellm_core_utils.agentic_loop_settings import (
+ validated_max_agentic_loops,
+)
from litellm.llms.base_llm.search.transformation import SearchResponse
from litellm.types.integrations.custom_logger import (
CHAT_COMPLETION_AGENTIC_SURFACE,
@@ -150,21 +153,8 @@ class WebSearchInterceptionLogger(CustomLogger):
def _validated_max_agentic_loops(max_agentic_loops: object) -> int | None:
"""
Reject loop ceilings the agentic loop cannot honor, at config load time.
-
- ``bool`` is excluded explicitly because it is an ``int`` subclass, so
- ``max_agentic_loops: true`` would otherwise be read as a ceiling of 1.
"""
- if max_agentic_loops is None:
- return None
- if isinstance(max_agentic_loops, bool) or not isinstance(max_agentic_loops, int):
- raise TypeError(
- f"websearch_interception_params.max_agentic_loops must be an integer, got {max_agentic_loops!r}"
- )
- if max_agentic_loops < 1:
- raise ValueError(
- f"websearch_interception_params.max_agentic_loops must be at least 1, got {max_agentic_loops}"
- )
- return max_agentic_loops
+ return validated_max_agentic_loops(max_agentic_loops, field="websearch_interception_params.max_agentic_loops")
async def try_short_circuit_search(
self,
diff --git a/litellm/litellm_core_utils/agentic_loop_settings.py b/litellm/litellm_core_utils/agentic_loop_settings.py
new file mode 100644
index 00000000000..538f2d64c1b
--- /dev/null
+++ b/litellm/litellm_core_utils/agentic_loop_settings.py
@@ -0,0 +1,35 @@
+"""
+Shared validation for the agentic loop ceiling.
+
+``max_agentic_loops`` can be set in two places, and the two disagreed about
+what a bad value means. The feature-level
+``litellm_settings.websearch_interception_params.max_agentic_loops`` was
+checked at config load, while a per-deployment
+``model_list[].litellm_params.max_agentic_loops`` was passed straight through
+to ``int(... or 3)``. That let a per-deployment ``0`` read as the default 3,
+turning the tightest ceiling into the loosest one, and let a per-deployment
+``"three"`` boot the proxy and then fail every request to that model.
+
+Both settings now go through :func:`validated_max_agentic_loops`, which names
+the field it rejected so the error says which line of the config to fix.
+"""
+
+from typing import Final
+
+DEFAULT_MAX_AGENTIC_LOOPS: Final = 3
+
+
+def validated_max_agentic_loops(max_agentic_loops: object, field: str) -> int | None:
+ """
+ Return ``max_agentic_loops`` as an int, or raise naming ``field``.
+
+ ``bool`` is excluded explicitly because it is an ``int`` subclass, so
+ ``max_agentic_loops: true`` would otherwise be read as a ceiling of 1.
+ """
+ if max_agentic_loops is None:
+ return None
+ if isinstance(max_agentic_loops, bool) or not isinstance(max_agentic_loops, int):
+ raise TypeError(f"{field} must be an integer, got {max_agentic_loops!r}")
+ if max_agentic_loops < 1:
+ raise ValueError(f"{field} must be at least 1, got {max_agentic_loops}")
+ return max_agentic_loops
diff --git a/litellm/litellm_core_utils/chat_completion_agentic_loop.py b/litellm/litellm_core_utils/chat_completion_agentic_loop.py
index b91c1785a54..07bed1f88ad 100644
--- a/litellm/litellm_core_utils/chat_completion_agentic_loop.py
+++ b/litellm/litellm_core_utils/chat_completion_agentic_loop.py
@@ -5,6 +5,10 @@ from typing import Final, cast
from litellm._logging import verbose_logger
from litellm.integrations.custom_logger import CustomLogger
+from litellm.litellm_core_utils.agentic_loop_settings import (
+ DEFAULT_MAX_AGENTIC_LOOPS,
+ validated_max_agentic_loops,
+)
from litellm.types.integrations.custom_logger import (
CHAT_COMPLETION_AGENTIC_SURFACE,
NON_CODE_INTERPRETER_INTERCEPTION_INTERNAL_PREFIXES,
@@ -52,7 +56,10 @@ def _coerce_int(value: object, default: int) -> int:
def _agentic_loop_settings(kwargs: dict[str, object]) -> tuple[int, int, list[str]]:
depth: Final = _coerce_int(kwargs.get("_agentic_loop_depth"), 0)
- max_loops: Final = max(_coerce_int(kwargs.get("max_agentic_loops"), 3), 1)
+ configured: Final = validated_max_agentic_loops(
+ kwargs.get("max_agentic_loops"), field="litellm_params.max_agentic_loops"
+ )
+ max_loops: Final = DEFAULT_MAX_AGENTIC_LOOPS if configured is None else configured
raw_fingerprints: Final = kwargs.get("_agentic_loop_fingerprints")
fingerprints: Final = [str(fp) for fp in raw_fingerprints] if isinstance(raw_fingerprints, list) else []
return depth, max_loops, fingerprints
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index ebc76e6c7ea..862d98f65e6 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -19,6 +19,10 @@ import litellm.types.utils
from litellm._logging import _redact_string, verbose_logger
from litellm.anthropic_beta_headers_manager import update_headers_with_filtered_beta
from litellm.constants import REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES
+from litellm.litellm_core_utils.agentic_loop_settings import (
+ DEFAULT_MAX_AGENTIC_LOOPS,
+ validated_max_agentic_loops,
+)
from litellm.litellm_core_utils.asyncify import run_async_function
from litellm.litellm_core_utils.realtime_errors import realtime_error_event, websocket_close_reason
from litellm.litellm_core_utils.realtime_streaming import RealTimeStreaming
@@ -5078,9 +5082,12 @@ class BaseLLMHTTPHandler:
@staticmethod
def _get_agentic_loop_settings(kwargs: dict) -> tuple[int, int, list[str]]:
depth: Final = int(kwargs.get("_agentic_loop_depth", 0) or 0)
- max_loops: Final = int(kwargs.get("max_agentic_loops", 3) or 3)
+ configured: Final = validated_max_agentic_loops(
+ kwargs.get("max_agentic_loops"), field="litellm_params.max_agentic_loops"
+ )
+ max_loops: Final = DEFAULT_MAX_AGENTIC_LOOPS if configured is None else configured
fingerprints: Final = list(kwargs.get("_agentic_loop_fingerprints", []) or [])
- return depth, max(max_loops, 1), fingerprints
+ return depth, max_loops, fingerprints
@staticmethod
def _has_agentic_completion_hook(logging_obj: LiteLLMLoggingObj) -> bool:
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 9f16584340d..7dced4e26b6 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -254,6 +254,9 @@ from litellm.exceptions import RejectedRequestError
from litellm.integrations.custom_guardrail import ModifyResponseException
from litellm.integrations.custom_logger import CustomLogger
from litellm.integrations.SlackAlerting.slack_alerting import SlackAlerting
+from litellm.litellm_core_utils.agentic_loop_settings import (
+ validated_max_agentic_loops,
+)
from litellm.litellm_core_utils.asyncify import asyncify
from litellm.litellm_core_utils.core_helpers import (
_get_parent_otel_span_from_kwargs,
@@ -4081,6 +4084,27 @@ def resolve_complexity_router_plugins(
complexity_router_config["classifier_plugin"] = resolved_classifier # rebind-ok: out-param, resolved in place
+def validate_deployment_max_agentic_loops(model: Mapping[str, Any]) -> None:
+ """
+ Reject a per-deployment `max_agentic_loops` the agentic loop cannot honor.
+
+ Checked here rather than on `LiteLLM_Params` because the proxy builds its
+ router with `ignore_invalid_deployments=True`, so a validator down there
+ turns a bad value into a silently missing model instead of a refusal to
+ start. Left unchecked entirely, a `0` used to read as the default ceiling
+ of 3 and a non-integer failed every request to that model instead.
+ """
+ litellm_params: Final = model.get("litellm_params") or {}
+ if "max_agentic_loops" not in litellm_params:
+ return
+
+ model_name: Final = model.get("model_name", "")
+ validated_max_agentic_loops(
+ litellm_params["max_agentic_loops"],
+ field=f"litellm_params.max_agentic_loops on model {model_name!r}",
+ )
+
+
def pin_complexity_router_model_id(model: dict) -> None: # mutable-ok: out-param, model_info is stamped in place
"""
Stamps `model_info.id` from the raw litellm_params before plugin resolution swaps
@@ -5416,6 +5440,7 @@ class ProxyConfig:
for k, v in model["litellm_params"].items():
if isinstance(v, str) and v.startswith("os.environ/"):
model["litellm_params"][k] = get_secret(v)
+ validate_deployment_max_agentic_loops(model)
pin_complexity_router_model_id(model)
complexity_router_config = model["litellm_params"].get("complexity_router_config")
if isinstance(complexity_router_config, dict):
diff --git a/tests/test_litellm/integrations/websearch_interception/test_websearch_agentic_loop_cap.py b/tests/test_litellm/integrations/websearch_interception/test_websearch_agentic_loop_cap.py
index 91148f7cf6d..327b1b066b4 100644
--- a/tests/test_litellm/integrations/websearch_interception/test_websearch_agentic_loop_cap.py
+++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_agentic_loop_cap.py
@@ -24,6 +24,7 @@ from litellm.integrations.websearch_interception.handler import (
from litellm.llms.anthropic.experimental_pass_through.messages.fake_stream_iterator import (
FakeAnthropicMessagesStreamIterator,
)
+from litellm.litellm_core_utils.agentic_loop_settings import DEFAULT_MAX_AGENTIC_LOOPS
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
from litellm.types.integrations.custom_logger import (
AgenticLoopPlan,
@@ -409,7 +410,7 @@ class TestCappedLoopReturnsTerminalResponse:
def test_rails_cannot_trip_in_the_outermost_frame(self):
"""
Backs the invariant the test above relies on: at depth 0 the fingerprint set
- is empty and max_loops is clamped to at least 1, so neither rail can refuse.
+ is empty and the ceiling is at least 1, so neither rail can refuse.
"""
depth, max_loops, fingerprints = BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={})
@@ -418,10 +419,10 @@ class TestCappedLoopReturnsTerminalResponse:
assert max_loops >= 1
depth, max_loops, fingerprints = BaseLLMHTTPHandler._get_agentic_loop_settings(
- kwargs={"max_agentic_loops": 0}
+ kwargs={"max_agentic_loops": 1}
)
- assert max_loops >= 1
+ assert max_loops == 1
assert BaseLLMHTTPHandler._check_agentic_loop_safety(
tool_calls={"tool_calls": [_internal_tool_use_block()]},
fingerprints=fingerprints,
@@ -570,6 +571,55 @@ def _stream_events(response: dict) -> list[dict]:
return events
+class TestBothCeilingKnobsAreValidated:
+ """
+ ``max_agentic_loops`` is settable per deployment and feature-wide, and the
+ per-deployment one wins. Only the feature-wide one used to be checked, so a
+ per-deployment ``0`` was swallowed by an ``or 3`` and read as the default 3,
+ handing the loosest ceiling to whoever asked for the tightest.
+ """
+
+ def test_a_per_deployment_zero_is_rejected_not_read_as_the_default(self):
+ with pytest.raises(ValueError, match="must be at least 1, got 0"):
+ BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={"max_agentic_loops": 0})
+
+ def test_a_per_deployment_non_integer_names_the_field_it_came_from(self):
+ with pytest.raises(TypeError, match=r"litellm_params\.max_agentic_loops must be an integer"):
+ BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={"max_agentic_loops": "three"})
+
+ def test_a_per_deployment_true_is_not_read_as_a_ceiling_of_one(self):
+ with pytest.raises(TypeError, match="must be an integer"):
+ BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={"max_agentic_loops": True})
+
+ def test_an_absent_ceiling_falls_back_to_the_shared_default(self):
+ _, max_loops, _ = BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={})
+
+ assert max_loops == DEFAULT_MAX_AGENTIC_LOOPS
+
+ def test_an_explicit_none_falls_back_to_the_shared_default(self):
+ _, max_loops, _ = BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={"max_agentic_loops": None})
+
+ assert max_loops == DEFAULT_MAX_AGENTIC_LOOPS
+
+ def test_a_valid_per_deployment_ceiling_is_passed_through(self):
+ _, max_loops, _ = BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={"max_agentic_loops": 6})
+
+ assert max_loops == 6
+
+ @pytest.mark.parametrize("rejected", [0, -1, "three", True])
+ def test_the_two_knobs_reject_the_same_values(self, rejected):
+ with pytest.raises((TypeError, ValueError)):
+ WebSearchInterceptionLogger(max_agentic_loops=rejected)
+ with pytest.raises((TypeError, ValueError)):
+ BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={"max_agentic_loops": rejected})
+
+ def test_each_knob_names_its_own_config_field(self):
+ with pytest.raises(ValueError, match=r"websearch_interception_params\.max_agentic_loops"):
+ WebSearchInterceptionLogger(max_agentic_loops=0)
+ with pytest.raises(ValueError, match=r"litellm_params\.max_agentic_loops"):
+ BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={"max_agentic_loops": 0})
+
+
class TestRebuiltStreamIsWellFormed:
"""
A capped turn is rebuilt into SSE by FakeAnthropicMessagesStreamIterator.
diff --git a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py
index b0b2c68e30d..fa8355ad8c4 100644
--- a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py
+++ b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py
@@ -26,6 +26,7 @@ from litellm.proxy.proxy_server import (
_scrub_guardrail_inner,
resolve_complexity_router_plugins,
resolve_routing_plugins,
+ validate_deployment_max_agentic_loops,
)
from .conftest import normalize
@@ -153,6 +154,58 @@ def test_resolve_complexity_router_plugins_resolves_dotted_path_to_live_instance
assert type(config["plugins"][0]).__name__ == "_Plugin"
+def test_validate_deployment_max_agentic_loops_allows_a_deployment_without_the_key():
+ model = {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}}
+
+ validate_deployment_max_agentic_loops(model)
+
+ assert "max_agentic_loops" not in model["litellm_params"]
+
+
+def test_validate_deployment_max_agentic_loops_leaves_a_valid_ceiling_alone():
+ model = {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o", "max_agentic_loops": 5}}
+
+ validate_deployment_max_agentic_loops(model)
+
+ assert model["litellm_params"]["max_agentic_loops"] == 5
+
+
+def test_validate_deployment_max_agentic_loops_rejects_zero():
+ """
+ A per-deployment 0 used to be swallowed by an `or 3` and read as the default
+ ceiling of 3, handing the loosest setting to whoever asked for the tightest.
+ """
+ with pytest.raises(ValueError, match="must be at least 1, got 0"):
+ validate_deployment_max_agentic_loops(
+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o", "max_agentic_loops": 0}}
+ )
+
+
+def test_validate_deployment_max_agentic_loops_rejects_a_non_integer():
+ """
+ A per-deployment non-integer used to let the proxy boot and then fail every
+ request to that model with `invalid literal for int() with base 10`.
+ """
+ with pytest.raises(TypeError, match="must be an integer"):
+ validate_deployment_max_agentic_loops(
+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o", "max_agentic_loops": "three"}}
+ )
+
+
+def test_validate_deployment_max_agentic_loops_rejects_a_bool():
+ with pytest.raises(TypeError, match="must be an integer"):
+ validate_deployment_max_agentic_loops(
+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o", "max_agentic_loops": True}}
+ )
+
+
+def test_validate_deployment_max_agentic_loops_names_the_offending_model():
+ with pytest.raises(ValueError, match="on model 'claude-sonnet-4-5'"):
+ validate_deployment_max_agentic_loops(
+ {"model_name": "claude-sonnet-4-5", "litellm_params": {"max_agentic_loops": -1}}
+ )
+
+
def test_resolve_complexity_router_plugins_rejects_non_routing_plugin_object(tmp_path):
plugin_file = tmp_path / "bad_plugin.py"
plugin_file.write_text("not_a_plugin = object()\n")