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]

feat(guardrails): add num_retries to generic_guardrail_api for checks lost after connect (#46965)

ryan-crabbe-berrif6ae25939e86
diff --git a/litellm/proxy/_lazy_openapi_snapshot.json b/litellm/proxy/_lazy_openapi_snapshot.json
index 961d32ab664..7198d74909c 100644
--- a/litellm/proxy/_lazy_openapi_snapshot.json
+++ b/litellm/proxy/_lazy_openapi_snapshot.json
@@ -14412,6 +14412,20 @@
"description": "Optional field if guardrail requires a 'model' parameter",
"title": "Model"
},
+ "num_retries": {
+ "anyOf": [
+ {
+ "maximum": 5.0,
+ "minimum": 0.0,
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "How many more times to send a guardrail check whose connection timed out waiting for the answer or was dropped after the request went out. Each retry opens a fresh connection and gets the full timeout. Connect failures, HTTP error statuses and BLOCKED verdicts are not retried. Unset or 0 sends each check once, and the most allowed is 5. Implemented by guardrail='generic_guardrail_api', other guardrails ignore it.",
+ "title": "Num Retries"
+ },
"on_sensitive_data": {
"anyOf": [
{
@@ -17001,6 +17015,20 @@
"description": "If True, logs violations without blocking. Defaults to False if not provided",
"title": "Monitor Mode"
},
+ "num_retries": {
+ "anyOf": [
+ {
+ "maximum": 5.0,
+ "minimum": 0.0,
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "How many more times to send a guardrail check whose connection timed out waiting for the answer or was dropped after the request went out. Each retry opens a fresh connection and gets the full timeout. Connect failures, HTTP error statuses and BLOCKED verdicts are not retried. Unset or 0 sends each check once, and the most allowed is 5. Implemented by guardrail='generic_guardrail_api', other guardrails ignore it.",
+ "title": "Num Retries"
+ },
"on_disallowed_action": {
"default": "block",
"description": "Choose whether disallowed tools block the request or get rewritten out of the payload",
diff --git a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.py
index 242354ac417..44705c4d166 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.py
@@ -44,6 +44,7 @@ def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"
litellm_params, optional_params, "streaming_buffer_until_moderated"
),
timeout=litellm_params.timeout,
+ num_retries=litellm_params.num_retries,
)
litellm.logging_callback_manager.add_litellm_callback(_generic_guardrail_api_callback)
diff --git a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py
index 93b08831d84..199da7df30d 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py
@@ -22,6 +22,7 @@ from litellm.integrations.custom_guardrail import (
log_guardrail_information,
)
from litellm.llms.custom_httpx.http_handler import (
+ AsyncHTTPHandler,
get_async_httpx_client,
httpxSpecialProvider,
)
@@ -63,6 +64,21 @@ _HEADER_VALUE_ALLOWLIST: Final = frozenset(
# Placeholder for headers that exist but are not on the allowlist (we don't expose their value).
_HEADER_PRESENT_PLACEHOLDER: Final = "[present]"
+_AFTER_CONNECT_FAILURES: Final = (
+ httpx.ReadTimeout,
+ httpx.WriteTimeout,
+ httpx.ReadError,
+ httpx.WriteError,
+ httpx.RemoteProtocolError,
+)
+
+
+def _after_connect_failure(error: Timeout | httpx.TransportError) -> httpx.TransportError | None:
+ """AsyncHTTPHandler re-raises connect and read timeouts as the same litellm Timeout, so the phase comes from
+ the httpx error it was raised while handling."""
+ origin: Final = error if isinstance(error, httpx.TransportError) else error.__cause__ or error.__context__
+ return origin if isinstance(origin, _AFTER_CONNECT_FAILURES) else None
+
def _header_value_allowed(
header_name: str,
@@ -81,7 +97,7 @@ def _header_value_allowed(
def _sanitize_inbound_headers(
- headers: object,
+ headers: Mapping[object, object] | None,
extra_allowlist: set[str] | None = None,
) -> dict[str, str] | None:
"""
@@ -254,9 +270,18 @@ class GenericGuardrailAPI(CustomGuardrail):
streaming_sampling_rate: int | None = None,
streaming_transform_mode: Literal["block_only", "incremental_diff"] | None = None,
streaming_buffer_until_moderated: bool | None = None,
+ num_retries: int | None = None,
+ async_handler: AsyncHTTPHandler | None = None,
+ fresh_handler_factory: Callable[[], AsyncHTTPHandler] | None = None,
**kwargs,
):
- self.async_handler = get_async_httpx_client(llm_provider=httpxSpecialProvider.GuardrailCallback)
+ self.async_handler = async_handler or get_async_httpx_client(
+ llm_provider=httpxSpecialProvider.GuardrailCallback
+ )
+ self.fresh_handler_factory: Callable[[], AsyncHTTPHandler] = fresh_handler_factory or (
+ lambda: AsyncHTTPHandler(timeout=self.async_handler.timeout)
+ )
+ self.num_retries: int = num_retries or 0
self.headers = headers or {}
self.extra_headers = extra_headers or []
@@ -384,12 +409,9 @@ class GenericGuardrailAPI(CustomGuardrail):
return_inputs.update(inputs)
return return_inputs
- def _build_request_headers(self) -> dict:
+ def _build_request_headers(self) -> Mapping[str, str]:
"""Build HTTP headers for the guardrail API request."""
- headers: Final = {"Content-Type": "application/json"}
- if self.headers:
- headers.update(self.headers)
- return headers
+ return {"Content-Type": "application/json", **self.headers}
def _request_body(
self,
@@ -463,6 +485,35 @@ class GenericGuardrailAPI(CustomGuardrail):
verbose_proxy_logger.error("Generic Guardrail API: failed to make request: %s", str(error))
raise Exception(f"Generic Guardrail API failed: {error}")
+ async def _post_check(
+ self,
+ payload: Mapping[str, object],
+ headers: Mapping[str, str],
+ retries_left: int,
+ fresh: bool = False,
+ ) -> httpx.Response:
+ handler: Final = self.fresh_handler_factory() if fresh else self.async_handler
+ try:
+ return await handler.post(
+ url=self.api_base, json=dict(payload), headers=dict(headers), timeout=self.timeout
+ )
+ except (Timeout, httpx.TransportError) as error:
+ failure: Final = _after_connect_failure(error)
+ if retries_left < 1 or failure is None:
+ raise
+ verbose_proxy_logger.warning(
+ "Generic Guardrail API check timed out or lost its connection, retrying on a fresh connection. "
+ "guardrail_name=%s api_base=%s error_type=%s retries_left=%d",
+ getattr(self, "guardrail_name", None),
+ self.api_base,
+ type(failure).__name__,
+ retries_left - 1,
+ )
+ finally:
+ if fresh:
+ await handler.close()
+ return await self._post_check(payload, headers, retries_left - 1, fresh=True)
+
@log_guardrail_information
async def apply_guardrail(
self,
@@ -508,12 +559,8 @@ class GenericGuardrailAPI(CustomGuardrail):
request_body: Final = request_data.get("body") or {}
# Merge additional provider specific params from config and dynamic params
- additional_params: Final = {**self.additional_provider_specific_params}
-
- # Get dynamic params from request if available
- dynamic_params: Final = self.get_guardrail_dynamic_request_body_params(request_body)
- if dynamic_params:
- additional_params.update(dynamic_params)
+ dynamic_params: Final[Mapping[str, object]] = self.get_guardrail_dynamic_request_body_params(request_body) or {}
+ additional_params: Final = {**self.additional_provider_specific_params, **dynamic_params}
# Extract user API key metadata
user_metadata: Final = self._extract_user_api_key_metadata(request_data)
@@ -546,11 +593,10 @@ class GenericGuardrailAPI(CustomGuardrail):
# Make the API request
# Use mode="json" to ensure all iterables are converted to lists
- response: Final = await self.async_handler.post(
- url=self.api_base,
- json=dict(self._request_body(guardrail_request, structured_messages)),
- headers=headers,
- timeout=self.timeout,
+ response: Final = await self._post_check(
+ self._request_body(guardrail_request, structured_messages),
+ headers,
+ self.num_retries,
)
response.raise_for_status()
diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.py
index 33db8cbc6f0..ff063d2e233 100644
--- a/litellm/types/guardrails.py
+++ b/litellm/types/guardrails.py
@@ -2,7 +2,7 @@ from collections.abc import Mapping
from datetime import datetime
from enum import Enum
from types import MappingProxyType
-from typing import Final, Literal, cast
+from typing import Annotated, Final, Literal, TypeAlias, cast
from pydantic import ConfigDict, Field, field_validator, model_validator
from pydantic.fields import FieldInfo
@@ -1012,6 +1012,22 @@ def _default_if_blank(field: FieldInfo | None, value: object) -> object:
return field.get_default(call_default_factory=True)
+GuardrailNumRetries: TypeAlias = Annotated[
+ int | None,
+ Field(
+ ge=0,
+ le=5,
+ description=(
+ "How many more times to send a guardrail check whose connection timed out waiting for the answer "
+ "or was dropped after the request went out. Each retry opens a fresh connection and gets the full "
+ "timeout. Connect failures, HTTP error statuses and BLOCKED verdicts are not retried. Unset or 0 "
+ "sends each check once, and the most allowed is 5. Implemented by guardrail='generic_guardrail_api', "
+ "other guardrails ignore it."
+ ),
+ ),
+]
+
+
class BaseLitellmParams(ContentFilterConfigModel): # works for new and patch update guardrails
api_key: str | None = Field(default=None, description="API key for the guardrail service")
api_base: str | None = Field(default=None, description="Base URL for the guardrail service API")
@@ -1220,6 +1236,8 @@ class BaseLitellmParams(ContentFilterConfigModel): # works for new and patch up
description="Python-like code containing the apply_guardrail function for custom guardrail logic",
)
+ num_retries: GuardrailNumRetries = None
+
timeout: float | None = Field(
default=None,
description=(
@@ -1437,7 +1455,7 @@ class LitellmParams( # pyright: ignore[reportIncompatibleVariableOverride] # o
super().__init__(**kwargs) # pyright: ignore[reportArgumentType] # pydantic validates each field's type at runtime
- def __contains__(self, key) -> bool:
+ def __contains__(self, key: str) -> bool:
# Define custom behavior for the 'in' operator
return hasattr(self, key)
diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py b/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py
index d34a3a13838..d38e54986b9 100644
--- a/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py
+++ b/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py
@@ -4,6 +4,7 @@ from typing import Any, Final, Literal, cast # noqa: TID251 # JSON chat rows h
from pydantic import ConfigDict, Field, SerializerFunctionWrapHandler, model_serializer
from typing_extensions import TypedDict
+from litellm.types.guardrails import GuardrailNumRetries
from litellm.types.llms.base import LiteLLMBaseModel
from litellm.types.llms.openai import (
AllMessageValues,
@@ -70,6 +71,8 @@ class GenericGuardrailAPIOptionalParams(LiteLLMBaseModel):
),
)
+ num_retries: GuardrailNumRetries = None
+
forward_messages_as_sent: bool | None = Field(
default=False,
description=(
diff --git a/tests/code_coverage_tests/ensure_async_clients_test.py b/tests/code_coverage_tests/ensure_async_clients_test.py
index 5a534199cbc..93ae2e2837b 100644
--- a/tests/code_coverage_tests/ensure_async_clients_test.py
+++ b/tests/code_coverage_tests/ensure_async_clients_test.py
@@ -5,6 +5,9 @@ ALLOWED_FILES = [
# Lens data traffic owns one pool per app lifespan, isolated from model traffic and closed on shutdown.
"../../litellm/tracing/remote.py",
"./litellm/tracing/remote.py",
+ # Only a guardrail check retry opens a client, on purpose to get a new connection, and closes it right after.
+ "../../litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py",
+ "./litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py",
# local files
"../../litellm/__init__.py",
"../../litellm/llms/custom_httpx/http_handler.py",
diff --git a/tests/integration/observability/test_generic_guardrail_num_retries.py b/tests/integration/observability/test_generic_guardrail_num_retries.py
new file mode 100644
index 00000000000..df761d25968
--- /dev/null
+++ b/tests/integration/observability/test_generic_guardrail_num_retries.py
@@ -0,0 +1,179 @@
+"""generic_guardrail_api `num_retries` resends a check that timed out waiting for its answer, through a real proxy.
+
+Each guardrail points at its own owned stub. A stub that holds a check never answers it before the 1s guardrail
+timeout, and holding lasts until teardown so a resent check can only be answered by a later arrival.
+"""
+
+import itertools
+import json
+import threading
+from collections.abc import Callable, Iterator, Mapping
+from contextlib import ExitStack
+from dataclasses import dataclass
+from pathlib import Path
+from types import MappingProxyType
+from typing import Final
+
+import httpx
+import pytest
+import yaml
+from integration._support.client import Gateway
+from integration._support.openai_wire import chat_reply
+from integration._support.process import OwnedProxy, owned_proxy_process
+from integration._support.wire import Reply, Request, Wire, wire_server
+from pydantic import JsonValue, TypeAdapter
+
+MODEL: Final = "guarded-chat"
+UPSTREAM_MODEL: Final = "openai/gpt-6.1-sol"
+GUARDRAIL_TIMEOUT_SECONDS: Final = 1
+HOLDS_FIRST_RETRIED: Final = "holds-first-check-retried-once"
+HOLDS_FIRST_UNSET: Final = "holds-first-check-num-retries-unset"
+HOLDS_ALL_RETRIED_TWICE: Final = "holds-every-check-retried-twice"
+UNAVAILABLE_RETRIED_TWICE: Final = "unavailable-retried-twice"
+ANSWER: Final = "upstream answer"
+NO_ACTION: Final = Reply(body=json.dumps({"action": "NONE"}).encode())
+_CONFIG: Final = Path(__file__).resolve().parents[1] / "proxy_config.yaml"
+_JSON: Final = TypeAdapter(dict[str, JsonValue])
+
+
+@dataclass(frozen=True, slots=True)
+class Rig:
+ owned: OwnedProxy
+ upstream: Wire
+ guardrails: Mapping[str, Wire]
+
+
+def _holds_first(release: threading.Event) -> Callable[[Request], Reply]:
+ arrivals: Final = itertools.count()
+
+ def respond(_request: Request) -> Reply:
+ if next(arrivals) == 0:
+ release.wait()
+ return NO_ACTION
+
+ return respond
+
+
+def _holds_all(release: threading.Event) -> Callable[[Request], Reply]:
+ def respond(_request: Request) -> Reply:
+ release.wait()
+ return NO_ACTION
+
+ return respond
+
+
+def _unavailable(_request: Request) -> Reply:
+ return Reply(status=503, body=b'{"error": "guardrail unavailable"}')
+
+
+def _upstream(_request: Request) -> Reply:
+ return chat_reply("chatcmpl-num-retries", "gpt-6.1-sol", ANSWER, stream=False)
+
+
+def _guardrail(name: str, wire: Wire, num_retries: int | None) -> dict[str, JsonValue]:
+ return {
+ "guardrail_name": name,
+ "litellm_params": {
+ "guardrail": "generic_guardrail_api",
+ "mode": "pre_call",
+ "default_on": False,
+ "api_base": wire.url,
+ "api_key": "synthetic-guardrail-key",
+ "timeout": GUARDRAIL_TIMEOUT_SECONDS,
+ **({} if num_retries is None else {"num_retries": num_retries}),
+ },
+ }
+
+
[email protected](scope="module")
+def rig(session_gateway: Gateway, tmp_path_factory: pytest.TempPathFactory) -> Iterator[Rig]:
+ directory: Final = tmp_path_factory.mktemp("generic-guardrail-num-retries")
+ release: Final = threading.Event()
+ with ExitStack() as stack:
+ upstream: Final = stack.enter_context(wire_server(_upstream))
+ guardrails: Final = MappingProxyType(
+ {
+ HOLDS_FIRST_RETRIED: stack.enter_context(wire_server(_holds_first(release), keep_alive=True)),
+ HOLDS_FIRST_UNSET: stack.enter_context(wire_server(_holds_first(release), keep_alive=True)),
+ HOLDS_ALL_RETRIED_TWICE: stack.enter_context(wire_server(_holds_all(release), keep_alive=True)),
+ UNAVAILABLE_RETRIED_TWICE: stack.enter_context(wire_server(_unavailable, keep_alive=True)),
+ }
+ )
+ stack.callback(release.set)
+ retries: Final = MappingProxyType(
+ {HOLDS_FIRST_RETRIED: 1, HOLDS_FIRST_UNSET: None, HOLDS_ALL_RETRIED_TWICE: 2, UNAVAILABLE_RETRIED_TWICE: 2}
+ )
+ base: Final = _JSON.validate_python(yaml.safe_load(_CONFIG.read_text()))
+ path: Final = directory / "generic-guardrail-num-retries.yaml"
+ path.write_text(
+ yaml.safe_dump(
+ {
+ **base,
+ "model_list": [
+ {
+ "model_name": MODEL,
+ "litellm_params": {
+ "model": UPSTREAM_MODEL,
+ "api_base": f"{upstream.url}/v1",
+ "api_key": "synthetic-openai-key",
+ },
+ }
+ ],
+ "guardrails": [_guardrail(name, wire, retries[name]) for name, wire in guardrails.items()],
+ }
+ )
+ )
+ owned: Final = stack.enter_context(owned_proxy_process(session_gateway, directory, {}, config=path))
+ yield Rig(owned, upstream, guardrails)
+
+
+def _chat(rig: Rig, guardrail: str) -> httpx.Response:
+ return rig.owned.gateway.request(
+ "POST",
+ "/v1/chat/completions",
+ {"model": MODEL, "messages": [{"role": "user", "content": "is this allowed?"}], "guardrails": [guardrail]},
+ )
+
+
+def _checks(wire: Wire) -> tuple[bytes, ...]:
+ return tuple(request.body for request in wire.drain())
+
+
+def test_check_held_past_the_timeout_is_resent_on_a_fresh_connection_and_the_request_is_served(rig: Rig) -> None:
+ response: Final = _chat(rig, HOLDS_FIRST_RETRIED)
+
+ assert response.status_code == 200, response.text
+ assert response.json()["choices"][0]["message"]["content"] == ANSWER
+ stub: Final = rig.guardrails[HOLDS_FIRST_RETRIED]
+ checks: Final = _checks(stub)
+ assert len(checks) == 2, checks
+ assert checks[0] == checks[1]
+ assert stub.connections() == 2
+ assert len(rig.upstream.drain()) == 1
+
+
+def test_check_held_past_the_timeout_is_sent_once_when_num_retries_is_unset(rig: Rig) -> None:
+ response: Final = _chat(rig, HOLDS_FIRST_UNSET)
+
+ assert response.status_code != 200, response.text
+ assert "Generic Guardrail API failed" in response.text
+ assert len(_checks(rig.guardrails[HOLDS_FIRST_UNSET])) == 1
+ assert rig.upstream.drain() == ()
+
+
+def test_num_retries_bounds_how_many_times_a_held_check_is_sent(rig: Rig) -> None:
+ response: Final = _chat(rig, HOLDS_ALL_RETRIED_TWICE)
+
+ assert response.status_code != 200, response.text
+ assert "Generic Guardrail API failed" in response.text
+ assert len(_checks(rig.guardrails[HOLDS_ALL_RETRIED_TWICE])) == 3
+ assert rig.upstream.drain() == ()
+
+
+def test_error_status_from_the_guardrail_is_not_resent(rig: Rig) -> None:
+ response: Final = _chat(rig, UNAVAILABLE_RETRIED_TWICE)
+
+ assert response.status_code != 200, response.text
+ assert "Generic Guardrail API failed" in response.text
+ assert len(_checks(rig.guardrails[UNAVAILABLE_RETRIED_TWICE])) == 1
+ assert rig.upstream.drain() == ()
diff --git a/tests/integration/providers/_idle_upstream_support.py b/tests/integration/providers/_idle_upstream_support.py
index ca808abc008..5fccd9804a6 100644
--- a/tests/integration/providers/_idle_upstream_support.py
+++ b/tests/integration/providers/_idle_upstream_support.py
@@ -294,11 +294,11 @@ def chat_httpx(target: ProxyTarget, model: str, marker: str) -> Answer:
)
-def chat_with_guardrail(target: ProxyTarget, model: str, marker: str) -> Answer:
+def chat_with_guardrail(target: ProxyTarget, model: str, marker: str, guardrail: str = GUARDRAIL) -> Answer:
return _post(
target,
"/v1/chat/completions",
- {"model": model, "messages": [{"role": "user", "content": marker}], "guardrails": [GUARDRAIL]},
+ {"model": model, "messages": [{"role": "user", "content": marker}], "guardrails": [guardrail]},
_chat_body,
)
@@ -517,18 +517,21 @@ def pass_through_deployment(_model: str, url: str, _steady: str) -> ConfigPart:
return ConfigPart(pass_through=({"path": PASS_THROUGH, "target": f"{url}/passthrough"},))
-def guardrail_deployment(model: str, url: str, steady: str) -> ConfigPart:
+def guardrail_deployment(
+ model: str, url: str, steady: str, guardrail: str = GUARDRAIL, num_retries: int | None = None
+) -> ConfigPart:
return ConfigPart(
models=openai_deployment(model, steady, steady).models,
guardrails=(
{
- "guardrail_name": GUARDRAIL,
+ "guardrail_name": guardrail,
"litellm_params": {
"guardrail": "generic_guardrail_api",
"mode": "pre_call",
"default_on": False,
"api_base": url,
"api_key": PROVIDER_KEY,
+ **({} if num_retries is None else {"num_retries": num_retries}),
},
},
),
diff --git a/tests/integration/providers/test_idle_upstream_guardrail_cut_wire.py b/tests/integration/providers/test_idle_upstream_guardrail_cut_wire.py
new file mode 100644
index 00000000000..6b12e61aa4e
--- /dev/null
+++ b/tests/integration/providers/test_idle_upstream_guardrail_cut_wire.py
@@ -0,0 +1,134 @@
+import threading
+from collections.abc import Iterator, Mapping
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass, field
+from functools import partial
+from itertools import chain
+from types import MappingProxyType
+from typing import Final
+
+import pytest
+from integration._support.client import Gateway
+from integration._support.idle_gateway import Arrival
+from integration._support.process import graceful_stop_seconds
+from integration._support.wire import Reply, Request
+from integration.providers._idle_upstream_support import (
+ REUSE_IDLE_SECONDS,
+ ProxyTarget,
+ Row,
+ Sent,
+ UpstreamProxy,
+ answer,
+ answered,
+ chat_with_guardrail,
+ expected_answers,
+ guardrail_deployment,
+ landed,
+ on_each_worker,
+ send,
+ spend_statuses,
+ stay_idle,
+ upstream_proxy,
+)
+
+CUT_AFTER_SECONDS: Final = 3.0
+POOLED_PER_WORKER: Final = 2
+RETRIED: Final = "guardrail-cut-num-retries-1"
+UNSET: Final = "guardrail-cut-num-retries-unset"
+
+pytestmark: Final = pytest.mark.timeout(int(2 * graceful_stop_seconds() + 180 + REUSE_IDLE_SECONDS))
+
+
+@dataclass(frozen=True, slots=True)
+class PairedWarmup:
+ """While warming, each check waits for a second one so every worker pools two connections to the guardrail."""
+
+ warming: threading.Event = field(default_factory=threading.Event)
+ pair: threading.Barrier = field(default_factory=lambda: threading.Barrier(POOLED_PER_WORKER))
+
+ def respond(self, request: Request) -> Reply:
+ if self.warming.is_set():
+ self.pair.wait(timeout=30)
+ return answer(request)
+
+
+@dataclass(frozen=True, slots=True)
+class StaleGuardrails:
+ proxy: UpstreamProxy
+ pooled: Mapping[str, frozenset[int]]
+
+
+WARMUPS: Final = MappingProxyType({RETRIED: PairedWarmup(), UNSET: PairedWarmup()})
+ROWS: Final = (
+ Row(
+ RETRIED,
+ partial(guardrail_deployment, guardrail=RETRIED, num_retries=1),
+ partial(chat_with_guardrail, guardrail=RETRIED),
+ respond=WARMUPS[RETRIED].respond,
+ ),
+ Row(
+ UNSET,
+ partial(guardrail_deployment, guardrail=UNSET),
+ partial(chat_with_guardrail, guardrail=UNSET),
+ respond=WARMUPS[UNSET].respond,
+ ),
+)
+
+
+def _pair(row: Row, target: ProxyTarget) -> tuple[Sent, ...]:
+ with ThreadPoolExecutor(max_workers=POOLED_PER_WORKER) as pool:
+ return tuple(pool.map(send, (row,) * POOLED_PER_WORKER, (target,) * POOLED_PER_WORKER))
+
+
+def _warm(proxy: UpstreamProxy, row: Row) -> frozenset[int]:
+ warmup: Final = WARMUPS[row.name]
+ warmup.warming.set()
+ sents: Final = on_each_worker(proxy.owned, proxy.workers, lambda: _pair(row, proxy.target))
+ warmup.warming.clear()
+ assert answered(sents) == expected_answers(row, sents), sents
+ return frozenset(arrival.connection for arrival in proxy.gateways[row.name].drain())
+
+
[email protected](scope="module")
+def stale(session_gateway: Gateway, tmp_path_factory: pytest.TempPathFactory) -> Iterator[StaleGuardrails]:
+ directory: Final = tmp_path_factory.mktemp("idle-upstream-guardrail-cut")
+ with upstream_proxy(session_gateway, directory, ROWS, {}, drop_after=CUT_AFTER_SECONDS) as proxy:
+ pooled: Final = MappingProxyType({row.name: _warm(proxy, row) for row in ROWS})
+ assert {name: len(connections) for name, connections in pooled.items()} == {
+ row.name: 2 * POOLED_PER_WORKER for row in ROWS
+ }, pooled
+ stay_idle(tuple(proxy.gateways.values()), REUSE_IDLE_SECONDS)
+ yield StaleGuardrails(proxy, pooled)
+
+
+def _cut_once(sents: tuple[Sent, ...]) -> tuple[tuple[str, bool], ...]:
+ return tuple(sorted((sent.marker, True) for sent in sents))
+
+
+def _cut_once_then_landed(sents: tuple[Sent, ...]) -> tuple[tuple[str, bool], ...]:
+ return tuple(sorted(chain.from_iterable(((sent.marker, False), (sent.marker, True)) for sent in sents)))
+
+
+def _landed_on(arrivals: tuple[Arrival, ...]) -> frozenset[int]:
+ return frozenset(arrival.connection for arrival in arrivals if not arrival.dropped)
+
+
+def test_retried_check_cut_on_a_stale_pooled_connection_lands_on_a_connection_that_was_never_pooled(
+ stale: StaleGuardrails,
+) -> None:
+ sents, arrivals = stale.proxy.probe(RETRIED)
+
+ assert answered(sents) == expected_answers(stale.proxy.rows[RETRIED], sents), (sents, arrivals)
+ assert landed(arrivals) == _cut_once_then_landed(sents), arrivals
+ assert _landed_on(arrivals).isdisjoint(stale.pooled[RETRIED]), (arrivals, stale.pooled)
+ assert spend_statuses(sents) == ("success",) * len(sents), sents
+
+
+def test_check_cut_on_a_stale_pooled_connection_is_not_resent_when_num_retries_is_unset(
+ stale: StaleGuardrails,
+) -> None:
+ sents, arrivals = stale.proxy.probe(UNSET)
+
+ assert [sent.answer.status == 200 for sent in sents] == [False] * len(sents), sents
+ assert all("Generic Guardrail API failed" in sent.answer.text for sent in sents), sents
+ assert landed(arrivals) == _cut_once(sents), arrivals
diff --git a/tests/unit/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py b/tests/unit/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py
index f50da1bff64..8308a7ba386 100644
--- a/tests/unit/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py
+++ b/tests/unit/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py
@@ -8,6 +8,9 @@ specifically focusing on metadata extraction and passing.
import json
import logging
import os
+from collections.abc import Callable
+from functools import partial
+from queue import SimpleQueue
from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch
@@ -26,7 +29,7 @@ from litellm.proxy.guardrails.guardrail_hooks.generic_guardrail_api import (
from litellm.proxy.guardrails.guardrail_hooks.generic_guardrail_api.generic_guardrail_api import (
_HEADER_PRESENT_PLACEHOLDER,
)
-from litellm.types.utils import Choices, Message
+from litellm.types.utils import Choices, GenericGuardrailAPIInputs, Message
@pytest.fixture
@@ -2470,3 +2473,151 @@ class TestFailOnError:
request_data={},
input_type="response",
)
+
+
+Outcome = Exception | Callable[[], httpx.Response]
+
+REWRITTEN: Final = partial(httpx.Response, 200, json={"action": "GUARDRAIL_INTERVENED", "texts": ["redacted"]})
+
+
+def _scripted(*outcomes: Outcome) -> tuple[httpx.MockTransport, SimpleQueue[bytes]]:
+ """Each check gets the next outcome; the last one repeats once the script runs out."""
+ sent: Final[SimpleQueue[bytes]] = SimpleQueue()
+ script: Final = iter(outcomes)
+
+ def answer(request: httpx.Request) -> httpx.Response:
+ sent.put(request.read())
+ outcome: Final = next(script, outcomes[-1])
+ if isinstance(outcome, Exception):
+ raise outcome
+ return outcome()
+
+ return httpx.MockTransport(answer), sent
+
+
+def _guardrail_on(
+ transport: httpx.MockTransport, num_retries: int | None, fail_on_error: bool = True
+) -> GenericGuardrailAPI:
+ return GenericGuardrailAPI(
+ api_base="https://api.test.guardrail.com",
+ guardrail_name="retrying-guardrail",
+ fail_on_error=fail_on_error,
+ num_retries=num_retries,
+ timeout=5,
+ async_handler=AsyncHTTPHandler(transport=transport),
+ fresh_handler_factory=lambda: AsyncHTTPHandler(transport=transport),
+ )
+
+
+async def _check(guardrail: GenericGuardrailAPI) -> GenericGuardrailAPIInputs:
+ return await guardrail.apply_guardrail(inputs={"texts": ["hi"]}, request_data={}, input_type="request")
+
+
+async def _attempts_until_it_raises(outcome: Outcome, num_retries: int | None) -> int:
+ transport, sent = _scripted(outcome)
+ with pytest.raises(Exception, match=r"Generic Guardrail API failed|policy violation"):
+ await _check(_guardrail_on(transport, num_retries))
+ return sent.qsize()
+
+
+class _OpenCloseLoggingHandler(AsyncHTTPHandler):
+ def __init__(self, transport: httpx.MockTransport, events: SimpleQueue[str]) -> None:
+ super().__init__(transport=transport)
+ self._events: Final = events
+ events.put("open")
+
+ async def close(self) -> None:
+ self._events.put("close")
+ await super().close()
+
+
+class TestNumRetries:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("outcomes", "fresh_connections"),
+ [
+ ((httpx.ReadTimeout("no answer before the read timeout"),), 3),
+ ((httpx.ReadTimeout("no answer"), httpx.ReadTimeout("no answer"), REWRITTEN), 2),
+ ],
+ ids=["every_retry_fails", "second_retry_succeeds"],
+ )
+ async def test_each_retry_connection_closes_before_the_next_attempt(
+ self, outcomes: tuple[Outcome, ...], fresh_connections: int
+ ) -> None:
+ transport, _ = _scripted(*outcomes)
+ events: Final[SimpleQueue[str]] = SimpleQueue()
+ guardrail: Final = GenericGuardrailAPI(
+ api_base="https://api.test.guardrail.com",
+ guardrail_name="retrying-guardrail",
+ fail_on_error=False,
+ num_retries=3,
+ timeout=5,
+ async_handler=AsyncHTTPHandler(transport=transport),
+ fresh_handler_factory=lambda: _OpenCloseLoggingHandler(transport, events),
+ )
+
+ await _check(guardrail)
+
+ assert [events.get_nowait() for _ in range(events.qsize())] == ["open", "close"] * fresh_connections
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "failure",
+ [
+ httpx.ReadTimeout("no answer before the read timeout"),
+ httpx.WriteTimeout("request body stalled"),
+ httpx.ReadError("connection reset by peer"),
+ httpx.WriteError("broken pipe"),
+ httpx.RemoteProtocolError("Server disconnected without sending a response."),
+ ],
+ ids=["read_timeout", "write_timeout", "read_error", "write_error", "remote_protocol_error"],
+ )
+ async def test_check_lost_after_connect_is_resent_and_the_retry_verdict_applies(self, failure: Exception) -> None:
+ transport, sent = _scripted(failure, REWRITTEN)
+
+ result: Final = await _check(_guardrail_on(transport, num_retries=1))
+
+ bodies: Final = [sent.get_nowait() for _ in range(sent.qsize())]
+ assert len(bodies) == 2
+ assert bodies[0] == bodies[1]
+ assert result == {"texts": ["redacted"]}
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "outcome",
+ [
+ httpx.ConnectTimeout("no TCP handshake before the timeout"),
+ httpx.ConnectError("connection refused"),
+ httpx.PoolTimeout("no free pooled connection"),
+ partial(httpx.Response, 503, json={"error": "unavailable"}),
+ partial(httpx.Response, 500, json={"error": "boom"}),
+ partial(httpx.Response, 200, json={"action": "BLOCKED", "blocked_reason": "policy violation"}),
+ ],
+ ids=["connect_timeout", "connect_error", "pool_timeout", "http_503", "http_500", "blocked"],
+ )
+ async def test_num_retries_does_not_resend_connect_failures_error_statuses_or_blocks(
+ self, outcome: Outcome
+ ) -> None:
+ assert await _attempts_until_it_raises(outcome, num_retries=3) == await _attempts_until_it_raises(
+ outcome, num_retries=None
+ )
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("num_retries", [None, 0])
+ async def test_unset_num_retries_sends_a_timed_out_check_once(self, num_retries: int | None) -> None:
+ transport, sent = _scripted(httpx.ReadTimeout("no answer before the read timeout"), REWRITTEN)
+
+ with pytest.raises(Exception, match="Generic Guardrail API failed"):
+ await _check(_guardrail_on(transport, num_retries))
+
+ assert sent.qsize() == 1
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("num_retries", [1, 3])
+ async def test_num_retries_bounds_the_attempts_before_fail_on_error_applies(self, num_retries: int) -> None:
+ transport, sent = _scripted(httpx.ReadTimeout("no answer before the read timeout"))
+
+ result: Final = await _check(_guardrail_on(transport, num_retries, fail_on_error=False))
+
+ assert sent.qsize() == num_retries + 1
+ assert result == {"texts": ["hi"]}
diff --git a/tests/unit/types/test_guardrails.py b/tests/unit/types/test_guardrails.py
index 5c652a10e16..97bab8295f4 100644
--- a/tests/unit/types/test_guardrails.py
+++ b/tests/unit/types/test_guardrails.py
@@ -7,6 +7,7 @@ from typing import Any, List, Optional, Tuple
from unittest.mock import MagicMock, patch
import pytest
+from pydantic import ValidationError
import litellm
import litellm.litellm_core_utils
@@ -178,3 +179,16 @@ def test_litellm_params_treats_blank_values_as_unset(blank: str) -> None:
assert with_blank_values.model_dump() == omitted.model_dump()
assert BaseLitellmParams(fail_on_error=blank).model_dump() == BaseLitellmParams().model_dump()
+
+
[email protected](("configured", "loaded"), [("2", 2), (2, 2), ("0", 0), (5, 5), ("", None)])
+def test_num_retries_loads_the_dashboard_string_and_blank_means_unset(configured: object, loaded: int | None) -> None:
+ assert (
+ LitellmParams(guardrail="generic_guardrail_api", mode="pre_call", num_retries=configured).num_retries == loaded
+ )
+
+
[email protected]("configured", [-1, 6, "1.5", "twice"])
+def test_num_retries_rejects_values_that_are_not_a_retry_count(configured: object) -> None:
+ with pytest.raises(ValidationError, match="num_retries"):
+ LitellmParams(guardrail="generic_guardrail_api", mode="pre_call", num_retries=configured)
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index 7fae3437f22..e5c1b9f2c26 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -27052,6 +27052,11 @@ export interface components {
* @description Optional field if guardrail requires a 'model' parameter
*/
model?: string | null;
+ /**
+ * Num Retries
+ * @description How many more times to send a guardrail check whose connection timed out waiting for the answer or was dropped after the request went out. Each retry opens a fresh connection and gets the full timeout. Connect failures, HTTP error statuses and BLOCKED verdicts are not retried. Unset or 0 sends each check once, and the most allowed is 5. Implemented by guardrail='generic_guardrail_api', other guardrails ignore it.
+ */
+ num_retries?: number | null;
/**
* On Sensitive Data
* @description Action to take when sensitive data is detected. 'block' raises an exception (default behavior). 'route' reroutes the request to the model specified in sensitive_data_route_to_model.
@@ -36638,6 +36643,11 @@ export interface components {
* @description If True, logs violations without blocking. Defaults to False if not provided
*/
monitor_mode?: boolean | null;
+ /**
+ * Num Retries
+ * @description How many more times to send a guardrail check whose connection timed out waiting for the answer or was dropped after the request went out. Each retry opens a fresh connection and gets the full timeout. Connect failures, HTTP error statuses and BLOCKED verdicts are not retried. Unset or 0 sends each check once, and the most allowed is 5. Implemented by guardrail='generic_guardrail_api', other guardrails ignore it.
+ */
+ num_retries?: number | null;
/**
* On Disallowed Action
* @description Choose whether disallowed tools block the request or get rewritten out of the payload