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(websearch_interception): end the turn when the agentic loop hits its ceiling

mateo-berri23a9300da6e9
diff --git a/litellm/integrations/websearch_interception/ARCHITECTURE.md b/litellm/integrations/websearch_interception/ARCHITECTURE.md
index ce7f01c5a2a..691bb26880e 100644
--- a/litellm/integrations/websearch_interception/ARCHITECTURE.md
+++ b/litellm/integrations/websearch_interception/ARCHITECTURE.md
@@ -207,6 +207,41 @@ response = await litellm.messages.acreate(
---
+## Loop Ceiling
+
+One intercepted request can chain several follow-up model calls, since the model often searches again after
+reading the first set of results. `max_agentic_loops` caps how many of those follow-ups run, and it defaults
+to 3. LiteLLM also breaks the loop early when the model asks for the exact same tool call twice in a row.
+
+Set the ceiling on the feature, which the interceptor applies to `/v1/messages` requests:
+
+```yaml
+litellm_settings:
+ websearch_interception_params:
+ enabled_providers: ["bedrock"]
+ max_agentic_loops: 5
+```
+
+Or per deployment, which wins over the feature-level setting:
+
+```yaml
+model_list:
+ - model_name: claude-sonnet-4-5
+ litellm_params:
+ model: bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0
+ max_agentic_loops: 5
+```
+
+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.
+
+When the ceiling is reached, 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. The answer can be less complete than
+it would have been with more loops, which is the tradeoff the ceiling buys
+
+---
+
## Streaming Support
WebSearch interception works transparently with both streaming and non-streaming requests.
diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py
index e59ef0449d0..760824f820f 100644
--- a/litellm/integrations/websearch_interception/handler.py
+++ b/litellm/integrations/websearch_interception/handler.py
@@ -122,6 +122,7 @@ class WebSearchInterceptionLogger(CustomLogger):
self,
enabled_providers: list[LlmProviders | str] | None = None,
search_tool_name: str | None = None,
+ max_agentic_loops: int | None = None,
):
"""
Args:
@@ -131,6 +132,9 @@ class WebSearchInterceptionLogger(CustomLogger):
Default: None (all providers enabled)
search_tool_name: Name of search tool configured in router's search_tools.
If None, will attempt to use first available search tool.
+ max_agentic_loops: How many follow-up model calls one intercepted request
+ may chain before the loop is refused and the turn ends.
+ If None, LiteLLM's default of 3 applies.
"""
super().__init__()
# Convert enum values to strings for comparison
@@ -139,8 +143,29 @@ class WebSearchInterceptionLogger(CustomLogger):
else:
self.enabled_providers = [p.value if isinstance(p, LlmProviders) else p for p in enabled_providers]
self.search_tool_name = search_tool_name
+ self.max_agentic_loops = self._validated_max_agentic_loops(max_agentic_loops)
self._request_has_websearch = False # Track if current request has web search
+ @staticmethod
+ 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
+
async def try_short_circuit_search(
self,
model: str,
@@ -398,6 +423,7 @@ class WebSearchInterceptionLogger(CustomLogger):
websearch_interception_params:
enabled_providers: ["bedrock"]
search_tool_name: "my-perplexity-search"
+ max_agentic_loops: 5
Usage:
config = litellm_settings.get("websearch_interception_params", {})
@@ -406,6 +432,7 @@ class WebSearchInterceptionLogger(CustomLogger):
# Extract parameters from config
enabled_providers_str: Final = config.get("enabled_providers", None)
search_tool_name: Final = config.get("search_tool_name", None)
+ max_agentic_loops: Final = config.get("max_agentic_loops", None)
# Convert string provider names to LlmProviders enum values
enabled_providers: list[LlmProviders | str] | None = None
@@ -423,6 +450,7 @@ class WebSearchInterceptionLogger(CustomLogger):
return cls(
enabled_providers=enabled_providers,
search_tool_name=search_tool_name,
+ max_agentic_loops=max_agentic_loops,
)
@staticmethod
@@ -493,6 +521,10 @@ class WebSearchInterceptionLogger(CustomLogger):
verbose_logger.debug("WebSearchInterception: Pre-request hook triggered for provider=%s", custom_llm_provider)
+ deployment_max_agentic_loops: Final = kwargs.get("max_agentic_loops")
+ if self.max_agentic_loops is not None and deployment_max_agentic_loops is None:
+ kwargs["max_agentic_loops"] = self.max_agentic_loops # rebind-ok: this hook returns the kwargs it edits
+
# If the client sent an Anthropic-native web_search_* tool, mark the
# request so the agentic loop emits native web_search_tool_result
# blocks in the final response (for citations panels, etc.). The flag
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index 8c98c526da1..a14a89613c6 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -89,6 +89,7 @@ from litellm.types.files import StreamingMediaUploadConfig, TwoStepFileUploadCon
from litellm.types.integrations.custom_logger import (
AgenticLoopPlan,
AgenticLoopRequestPatch,
+ AgenticLoopSafetyError,
)
from litellm.types.llms.anthropic_messages.anthropic_response import (
AnthropicMessagesResponse,
@@ -5122,7 +5123,8 @@ class BaseLLMHTTPHandler:
"""
Evaluate agentic-loop safety guards (fingerprint cycle / max depth).
- Raises ValueError on abort. Returns the current fingerprint on success.
+ Raises AgenticLoopSafetyError on abort. Returns the current fingerprint
+ on success.
These checks must not be swallowed by the per-callback ``except Exception``
block that wraps callback dispatch — they are bounded-loop / cycle-break
@@ -5130,9 +5132,9 @@ class BaseLLMHTTPHandler:
"""
fingerprint: Final = BaseLLMHTTPHandler._fingerprint_agentic_tools(tool_calls)
if fingerprint in fingerprints:
- raise ValueError("Agentic loop detected repeated tool-call fingerprint; aborting rerun")
+ raise AgenticLoopSafetyError("Agentic loop detected repeated tool-call fingerprint; aborting rerun")
if depth >= max_loops:
- raise ValueError(f"Exceeded max_agentic_loops={max_loops} for model={model}")
+ raise AgenticLoopSafetyError(f"Exceeded max_agentic_loops={max_loops} for model={model}")
return fingerprint
@staticmethod
@@ -5142,6 +5144,92 @@ class BaseLLMHTTPHandler:
except Exception:
return str(tools)
+ @staticmethod
+ def _refused_agentic_tool_identifiers(tool_calls: object) -> tuple[frozenset[str], frozenset[str]]:
+ """
+ Collect the ids and names of the tool calls a safety rail just refused.
+
+ Callbacks hand back either a bare list of tool calls or a dict wrapping
+ that list under ``tool_calls``, and both the anthropic and responses
+ shapes carry an ``id`` (or ``call_id``) plus a ``name``.
+ """
+ calls: Final = tool_calls.get("tool_calls") if isinstance(tool_calls, dict) else tool_calls
+ if not isinstance(calls, list):
+ return frozenset(), frozenset()
+ dict_calls: Final = (call for call in calls if isinstance(call, dict))
+ fields: Final = tuple((call.get("id"), call.get("call_id"), call.get("name")) for call in dict_calls)
+ ids: Final = frozenset(
+ value for call_id, caller_id, _ in fields for value in (call_id, caller_id) if isinstance(value, str)
+ )
+ names: Final = frozenset(name for _, _, name in fields if isinstance(name, str))
+ return ids, names
+
+ @staticmethod
+ def _is_refused_tool_use_block(block: object, refused_ids: frozenset[str], refused_names: frozenset[str]) -> bool:
+ """
+ Whether this response block belongs to a tool call the rail refused.
+
+ An id settles it on its own, so a block carrying one is matched on the id
+ alone and a client's own tool call survives even where it happens to
+ share a name with a refused one. The name is only consulted for tool call
+ shapes that arrive without an id.
+ """
+ if not isinstance(block, dict) or block.get("type") != "tool_use":
+ return False
+ block_id: Final = block.get("id")
+ if isinstance(block_id, str) and refused_ids:
+ return block_id in refused_ids
+ return block.get("name") in refused_names
+
+ @staticmethod
+ def _can_replace_turn_with_terminal_response(stream: bool, api_surface: str) -> bool:
+ """
+ Whether a refused rerun can still be answered with a finalized turn.
+
+ Only the non-streaming anthropic messages path can. A streaming caller
+ has already sent the original message to the client, so a finalized one
+ would arrive as a second message rather than as a replacement, and the
+ responses surface carries a pydantic model that the finalizer does not
+ rewrite. Both keep raising, which is what every surface did before this
+ path learned to end the turn.
+ """
+ return not stream and api_surface == "anthropic_messages"
+
+ @staticmethod
+ def _finalize_refused_agentic_response(response: object, tool_calls: object) -> object:
+ """
+ Turn the response into a terminal turn after a safety rail refused the rerun.
+
+ The refused tool calls target tools LiteLLM injected on the client's
+ behalf, so a client that never declared them cannot send back a matching
+ ``tool_result``. Their blocks are dropped and a ``tool_use`` stop reason
+ is closed out as ``end_turn``, which is what a provider-native web search
+ turn returns once it stops calling tools.
+
+ A ``tool_use`` block the client itself declared is left alone, and while
+ one is still in the response the stop reason stays ``tool_use`` so the
+ client knows to answer it.
+ """
+ if not isinstance(response, dict):
+ return response
+
+ refused_ids, refused_names = BaseLLMHTTPHandler._refused_agentic_tool_identifiers(tool_calls)
+ finalized: Final = dict(response)
+ content: Final = finalized.get("content")
+ if isinstance(content, list):
+ kept_blocks: Final = [
+ block
+ for block in content
+ if not BaseLLMHTTPHandler._is_refused_tool_use_block(block, refused_ids, refused_names)
+ ]
+ finalized["content"] = kept_blocks
+ client_tool_use_remains: Final = any(
+ isinstance(block, dict) and block.get("type") == "tool_use" for block in kept_blocks
+ )
+ if not client_tool_use_remains and finalized.get("stop_reason") == "tool_use":
+ finalized["stop_reason"] = "end_turn"
+ return finalized
+
async def _execute_anthropic_agentic_plan(
self,
plan: AgenticLoopPlan,
@@ -5507,14 +5595,30 @@ class BaseLLMHTTPHandler:
continue
# Safety guards must run OUTSIDE the callback try/except — they are
- # bounded-loop / cycle-break rails that must propagate to the caller.
- fingerprint = self._check_agentic_loop_safety(
- tool_calls=tool_calls,
- fingerprints=fingerprints,
- depth=depth,
- max_loops=max_loops,
- model=model,
- )
+ # bounded-loop / cycle-break rails, not callback bugs.
+ try:
+ fingerprint = self._check_agentic_loop_safety(
+ tool_calls=tool_calls,
+ fingerprints=fingerprints,
+ depth=depth,
+ max_loops=max_loops,
+ model=model,
+ )
+ except AgenticLoopSafetyError as e:
+ if not self._can_replace_turn_with_terminal_response(stream, api_surface):
+ raise
+ _call_id = getattr(logging_obj, "litellm_call_id", "unknown")
+ verbose_logger.warning(
+ "LiteLLM.AgenticLoopRefused: ending turn [call_id=%s model=%s]: %s",
+ _call_id,
+ model,
+ str(e),
+ )
+ return self._maybe_wrap_in_fake_stream(
+ self._finalize_refused_agentic_response(response=response, tool_calls=tool_calls),
+ logging_obj,
+ api_surface,
+ )
try:
kwargs_with_provider = hook_kwargs.copy()
diff --git a/litellm/types/integrations/custom_logger.py b/litellm/types/integrations/custom_logger.py
index 89b85bc5114..6b1bb2f449f 100644
--- a/litellm/types/integrations/custom_logger.py
+++ b/litellm/types/integrations/custom_logger.py
@@ -23,6 +23,16 @@ def is_interception_internal_key(
return any(key.startswith(prefix) for prefix in prefixes)
+class AgenticLoopSafetyError(ValueError):
+ """
+ Raised when an agentic-loop safety rail refuses a rerun.
+
+ Covers both rails: the bounded-loop cap (``max_agentic_loops``) and the
+ repeated tool-call fingerprint cycle break. Subclasses ``ValueError`` so
+ callers that already catch the broader type keep working.
+ """
+
+
class StandardCustomLoggerInitParams(BaseModel):
"""
Params for initializing a CustomLogger.
diff --git a/litellm/types/integrations/websearch_interception.py b/litellm/types/integrations/websearch_interception.py
index 90713b270be..7926b9eee0a 100644
--- a/litellm/types/integrations/websearch_interception.py
+++ b/litellm/types/integrations/websearch_interception.py
@@ -5,6 +5,7 @@ Type definitions for WebSearch Interception integration.
from typing import Literal, TypedDict
from pydantic import BaseModel
+from typing_extensions import ReadOnly
class AnthropicSearchQuery(BaseModel):
@@ -35,6 +36,7 @@ class WebSearchInterceptionConfig(TypedDict, total=False):
websearch_interception_params:
enabled_providers: ["bedrock"]
search_tool_name: "my-perplexity-search"
+ max_agentic_loops: 5
"""
enabled_providers: list[str]
@@ -42,3 +44,6 @@ class WebSearchInterceptionConfig(TypedDict, total=False):
search_tool_name: str | None
"""Name of search tool configured in router's search_tools. If None, uses first available."""
+
+ max_agentic_loops: ReadOnly[int | None]
+ """How many follow-up model calls one intercepted request may chain. If None, LiteLLM's default of 3 applies."""
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
new file mode 100644
index 00000000000..1d36ca76832
--- /dev/null
+++ b/tests/test_litellm/integrations/websearch_interception/test_websearch_agentic_loop_cap.py
@@ -0,0 +1,527 @@
+"""
+Unit tests for what an intercepted request returns once a safety rail refuses
+another agentic loop.
+
+The web search interception loop injects an internal tool (litellm_web_search)
+that the client never declared. When the loop cap or the repeated-fingerprint
+guard trips, the turn has to end with a terminal response: leaking that internal
+tool_use block leaves the client holding a tool call it cannot answer.
+
+Also covers the max_agentic_loops knob on websearch_interception_params, from
+config.yaml through to the settings the loop actually reads.
+"""
+
+import json
+from unittest.mock import MagicMock
+
+import pytest
+
+import litellm
+from litellm.integrations.custom_logger import CustomLogger
+from litellm.integrations.websearch_interception.handler import (
+ WebSearchInterceptionLogger,
+)
+from litellm.llms.anthropic.experimental_pass_through.messages.fake_stream_iterator import (
+ FakeAnthropicMessagesStreamIterator,
+)
+from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
+from litellm.types.integrations.custom_logger import (
+ AgenticLoopPlan,
+ AgenticLoopRequestPatch,
+ AgenticLoopSafetyError,
+)
+
+INTERNAL_TOOL_NAME = "litellm_web_search"
+
+
[email protected](autouse=True)
+def only_the_callbacks_these_tests_register(monkeypatch):
+ """
+ These tests drive the hooks with a callback of their own on the logging
+ object, so a logger another test left on litellm.callbacks would join the
+ run and change what the hooks do.
+ """
+ monkeypatch.setattr(litellm, "callbacks", [])
+
+
+def _internal_tool_use_block(block_id: str = "toolu_internal_1") -> dict:
+ return {
+ "id": block_id,
+ "type": "tool_use",
+ "name": INTERNAL_TOOL_NAME,
+ "input": {"query": "who won the world cup"},
+ }
+
+
+def _native_search_blocks(index: int = 1) -> list[dict]:
+ return [
+ {
+ "type": "server_tool_use",
+ "id": f"srvtoolu_{index}",
+ "name": "web_search",
+ "input": {"query": "who won the world cup"},
+ },
+ {
+ "type": "web_search_tool_result",
+ "tool_use_id": f"srvtoolu_{index}",
+ "content": [{"type": "web_search_result", "url": "https://example.com", "title": "Result"}],
+ },
+ ]
+
+
+def _response_asking_for_another_search(block_id: str = "toolu_internal_1") -> dict:
+ return {
+ "id": "msg_123",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-sonnet-4-5",
+ "content": [
+ *_native_search_blocks(index=1),
+ {"type": "text", "text": "Let me check one more source."},
+ _internal_tool_use_block(block_id),
+ ],
+ "stop_reason": "tool_use",
+ "usage": {"input_tokens": 10, "output_tokens": 5},
+ }
+
+
+def _block_types(response: dict) -> list[str]:
+ return [block["type"] for block in response["content"]]
+
+
+def _tool_use_names(response: dict) -> list[str]:
+ return [block.get("name") for block in response["content"] if block.get("type") == "tool_use"]
+
+
+class _InterceptingCallback(CustomLogger):
+ """
+ Stands in for the websearch interceptor: asks for another loop whenever the
+ response carries an internal web search tool_use block, and injects the
+ native block pair on the way back out.
+ """
+
+ def __init__(self):
+ self.plan_calls = 0
+ self.post_hook_calls = 0
+
+ async def async_should_run_agentic_loop(
+ self, response, model, messages, tools, stream, custom_llm_provider, kwargs
+ ):
+ if not isinstance(response, dict):
+ return True, {"tool_calls": [_internal_tool_use_block()]}
+ tool_calls = [
+ block
+ for block in response.get("content", [])
+ if block.get("type") == "tool_use" and block.get("name") == INTERNAL_TOOL_NAME
+ ]
+ if not tool_calls:
+ return False, {}
+ return True, {"tool_calls": tool_calls, "tool_type": "websearch"}
+
+ async def async_build_agentic_loop_plan(
+ self,
+ tools,
+ model,
+ messages,
+ response,
+ anthropic_messages_provider_config,
+ anthropic_messages_optional_request_params,
+ logging_obj,
+ stream,
+ kwargs,
+ ):
+ self.plan_calls += 1
+ return AgenticLoopPlan(
+ run_agentic_loop=True,
+ request_patch=AgenticLoopRequestPatch(
+ messages=[{"role": "user", "content": "here are the search results"}],
+ max_tokens=1024,
+ ),
+ )
+
+ async def async_post_agentic_loop_response_hook(self, response, plan, kwargs):
+ self.post_hook_calls += 1
+ if isinstance(response, dict):
+ response["content"] = [*_native_search_blocks(index=2), *response.get("content", [])]
+ return response
+
+
+def _logging_obj(callback: CustomLogger, converted_stream: bool = False) -> MagicMock:
+ logging_obj = MagicMock()
+ logging_obj.model_call_details = {"websearch_interception_converted_stream": converted_stream}
+ logging_obj.dynamic_success_callbacks = [callback]
+ logging_obj.litellm_call_id = "call-abc"
+ return logging_obj
+
+
+async def _run_hooks(
+ handler: BaseLLMHTTPHandler,
+ callback: CustomLogger,
+ kwargs: dict,
+ response: object = None,
+ stream: bool = False,
+ converted_stream: bool = False,
+ api_surface: str = "anthropic_messages",
+):
+ return await handler._call_agentic_completion_hooks(
+ response=_response_asking_for_another_search() if response is None else response,
+ model="claude-sonnet-4-5",
+ messages=[{"role": "user", "content": "who won the world cup"}],
+ anthropic_messages_provider_config=MagicMock(),
+ anthropic_messages_optional_request_params={},
+ logging_obj=_logging_obj(callback, converted_stream=converted_stream),
+ stream=stream,
+ custom_llm_provider="anthropic",
+ kwargs=kwargs,
+ api_surface=api_surface,
+ )
+
+
+class TestCappedLoopReturnsTerminalResponse:
+ def setup_method(self):
+ self.handler = BaseLLMHTTPHandler()
+ self.callback = _InterceptingCallback()
+
+ @pytest.mark.asyncio
+ async def test_internal_tool_use_block_is_dropped(self):
+ result = await _run_hooks(
+ self.handler,
+ self.callback,
+ kwargs={"_agentic_loop_depth": 3, "max_agentic_loops": 3},
+ )
+
+ assert isinstance(result, dict)
+ assert INTERNAL_TOOL_NAME not in _tool_use_names(result)
+
+ @pytest.mark.asyncio
+ async def test_stop_reason_is_closed_out(self):
+ result = await _run_hooks(
+ self.handler,
+ self.callback,
+ kwargs={"_agentic_loop_depth": 3, "max_agentic_loops": 3},
+ )
+
+ assert result["stop_reason"] == "end_turn"
+
+ @pytest.mark.asyncio
+ async def test_native_blocks_and_text_survive(self):
+ result = await _run_hooks(
+ self.handler,
+ self.callback,
+ kwargs={"_agentic_loop_depth": 3, "max_agentic_loops": 3},
+ )
+
+ assert _block_types(result) == ["server_tool_use", "web_search_tool_result", "text"]
+
+ @pytest.mark.asyncio
+ async def test_no_follow_up_model_call_is_planned(self):
+ """
+ The rail has to end the turn without planning another model call, and it
+ has to end it by returning rather than by raising, which is the half that
+ the caller's response depends on.
+ """
+ result = await _run_hooks(
+ self.handler,
+ self.callback,
+ kwargs={"_agentic_loop_depth": 3, "max_agentic_loops": 3},
+ )
+
+ assert self.callback.plan_calls == 0
+ assert result["stop_reason"] == "end_turn"
+
+ @pytest.mark.asyncio
+ async def test_original_response_is_not_mutated(self):
+ response = _response_asking_for_another_search()
+
+ await _run_hooks(
+ self.handler,
+ self.callback,
+ kwargs={"_agentic_loop_depth": 3, "max_agentic_loops": 3},
+ response=response,
+ )
+
+ assert response["stop_reason"] == "tool_use"
+ assert INTERNAL_TOOL_NAME in _tool_use_names(response)
+
+ @pytest.mark.asyncio
+ async def test_repeated_fingerprint_guard_is_terminal_too(self):
+ tool_calls = {"tool_calls": [_internal_tool_use_block()], "tool_type": "websearch"}
+ seen = json.dumps(tool_calls, sort_keys=True, default=str)
+
+ result = await _run_hooks(
+ self.handler,
+ self.callback,
+ kwargs={"_agentic_loop_depth": 0, "max_agentic_loops": 3, "_agentic_loop_fingerprints": [seen]},
+ )
+
+ assert self.callback.plan_calls == 0
+ assert INTERNAL_TOOL_NAME not in _tool_use_names(result)
+ assert result["stop_reason"] == "end_turn"
+
+ @pytest.mark.asyncio
+ async def test_client_declared_tool_use_is_left_alone(self):
+ response = _response_asking_for_another_search()
+ client_tool_use = {"id": "toolu_client_1", "type": "tool_use", "name": "get_weather", "input": {}}
+ response["content"].append(client_tool_use)
+
+ result = await _run_hooks(
+ self.handler,
+ self.callback,
+ kwargs={"_agentic_loop_depth": 3, "max_agentic_loops": 3},
+ response=response,
+ )
+
+ assert _tool_use_names(result) == ["get_weather"]
+ assert result["stop_reason"] == "tool_use"
+
+ def test_only_the_refused_tool_calls_are_dropped(self):
+ """
+ A block is matched on the id the rail refused, not on the tool name, so a
+ second block sharing that name survives when the rail never listed it. A
+ callback that picks its tool calls out by name hands both over and both
+ go, which is its own call to make; this is about not widening it here.
+ """
+ response = _response_asking_for_another_search()
+ response["content"].append(
+ {"id": "toolu_client_1", "type": "tool_use", "name": INTERNAL_TOOL_NAME, "input": {}}
+ )
+
+ result = BaseLLMHTTPHandler._finalize_refused_agentic_response(
+ response=response,
+ tool_calls={"tool_calls": [_internal_tool_use_block()]},
+ )
+
+ assert [block["id"] for block in result["content"] if block.get("type") == "tool_use"] == ["toolu_client_1"]
+ assert result["stop_reason"] == "tool_use"
+
+ def test_tool_calls_without_ids_still_match_by_name(self):
+ """
+ Not every callback shape carries ids on its tool calls, so the name is
+ still what decides when the rail refused a call that has no id.
+ """
+ result = BaseLLMHTTPHandler._finalize_refused_agentic_response(
+ response=_response_asking_for_another_search(),
+ tool_calls={"tool_calls": [{"name": INTERNAL_TOOL_NAME, "input": {}}]},
+ )
+
+ assert _tool_use_names(result) == []
+ assert result["stop_reason"] == "end_turn"
+
+ @pytest.mark.asyncio
+ async def test_streaming_caller_is_left_to_its_existing_behavior(self):
+ """
+ A streaming caller has already sent the original message to the client, so
+ a finalized turn would land as a second message rather than replace the
+ first. The rail keeps raising there and the caller handles it as before.
+ """
+ with pytest.raises(AgenticLoopSafetyError):
+ await _run_hooks(
+ self.handler,
+ self.callback,
+ kwargs={"_agentic_loop_depth": 3, "max_agentic_loops": 3},
+ stream=True,
+ )
+
+ assert self.callback.plan_calls == 0
+
+ @pytest.mark.asyncio
+ async def test_responses_surface_is_left_to_its_existing_behavior(self):
+ """
+ The responses surface carries a pydantic model rather than the anthropic
+ dict this finalizer rewrites, so it keeps raising instead of being handed
+ a response that was never actually finalized.
+ """
+ with pytest.raises(AgenticLoopSafetyError):
+ await _run_hooks(
+ self.handler,
+ self.callback,
+ kwargs={"_agentic_loop_depth": 3, "max_agentic_loops": 3},
+ api_surface="responses",
+ )
+
+ @pytest.mark.asyncio
+ async def test_non_dict_response_is_returned_untouched(self):
+ response = MagicMock()
+
+ result = await _run_hooks(
+ self.handler,
+ self.callback,
+ kwargs={"_agentic_loop_depth": 3, "max_agentic_loops": 3},
+ response=response,
+ )
+
+ assert result is response
+
+ @pytest.mark.asyncio
+ async def test_converted_stream_gets_a_terminal_fake_stream(self):
+ """
+ A converted stream is wrapped back into an Anthropic SSE stream here, the
+ same as every other return in this function, so a streaming client gets a
+ terminal stream rather than a bare dict. The interceptor turns the client's
+ stream into a non-streaming upstream call, so stream is False on this path
+ and the converted flag on the logging object is what marks it.
+ """
+ result = await _run_hooks(
+ self.handler,
+ self.callback,
+ kwargs={"_agentic_loop_depth": 3, "max_agentic_loops": 3},
+ converted_stream=True,
+ )
+
+ assert isinstance(result, FakeAnthropicMessagesStreamIterator)
+ assert result.response["stop_reason"] == "end_turn"
+ assert INTERNAL_TOOL_NAME not in _tool_use_names(result.response)
+
+ 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.
+ """
+ depth, max_loops, fingerprints = BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs={})
+
+ assert depth == 0
+ assert fingerprints == []
+ assert max_loops >= 1
+
+ depth, max_loops, fingerprints = BaseLLMHTTPHandler._get_agentic_loop_settings(
+ kwargs={"max_agentic_loops": 0}
+ )
+
+ assert max_loops >= 1
+ assert BaseLLMHTTPHandler._check_agentic_loop_safety(
+ tool_calls={"tool_calls": [_internal_tool_use_block()]},
+ fingerprints=fingerprints,
+ depth=depth,
+ max_loops=max_loops,
+ model="claude-sonnet-4-5",
+ )
+
+ def test_safety_error_is_still_a_value_error(self):
+ assert issubclass(AgenticLoopSafetyError, ValueError)
+
+ def test_safety_error_type_names_the_rail(self):
+ with pytest.raises(AgenticLoopSafetyError, match="max_agentic_loops"):
+ BaseLLMHTTPHandler._check_agentic_loop_safety(
+ tool_calls={"tool_calls": [_internal_tool_use_block()]},
+ fingerprints=[],
+ depth=3,
+ max_loops=3,
+ model="claude-sonnet-4-5",
+ )
+
+
+class TestOuterFramePostHookStillRuns:
+ """
+ The cap used to raise through the parent frame's await, which skipped the
+ parent's post-loop hook. The parent now gets its terminal response back and
+ finishes normally, so the blocks it was going to inject still land.
+ """
+
+ @pytest.mark.asyncio
+ async def test_parent_frame_injects_its_blocks_after_the_cap_trips(self, monkeypatch):
+ handler = BaseLLMHTTPHandler()
+ callback = _InterceptingCallback()
+
+ async def fake_acreate(**call_kwargs):
+ return await handler._call_agentic_completion_hooks(
+ response=_response_asking_for_another_search(block_id="toolu_internal_2"),
+ model=call_kwargs["model"],
+ messages=call_kwargs["messages"],
+ anthropic_messages_provider_config=MagicMock(),
+ anthropic_messages_optional_request_params={},
+ logging_obj=_logging_obj(callback),
+ stream=False,
+ custom_llm_provider="anthropic",
+ kwargs={
+ key: call_kwargs[key]
+ for key in ("_agentic_loop_depth", "max_agentic_loops", "_agentic_loop_fingerprints")
+ if key in call_kwargs
+ },
+ )
+
+ monkeypatch.setattr("litellm.anthropic_interface.messages.acreate", fake_acreate)
+
+ result = await _run_hooks(
+ handler,
+ callback,
+ kwargs={"_agentic_loop_depth": 0, "max_agentic_loops": 1},
+ )
+
+ assert callback.plan_calls == 1
+ assert callback.post_hook_calls == 1
+ assert _block_types(result)[:2] == ["server_tool_use", "web_search_tool_result"]
+ assert INTERNAL_TOOL_NAME not in _tool_use_names(result)
+ assert result["stop_reason"] == "end_turn"
+
+
+class TestMaxAgenticLoopsConfigKnob:
+ def test_from_config_yaml_reads_the_knob(self):
+ logger = WebSearchInterceptionLogger.from_config_yaml(
+ {"enabled_providers": ["bedrock"], "max_agentic_loops": 7}
+ )
+
+ assert logger.max_agentic_loops == 7
+
+ def test_from_config_yaml_leaves_it_unset_by_default(self):
+ logger = WebSearchInterceptionLogger.from_config_yaml({"enabled_providers": ["bedrock"]})
+
+ assert logger.max_agentic_loops is None
+
+ @pytest.mark.parametrize("bad_value", [0, -1])
+ def test_out_of_range_ceilings_are_rejected_at_config_load(self, bad_value):
+ with pytest.raises(ValueError, match="max_agentic_loops"):
+ WebSearchInterceptionLogger.from_config_yaml(
+ {"enabled_providers": ["bedrock"], "max_agentic_loops": bad_value}
+ )
+
+ @pytest.mark.parametrize("bad_value", ["5", 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}
+ )
+
+ @pytest.mark.asyncio
+ async def test_knob_reaches_the_loop_settings(self):
+ logger = WebSearchInterceptionLogger.from_config_yaml(
+ {"enabled_providers": ["bedrock"], "max_agentic_loops": 7}
+ )
+ kwargs = {
+ "tools": [{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}],
+ "litellm_params": {"custom_llm_provider": "bedrock"},
+ }
+
+ updated = await logger.async_pre_request_hook(model="claude-sonnet-4-5", messages=[], kwargs=kwargs)
+
+ _, max_loops, _ = BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs=updated)
+ assert max_loops == 7
+
+ @pytest.mark.asyncio
+ async def test_deployment_setting_wins_over_the_feature_setting(self):
+ logger = WebSearchInterceptionLogger.from_config_yaml(
+ {"enabled_providers": ["bedrock"], "max_agentic_loops": 7}
+ )
+ kwargs = {
+ "tools": [{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}],
+ "litellm_params": {"custom_llm_provider": "bedrock"},
+ "max_agentic_loops": 2,
+ }
+
+ updated = await logger.async_pre_request_hook(model="claude-sonnet-4-5", messages=[], kwargs=kwargs)
+
+ _, max_loops, _ = BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs=updated)
+ assert max_loops == 2
+
+ @pytest.mark.asyncio
+ async def test_default_ceiling_applies_when_the_knob_is_unset(self):
+ logger = WebSearchInterceptionLogger.from_config_yaml({"enabled_providers": ["bedrock"]})
+ kwargs = {
+ "tools": [{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}],
+ "litellm_params": {"custom_llm_provider": "bedrock"},
+ }
+
+ updated = await logger.async_pre_request_hook(model="claude-sonnet-4-5", messages=[], kwargs=kwargs)
+
+ assert "max_agentic_loops" not in updated
+ _, max_loops, _ = BaseLLMHTTPHandler._get_agentic_loop_settings(kwargs=updated)
+ assert max_loops == 3