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(guardrails): accept Gemini tools in generic_guardrail_api, add opt-in forward_messages_as_sent, name the error type on fail-open (#46338)

ryan-crabbe-berri0dac61a555cd
diff --git a/litellm/proxy/_lazy_openapi_snapshot.json b/litellm/proxy/_lazy_openapi_snapshot.json
index 467cb2d624c..961d32ab664 100644
--- a/litellm/proxy/_lazy_openapi_snapshot.json
+++ b/litellm/proxy/_lazy_openapi_snapshot.json
@@ -14261,6 +14261,19 @@
"description": "Whether to fail the request if the guardrail encounters an error. Implemented by guardrail='model_armor', 'generic_guardrail_api' and 'crowdstrike_aidr'. True (default) raises the error. False logs a critical error and lets the request proceed, so only a valid guardrail response can block or modify it.",
"title": "Fail On Error"
},
+ "forward_messages_as_sent": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": false,
+ "description": "Only honored by guardrail='generic_guardrail_api'. When True, structured_messages reaches the guardrail exactly as the client sent it, so rows can carry provider-native content blocks and keys the OpenAI chat types do not declare. Default False sends OpenAI-format chat rows with undeclared keys removed.",
+ "title": "Forward Messages As Sent"
+ },
"guard_name": {
"anyOf": [
{
@@ -16612,6 +16625,19 @@
"description": "HTTP timeout in seconds for checking attached files. Default: 10.",
"title": "File Guardrail Timeout"
},
+ "forward_messages_as_sent": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": false,
+ "description": "Only honored by guardrail='generic_guardrail_api'. When True, structured_messages reaches the guardrail exactly as the client sent it, so rows can carry provider-native content blocks and keys the OpenAI chat types do not declare. Default False sends OpenAI-format chat rows with undeclared keys removed.",
+ "title": "Forward Messages As Sent"
+ },
"gateway_name": {
"anyOf": [
{
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 320d687b3aa..242354ac417 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.py
@@ -32,6 +32,7 @@ def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"
additional_provider_specific_params=getattr(litellm_params, "additional_provider_specific_params", {}),
unreachable_fallback=getattr(litellm_params, "unreachable_fallback", "fail_closed"),
fail_on_error=getattr(litellm_params, "fail_on_error", True),
+ forward_messages_as_sent=getattr(litellm_params, "forward_messages_as_sent", False),
extra_headers=getattr(litellm_params, "extra_headers", None),
guardrail_name=guardrail.get("guardrail_name", ""),
event_hook=litellm_params.mode,
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 25df7a20e14..93b08831d84 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
@@ -7,10 +7,12 @@
import fnmatch
import os
-from collections.abc import Mapping, Sequence
+from collections.abc import Callable, Mapping, Sequence
from typing import TYPE_CHECKING, Final, Literal, Optional
import httpx
+from pydantic import JsonValue, TypeAdapter, ValidationError
+from pydantic_core import PydanticSerializationError
from litellm._logging import verbose_proxy_logger
from litellm._version import version as litellm_version
@@ -38,6 +40,10 @@ if TYPE_CHECKING:
from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel
GUARDRAIL_NAME: Final = "generic_guardrail_api"
+_CHAT_ROW: Final[TypeAdapter[AllMessageValues]] = TypeAdapter(AllMessageValues)
+_SENT_ROW: Final = TypeAdapter(Mapping[str, object])
+_SENT_ROWS: Final = TypeAdapter(Sequence[Mapping[str, object]])
+_JSON: Final[TypeAdapter[JsonValue]] = TypeAdapter(JsonValue)
# Headers whose values are forwarded as-is (case-insensitive). Glob patterns supported (e.g. x-stainless-*, x-litellm*).
_HEADER_VALUE_ALLOWLIST: Final = frozenset(
@@ -150,23 +156,65 @@ def _extract_inbound_headers(
return None
+def _is_contained_in(part: JsonValue, whole: JsonValue) -> bool:
+ pending: Final[list[tuple[JsonValue, JsonValue]]] = [(part, whole)] # mutable-ok: worklist, recursion is banned
+ while pending:
+ match pending.pop():
+ case dict() as part_dict, dict() as whole_dict:
+ if not part_dict.keys() <= whole_dict.keys():
+ return False
+ pending.extend((value, whole_dict[key]) for key, value in part_dict.items())
+ case list() as part_list, list() as whole_list:
+ if len(part_list) != len(whole_list):
+ return False
+ pending.extend(zip(part_list, whole_list, strict=True))
+ case part_leaf, whole_leaf if part_leaf != whole_leaf:
+ return False
+ case _:
+ pass
+ return True
+
+
+def _is_shown_row(shown: AllMessageValues, returned: AllMessageValues) -> bool:
+ return returned == shown
+
+
+def _is_echo(original: AllMessageValues, returned: AllMessageValues) -> bool:
+ """A server that parses rows with its own message types and echoes them back drops the
+ keys those types do not declare. That is still an echo as long as nothing changed and
+ every key the chat completion types declare is kept."""
+ if returned == original:
+ return True
+ try:
+ sent: Final[JsonValue] = _JSON.validate_json(_SENT_ROW.dump_json(original))
+ declared: Final[JsonValue] = _JSON.validate_json(
+ _CHAT_ROW.dump_json(_CHAT_ROW.validate_python(original), warnings="error")
+ )
+ echoed: Final[JsonValue] = _JSON.validate_python(returned)
+ except (ValidationError, PydanticSerializationError):
+ return False
+ return _is_contained_in(echoed, sent) and _is_contained_in(declared, echoed)
+
+
def _structured_rows_to_write_back(
original_rows: Sequence[AllMessageValues] | None,
- shown_rows: Sequence[AllMessageValues] | None,
+ compared_rows: Sequence[AllMessageValues] | None,
returned_rows: Sequence[AllMessageValues],
+ is_echo: Callable[[AllMessageValues, AllMessageValues], bool],
) -> tuple[AllMessageValues, ...] | None:
- """The request model drops row keys its message types do not declare, so a
- row the server echoes back verbatim is restored to the original row object.
- A server that echoes every row back unchanged has not rewritten anything
- per row, so its answer is read from texts, as it was before rows could be
- returned at all."""
- if original_rows is None or shown_rows is None or len(returned_rows) != len(original_rows):
+ """A row the server echoes back is restored to the original row object. A server
+ that echoes every row back has not rewritten anything per row, so its answer is
+ read from texts, as it was before rows could be returned at all."""
+ if original_rows is None or compared_rows is None or len(returned_rows) != len(original_rows):
return tuple(returned_rows)
- if all(returned == shown for shown, returned in zip(shown_rows, returned_rows)):
+ echoed: Final = tuple(
+ is_echo(compared, returned) for compared, returned in zip(compared_rows, returned_rows, strict=True)
+ )
+ if all(echoed):
return None
return tuple(
- original if returned == shown else returned
- for original, shown, returned in zip(original_rows, shown_rows, returned_rows)
+ original if was_echoed else returned
+ for original, returned, was_echoed in zip(original_rows, returned_rows, echoed, strict=True)
)
@@ -200,6 +248,7 @@ class GenericGuardrailAPI(CustomGuardrail):
additional_provider_specific_params: Mapping[str, object] | None = None,
unreachable_fallback: Literal["fail_closed", "fail_open"] = "fail_closed",
fail_on_error: bool | None = True,
+ forward_messages_as_sent: bool | None = False,
extra_headers: list | None = None,
streaming_end_of_stream_only: bool | None = None,
streaming_sampling_rate: int | None = None,
@@ -235,6 +284,7 @@ class GenericGuardrailAPI(CustomGuardrail):
self.unreachable_fallback: Literal["fail_closed", "fail_open"] = unreachable_fallback
self.fail_on_error: bool = True if fail_on_error is None else fail_on_error
+ self.forward_messages_as_sent: bool = bool(forward_messages_as_sent)
# Read by UnifiedLLMGuardrails.async_post_call_streaming_iterator_hook
# via getattr(guardrail_to_apply, "streaming_*", default).
@@ -316,15 +366,17 @@ class GenericGuardrailAPI(CustomGuardrail):
http_status_code: int | None = None,
) -> GenericGuardrailAPIInputs:
status_suffix: Final = f" http_status_code={http_status_code}" if http_status_code else ""
+ error_type: Final = "HTTPStatusError" if isinstance(error, httpx.HTTPStatusError) else type(error).__name__
verbose_proxy_logger.critical(
"Generic Guardrail API error (fail-open). Proceeding without guardrail.%s "
- "guardrail_name=%s api_base=%s input_type=%s litellm_call_id=%s litellm_trace_id=%s",
+ "guardrail_name=%s api_base=%s input_type=%s litellm_call_id=%s litellm_trace_id=%s error_type=%s",
status_suffix,
getattr(self, "guardrail_name", None),
getattr(self, "api_base", None),
input_type,
getattr(logging_obj, "litellm_call_id", None) if logging_obj else None,
getattr(logging_obj, "litellm_trace_id", None) if logging_obj else None,
+ error_type,
exc_info=error,
)
# Keep flow going - treat as action=NONE (no modifications)
@@ -339,10 +391,23 @@ class GenericGuardrailAPI(CustomGuardrail):
headers.update(self.headers)
return headers
+ def _request_body(
+ self,
+ guardrail_request: GenericGuardrailAPIRequest,
+ structured_messages: Sequence[AllMessageValues] | None,
+ ) -> Mapping[str, object]:
+ body: Final[Mapping[str, object]] = guardrail_request.model_dump(mode="json")
+ if not self.forward_messages_as_sent or structured_messages is None:
+ return body
+ return {
+ **body,
+ "structured_messages": _SENT_ROWS.dump_python(_SENT_ROWS.validate_python(structured_messages), mode="json"),
+ }
+
def _build_guardrail_return_inputs(
self,
*,
- texts: list,
+ texts: list[str],
images: list[str] | None,
tools: list[ChatCompletionToolParam] | None,
structured_messages: Sequence[AllMessageValues] | None,
@@ -361,8 +426,13 @@ class GenericGuardrailAPI(CustomGuardrail):
return_inputs["tools"] = guardrail_response.tools
elif tools:
return_inputs["tools"] = tools
+ compared_rows, is_echo = (
+ (structured_messages, _is_echo) if self.forward_messages_as_sent else (shown_messages, _is_shown_row)
+ )
rows_to_write_back: Final = (
- _structured_rows_to_write_back(structured_messages, shown_messages, guardrail_response.structured_messages)
+ _structured_rows_to_write_back(
+ structured_messages, compared_rows, guardrail_response.structured_messages, is_echo
+ )
if guardrail_response.structured_messages
else None
)
@@ -465,7 +535,7 @@ class GenericGuardrailAPI(CustomGuardrail):
litellm_version=litellm_version,
images=images,
tools=([GuardrailToolParam.model_validate(t) for t in tools] if tools else None),
- structured_messages=structured_messages,
+ structured_messages=None if self.forward_messages_as_sent else structured_messages,
tool_calls=tool_calls,
additional_provider_specific_params=additional_params,
input_type=input_type,
@@ -478,7 +548,7 @@ class GenericGuardrailAPI(CustomGuardrail):
# Use mode="json" to ensure all iterables are converted to lists
response: Final = await self.async_handler.post(
url=self.api_base,
- json=guardrail_request.model_dump(mode="json"),
+ json=dict(self._request_body(guardrail_request, structured_messages)),
headers=headers,
timeout=self.timeout,
)
diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.py
index f20a3fa3d7c..33db8cbc6f0 100644
--- a/litellm/types/guardrails.py
+++ b/litellm/types/guardrails.py
@@ -1195,6 +1195,16 @@ class BaseLitellmParams(ContentFilterConfigModel): # works for new and patch up
description="Maximum decisions calls in flight at once on the guardrail in each proxy worker. Implemented by guardrail='decision_model'.",
)
+ forward_messages_as_sent: bool | None = Field(
+ default=False,
+ description=(
+ "Only honored by guardrail='generic_guardrail_api'. When True, structured_messages reaches the "
+ "guardrail exactly as the client sent it, so rows can carry provider-native content blocks and "
+ "keys the OpenAI chat types do not declare. Default False sends OpenAI-format chat rows with "
+ "undeclared keys removed."
+ ),
+ )
+
extra_headers: list[str] | None = Field(
default=None,
description=(
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 49eaa154fec..d34a3a13838 100644
--- a/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py
+++ b/litellm/types/proxy/guardrails/guardrail_hooks/generic_guardrail_api.py
@@ -1,7 +1,7 @@
from collections.abc import Mapping, Sequence
from typing import Any, Final, Literal, cast # noqa: TID251 # JSON chat rows have no typed constructor across roles
-from pydantic import ConfigDict, Field
+from pydantic import ConfigDict, Field, SerializerFunctionWrapHandler, model_serializer
from typing_extensions import TypedDict
from litellm.types.llms.base import LiteLLMBaseModel
@@ -17,12 +17,20 @@ class GuardrailToolParam(LiteLLMBaseModel):
"""A tool forwarded verbatim to the guardrail for inspection.
Built-in tools (code_interpreter, file_search, ...) have no ``function`` block
- and stash their config in tool-specific keys, so only ``type`` is required and
- ``extra="allow"`` preserves the rest instead of stripping it.
+ and stash their config in tool-specific keys, and provider-native tools such as
+ Gemini ``function_declarations`` carry no ``type`` at all, so nothing is required
+ and ``extra="allow"`` preserves the rest instead of stripping it.
"""
model_config = ConfigDict(extra="allow")
- type: str
+ type: str | None = None
+
+ @model_serializer(mode="wrap")
+ def _without_absent_type(self, handler: SerializerFunctionWrapHandler) -> Mapping[str, object]:
+ dumped: Final = cast("Mapping[str, object]", handler(self)) # cast-ok: handler dumps this model's fields
+ if self.type is not None:
+ return dumped
+ return {key: value for key, value in dumped.items() if key != "type"}
class GenericGuardrailAPIMetadata(TypedDict, total=False):
@@ -62,6 +70,15 @@ class GenericGuardrailAPIOptionalParams(LiteLLMBaseModel):
),
)
+ forward_messages_as_sent: bool | None = Field(
+ default=False,
+ description=(
+ "When True, structured_messages reaches the guardrail exactly as the client sent it, so rows can "
+ "carry provider-native content blocks and keys the OpenAI chat types do not declare. False "
+ "(default) sends OpenAI-format chat rows with undeclared keys removed."
+ ),
+ )
+
streaming_end_of_stream_only: bool | None = Field(
default=None,
description=(
diff --git a/tests/integration/observability/test_generic_guardrail_api_wire.py b/tests/integration/observability/test_generic_guardrail_api_wire.py
new file mode 100644
index 00000000000..0796feb5f37
--- /dev/null
+++ b/tests/integration/observability/test_generic_guardrail_api_wire.py
@@ -0,0 +1,308 @@
+import json
+import threading
+from collections.abc import Iterator, Mapping
+from contextlib import ExitStack
+from dataclasses import dataclass
+from pathlib import Path
+from types import MappingProxyType
+from typing import Final
+
+import pytest
+import yaml
+from integration._support.anthropic_sse import message_json
+from integration._support.client import Gateway, eventually
+from integration._support.openai_wire import chat_reply
+from integration._support.ports import allocate_port
+from integration._support.process import OwnedProxy, owned_proxy_process
+from integration._support.wire import Reply, Request, Wire, wire_server
+from pydantic import JsonValue, TypeAdapter
+
+GEMINI_MODEL: Final = "gemini/gemini-3.8-flash"
+ANTHROPIC_MODEL: Final = "anthropic/claude-sonnet-5-5"
+OPENAI_MODEL: Final = "openai/gpt-5.6"
+ECHO_GEMINI_TOOLS: Final = "echo-gemini-tools"
+NONE_CHAT_ROWS: Final = "none-chat-rows"
+NONE_CHAT_ROWS_DEFAULT: Final = "none-chat-rows-default"
+NONE_ANTHROPIC_IMAGE: Final = "none-anthropic-image"
+ECHO_ANTHROPIC_MESSAGES: Final = "echo-anthropic-messages"
+FORWARDS_MESSAGES_AS_SENT: Final = frozenset({NONE_CHAT_ROWS, NONE_ANTHROPIC_IMAGE, ECHO_ANTHROPIC_MESSAGES})
+FAIL_OPEN_CONNECT_ERROR: Final = "fail-open-connect-error"
+FAIL_OPEN_TIMEOUT: Final = "fail-open-timeout"
+FAIL_OPEN_HTTP_STATUS: Final = "fail-open-http-status"
+FAIL_OPEN_LINE: Final = "Generic Guardrail API error (fail-open)"
+PNG: Final = (
+ "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAFklEQVR4nGO4IydHEmIY1TCqYfhqAACaMxgQdGu1YAAAAABJRU5ErkJggg=="
+)
+_CONFIG: Final = Path(__file__).resolve().parents[1] / "proxy_config.yaml"
+_JSON: Final = TypeAdapter(dict[str, JsonValue])
+
+
+def _verdict_none(_request: Request) -> Reply:
+ return Reply(body=json.dumps({"action": "NONE"}).encode())
+
+
+def _verdict_echo(request: Request) -> Reply:
+ body: Final = _JSON.validate_json(request.body)
+ echoed: Final = {key: body[key] for key in ("structured_messages", "tools") if body.get(key)}
+ return Reply(body=json.dumps({"action": "NONE", **echoed}).encode())
+
+
+def _unavailable(_request: Request) -> Reply:
+ return Reply(status=503, body=b'{"error": "guardrail unavailable"}')
+
+
+def _gemini_reply(_request: Request) -> Reply:
+ return Reply(
+ body=json.dumps(
+ {
+ "candidates": [{"content": {"role": "model", "parts": [{"text": "ok"}]}, "finishReason": "STOP"}],
+ "usageMetadata": {"promptTokenCount": 3, "candidatesTokenCount": 1, "totalTokenCount": 4},
+ }
+ ).encode()
+ )
+
+
+def _anthropic_reply(_request: Request) -> Reply:
+ return Reply(body=message_json("msg_guardrail_wire", "claude-sonnet-5-5", "ok"))
+
+
+def _openai_reply(_request: Request) -> Reply:
+ return chat_reply("chatcmpl-guardrail-wire", "gpt-5.6", "ok", stream=False)
+
+
+def _guardrail(name: str, api_base: str, **params: JsonValue) -> dict[str, JsonValue]:
+ return {
+ "guardrail_name": name,
+ "litellm_params": {
+ "guardrail": "generic_guardrail_api",
+ "mode": "pre_call",
+ "default_on": False,
+ "api_base": api_base,
+ "api_key": "synthetic-guardrail-key",
+ **params,
+ },
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class GuardrailRig:
+ owned: OwnedProxy
+ policies: Mapping[str, Wire]
+
+
[email protected](scope="module")
+def rig(session_gateway: Gateway, tmp_path_factory: pytest.TempPathFactory) -> Iterator[GuardrailRig]:
+ directory: Final = tmp_path_factory.mktemp("generic-guardrail-wire")
+ release: Final = threading.Event()
+
+ def held_until_teardown(request: Request) -> Reply:
+ release.wait()
+ return _verdict_none(request)
+
+ with ExitStack() as stack:
+ policies: Final = MappingProxyType(
+ {
+ ECHO_GEMINI_TOOLS: stack.enter_context(wire_server(_verdict_echo)),
+ NONE_CHAT_ROWS: stack.enter_context(wire_server(_verdict_none)),
+ NONE_CHAT_ROWS_DEFAULT: stack.enter_context(wire_server(_verdict_none)),
+ NONE_ANTHROPIC_IMAGE: stack.enter_context(wire_server(_verdict_none)),
+ ECHO_ANTHROPIC_MESSAGES: stack.enter_context(wire_server(_verdict_echo)),
+ }
+ )
+ stalled: Final = stack.enter_context(wire_server(held_until_teardown))
+ stack.callback(release.set)
+ unavailable: Final = stack.enter_context(wire_server(_unavailable))
+ config: Final = _JSON.validate_python(yaml.safe_load(_CONFIG.read_text()))
+ path: Final = directory / "generic-guardrail-wire.yaml"
+ path.write_text(
+ yaml.safe_dump(
+ {
+ **config,
+ "guardrails": [
+ *(
+ _guardrail(name, wire.url, forward_messages_as_sent=name in FORWARDS_MESSAGES_AS_SENT)
+ for name, wire in policies.items()
+ ),
+ _guardrail(FAIL_OPEN_CONNECT_ERROR, f"http://127.0.0.1:{allocate_port()}", fail_on_error=False),
+ _guardrail(FAIL_OPEN_TIMEOUT, stalled.url, fail_on_error=False, timeout=1),
+ _guardrail(FAIL_OPEN_HTTP_STATUS, unavailable.url, fail_on_error=False),
+ ],
+ }
+ )
+ )
+ owned: Final = stack.enter_context(owned_proxy_process(session_gateway, directory, {}, config=path))
+ yield GuardrailRig(owned, policies)
+
+
+def _bodies(wire: Wire) -> list[dict[str, JsonValue]]:
+ return [_JSON.validate_json(request.body) for request in wire.drain()]
+
+
+def _fail_open_lines(log: Path, guardrail: str) -> list[str]:
+ return [
+ line
+ for line in log.read_text(errors="replace").splitlines()
+ if FAIL_OPEN_LINE in line and f"guardrail_name={guardrail} " in line
+ ]
+
+
+def test_gemini_native_tools_reach_the_guardrail_and_gemini_as_sent(rig: GuardrailRig) -> None:
+ tools: Final = [
+ {"function_declarations": [{"name": "get_weather", "parameters": {"type": "object", "properties": {}}}]},
+ {"googleSearch": {}},
+ ]
+ with wire_server(_gemini_reply) as gemini, rig.owned.gateway.scenario() as scenario:
+ model: Final = scenario.model(model=GEMINI_MODEL, api_base=gemini.url, api_key="synthetic-gemini-key")
+ response: Final = rig.owned.gateway.request(
+ "POST",
+ "/v1/chat/completions",
+ {
+ "model": model,
+ "messages": [{"role": "user", "content": "weather in Paris?"}],
+ "tools": tools,
+ "guardrails": [ECHO_GEMINI_TOOLS],
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert [body["tools"] for body in _bodies(rig.policies[ECHO_GEMINI_TOOLS])] == [tools]
+ sent: Final = _bodies(gemini)
+ assert len(sent) == 1, sent
+ assert {"googleSearch": {}} in sent[0]["tools"], sent
+ assert [tool for tool in sent[0]["tools"] if "type" in tool] == [], sent
+
+
+CHAT_ROWS: Final = (
+ {"role": "user", "name": "pat", "content": "weather in Paris?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"index": 0, "id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "sunny"},
+)
+OPENAI_CHAT_ROWS: Final = (
+ {"role": "user", "content": "weather in Paris?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "sunny"},
+)
+
+
+ ("guardrail", "seen"),
+ [(NONE_CHAT_ROWS, CHAT_ROWS), (NONE_CHAT_ROWS_DEFAULT, OPENAI_CHAT_ROWS)],
+ ids=["forward_messages_as_sent", "default"],
+)
+def test_guardrail_sees_chat_rows_as_sent_only_when_configured(
+ rig: GuardrailRig, guardrail: str, seen: tuple[dict[str, JsonValue], ...]
+) -> None:
+ messages: Final = list(CHAT_ROWS)
+ with wire_server(_openai_reply) as openai_peer, rig.owned.gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=OPENAI_MODEL, api_base=f"{openai_peer.url}/v1", api_key="synthetic-openai-key"
+ )
+ response: Final = rig.owned.gateway.request(
+ "POST", "/v1/chat/completions", {"model": model, "messages": messages, "guardrails": [guardrail]}
+ )
+ assert response.status_code == 200, response.text
+ assert [body["structured_messages"] for body in _bodies(rig.policies[guardrail])] == [list(seen)]
+ assert len(openai_peer.drain()) == 1
+
+
+def test_guardrail_sees_an_anthropic_image_block_on_chat_completions_as_sent(rig: GuardrailRig) -> None:
+ image: Final = [{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": PNG}}]
+ with wire_server(_anthropic_reply) as anthropic_peer, rig.owned.gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=ANTHROPIC_MODEL, api_base=anthropic_peer.url, api_key="synthetic-anthropic-key"
+ )
+ rig.owned.gateway.request(
+ "POST",
+ "/v1/chat/completions",
+ {
+ "model": model,
+ "max_tokens": 16,
+ "messages": [{"role": "user", "content": image}, {"role": "user", "content": "what color?"}],
+ "guardrails": [NONE_ANTHROPIC_IMAGE],
+ },
+ )
+ seen: Final = _bodies(rig.policies[NONE_ANTHROPIC_IMAGE])
+ assert [body["structured_messages"][0]["content"] for body in seen] == [image], seen
+
+
+def test_echoing_guardrail_leaves_the_anthropic_messages_request_unchanged(rig: GuardrailRig) -> None:
+ messages: Final = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "What color is this square? Also check the weather in Paris."},
+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": PNG}},
+ {"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "Trip notes."}},
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {"city": "Paris"}}],
+ },
+ {
+ "role": "user",
+ "content": [
+ {"type": "tool_result", "tool_use_id": "toolu_1", "content": "sunny, 21C"},
+ {"type": "text", "text": "Answer both in one sentence."},
+ ],
+ },
+ ]
+ tools: Final = [
+ {
+ "name": "get_weather",
+ "description": "Weather for a city",
+ "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}},
+ }
+ ]
+ with wire_server(_anthropic_reply) as anthropic_peer, rig.owned.gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=ANTHROPIC_MODEL, api_base=anthropic_peer.url, api_key="synthetic-anthropic-key"
+ )
+ response: Final = rig.owned.gateway.request(
+ "POST",
+ "/v1/messages",
+ {
+ "model": model,
+ "max_tokens": 64,
+ "messages": messages,
+ "tools": tools,
+ "guardrails": [ECHO_ANTHROPIC_MESSAGES],
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert len(rig.policies[ECHO_ANTHROPIC_MESSAGES].drain()) == 1
+ assert [body["messages"] for body in _bodies(anthropic_peer)] == [messages]
+
+
+ ("guardrail", "tokens"),
+ [
+ (FAIL_OPEN_CONNECT_ERROR, ("error_type=ConnectError",)),
+ (FAIL_OPEN_TIMEOUT, ("error_type=Timeout",)),
+ (FAIL_OPEN_HTTP_STATUS, ("error_type=HTTPStatusError", "http_status_code=503")),
+ ],
+ ids=["connect_error", "timeout", "http_status"],
+)
+def test_fail_open_log_line_names_the_error_type(rig: GuardrailRig, guardrail: str, tokens: tuple[str, ...]) -> None:
+ with wire_server(_openai_reply) as openai_peer, rig.owned.gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model=OPENAI_MODEL, api_base=f"{openai_peer.url}/v1", api_key="synthetic-openai-key"
+ )
+ response: Final = rig.owned.gateway.request(
+ "POST",
+ "/v1/chat/completions",
+ {"model": model, "messages": [{"role": "user", "content": "hi"}], "guardrails": [guardrail]},
+ )
+ assert response.status_code == 200, response.text
+ assert len(openai_peer.drain()) == 1
+ lines: Final = eventually(lambda: _fail_open_lines(rig.owned.log, guardrail), bool, seconds=30)
+ assert [line for line in lines if not all(token in line for token in tokens)] == [], lines
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 19eb3c71a5b..f50da1bff64 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
@@ -5,6 +5,8 @@ This test file tests the Generic Guardrail API implementation,
specifically focusing on metadata extraction and passing.
"""
+import json
+import logging
import os
from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch
@@ -16,6 +18,7 @@ import litellm
from litellm import ModelResponse
from litellm._version import version as litellm_version
from litellm.exceptions import GuardrailRaisedException, Timeout
+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, MaskedHTTPStatusError
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.guardrails.guardrail_hooks.generic_guardrail_api import (
GenericGuardrailAPI,
@@ -38,6 +41,38 @@ def generic_guardrail():
)
+def raw_rows_guardrail():
+ return GenericGuardrailAPI(
+ api_base="https://api.test.guardrail.com",
+ headers={"Authorization": "Bearer test-key"},
+ guardrail_name="test-generic-guardrail-raw-rows",
+ event_hook="pre_call",
+ default_on=True,
+ forward_messages_as_sent=True,
+ )
+
+
+async def _structured_messages_sent(guardrail: GenericGuardrailAPI, rows: list[dict]) -> list:
+ sent_bodies: Final[list[bytes]] = [] # mutable-ok: records every body the guardrail endpoint received
+
+ async def answer(request: httpx.Request) -> httpx.Response:
+ sent_bodies.append(request.content)
+ return httpx.Response(200, json={"action": "NONE"}, request=request)
+
+ endpoint: Final = AsyncHTTPHandler(transport=httpx.MockTransport(answer))
+ try:
+ with patch.object(guardrail, "async_handler", endpoint):
+ await guardrail.apply_guardrail(
+ inputs={"texts": ["Look up 123-45-6789 for me."], "structured_messages": rows},
+ request_data={},
+ input_type="request",
+ )
+ finally:
+ await endpoint.close()
+ return [json.loads(body)["structured_messages"] for body in sent_bodies]
+
+
@pytest.fixture
def mock_user_api_key_dict():
"""Create a mock UserAPIKeyAuth object"""
@@ -638,6 +673,157 @@ class TestStructuredMessagesInResponse:
assert returned_rows[1] is tool_call_row
assert returned_rows[2] == {"role": "tool", "tool_call_id": "call_1", "content": '{"ssn": "[REDACTED]"}'}
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("row", "openai_row"),
+ [
+ (
+ {"role": "user", "content": "Look up 123-45-6789 for me.", "name": "pat"},
+ {"role": "user", "content": "Look up 123-45-6789 for me."},
+ ),
+ (
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "lookup", "arguments": "{}"},
+ "index": 0,
+ }
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "call_1", "type": "function", "function": {"name": "lookup", "arguments": "{}"}}
+ ],
+ },
+ ),
+ (
+ {
+ "role": "user",
+ "content": [
+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAA="}}
+ ],
+ },
+ {"role": "user", "content": []},
+ ),
+ ],
+ ids=["extra_key", "tool_call_index", "image_block"],
+ )
+ async def test_rows_reach_the_guardrail_as_openai_chat_rows_by_default(
+ self, generic_guardrail: GenericGuardrailAPI, row, openai_row
+ ):
+ assert await _structured_messages_sent(generic_guardrail, [row]) == [[openai_row]]
+
+ @pytest.mark.asyncio
+ async def test_a_returned_row_that_differs_from_the_shown_row_is_written_back_by_default(
+ self, generic_guardrail, mock_request_data_input
+ ):
+ sent_row = {"role": "user", "content": "my ssn is 123-45-6789", "name": "pat"}
+
+ def answer_with_the_row_as_the_client_sent_it(url, json, headers, **_kwargs):
+ answer = MagicMock()
+ answer.json.return_value = {
+ "action": "GUARDRAIL_INTERVENED",
+ "texts": ["my ssn is [SSN]"],
+ "structured_messages": [sent_row],
+ }
+ answer.raise_for_status = MagicMock()
+ return answer
+
+ with patch.object(
+ generic_guardrail.async_handler, "post", side_effect=answer_with_the_row_as_the_client_sent_it
+ ):
+ guardrailed_inputs = await generic_guardrail.apply_guardrail(
+ inputs={"texts": ["my ssn is 123-45-6789"], "structured_messages": [sent_row]},
+ request_data=mock_request_data_input,
+ input_type="request",
+ )
+
+ assert guardrailed_inputs["structured_messages"] == [sent_row]
+
+ @pytest.mark.asyncio
+ async def test_rows_echoed_back_with_one_rewrite_write_back_the_rewrite_only(
+ self, raw_rows_guardrail, mock_request_data_input
+ ):
+ tool_call_row = {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "call_1", "type": "function", "function": {"name": "lookup", "arguments": "{}"}, "index": 0}
+ ],
+ }
+ original_rows = [
+ {"role": "user", "content": "Look up 123-45-6789 for me.", "name": "pat"},
+ tool_call_row,
+ {"role": "tool", "tool_call_id": "call_1", "content": '{"ssn": "123-45-6789"}'},
+ ]
+
+ def echo_with_tool_output_redacted(url, json, headers, **_kwargs):
+ shown_rows = json["structured_messages"]
+ answer = MagicMock()
+ answer.json.return_value = {
+ "action": "GUARDRAIL_INTERVENED",
+ "texts": ["Look up 123-45-6789 for me."],
+ "structured_messages": [
+ shown_rows[0],
+ shown_rows[1],
+ {**shown_rows[2], "content": '{"ssn": "[REDACTED]"}'},
+ ],
+ }
+ answer.raise_for_status = MagicMock()
+ return answer
+
+ with patch.object(raw_rows_guardrail.async_handler, "post", side_effect=echo_with_tool_output_redacted):
+ guardrailed_inputs = await raw_rows_guardrail.apply_guardrail(
+ inputs={"texts": ["Look up 123-45-6789 for me."], "structured_messages": original_rows},
+ request_data=mock_request_data_input,
+ input_type="request",
+ )
+
+ returned_rows = guardrailed_inputs["structured_messages"]
+ assert returned_rows[0] == original_rows[0]
+ assert returned_rows[1] == tool_call_row
+ assert returned_rows[2] == {"role": "tool", "tool_call_id": "call_1", "content": '{"ssn": "[REDACTED]"}'}
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "row",
+ [
+ {"role": "user", "content": "Look up 123-45-6789 for me.", "name": "pat"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "call_1", "type": "function", "function": {"name": "lookup", "arguments": "{}"}, "index": 0}
+ ],
+ },
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "123-45-6789"}]},
+ {"role": "assistant", "content": [{"type": "tool_use", "id": "call_1", "name": "lookup", "input": {}}]},
+ {
+ "role": "user",
+ "content": [{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAA="}}],
+ },
+ {
+ "role": "user",
+ "content": [
+ {"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "ssn"}}
+ ],
+ },
+ ],
+ ids=["extra_key", "tool_call_index", "tool_result_block", "tool_use_block", "image_block", "document_block"],
+ )
+ async def test_rows_reach_the_guardrail_verbatim_when_forwarded_as_sent(
+ self, raw_rows_guardrail: GenericGuardrailAPI, row
+ ):
+ """Rows are the provider's own shape, so the guardrail must see every key and
+ content block as sent, not a copy filtered through the chat completion types."""
+ assert await _structured_messages_sent(raw_rows_guardrail, [row]) == [[row]]
+
@pytest.mark.asyncio
async def test_rows_all_echoed_back_as_shown_leave_the_rewrite_to_texts(
self, generic_guardrail, mock_request_data_input
@@ -672,6 +858,126 @@ class TestStructuredMessagesInResponse:
assert "structured_messages" not in guardrailed_inputs
assert guardrailed_inputs["texts"] == ["Never repeat an SSN.", "Look up [REDACTED] for me."]
+ @pytest.mark.asyncio
+ async def test_rows_echoed_without_the_keys_the_server_does_not_know_leave_the_rewrite_to_texts(
+ self, raw_rows_guardrail, mock_request_data_input
+ ):
+ """A server that parses rows with its own message types echoes them back without
+ the keys those types lack, and its texts redaction must still reach the LLM."""
+ original_rows = [
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "call_1", "type": "function", "function": {"name": "lookup", "arguments": "{}"}, "index": 0}
+ ],
+ "refusal": None,
+ "annotations": [],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "found"},
+ {"role": "user", "content": "my ssn is 123-45-6789"},
+ ]
+
+ def echo_known_keys_and_redact_texts(url, json, headers, **_kwargs):
+ rows = json["structured_messages"]
+ answer = MagicMock()
+ answer.json.return_value = {
+ "action": "GUARDRAIL_INTERVENED",
+ "texts": [text.replace("123-45-6789", "[SSN]") for text in json["texts"]],
+ "structured_messages": [
+ {
+ "role": "assistant",
+ "content": None,
+ "refusal": None,
+ "tool_calls": [
+ {key: value for key, value in rows[0]["tool_calls"][0].items() if key != "index"}
+ ],
+ },
+ rows[1],
+ rows[2],
+ ],
+ }
+ answer.raise_for_status = MagicMock()
+ return answer
+
+ with patch.object(raw_rows_guardrail.async_handler, "post", side_effect=echo_known_keys_and_redact_texts):
+ guardrailed_inputs = await raw_rows_guardrail.apply_guardrail(
+ inputs={"texts": ["found", "my ssn is 123-45-6789"], "structured_messages": original_rows},
+ request_data=mock_request_data_input,
+ input_type="request",
+ )
+
+ assert "structured_messages" not in guardrailed_inputs
+ assert guardrailed_inputs["texts"] == ["found", "my ssn is [SSN]"]
+
+ @pytest.mark.asyncio
+ async def test_a_row_rewrite_echoes_the_other_rows_back_as_their_original_rows(
+ self, raw_rows_guardrail, mock_request_data_input
+ ):
+ assistant_row = {
+ "role": "assistant",
+ "content": "Looking it up.",
+ "annotations": [{"type": "url_citation", "url_citation": {"url": "https://example.com"}}],
+ }
+ original_rows = [assistant_row, {"role": "user", "content": "my ssn is 123-45-6789"}]
+ redacted_row = {"role": "user", "content": "my ssn is [SSN]"}
+
+ def redact_one_row(url, json, headers, **_kwargs):
+ answer = MagicMock()
+ answer.json.return_value = {
+ "action": "GUARDRAIL_INTERVENED",
+ "structured_messages": [{"role": "assistant", "content": "Looking it up."}, redacted_row],
+ }
+ answer.raise_for_status = MagicMock()
+ return answer
+
+ with patch.object(raw_rows_guardrail.async_handler, "post", side_effect=redact_one_row):
+ guardrailed_inputs = await raw_rows_guardrail.apply_guardrail(
+ inputs={"texts": ["my ssn is 123-45-6789"], "structured_messages": original_rows},
+ request_data=mock_request_data_input,
+ input_type="request",
+ )
+
+ assert guardrailed_inputs["structured_messages"] == [assistant_row, redacted_row]
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "returned_row",
+ [
+ {"role": "assistant", "content": None},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "lookup", "arguments": "{}"}}],
+ "annotations": [],
+ "refusal": "blocked",
+ },
+ ],
+ ids=["drops_a_declared_key", "changes_a_value"],
+ )
+ async def test_a_row_that_loses_a_declared_key_or_changes_a_value_is_a_rewrite(
+ self, raw_rows_guardrail, mock_request_data_input, returned_row
+ ):
+ original_row = {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "lookup", "arguments": "{}"}}],
+ "annotations": [],
+ "refusal": None,
+ }
+ answer = MagicMock()
+ answer.json.return_value = {"action": "GUARDRAIL_INTERVENED", "structured_messages": [returned_row]}
+ answer.raise_for_status = MagicMock()
+
+ with patch.object(raw_rows_guardrail.async_handler, "post", return_value=answer):
+ guardrailed_inputs = await raw_rows_guardrail.apply_guardrail(
+ inputs={"texts": [], "structured_messages": [original_row]},
+ request_data=mock_request_data_input,
+ input_type="request",
+ )
+
+ assert guardrailed_inputs["structured_messages"] == [returned_row]
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
"structured_messages",
@@ -1253,6 +1559,40 @@ class TestGenericGuardrailAPIStreamingConfig:
)
assert guardrail.streaming_transform_mode == "incremental_diff"
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("configured", "forwards_as_sent"),
+ [
+ pytest.param({}, False, id="unset"),
+ pytest.param({"forward_messages_as_sent": ""}, False, id="blank"),
+ pytest.param({"forward_messages_as_sent": False}, False, id="false"),
+ pytest.param({"forward_messages_as_sent": "true"}, True, id="string-true"),
+ pytest.param({"forward_messages_as_sent": True}, True, id="true"),
+ ],
+ )
+ async def test_forward_messages_as_sent_config_decides_which_rows_reach_the_guardrail(
+ self, configured, forwards_as_sent
+ ):
+ from litellm.proxy.guardrails.guardrail_hooks.generic_guardrail_api import (
+ initialize_guardrail,
+ )
+ from litellm.types.guardrails import LitellmParams
+
+ litellm_params = LitellmParams.model_validate(
+ {
+ "guardrail": "generic_guardrail_api",
+ "mode": "pre_call",
+ "api_base": "https://api.test.guardrail.com",
+ **configured,
+ }
+ )
+ with patch("litellm.logging_callback_manager.add_litellm_callback"):
+ guardrail = initialize_guardrail(litellm_params, {"guardrail_name": "test-forward-as-sent"})
+
+ row = {"role": "user", "content": "hi", "name": "pat"}
+ expected_row = row if forwards_as_sent else {"role": "user", "content": "hi"}
+ assert await _structured_messages_sent(guardrail, [row]) == [[expected_row]]
+
def test_initialize_guardrail_forwards_streaming_flags(self):
from litellm.proxy.guardrails.guardrail_hooks.generic_guardrail_api import (
initialize_guardrail,
@@ -1945,6 +2285,34 @@ class TestToolSupport:
assert forwarded_tools == tools
+ @pytest.mark.asyncio
+ async def test_provider_native_tools_without_a_type_reach_the_guardrail_and_come_back_unchanged(
+ self, generic_guardrail
+ ):
+ """Gemini tools are declared as function_declarations, googleSearch and the
+ like with no type key, so they must be scanned, and a server that echoes
+ them back must not write a type key into the request to the provider."""
+ tools = [
+ {"function_declarations": [{"name": "get_weather", "parameters": {"type": "object", "properties": {}}}]},
+ {"googleSearch": {}},
+ ]
+
+ def echo_tools(url, json, headers, **_kwargs):
+ answer = MagicMock()
+ answer.json.return_value = {"action": "NONE", "texts": ["hi"], "tools": json["tools"]}
+ answer.raise_for_status = MagicMock()
+ return answer
+
+ with patch.object(generic_guardrail.async_handler, "post", side_effect=echo_tools) as mock_post:
+ guardrailed_inputs = await generic_guardrail.apply_guardrail(
+ inputs={"texts": ["hi"], "tools": tools},
+ request_data={},
+ input_type="request",
+ )
+
+ assert mock_post.call_args.kwargs["json"]["tools"] == tools
+ assert guardrailed_inputs["tools"] == tools
+
class TestFailOnError:
"""Test fail_on_error: complete fail-open on any guardrail error"""
@@ -2032,6 +2400,59 @@ class TestFailOnError:
assert result == {"texts": ["model output"]}
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("error", "error_type", "pre_pr_text"),
+ [
+ (
+ Timeout(message="guardrail took too long", model="gpt-5", llm_provider="openai"),
+ "Timeout",
+ "Proceeding without guardrail. guardrail_name=",
+ ),
+ (
+ httpx.ConnectError("connection refused", request=MagicMock()),
+ "ConnectError",
+ "Proceeding without guardrail. guardrail_name=",
+ ),
+ (
+ MaskedHTTPStatusError(
+ httpx.HTTPStatusError(
+ "bad gateway",
+ request=httpx.Request("POST", "http://guardrail.invalid/scan"),
+ response=httpx.Response(502, request=httpx.Request("POST", "http://guardrail.invalid/scan")),
+ )
+ ),
+ "HTTPStatusError",
+ "Proceeding without guardrail. http_status_code=502 guardrail_name=",
+ ),
+ ],
+ ids=["timeout", "connect_error", "http_status"],
+ )
+ async def test_fail_open_log_line_names_the_error_type(
+ self, fail_open_guardrail, caplog: pytest.LogCaptureFixture, error, error_type, pre_pr_text
+ ):
+ """An operator grepping the fail-open line must be able to tell a timeout
+ from a refused connection from an upstream status without the traceback."""
+ from litellm._logging import verbose_proxy_logger
+
+ verbose_proxy_logger.addHandler(caplog.handler)
+ try:
+ with patch.object(fail_open_guardrail.async_handler, "post", side_effect=error):
+ await fail_open_guardrail.apply_guardrail(
+ inputs={"texts": ["hi"]},
+ request_data={},
+ input_type="request",
+ )
+ finally:
+ verbose_proxy_logger.removeHandler(caplog.handler)
+
+ fail_open_lines: Final = [
+ record.getMessage() for record in caplog.records if record.levelno == logging.CRITICAL
+ ]
+ assert fail_open_lines
+ assert all(f"error_type={error_type}" in line.split() for line in fail_open_lines)
+ assert all(pre_pr_text in line for line in fail_open_lines)
+
@pytest.mark.asyncio
async def test_response_path_valid_block_still_blocks(self, fail_open_guardrail):
"""On the response path too, a valid BLOCKED decision raises despite fail_on_error=False."""
diff --git a/tests/unit/proxy/guardrails/test_guardrail_endpoints.py b/tests/unit/proxy/guardrails/test_guardrail_endpoints.py
index 908a49946bb..2e968ec04f5 100644
--- a/tests/unit/proxy/guardrails/test_guardrail_endpoints.py
+++ b/tests/unit/proxy/guardrails/test_guardrail_endpoints.py
@@ -953,6 +953,17 @@ async def test_provider_specific_params_includes_embedding_toggle():
assert field["default_value"] is False
+async def test_provider_specific_params_offers_forward_messages_as_sent_off_by_default():
+ from litellm.proxy.guardrails.guardrail_endpoints import get_provider_specific_params
+
+ provider_params = await get_provider_specific_params()
+
+ field = provider_params["generic_guardrail_api"]["optional_params"]["fields"]["forward_messages_as_sent"]
+ assert field["type"] == "boolean"
+ assert field["default_value"] is False
+
+
@pytest.mark.asyncio
async def test_provider_specific_params_exposes_bedrock_streaming_flags():
from litellm.proxy.guardrails.guardrail_endpoints import get_provider_specific_params
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index bdf936d8bf3..18ce90fb19c 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -26991,6 +26991,12 @@ export interface components {
* @default true
*/
fail_on_error: boolean | null;
+ /**
+ * Forward Messages As Sent
+ * @description Only honored by guardrail='generic_guardrail_api'. When True, structured_messages reaches the guardrail exactly as the client sent it, so rows can carry provider-native content blocks and keys the OpenAI chat types do not declare. Default False sends OpenAI-format chat rows with undeclared keys removed.
+ * @default false
+ */
+ forward_messages_as_sent: boolean | null;
/**
* Guard Name
* @description Name of the guardrail in guardrails.ai
@@ -36471,6 +36477,12 @@ export interface components {
* @description HTTP timeout in seconds for checking attached files. Default: 10.
*/
file_guardrail_timeout?: number | null;
+ /**
+ * Forward Messages As Sent
+ * @description Only honored by guardrail='generic_guardrail_api'. When True, structured_messages reaches the guardrail exactly as the client sent it, so rows can carry provider-native content blocks and keys the OpenAI chat types do not declare. Default False sends OpenAI-format chat rows with undeclared keys removed.
+ * @default false
+ */
+ forward_messages_as_sent: boolean | null;
/**
* Gateway Name
* @description noma_v2 only: name of this gateway, used as the gateway_host label on Noma scans