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: keep accepting a loop ceiling that spells a whole number
mateo-berrib103edb588ce
diff --git a/litellm/litellm_core_utils/agentic_loop_settings.py b/litellm/litellm_core_utils/agentic_loop_settings.pyindex 538f2d64c1b..3dd8d437aef 100644--- a/litellm/litellm_core_utils/agentic_loop_settings.py+++ b/litellm/litellm_core_utils/agentic_loop_settings.py@@ -12,6 +12,11 @@ turning the tightest ceiling into the loosest one, and let a per-deploymentBoth settings now go through :func:`validated_max_agentic_loops`, which namesthe field it rejected so the error says which line of the config to fix.++Anything that spells a whole number is still accepted, because the old+``int(... or 3)`` accepted those and a ceiling is routinely parameterized as+``max_agentic_loops: os.environ/MAX_AGENTIC_LOOPS``, which resolves to a+string. Rejecting ``"5"`` would stop such a proxy from booting on upgrade."""from typing import Final@@ -19,17 +24,36 @@ from typing import FinalDEFAULT_MAX_AGENTIC_LOOPS: Final = 3-def validated_max_agentic_loops(max_agentic_loops: object, field: str) -> int | None:+def _as_whole_number(value: object) -> int | None:"""- Return ``max_agentic_loops`` as an int, or raise naming ``field``.+ Return ``value`` as an int when it spells a whole number, else ``None``.``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 isinstance(value, bool):+ return None+ if isinstance(value, int):+ return value+ if isinstance(value, float):+ return int(value) if value.is_integer() else None+ if isinstance(value, str):+ try:+ return int(value.strip())+ except ValueError:+ return None+ return None+++def validated_max_agentic_loops(max_agentic_loops: object, field: str) -> int | None:+ """+ Return ``max_agentic_loops`` as an int, or raise naming ``field``.+ """if max_agentic_loops is None:return None- if isinstance(max_agentic_loops, bool) or not isinstance(max_agentic_loops, int):+ ceiling: Final = _as_whole_number(max_agentic_loops)+ if ceiling is None: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+ if ceiling < 1:+ raise ValueError(f"{field} must be at least 1, got {ceiling}")+ return ceilingdiff --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.pyindex 327b1b066b4..40fd8c4e9e6 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@@ -26,6 +26,7 @@ from litellm.llms.anthropic.experimental_pass_through.messages.fake_stream_itera)from litellm.litellm_core_utils.agentic_loop_settings import DEFAULT_MAX_AGENTIC_LOOPSfrom litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler+from litellm.secret_managers.main import get_secretfrom litellm.types.integrations.custom_logger import (AgenticLoopPlan,AgenticLoopRequestPatch,@@ -509,13 +510,25 @@ class TestMaxAgenticLoopsConfigKnob:{"enabled_providers": ["bedrock"], "max_agentic_loops": bad_value})- @pytest.mark.parametrize("bad_value", ["5", True, 2.5])+ @pytest.mark.parametrize("bad_value", ["three", True, 2.5])def test_non_integer_ceilings_are_rejected_at_config_load(self, bad_value):with pytest.raises(TypeError, match="max_agentic_loops"):WebSearchInterceptionLogger.from_config_yaml({"enabled_providers": ["bedrock"], "max_agentic_loops": bad_value})+ def test_a_ceiling_spelled_as_a_string_is_read_at_config_load(self):+ """+ `max_agentic_loops: os.environ/MAX_AGENTIC_LOOPS` resolves to a string+ before it reaches the knob, so refusing "5" would break a config that+ works today.+ """+ logger = WebSearchInterceptionLogger.from_config_yaml(+ {"enabled_providers": ["bedrock"], "max_agentic_loops": "5"}+ )++ assert logger.max_agentic_loops == 5+@pytest.mark.asyncioasync def test_knob_reaches_the_loop_settings(self):logger = WebSearchInterceptionLogger.from_config_yaml(@@ -620,6 +633,43 @@ class TestBothCeilingKnobsAreValidated:BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={"max_agentic_loops": 0})+class TestACeilingThatSpellsAWholeNumberStillWorks:+ """+ The ceiling used to go through ``int(... or 3)``, which accepted anything+ ``int()`` accepted. A ceiling is routinely parameterized as+ ``max_agentic_loops: os.environ/MAX_AGENTIC_LOOPS``, and ``get_secret``+ hands that back as the string ``"5"``, so tightening the check to+ ``isinstance(int)`` would stop such a proxy from booting on upgrade.+ """++ @pytest.mark.parametrize("spelled", ["5", " 5 ", 5.0])+ def test_a_ceiling_that_spells_five_is_accepted_by_both_knobs(self, spelled):+ _, max_loops, _ = BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={"max_agentic_loops": spelled})++ assert max_loops == 5+ assert WebSearchInterceptionLogger(max_agentic_loops=spelled).max_agentic_loops == 5++ def test_an_env_var_sourced_ceiling_survives_secret_resolution(self, monkeypatch):+ monkeypatch.setenv("MAX_AGENTIC_LOOPS_UNDER_TEST", "7")+ resolved = get_secret("os.environ/MAX_AGENTIC_LOOPS_UNDER_TEST")++ assert isinstance(resolved, str)+ _, max_loops, _ = BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={"max_agentic_loops": resolved})+ assert max_loops == 7++ def test_a_spelled_zero_is_still_refused_and_reports_the_number(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_word_is_still_refused(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_fractional_ceiling_is_refused_rather_than_truncated(self):+ with pytest.raises(TypeError, match="must be an integer"):+ BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={"max_agentic_loops": 5.5})++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.pyindex fa8355ad8c4..ee0de8840f6 100644--- a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py+++ b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py@@ -199,6 +199,19 @@ def test_validate_deployment_max_agentic_loops_rejects_a_bool():)+def test_validate_deployment_max_agentic_loops_accepts_a_ceiling_from_an_env_var():+ """+ `max_agentic_loops: os.environ/MAX_AGENTIC_LOOPS` is resolved to a string+ before this check runs, and the old `int(... or 3)` accepted that, so+ refusing it here would stop an already working proxy from booting.+ """+ 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_names_the_offending_model():with pytest.raises(ValueError, match="on model 'claude-sonnet-4-5'"):validate_deployment_max_agentic_loops(