The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(guardrails)!: preserve Bedrock Converse redactions and honor tool-only scans (#45874)
moyai-berriai[bot]f370235bb48f
diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.pyindex 93dd3d0f5ee..1c12ac395c7 100644--- a/litellm/integrations/custom_guardrail.py+++ b/litellm/integrations/custom_guardrail.py@@ -1139,6 +1139,17 @@ class CustomGuardrail(CustomLogger):"""return False+ def supports_structured_messages(self) -> bool:+ """Whether this guardrail scans every row of ``structured_messages`` and returns texts that agree with them.++ Guardrails that scan only part of the rows (the latest user turn, the+ last row, the turns after the last assistant turn, or no tool results),+ derive their returned texts from the rows, or cannot rewrite rows whose+ content is a list of parts, override this to return False. Translation handlers that can rewrite the request from ``texts``+ alone, like Bedrock Converse, then hand them only ``texts``.+ """+ return True+def _suppressed_by_auto_router_compression(self) -> bool:"""True when an auto router's own compression policy suppresses this guardrail.diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.pyindex 0549b0af11e..e2fb2be4ec2 100644--- a/litellm/litellm_core_utils/prompt_templates/factory.py+++ b/litellm/litellm_core_utils/prompt_templates/factory.py@@ -5533,6 +5533,11 @@ def _bedrock_tools_pt(return tool_block_list+def bedrock_tool_blocks(tools: Sequence[Mapping[str, object]], model: str | None) -> tuple[BedrockToolBlock, ...]:+ """Bedrock Converse ``toolConfig.tools`` entries for OpenAI or Anthropic tool definitions."""+ return tuple(_bedrock_tools_pt([dict(tool) for tool in tools], model=model))++def _is_system_message(message: Mapping[str, object]) -> bool:role: Final = message.get("role")return isinstance(role, str) and "system" in rolediff --git a/litellm/llms/bedrock/chat/converse_to_openai.py b/litellm/llms/bedrock/chat/converse_to_openai.pynew file mode 100644index 00000000000..ce80a2dc8bb--- /dev/null+++ b/litellm/llms/bedrock/chat/converse_to_openai.py@@ -0,0 +1,353 @@+import json+from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence+from dataclasses import dataclass+from itertools import accumulate, chain, groupby, repeat, takewhile+from typing import Final, TypeAlias, TypeVar++from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError++from litellm._logging import verbose_proxy_logger+from litellm.types.llms.openai import (+ AllMessageValues,+ ChatCompletionAssistantMessage,+ ChatCompletionAssistantToolCall,+ ChatCompletionSystemMessage,+ ChatCompletionTextObject,+ ChatCompletionToolCallFunctionChunk,+ ChatCompletionToolMessage,+ ChatCompletionToolParam,+ ChatCompletionToolParamFunctionChunk,+ ChatCompletionUserMessage,+)++JsonPath: TypeAlias = tuple[str | int, ...]+_Node: Final = TypeVar("_Node")+_OBJECT: Final = TypeAdapter(Mapping[str, object])+_ITEMS: Final = TypeAdapter(Sequence[object])+++class _ConverseModel(BaseModel):+ model_config = ConfigDict(extra="ignore", frozen=True)+++class _GuardText(_ConverseModel):+ text: str = ""+++class _GuardContent(_ConverseModel):+ text: _GuardText | None = None+++class _ToolUse(_ConverseModel):+ tool_use_id: str = Field(default="", alias="toolUseId")+ name: str = ""+ tool_input: object = Field(default=None, alias="input")+++class _ToolResultContent(_ConverseModel):+ text: str = ""+ json_value: object = Field(default=None, alias="json")+++class _ToolResult(_ConverseModel):+ tool_use_id: str = Field(default="", alias="toolUseId")+ content: tuple[_ToolResultContent, ...] = ()+++class _ContentBlock(_ConverseModel):+ text: str = ""+ guard_content: _GuardContent | None = Field(default=None, alias="guardContent")+ tool_use: _ToolUse | None = Field(default=None, alias="toolUse")+ tool_result: _ToolResult | None = Field(default=None, alias="toolResult")+++class _Message(_ConverseModel):+ role: str = ""+ content: tuple[_ContentBlock, ...] = ()+++class _ToolInputSchema(_ConverseModel):+ json_schema: Mapping[str, object] | None = Field(default=None, alias="json")+++class _ToolSpec(_ConverseModel):+ name: str = ""+ description: str = ""+ input_schema: _ToolInputSchema | None = Field(default=None, alias="inputSchema")+++class _Tool(_ConverseModel):+ tool_spec: _ToolSpec | None = Field(default=None, alias="toolSpec")+++class _ToolConfig(_ConverseModel):+ tools: tuple[_Tool, ...] = ()+++class ConverseRequest(_ConverseModel):+ system: tuple[_ContentBlock, ...] = ()+ messages: tuple[_Message, ...] = ()+ tool_config: _ToolConfig | None = Field(default=None, alias="toolConfig")+ additional_model_request_fields: object = Field(default=None, alias="additionalModelRequestFields")+++@dataclass(frozen=True, slots=True)+class TextSlot:+ path: JsonPath+ text: str+++@dataclass(frozen=True, slots=True)+class JsonSlot:+ path: JsonPath+ value: object+++Slot: TypeAlias = TextSlot | JsonSlot+++@dataclass(frozen=True, slots=True)+class ConverseRow:+ message: AllMessageValues+ content: tuple[Slot, ...]+ calls: tuple[JsonSlot, ...] = ()+++def parse_converse_request(body: Mapping[str, object]) -> ConverseRequest | None:+ try:+ return ConverseRequest.model_validate(body)+ except ValidationError:+ verbose_proxy_logger.debug("Converse body not convertible to OpenAI messages")+ return None+++def as_json_object(value: object) -> Mapping[str, object] | None:+ try:+ return _OBJECT.validate_python(value)+ except ValidationError:+ return None+++def as_json_array(value: object) -> Sequence[object] | None:+ try:+ return _ITEMS.validate_python(value)+ except ValidationError:+ return None+++def breadth_first(root: _Node, children: Callable[[_Node], tuple[_Node, ...]]) -> Iterator[_Node]:+ def next_level(level: tuple[_Node, ...], _: None) -> tuple[_Node, ...]:+ return tuple(chain.from_iterable(map(children, level)))++ return chain.from_iterable(takewhile(bool, accumulate(repeat(None), next_level, initial=(root,))))+++def _json_children(node: tuple[JsonPath, object]) -> tuple[tuple[JsonPath, object], ...]:+ path, value = node+ fields: Final = as_json_object(value)+ if fields is not None:+ return tuple(((*path, key), child) for key, child in fields.items())+ items: Final = as_json_array(value)+ return () if items is None else tuple(((*path, index), child) for index, child in enumerate(items))+++def _text_leaf(node: tuple[JsonPath, object]) -> TextSlot | None:+ path, value = node+ return TextSlot(path, value) if isinstance(value, str) and value else None+++def _flat_text_order(root: tuple[JsonPath, object]) -> Iterator[tuple[JsonPath, object]]:+ """+ The nodes under ``root`` in the order the flat texts list their strings: each container's own strings in field+ order, then its nested containers, the last one first.+ """+ pending: Final = [root]+ while pending:+ children = _json_children(pending.pop())+ yield from (child for child in children if isinstance(child[1], str))+ pending.extend(child for child in children if not isinstance(child[1], str))+++def _string_leaves(path: JsonPath, value: object) -> tuple[TextSlot, ...]:+ leaves: Final = map(_text_leaf, _flat_text_order((path, value)))+ return tuple(leaf for leaf in leaves if leaf is not None)+++def _block_slot(path: JsonPath, block: _ContentBlock) -> TextSlot | None:+ if block.text:+ return TextSlot((*path, "text"), block.text)+ guard_text: Final = block.guard_content.text if block.guard_content else None+ return (+ TextSlot((*path, "guardContent", "text", "text"), guard_text.text) if guard_text and guard_text.text else None+ )+++def _text_slots(path: JsonPath, blocks: Iterable[tuple[int, _ContentBlock]]) -> tuple[TextSlot, ...]:+ slots: Final = (_block_slot((*path, index), block) for index, block in blocks)+ return tuple(slot for slot in slots if slot is not None)+++def _text_parts(slots: Sequence[TextSlot]) -> tuple[ChatCompletionTextObject, ...]:+ return tuple(ChatCompletionTextObject(type="text", text=slot.text) for slot in slots)+++def _slot_text(slot: Slot) -> str:+ match slot:+ case TextSlot():+ return slot.text+ case JsonSlot():+ return json.dumps(slot.value)+++def _tool_part_slot(path: JsonPath, part: _ToolResultContent) -> Slot | None:+ if part.text:+ return TextSlot((*path, "text"), part.text)+ return None if part.json_value is None else JsonSlot((*path, "json"), part.json_value)+++def _tool_result_row(path: JsonPath, result: _ToolResult) -> ConverseRow:+ slots: Final = tuple(+ slot+ for index, part in enumerate(result.content)+ if (slot := _tool_part_slot((*path, "content", index), part)) is not None+ )+ message: Final = ChatCompletionToolMessage(+ role="tool", tool_call_id=result.tool_use_id, content="\n".join(map(_slot_text, slots))+ )+ return ConverseRow(message, slots)+++def _user_group(+ path: JsonPath, is_tool_result: bool, group: Sequence[tuple[int, _ContentBlock]]+) -> tuple[ConverseRow, ...]:+ if is_tool_result:+ return tuple(+ _tool_result_row((*path, index, "toolResult"), result)+ for index, block in group+ if (result := block.tool_result) is not None+ )+ slots: Final = _text_slots(path, group)+ return (+ (ConverseRow(ChatCompletionUserMessage(role="user", content=list(_text_parts(slots))), slots),) if slots else ()+ )+++def _user_rows(path: JsonPath, blocks: Sequence[_ContentBlock]) -> tuple[ConverseRow, ...]:+ groups: Final = groupby(enumerate(blocks), key=lambda item: item[1].tool_result is not None)+ return tuple(+ chain.from_iterable(_user_group(path, is_tool_result, tuple(group)) for is_tool_result, group in groups)+ )+++def _tool_call(tool_use: _ToolUse) -> ChatCompletionAssistantToolCall:+ return ChatCompletionAssistantToolCall(+ id=tool_use.tool_use_id,+ type="function",+ function=ChatCompletionToolCallFunctionChunk(+ name=tool_use.name,+ arguments="{}" if tool_use.tool_input is None else json.dumps(tool_use.tool_input),+ ),+ )+++def _assistant_rows(+ path: JsonPath, blocks: Sequence[_ContentBlock], include_tool_calls: bool+) -> tuple[ConverseRow, ...]:+ slots: Final = _text_slots(path, enumerate(blocks))+ uses: Final = (+ tuple((index, tool_use) for index, block in enumerate(blocks) if (tool_use := block.tool_use) is not None)+ if include_tool_calls+ else ()+ )+ if uses:+ message: Final = ChatCompletionAssistantMessage(+ role="assistant",+ content=list(_text_parts(slots)) or None,+ tool_calls=[_tool_call(tool_use) for _, tool_use in uses],+ )+ calls: Final = tuple(+ JsonSlot((*path, index, "toolUse", "input"), tool_use.tool_input) for index, tool_use in uses+ )+ return (ConverseRow(message, slots, calls),)+ if not slots:+ return ()+ return (ConverseRow(ChatCompletionAssistantMessage(role="assistant", content=list(_text_parts(slots))), slots),)+++def _message_rows(index: int, message: _Message, include_tool_calls: bool) -> tuple[ConverseRow, ...]:+ path: Final = ("messages", index, "content")+ if message.role == "assistant":+ return _assistant_rows(path, message.content, include_tool_calls)+ return _user_rows(path, message.content)+++def _system_rows(blocks: Sequence[_ContentBlock]) -> tuple[ConverseRow, ...]:+ slots: Final = _text_slots(("system",), enumerate(blocks))+ return (+ (ConverseRow(ChatCompletionSystemMessage(role="system", content=list(_text_parts(slots))), slots),)+ if slots+ else ()+ )+++def _user_row(slots: Sequence[Slot]) -> ConverseRow:+ parts: Final = [ChatCompletionTextObject(type="text", text=_slot_text(slot)) for slot in slots]+ return ConverseRow(ChatCompletionUserMessage(role="user", content=parts), tuple(slots))+++def _with_request_fields(rows: tuple[ConverseRow, ...], value: object, user_turn: int) -> tuple[ConverseRow, ...]:+ """+ ``rows`` with the ``additionalModelRequestFields`` strings after the text of the latest user row, so a guardrail+ that judges only the latest user message reads both. When no user row has text they get a user row of their own+ at ``user_turn``, where the rows of the latest user turn that is not only tool results start.+ """+ slots: Final = _string_leaves(("additionalModelRequestFields",), value)+ if not slots:+ return rows+ latest: Final = next((index for index in reversed(range(len(rows))) if rows[index].message["role"] == "user"), None)+ if latest is None:+ return (*rows[:user_turn], _user_row(slots), *rows[user_turn:])+ return (*rows[:latest], _user_row((*rows[latest].content, *slots)), *rows[latest + 1 :])+++def _is_user_turn(message: _Message) -> bool:+ return message.role != "assistant" and any(block.tool_result is None for block in message.content)+++def converse_rows(request: ConverseRequest, include_tool_calls: bool) -> tuple[ConverseRow, ...]:+ system: Final = _system_rows(request.system)+ messages: Final = tuple(+ _message_rows(index, message, include_tool_calls) for index, message in enumerate(request.messages)+ )+ starts: Final = tuple(accumulate(map(len, messages), initial=len(system)))+ rows: Final = (*system, *chain.from_iterable(messages))+ user_turn: Final = next(+ (starts[index] for index in reversed(range(len(messages))) if _is_user_turn(request.messages[index])),+ len(rows),+ )+ return _with_request_fields(rows, request.additional_model_request_fields, user_turn)+++@dataclass(frozen=True, slots=True)+class ConverseTool:+ index: int+ param: ChatCompletionToolParam+++def converse_tools(request: ConverseRequest) -> tuple[ConverseTool, ...]:+ tools: Final = request.tool_config.tools if request.tool_config else ()+ return tuple(+ ConverseTool(+ index,+ ChatCompletionToolParam(+ type="function",+ function=ChatCompletionToolParamFunctionChunk(+ name=spec.name,+ description=spec.description,+ parameters=dict(spec.input_schema.json_schema),+ ),+ ),+ )+ for index, tool in enumerate(tools)+ if (spec := tool.tool_spec) and spec.name and spec.input_schema and spec.input_schema.json_schema is not None+ )diff --git a/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py b/litellm/llms/bedrock/passthrough/guardrail_translation/handler.pyindex ded3ce2415f..a90b4829634 100644--- a/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py+++ b/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py@@ -5,10 +5,12 @@ import structfrom binascii import crc32from collections.abc import AsyncGenerator, AsyncIterable, Callable, Mapping, Sequencefrom dataclasses import dataclass+from functools import partial, reduce+from itertools import accumulate, chainfrom types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Final, Optional, Protocol, TypeAlias, TypeVar-from pydantic import TypeAdapter, ValidationError+from pydantic import InstanceOf, TypeAdapter, ValidationErrorfrom typing_extensions import ReadOnly, TypedDictfrom litellm._logging import verbose_proxy_logger@@ -19,10 +21,31 @@ from litellm.llms.base_llm.guardrail_translation.base_translation import (StreamTransformSink,)from litellm.llms.base_llm.guardrail_translation.utils import (+ effective_scan_only_tool_results_for_guardrail,effective_skip_system_message_for_guardrail,effective_skip_tool_message_for_guardrail,+ scoped_structured_message_indices,+ unappliable_request_rewrite,)from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM+from litellm.llms.bedrock.chat.converse_to_openai import (+ ConverseRow,+ JsonPath,+ as_json_array,+ as_json_object,+ converse_rows,+ converse_tools,+ parse_converse_request,+)+from litellm.llms.bedrock.passthrough.guardrail_translation.structured_edits import (+ Edit,+ ReplacedTools,+ ReturnedTool,+ ToolResultText,+ structured_edits,+ tool_edits,+)+from litellm.proxy.guardrails.auto_router_compression import is_compression_guardrailfrom litellm.types.utils import GenericGuardrailAPIInputsif TYPE_CHECKING:@@ -62,7 +85,32 @@ def _generic_passthrough_handler() -> "PassThroughEndpointHandler":return PassThroughEndpointHandler()+def _reads_flat_texts_only(guardrail: "CustomGuardrail") -> bool:+ """Whether `guardrail` gets only the flat texts on Converse, without rows or tools."""+ return is_compression_guardrail(guardrail) or not guardrail.supports_structured_messages()++_StringHolder = tuple[Any, str | int]+_LeafIdentity: TypeAlias = tuple[int, str | int]+++@dataclass(frozen=True, slots=True)+class _Assign:+ holder: _StringHolder+ value: object+++@dataclass(frozen=True, slots=True)+class _Remove:+ holder: _StringHolder+++_Write: TypeAlias = _Assign+_ContentHolder: TypeAlias = tuple[object, str]+_BlankDrop: TypeAlias = tuple[_ContentHolder, frozenset[int]]+_BODY_BY_REFERENCE: Final = TypeAdapter(InstanceOf[dict[str, object]])+_OBJECT_BY_REFERENCE: Final = TypeAdapter(InstanceOf[Mapping[str, object]])+_ARRAY_BY_REFERENCE: Final = TypeAdapter(InstanceOf[list[object]])def _collect_strings(node: object, holders: list[_StringHolder]) -> None:@@ -98,10 +146,17 @@ def _collect_block_text(block: dict, holders: list[_StringHolder]) -> None:holders.append((block, "text"))+def _request_field_holders(body: Mapping[str, object]) -> tuple[_StringHolder, ...]:+ holders: Final = list[_StringHolder]()+ _collect_strings(body.get("additionalModelRequestFields"), holders)+ return tuple(holders)++def _extract_converse_texts(body: dict,skip_system: bool,skip_tool: bool,+ scan_only_tool_results: bool = False,) -> tuple[list[str], list[_StringHolder]]:"""Walk a Bedrock Converse request body and collect text content.@@ -121,22 +176,25 @@ def _extract_converse_texts(inflating guardrail usage for a request whose only prompt is one usermessage. No other guardrail translation handler puts tool definitions in``texts``; the chat and messages handlers carry them in the structured- ``tools`` input instead, which this handler does not populate because a- Bedrock ``toolSpec`` is not the OpenAI tool shape those consumers expect.+ ``tools`` input instead, which this handler also populates by converting+ each Bedrock ``toolSpec`` to the OpenAI tool shape.``additionalModelRequestFields`` is treated differently on purpose. Bedrockgives ``toolConfig.tools`` a fixed schema whose contents are tool metadata bycontract, while ``additionalModelRequestFields`` is free-form and defined bythe target model, so what it carries cannot be classified without knowing- that model. Scanning it stays the fail-closed default.+ that model. Scanning it stays the fail-closed default. Its strings come+ last, in the same order as they follow the latest user message in the rows."""- holders: Final[list[_StringHolder]] = []-- if not skip_system:+ system_holders: Final = list[_StringHolder]()+ if not skip_system and not scan_only_tool_results:for block in body.get("system") or []:if isinstance(block, dict):- _collect_block_text(block, holders)+ _collect_block_text(block, system_holders)++ request_field_holders: Final = () if scan_only_tool_results else _request_field_holders(body)+ message_holders: Final = list[_StringHolder]()for message in body.get("messages") or []:if not isinstance(message, dict):continue@@ -145,23 +203,273 @@ def _extract_converse_texts(continueif skip_tool and ("toolUse" in block or "toolResult" in block):continue- _collect_block_text(block, holders)+ if scan_only_tool_results and "toolResult" not in block:+ continue+ _collect_block_text(block, message_holders)tool_use = block.get("toolUse")if isinstance(tool_use, dict):- _collect_strings(tool_use.get("input"), holders)+ _collect_strings(tool_use.get("input"), message_holders)tool_result = block.get("toolResult")if isinstance(tool_result, dict):for inner in tool_result.get("content") or []:if isinstance(inner, dict):- _collect_block_text(inner, holders)- _collect_strings(inner.get("json"), holders)-- _collect_strings(body.get("additionalModelRequestFields"), holders)+ _collect_block_text(inner, message_holders)+ _collect_strings(inner.get("json"), message_holders)+ holders: Final = [*system_holders, *message_holders, *request_field_holders]texts: Final = [container[key] for container, key in holders]return texts, holders+@dataclass(frozen=True, slots=True)+class _Scope:+ skip_system: bool+ skip_tool: bool+ scan_only_tool_results: bool+++def _texts_applied_rows(body: Mapping[str, object], texts: Sequence[str], scope: _Scope) -> tuple[ConverseRow, ...]:+ rewritten: Final = _BODY_BY_REFERENCE.validate_python(json.loads(json.dumps(body)))+ _, holders = _extract_converse_texts(rewritten, scope.skip_system, scope.skip_tool, scope.scan_only_tool_results)+ _write_back_texts(texts, holders)+ request: Final = parse_converse_request(rewritten)+ return converse_rows(request, include_tool_calls=not scope.skip_tool) if request else ()+++def _texts_follow_rows(+ body: Mapping[str, object],+ rows: Sequence[ConverseRow],+ texts: Sequence[str],+ guardrailed_texts: Sequence[str],+ changed_rows: frozenset[int],+ scope: _Scope,+) -> bool:+ """Whether the returned texts sit in the flat layout and only touch rows the vendor also changed."""+ if len(guardrailed_texts) != len(texts):+ return False+ view: Final = _texts_applied_rows(body, guardrailed_texts, scope)+ if len(view) != len(rows):+ return False+ rows_changed_by_texts: Final = frozenset(+ index for index, (row, viewed) in enumerate(zip(rows, view)) if row.message != viewed.message+ )+ return rows_changed_by_texts <= changed_rows+++def _child(node: object, key: str | int) -> object:+ try:+ match key:+ case str():+ return _OBJECT_BY_REFERENCE.validate_python(node).get(key)+ case int():+ items: Final = _ARRAY_BY_REFERENCE.validate_python(node)+ return items[key] if 0 <= key < len(items) else None+ except ValidationError:+ return None+++def _holder(body: object, path: JsonPath) -> _StringHolder | None:+ container: Final = reduce(_child, path[:-1], body)+ return (container, path[-1]) if isinstance(_child(container, path[-1]), str) else None+++def _leaf_identity(holder: _StringHolder) -> _LeafIdentity:+ container, key = holder+ return id(container), key+++def _changed_leaves(+ holders: Sequence[_StringHolder], texts: Sequence[str], guardrailed_texts: Sequence[str]+) -> frozenset[_LeafIdentity]:+ return frozenset(+ _leaf_identity(holder) for holder, before, after in zip(holders, texts, guardrailed_texts) if after != before+ )+++def _tool_result_write(body: Mapping[str, object], edit: ToolResultText) -> _Write | None:+ container: Final = reduce(_child, edit.content[:-1], body)+ blocks: Final = as_json_array(_child(container, edit.content[-1]))+ if blocks is None:+ return None+ dropped: Final = frozenset(edit.indices[1:])+ return _Assign(+ (container, edit.content[-1]),+ [+ {"text": edit.text} if index == edit.indices[0] else block+ for index, block in enumerate(blocks)+ if index not in dropped+ ],+ )+++def _is_cache_point(entry: object) -> bool:+ fields: Final = as_json_object(entry)+ return fields is not None and "cachePoint" in fields+++def _tool_name(entry: object) -> object:+ return _child(_child(entry, "toolSpec"), "name")+++def _entries_after(unsent: Sequence[tuple[int, object]], anchor: int) -> tuple[object, ...]:+ return tuple(entry for at, entry in unsent if at == anchor)+++def _sent_anchor(sent: frozenset[int], anchor: int, index: int) -> int:+ return index if index in sent else anchor+++def _replaced(entry: ReturnedTool) -> int | None:+ return entry if isinstance(entry, int) else entry.replaces+++def _replaced_tools_write(body: Mapping[str, object], edit: ReplacedTools) -> _Write | None:+ """+ Rebuild ``toolConfig.tools`` in the order the guardrail returned. Entries it was never sent (cache points, system+ tools) stay right after the tool they followed, and a cache point goes away with its tool. Refuses when+ ``toolChoice`` names a tool that is no longer there, and creates ``toolConfig`` when the request had none. A+ ``toolConfig`` left with no tool stays until the request is sent, so later guardrails still see the tool history.+ """+ tool_config: Final = _child(body, "toolConfig")+ tools: Final = () if tool_config is None else as_json_array(_child(tool_config, "tools"))+ if tools is None:+ return None+ anchors: Final = tuple(accumulate(range(len(tools)), partial(_sent_anchor, edit.sent), initial=-1))[1:]+ unsent: Final = tuple(+ (anchor, tool) for index, (anchor, tool) in enumerate(zip(anchors, tools)) if index not in edit.sent+ )+ replaced: Final = frozenset(_replaced(entry) for entry in edit.tools)+ placed: Final = chain.from_iterable(+ (tools[entry], *_entries_after(unsent, entry))+ if isinstance(entry, int)+ else (*entry.blocks, *(() if entry.replaces is None else _entries_after(unsent, entry.replaces)))+ for entry in edit.tools+ )+ orphans: Final = tuple(tool for at, tool in unsent if at not in replaced and at >= 0 and not _is_cache_point(tool))+ rebuilt: Final = [*_entries_after(unsent, -1), *placed, *orphans]+ chosen: Final = _child(_child(_child(tool_config, "toolChoice"), "tool"), "name")+ if isinstance(chosen, str) and all(_tool_name(tool) != chosen for tool in rebuilt):+ return None+ if tool_config is None:+ return None if all(map(_is_cache_point, rebuilt)) else _Assign((body, "toolConfig"), {"tools": rebuilt})+ return _Assign((tool_config, "tools"), rebuilt)+++def _resolved(body: Mapping[str, object], edit: Edit) -> _Write | None:+ match edit:+ case ToolResultText():+ return _tool_result_write(body, edit)+ case ReplacedTools():+ return _replaced_tools_write(body, edit)+ case (path, text):+ holder: Final = _holder(body, path)+ return None if holder is None else _Assign(holder, text)+++def _kept_write(write: _Write, flat_changes: frozenset[_LeafIdentity]) -> bool:+ return _leaf_identity(write.holder) not in flat_changes+++def _holder_edits(+ body: Mapping[str, object], edits: Sequence[Edit], flat_changes: frozenset[_LeafIdentity]+) -> tuple[_Write, ...] | None:+ resolved: Final = tuple(_resolved(body, edit) for edit in edits)+ if any(write is None for write in resolved):+ return None+ return tuple(write for write in resolved if write is not None and _kept_write(write, flat_changes))+++def _apply(writes: Sequence[_Assign | _Remove]) -> None:+ for write in writes:+ match write:+ case _Assign(holder=(container, key), value=value):+ container[key] = value+ case _Remove(holder=(container, key)):+ del container[key]+++def _block_text_holder(block: object) -> _ContentHolder | None:+ if isinstance(_child(block, "text"), str):+ return block, "text"+ guarded: Final = _child(_child(block, "guardContent"), "text")+ return (guarded, "text") if isinstance(_child(guarded, "text"), str) else None+++def _final_texts(+ holders: Sequence[_StringHolder], applied_texts: Sequence[str], writes: Sequence[_Write]+) -> Mapping[_LeafIdentity, object]:+ flat: Final = {_leaf_identity(holder): text for holder, text in zip(holders, applied_texts)}+ structured: Final = {_leaf_identity(write.holder): write.value for write in writes}+ return MappingProxyType({**flat, **structured})+++def _blanked(final: Mapping[_LeafIdentity, object], block: object) -> bool:+ holder: Final = _block_text_holder(block)+ if holder is None:+ return False+ container, key = holder+ value: Final = final.get((id(container), key))+ return isinstance(value, str) and value != _child(container, key) and not value.strip()+++def _blank_blocks(final: Mapping[_LeafIdentity, object], holder: _ContentHolder) -> frozenset[int]:+ container, key = holder+ return frozenset(id(block) for block in as_json_array(_child(container, key)) or () if _blanked(final, block))+++def _empties_turn(drop: _BlankDrop) -> bool:+ (container, key), dropped = drop+ blocks: Final = as_json_array(_child(container, key)) or ()+ return bool(dropped) and all(id(block) in dropped or _is_cache_point(block) for block in blocks)+++def _turn_drop(final: Mapping[_LeafIdentity, object], message: object) -> _BlankDrop:+ return (message, "content"), _blank_blocks(final, (message, "content"))+++def _blank_drops(body: Mapping[str, object], final: Mapping[_LeafIdentity, object]) -> tuple[_BlankDrop, ...]:+ """The system and message text blocks the guardrail left blank, except in a turn they would leave empty."""+ turns: Final = (_turn_drop(final, message) for message in as_json_array(body.get("messages")) or ())+ system: Final = ((body, "system"), _blank_blocks(final, (body, "system")))+ return tuple(drop for drop in (system, *(turn for turn in turns if not _empties_turn(turn))) if drop[1])+++def _blank_drop_write(drop: _BlankDrop) -> _Assign | _Remove:+ holder, dropped = drop+ container, key = holder+ kept: Final = [block for block in as_json_array(_child(container, key)) or () if id(block) not in dropped]+ return _Assign(holder, kept) if not all(map(_is_cache_point, kept)) else _Remove(holder)+++def _edits_drop_a_text_change(+ body: Mapping[str, object],+ edits: Sequence[Edit],+ texts: Sequence[str],+ guardrailed_texts: Sequence[str],+ scope: _Scope,+) -> bool:+ """+ Whether the row and tool edits alone leave out a change the guardrail made in its returned texts. Texts of the+ length that was sent are read position by position, so a changed string whose field the edits leave at its+ original value is dropped. Texts of another length cannot be placed, so what they mask cannot be checked either,+ while an empty list leaves every text as it was.+ """+ if not guardrailed_texts:+ return False+ if len(guardrailed_texts) != len(texts):+ return True+ rewritten: Final = _BODY_BY_REFERENCE.validate_python(json.loads(json.dumps(body)))+ _, holders = _extract_converse_texts(rewritten, scope.skip_system, scope.skip_tool, scope.scan_only_tool_results)+ writes: Final = _holder_edits(rewritten, edits, frozenset())+ if writes is None:+ return True+ _apply(writes)+ edited: Final = [container[key] for container, key in holders]+ return any(+ returned != before and after == before for before, returned, after in zip(texts, guardrailed_texts, edited)+ )++def _extract_converse_output_texts(content_blocks: Sequence[object],) -> tuple[list[str], list[_StringHolder]]:@@ -196,8 +504,8 @@ def _extract_converse_output_texts(def _write_back_texts(- guardrailed_texts: list[str],- holders: list[_StringHolder],+ guardrailed_texts: Sequence[str],+ holders: Sequence[_StringHolder],) -> None:if len(guardrailed_texts) < len(holders):verbose_proxy_logger.warning(@@ -982,16 +1290,39 @@ class BedrockPassthroughGuardrailHandler(BaseTranslation):if not isinstance(body, dict) or not isinstance(body.get("messages"), list):return data+ request_body: Final = _BODY_BY_REFERENCE.validate_python(body)- skip_system: Final = effective_skip_system_message_for_guardrail(guardrail_to_apply)- skip_tool: Final = effective_skip_tool_message_for_guardrail(guardrail_to_apply)-- texts, holders = _extract_converse_texts(body, skip_system, skip_tool)+ reads_rows: Final = not _reads_flat_texts_only(guardrail_to_apply)+ scope: Final = _Scope(+ skip_system=effective_skip_system_message_for_guardrail(guardrail_to_apply),+ skip_tool=effective_skip_tool_message_for_guardrail(guardrail_to_apply),+ scan_only_tool_results=effective_scan_only_tool_results_for_guardrail(guardrail_to_apply),+ )+ texts, holders = _extract_converse_texts(+ request_body,+ scope.skip_system,+ scope.skip_tool,+ scope.scan_only_tool_results,+ )+ request: Final = parse_converse_request(request_body) if reads_rows else None+ rows: Final = converse_rows(request, include_tool_calls=not scope.skip_tool) if request else ()+ scoped_indices: Final = scoped_structured_message_indices(+ tuple(row.message for row in rows),+ scan_only_tool_results=scope.scan_only_tool_results,+ skip_system=scope.skip_system,+ skip_tool=scope.skip_tool,+ )- if not texts:+ if not texts and not scoped_indices:return data- inputs: Final = GenericGuardrailAPIInputs(texts=texts)+ sent_messages: Final = [rows[index].message for index in scoped_indices]+ inputs: Final = GenericGuardrailAPIInputs(texts=list(texts))+ if sent_messages:+ inputs["structured_messages"] = json.loads(json.dumps(sent_messages))+ tools: Final = converse_tools(request) if request and not scope.scan_only_tool_results else ()+ if tools:+ inputs["tools"] = copy.deepcopy([tool.param for tool in tools])model: Final = data.get("model")if model:inputs["model"] = model@@ -1004,8 +1335,60 @@ class BedrockPassthroughGuardrailHandler(BaseTranslation):)guardrailed_texts: Final = guardrailed_inputs.get("texts", [])- if guardrailed_texts:- _write_back_texts(guardrailed_texts, holders)+ guardrailed_messages: Final = guardrailed_inputs.get("structured_messages")+ rewritten_rows: Final = (+ guardrailed_messages+ if sent_messages and isinstance(guardrailed_messages, list) and guardrailed_messages != sent_messages+ else None+ )+ changed_rows: Final[frozenset[int]] = (+ frozenset()+ if rewritten_rows is None+ else frozenset(+ index+ for index, sent, returned in zip(scoped_indices, sent_messages, rewritten_rows)+ if sent != returned+ )+ )+ texts_follow_rows: Final = rewritten_rows is None or _texts_follow_rows(+ request_body, rows, texts, guardrailed_texts, changed_rows, scope+ )+ applied_texts: Final = guardrailed_texts if texts_follow_rows else texts+ row_edits: Final = (+ ()+ if rewritten_rows is None+ else structured_edits(+ rows, scoped_indices, rewritten_rows, partial(_texts_applied_rows, request_body, applied_texts, scope)+ )+ )+ returned_tools: Final = guardrailed_inputs.get("tools")+ tool_changes: Final = (+ ()+ if returned_tools is None or not reads_rows+ else tool_edits(tools, returned_tools, model if isinstance(model, str) else None)+ )+ holder_edits: Final = (+ None+ if row_edits is None+ or tool_changes is None+ or (+ not texts_follow_rows+ and _edits_drop_a_text_change(+ request_body, (*row_edits, *tool_changes), texts, guardrailed_texts, scope+ )+ )+ else _holder_edits(+ request_body, (*row_edits, *tool_changes), _changed_leaves(holders, texts, applied_texts)+ )+ )+ if holder_edits is None:+ raise unappliable_request_rewrite(guardrail_to_apply.guardrail_name)+ if holder_edits or (applied_texts and list(applied_texts) != texts):+ blank_drops: Final = _blank_drops(request_body, _final_texts(holders, applied_texts, holder_edits))+ if applied_texts:+ _write_back_texts(applied_texts, holders)+ _apply(holder_edits)+ _apply(tuple(_blank_drop_write(drop) for drop in blank_drops))return datadiff --git a/litellm/llms/bedrock/passthrough/guardrail_translation/structured_edits.py b/litellm/llms/bedrock/passthrough/guardrail_translation/structured_edits.pynew file mode 100644index 00000000000..61399f67ae1--- /dev/null+++ b/litellm/llms/bedrock/passthrough/guardrail_translation/structured_edits.py@@ -0,0 +1,337 @@+from collections.abc import Callable, Mapping, Sequence+from dataclasses import dataclass+from itertools import chain+from typing import Final, TypeAlias++from pydantic import TypeAdapter, ValidationError++from litellm.litellm_core_utils.prompt_templates.factory import bedrock_tool_blocks+from litellm.llms.bedrock.chat.converse_to_openai import (+ ConverseRow,+ ConverseTool,+ JsonPath,+ JsonSlot,+ Slot,+ TextSlot,+ as_json_array,+ as_json_object,+ breadth_first,+)+from litellm.types.llms.bedrock import BedrockToolBlock+from litellm.types.llms.openai import ChatCompletionTextObject+++@dataclass(frozen=True, slots=True)+class ToolResultText:+ content: JsonPath+ indices: tuple[int, ...]+ text: str+++@dataclass(frozen=True, slots=True)+class ConvertedTool:+ replaces: int | None+ blocks: tuple[BedrockToolBlock, ...]+++ReturnedTool: TypeAlias = int | ConvertedTool+++@dataclass(frozen=True, slots=True)+class ReplacedTools:+ sent: frozenset[int]+ tools: tuple[ReturnedTool, ...]+++TextEdit: TypeAlias = tuple[JsonPath, str]+Edit: TypeAlias = TextEdit | ToolResultText | ReplacedTools+_JsonPair: TypeAlias = tuple[JsonPath, object, object]+_TEXT_PARTS: Final = TypeAdapter(tuple[ChatCompletionTextObject, ...])+_PARSED_JSON: Final = TypeAdapter(object)+++def _without(mapping: Mapping[str, object], key: str) -> tuple[tuple[str, object], ...]:+ return tuple(sorted(((name, value) for name, value in mapping.items() if name != key), key=lambda item: item[0]))+++def _without_content(message: Mapping[str, object]) -> tuple[tuple[str, object], ...]:+ return _without(message, "content")+++def _text_parts(message: Mapping[str, object]) -> tuple[str, ...] | None:+ content: Final = message.get("content")+ if isinstance(content, str):+ return (content,)+ try:+ parts: Final = _TEXT_PARTS.validate_python(content)+ except ValidationError:+ return None+ return tuple(part["text"] for part in parts)+++def _merged(children: Sequence[tuple[Edit, ...] | None]) -> tuple[Edit, ...] | None:+ if any(child is None for child in children):+ return None+ return tuple(chain.from_iterable(child for child in children if child is not None))+++def _paired_children(path: JsonPath, original: object, returned: object) -> tuple[_JsonPair, ...] | None:+ original_object: Final = as_json_object(original)+ returned_object: Final = as_json_object(returned)+ if original_object is not None and returned_object is not None:+ if original_object.keys() != returned_object.keys():+ return None+ return tuple(((*path, key), value, returned_object[key]) for key, value in original_object.items())+ original_items: Final = as_json_array(original)+ returned_items: Final = as_json_array(returned)+ if original_items is None or returned_items is None or len(original_items) != len(returned_items):+ return None+ return tuple(((*path, index), value, returned_items[index]) for index, value in enumerate(original_items))+++def _pair_children(pair: _JsonPair | None) -> tuple[_JsonPair | None, ...]:+ if pair is None:+ return ()+ path, original, returned = pair+ if original == returned or (isinstance(original, str) and isinstance(returned, str)):+ return ()+ children: Final = _paired_children(path, original, returned)+ return (None,) if children is None else children+++def _leaf_edit(pair: _JsonPair | None) -> TextEdit | None:+ match pair:+ case (path, str() as original, str() as returned) if original != returned:+ return path, returned+ case _:+ return None+++def _json_edits(path: JsonPath, original: object, returned: object) -> tuple[TextEdit, ...] | None:+ pairs: Final = tuple(breadth_first((path, original, returned), _pair_children))+ if any(pair is None for pair in pairs):+ return None+ return tuple(edit for pair in pairs if (edit := _leaf_edit(pair)) is not None)+++def _slot_edits(slot: Slot, text: str) -> tuple[Edit, ...] | None:+ match slot:+ case TextSlot():+ return () if text == slot.text else ((slot.path, text),)+ case JsonSlot():+ try:+ parsed: Final = _PARSED_JSON.validate_json(text)+ except ValidationError:+ return None+ return _json_edits(slot.path, slot.value, parsed)+++def _call_function(call: object) -> Mapping[str, object] | None:+ fields: Final = as_json_object(call)+ return as_json_object(fields.get("function")) if fields is not None else None+++def _call_edits(slot: JsonSlot, original: object, returned: object) -> tuple[Edit, ...] | None:+ if original == returned:+ return ()+ original_call: Final = as_json_object(original)+ returned_call: Final = as_json_object(returned)+ original_function: Final = _call_function(original)+ returned_function: Final = _call_function(returned)+ if original_call is None or returned_call is None or original_function is None or returned_function is None:+ return None+ arguments: Final = returned_function.get("arguments")+ if (+ not isinstance(arguments, str)+ or _without(returned_call, "function") != _without(original_call, "function")+ or _without(returned_function, "arguments") != _without(original_function, "arguments")+ ):+ return None+ return _slot_edits(slot, arguments)+++def _calls_edits(slots: Sequence[JsonSlot], original: object, returned: object) -> tuple[Edit, ...] | None:+ original_calls: Final = as_json_array(original)+ returned_calls: Final = as_json_array(returned)+ if original_calls is None or returned_calls is None or len(original_calls) != len(returned_calls):+ return None+ return _merged(tuple(_call_edits(*call) for call in zip(slots, original_calls, returned_calls)))+++def _carries_no_text(content: object) -> bool:+ match content:+ case None | "" | []:+ return True+ case _:+ return False+++def _content_texts(row: ConverseRow, returned: Mapping[str, object]) -> tuple[str, ...] | None:+ content: Final = returned.get("content")+ sent: Final = _text_parts(row.message)+ if (+ isinstance(content, str)+ and len(row.content) > 1+ and sent is not None+ and all("\n" not in text for text in sent)+ ):+ return tuple(content.split("\n"))+ return _text_parts(returned)+++def _content_edits(row: ConverseRow, original: object, returned: Mapping[str, object]) -> tuple[Edit, ...] | None:+ if returned.get("content") == original:+ return ()+ if not row.content and _carries_no_text(returned.get("content")):+ return ()+ texts: Final = _content_texts(row, returned)+ if texts is None or len(texts) != len(row.content):+ return None+ return _merged(tuple(_slot_edits(slot, text) for slot, text in zip(row.content, texts)))+++def _field(message: Mapping[str, object], key: str) -> object:+ return message.get(key)+++def _row_edits(row: ConverseRow, returned: Mapping[str, object]) -> tuple[Edit, ...] | None:+ if returned == row.message:+ return ()+ calls: Final = _field(row.message, "tool_calls")+ call_edits: Final = _calls_edits(row.calls, calls, returned.get("tool_calls")) if row.calls else ()+ comparable: Final = {**returned, "tool_calls": calls} if row.calls else returned+ if call_edits is None or _without_content(comparable) != _without_content(row.message):+ return None+ return _merged((call_edits, _content_edits(row, _field(row.message, "content"), comparable)))+++def _same_content(expected: Mapping[str, object], returned: Mapping[str, object]) -> bool:+ if expected.get("content") == returned.get("content"):+ return True+ expected_parts: Final = _text_parts(expected)+ returned_parts: Final = _text_parts(returned)+ return (+ expected_parts is not None+ and returned_parts is not None+ and "\n".join(expected_parts) == "\n".join(returned_parts)+ )+++def _reproduces(expected: ConverseRow, returned: Mapping[str, object] | None) -> bool:+ return (+ returned is not None+ and _without_content(returned) == _without_content(expected.message)+ and _same_content(expected.message, returned)+ )+++def _tool_result_text(row: ConverseRow, returned: Mapping[str, object]) -> ToolResultText | None:+ texts: Final = _text_parts(returned)+ indices: Final = tuple(index for slot in row.content if isinstance(index := slot.path[-2], int))+ if (+ row.message["role"] != "tool"+ or not indices+ or texts is None+ or _without_content(returned) != _without_content(row.message)+ ):+ return None+ return ToolResultText(row.content[0].path[:-2], indices, "\n".join(texts))+++def _unmapped_edits(+ row: ConverseRow, view: ConverseRow, returned: Mapping[str, object] | None+) -> tuple[Edit, ...] | None:+ if _reproduces(view, returned):+ return ()+ rewrite: Final = _tool_result_text(row, returned) if returned is not None and view == row else None+ return None if rewrite is None else (rewrite,)+++def structured_edits(+ rows: Sequence[ConverseRow],+ scoped_indices: Sequence[int],+ returned: Sequence[object],+ texts_applied_rows: Callable[[], tuple[ConverseRow, ...]],+) -> tuple[Edit, ...] | None:+ if len(returned) != len(scoped_indices):+ return None+ returned_rows: Final = tuple(as_json_object(message) for message in returned)+ proposed: Final = tuple(+ _row_edits(rows[index], row) if row is not None else None for index, row in zip(scoped_indices, returned_rows)+ )+ unmapped: Final = tuple(+ (index, row) for index, row, edits in zip(scoped_indices, returned_rows, proposed) if edits is None+ )+ view: Final = texts_applied_rows() if unmapped else ()+ if unmapped and len(view) != len(rows):+ return None+ fallbacks: Final = tuple(_unmapped_edits(rows[index], view[index], row) for index, row in unmapped)+ return _merged((*(edits for edits in proposed if edits is not None), *fallbacks))+++def _spec_edit(index: int, edit: TextEdit) -> TextEdit | None:+ path, text = edit+ match path:+ case ("function", "description"):+ return ("toolConfig", "tools", index, "toolSpec", "description"), text+ case ("function", "parameters", *schema_path):+ return ("toolConfig", "tools", index, "toolSpec", "inputSchema", "json", *schema_path), text+ case _:+ return None+++def _tool_edits(tool: ConverseTool | None, returned: object) -> tuple[Edit, ...] | None:+ edits: Final = None if tool is None else _json_edits((), tool.param, returned)+ if tool is None or edits is None:+ return None+ spec_edits: Final = tuple(_spec_edit(tool.index, edit) for edit in edits)+ return None if None in spec_edits else tuple(edit for edit in spec_edits if edit is not None)+++def _tool_name(tool: object) -> object:+ function: Final = _call_function(tool)+ return None if function is None else function.get("name")+++def _named(first_by_name: Mapping[str, ConverseTool], returned: object) -> ConverseTool | None:+ name: Final = _tool_name(returned)+ return first_by_name.get(name) if isinstance(name, str) else None+++def _bedrock_blocks(returned: object, model: str | None) -> tuple[BedrockToolBlock, ...] | None:+ tool: Final = as_json_object(returned)+ function: Final = _call_function(returned)+ if (+ tool is None+ or function is None+ or not isinstance(function.get("name"), str)+ or ("parameters" in function and as_json_object(function["parameters"]) is None)+ ):+ return None+ return bedrock_tool_blocks((tool,), model)+++def _returned_tool(+ tool: ConverseTool | None, returned: object, model: str | None+) -> tuple[ReturnedTool, tuple[Edit, ...]] | None:+ edits: Final = _tool_edits(tool, returned)+ if tool is not None and edits is not None:+ return tool.index, edits+ blocks: Final = _bedrock_blocks(returned, model)+ return None if blocks is None else (ConvertedTool(None if tool is None else tool.index, blocks), ())+++def tool_edits(tools: Sequence[ConverseTool], returned: object, model: str | None) -> tuple[Edit, ...] | None:+ returned_tools: Final = as_json_array(returned)+ if returned_tools is None:+ return None+ first_by_name: Final = {tool.param["function"]["name"]: tool for tool in reversed(tools)}+ planned: Final = tuple(_returned_tool(_named(first_by_name, item), item, model) for item in returned_tools)+ placed: Final = tuple(plan for plan in planned if plan is not None)+ if len(placed) != len(planned):+ return None+ entries: Final = tuple(entry for entry, _ in placed)+ edits: Final = tuple(chain.from_iterable(edits for _, edits in placed))+ if entries == tuple(tool.index for tool in tools):+ return edits+ return (*edits, ReplacedTools(frozenset(tool.index for tool in tools), entries))diff --git a/litellm/llms/bedrock/passthrough/transformation.py b/litellm/llms/bedrock/passthrough/transformation.pyindex 36cd87aff06..9d895616336 100644--- a/litellm/llms/bedrock/passthrough/transformation.py+++ b/litellm/llms/bedrock/passthrough/transformation.py@@ -13,6 +13,7 @@ from litellm._logging import verbose_loggerfrom litellm.constants import AWS_ERROR_TYPE_HEADERfrom litellm.litellm_core_utils.litellm_logging import Loggingfrom litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfig, PassthroughStreamCollector+from litellm.llms.bedrock.chat.converse_to_openai import as_json_array, as_json_objectfrom litellm.types.llms.openai import ChatCompletionSystemMessage, ChatCompletionUserMessagefrom litellm.types.utils import ModelResponseStream@@ -122,6 +123,71 @@ def _with_invoke_request_metadata(return merge_bedrock_invoke_headers(dict(headers), (), metadata_headers, owned_names), body+def _is_cache_point(entry: object) -> bool:+ fields: Final = as_json_object(entry)+ return fields is not None and "cachePoint" in fields+++def _tool_result_part(item: object) -> str | None:+ fields: Final = as_json_object(item)+ if fields is None:+ return None+ text: Final = fields.get("text")+ if isinstance(text, str):+ return text+ return json.dumps(fields["json"]) if "json" in fields else None+++def _tool_result_text(tool_result: Mapping[str, object]) -> str:+ parts: Final = as_json_array(tool_result.get("content")) or ()+ rendered: Final = "\n".join(part for item in parts if (part := _tool_result_part(item)) is not None).strip()+ return rendered or "<non-text tool result omitted>"+++def _block_field(block: object, key: str) -> Mapping[str, object] | None:+ fields: Final = as_json_object(block)+ return None if fields is None else as_json_object(fields.get(key))+++def _as_text_block(block: object) -> object:+ tool_use: Final = _block_field(block, "toolUse")+ if tool_use is not None:+ arguments: Final = json.dumps(tool_use.get("input"))+ return {"text": f"[tool call {tool_use.get('toolUseId')}: {tool_use.get('name')}({arguments})]"}+ tool_result: Final = _block_field(block, "toolResult")+ if tool_result is None:+ return block+ return {"text": f"[tool result for {tool_result.get('toolUseId')}: {_tool_result_text(tool_result)}]"}+++def _has_tool_block(content: Sequence[object]) -> bool:+ return any(+ _block_field(block, "toolUse") is not None or _block_field(block, "toolResult") is not None for block in content+ )+++def _as_text_message(message: object) -> object:+ fields: Final = as_json_object(message)+ content: Final = None if fields is None else as_json_array(fields.get("content"))+ if fields is None or content is None or not _has_tool_block(content):+ return message+ return {**fields, "content": [_as_text_block(block) for block in content]}+++def _converse_body_to_send(body: Mapping[str, object]) -> Mapping[str, object]:+ """+ ``body`` without a Converse ``toolConfig`` that holds no tool, with every ``toolUse`` and ``toolResult`` turned into+ text, since Bedrock rejects tool blocks without a tool. Any other ``body`` comes back as it is.+ """+ tool_config: Final = as_json_object(body.get("toolConfig"))+ tools: Final = None if tool_config is None else as_json_array(tool_config.get("tools"))+ if tools is None or not all(map(_is_cache_point, tools)):+ return body+ messages: Final = as_json_array(body.get("messages"))+ rest: Final = {key: value for key, value in body.items() if key != "toolConfig"}+ return rest if messages is None else {**rest, "messages": [_as_text_message(message) for message in messages]}++_TEXT_ONLY_DELTA_FIELDS: Final = frozenset({"content", "role"})@@ -378,11 +444,13 @@ class BedrockPassthroughConfig(BaseAWSLLM, BedrockModelInfo, BedrockEventStreamDapi_base: str,model: str | None = None,) -> tuple[dict, bytes | None]:+ action: Final = _bedrock_endpoint_action(api_base)+ body: Final[Mapping[str, object]] = request_data or {}optional_params: Final = litellm_params.copy()signed_headers, signed_body = _with_request_metadata(- action=_bedrock_endpoint_action(api_base) if bedrock_request_metadata_is_owned() else None,+ action=action if bedrock_request_metadata_is_owned() else None,headers=headers,- body=request_data or {},+ body=_converse_body_to_send(body) if action in _BEDROCK_CONVERSE_ACTIONS else body,litellm_params=litellm_params,)return self._sign_request(diff --git a/litellm/proxy/guardrails/guardrail_hooks/airia/airia.py b/litellm/proxy/guardrails/guardrail_hooks/airia/airia.pyindex 442eca3f9a4..993c1d30949 100644--- a/litellm/proxy/guardrails/guardrail_hooks/airia/airia.py+++ b/litellm/proxy/guardrails/guardrail_hooks/airia/airia.py@@ -128,6 +128,9 @@ class AiriaGuardrail(CustomGuardrail):)verbose_proxy_logger.info("AiriaGuardrail initialized with gateway: %s", self.api_base)+ def supports_structured_messages(self) -> bool:+ return False+@log_guardrail_informationasync def apply_guardrail(self,diff --git a/litellm/proxy/guardrails/guardrail_hooks/akto/akto.py b/litellm/proxy/guardrails/guardrail_hooks/akto/akto.pyindex 22d4406fa4b..224f1f78270 100644--- a/litellm/proxy/guardrails/guardrail_hooks/akto/akto.py+++ b/litellm/proxy/guardrails/guardrail_hooks/akto/akto.py@@ -794,6 +794,10 @@ class AktoGuardrail(CustomGuardrail):raise failurereturn main_task.result()+ @override+ def supports_structured_messages(self) -> bool:+ return False+@override@log_guardrail_informationasync def apply_guardrail(diff --git a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.pyindex 0672ccf6a66..12b8e728b4e 100644--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py@@ -586,6 +586,9 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):def supports_scan_only_tool_results(self) -> bool:return self.experimental_use_latest_role_message_only is not True+ def supports_structured_messages(self) -> bool:+ return False+def _prepare_guardrail_messages_for_role(self,messages: list[AllMessageValues] | None,diff --git a/litellm/proxy/guardrails/guardrail_hooks/conduct/conduct.py b/litellm/proxy/guardrails/guardrail_hooks/conduct/conduct.pyindex 077255017f4..9e276f7486d 100644--- a/litellm/proxy/guardrails/guardrail_hooks/conduct/conduct.py+++ b/litellm/proxy/guardrails/guardrail_hooks/conduct/conduct.py@@ -125,6 +125,9 @@ else:def get_config_model() -> type[ConductGuardrailConfigModel]:return ConductGuardrailConfigModel+ def supports_structured_messages(self) -> bool:+ return False+@log_guardrail_informationasync def apply_guardrail(self,diff --git a/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/crowdstrike_aidr.py b/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/crowdstrike_aidr.pyindex 15803c9a0cf..34725803c60 100644--- a/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/crowdstrike_aidr.py+++ b/litellm/proxy/guardrails/guardrail_hooks/crowdstrike_aidr/crowdstrike_aidr.py@@ -469,6 +469,10 @@ class CrowdStrikeAIDRHandler(CustomGuardrail):def structured_messages_cover_full_request(self) -> bool:return effective_skip_system_message_for_guardrail(self) or effective_skip_tool_message_for_guardrail(self)+ @override+ def supports_structured_messages(self) -> bool:+ return False+def _writeback_messages(self,structured_messages: list[AllMessageValues],diff --git a/litellm/proxy/guardrails/guardrail_hooks/hiddenlayer/hiddenlayer.py b/litellm/proxy/guardrails/guardrail_hooks/hiddenlayer/hiddenlayer.pyindex 421cf2281db..2f2c2990dd4 100644--- a/litellm/proxy/guardrails/guardrail_hooks/hiddenlayer/hiddenlayer.py+++ b/litellm/proxy/guardrails/guardrail_hooks/hiddenlayer/hiddenlayer.py@@ -262,6 +262,9 @@ class HiddenlayerGuardrail(CustomGuardrail):self._http_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.GuardrailCallback)super().__init__(**kwargs)+ def supports_structured_messages(self) -> bool:+ return False+@log_guardrail_informationasync def apply_guardrail(self,@@ -472,6 +475,9 @@ class HiddenlayerGuardrailV2(CustomGuardrail):self._http_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.GuardrailCallback)super().__init__(**kwargs)+ def supports_structured_messages(self) -> bool:+ return False+@log_guardrail_informationasync def apply_guardrail(self,diff --git a/litellm/proxy/guardrails/guardrail_hooks/llm_as_a_judge/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/llm_as_a_judge/__init__.pyindex 5085181639f..d319e34f9fd 100644--- a/litellm/proxy/guardrails/guardrail_hooks/llm_as_a_judge/__init__.py+++ b/litellm/proxy/guardrails/guardrail_hooks/llm_as_a_judge/__init__.py@@ -256,6 +256,9 @@ class LLMAsAJudgeGuardrail(CustomGuardrail):raw: Final = response.choices[0].message.content or "{}"return _parse_judge_verdict(raw)+ def supports_structured_messages(self) -> bool:+ return False+async def apply_guardrail(self,inputs: GenericGuardrailAPIInputs,diff --git a/litellm/proxy/guardrails/guardrail_hooks/openai/moderations.py b/litellm/proxy/guardrails/guardrail_hooks/openai/moderations.pyindex 33884fda4ee..7af5eaf1da9 100644--- a/litellm/proxy/guardrails/guardrail_hooks/openai/moderations.py+++ b/litellm/proxy/guardrails/guardrail_hooks/openai/moderations.py@@ -200,6 +200,9 @@ class OpenAIModerationGuardrail(OpenAIGuardrailBase, CustomGuardrail):},)+ def supports_structured_messages(self) -> bool:+ return False+@log_guardrail_informationasync def apply_guardrail(self,diff --git a/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.py b/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.pyindex c239ac9e938..8e03f7db4f5 100644--- a/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.py+++ b/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/panw_prisma_airs.py@@ -1744,6 +1744,9 @@ class PanwPrismaAirsHandler(CustomGuardrail):def supports_scan_only_tool_results(self) -> bool:return False+ def supports_structured_messages(self) -> bool:+ return False+@classmethoddef _get_scannable_text_indices(cls,diff --git a/litellm/proxy/guardrails/guardrail_hooks/prompt_security/prompt_security.py b/litellm/proxy/guardrails/guardrail_hooks/prompt_security/prompt_security.pyindex cb7d7ecec0c..0f66135d038 100644--- a/litellm/proxy/guardrails/guardrail_hooks/prompt_security/prompt_security.py+++ b/litellm/proxy/guardrails/guardrail_hooks/prompt_security/prompt_security.py@@ -170,6 +170,9 @@ class PromptSecurityGuardrail(CustomGuardrail):def supports_scan_only_tool_results(self) -> bool:return self.check_tool_results+ def supports_structured_messages(self) -> bool:+ return False+@log_guardrail_informationasync def apply_guardrail(self,diff --git a/litellm/proxy/guardrails/guardrail_hooks/promptguard/promptguard.py b/litellm/proxy/guardrails/guardrail_hooks/promptguard/promptguard.pyindex 7b509a25d35..0ebb4c2a253 100644--- a/litellm/proxy/guardrails/guardrail_hooks/promptguard/promptguard.py+++ b/litellm/proxy/guardrails/guardrail_hooks/promptguard/promptguard.py@@ -119,6 +119,9 @@ class PromptGuardGuardrail(CustomGuardrail):GuardrailEventHooks.post_call,]+ def supports_structured_messages(self) -> bool:+ return False+@log_guardrail_informationasync def apply_guardrail(self,diff --git a/litellm/proxy/guardrails/guardrail_hooks/qualifire/qualifire.py b/litellm/proxy/guardrails/guardrail_hooks/qualifire/qualifire.pyindex c68d7e94717..a92e67046bd 100644--- a/litellm/proxy/guardrails/guardrail_hooks/qualifire/qualifire.py+++ b/litellm/proxy/guardrails/guardrail_hooks/qualifire/qualifire.py@@ -420,6 +420,9 @@ class QualifireGuardrail(CustomGuardrail):verbose_proxy_logger.exception("Qualifire Guardrail error: %s", e)raise+ def supports_structured_messages(self) -> bool:+ return False+@log_guardrail_informationasync def apply_guardrail(self,diff --git a/litellm/proxy/guardrails/guardrail_hooks/singulr/singulr.py b/litellm/proxy/guardrails/guardrail_hooks/singulr/singulr.pyindex a63695a3af2..fa5251ba558 100644--- a/litellm/proxy/guardrails/guardrail_hooks/singulr/singulr.py+++ b/litellm/proxy/guardrails/guardrail_hooks/singulr/singulr.py@@ -402,6 +402,9 @@ class SingulrGuardrail(CustomGuardrail):)return inputs+ def supports_structured_messages(self) -> bool:+ return False+@log_guardrail_informationasync def apply_guardrail(self,diff --git a/litellm/proxy/policy_engine/pipeline_executor.py b/litellm/proxy/policy_engine/pipeline_executor.pyindex f47b41592c2..1b1b2302236 100644--- a/litellm/proxy/policy_engine/pipeline_executor.py+++ b/litellm/proxy/policy_engine/pipeline_executor.py@@ -26,6 +26,7 @@ from litellm.litellm_core_utils.core_helpers import (get_or_create_metadata_bucket,independent_snapshot,)+from litellm.llms.base_llm.guardrail_translation.utils import UnappliableRequestRewritefrom litellm.proxy.common_utils.callback_utils import add_guardrail_to_applied_guardrails_headerfrom litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (UnifiedLLMGuardrails,@@ -410,7 +411,7 @@ class PipelineExecutor:duration = time.perf_counter() - start_time- action = _pipeline_action_for_outcome(step, outcome)+ action = _pipeline_action_for_step(step, outcome, original_exception)step_result = PipelineStepResult(guardrail_name=step.guardrail,@@ -748,6 +749,17 @@ def _carry_working_guardrail_information(_append_guardrail_information(request_data=request_data, entries=[e for e in recorded if e not in existing])+def _pipeline_action_for_step(step: PipelineStep, outcome: str, original_exception: Exception | None) -> str:+ """+ The action a step takes: block when its guardrail returned a rewrite the endpoint+ cannot apply, whatever on_fail and on_error say, else the action configured for+ the outcome.+ """+ if isinstance(original_exception, UnappliableRequestRewrite):+ return "block"+ return _pipeline_action_for_outcome(step, outcome)++def _pipeline_action_for_outcome(step: PipelineStep, outcome: str) -> str:"""Map pipeline step outcome to the configured action.diff --git a/tests/integration/observability/test_bedrock_converse_guardrail_rewrites.py b/tests/integration/observability/test_bedrock_converse_guardrail_rewrites.pynew file mode 100644index 00000000000..08303236c09--- /dev/null+++ b/tests/integration/observability/test_bedrock_converse_guardrail_rewrites.py@@ -0,0 +1,718 @@+from __future__ import annotations++import json+import re+import uuid+from collections.abc import Iterator, Mapping+from dataclasses import dataclass+from enum import Enum+from pathlib import Path+from typing import Final++import httpx+import pytest+import yaml+from pydantic import JsonValue, TypeAdapter++from tests.integration._support.client import (+ JSON_OBJECT,+ Gateway,+ gateway_from_environment,+ held,+ list_value,+ object_value,+)+from tests.integration._support.process import owned_proxy+from tests.integration._support.wire import Reply, Request, Wire, wire_server++_MODEL_ID: Final = "anthropic.claude-sonnet-5-v1:0"+_MODEL: Final = "converse-guarded"+_PIPELINED_ACTIONS: Final = {+ "converse-pipelined-error-allow": {"on_fail": "block", "on_error": "allow"},+ "converse-pipelined-fail-next": {"on_fail": "next", "on_error": "block"},+ "converse-pipelined-fail-allow": {"on_fail": "allow", "on_error": "block"},+ "converse-pipelined-allow-all": {"on_fail": "allow", "on_error": "allow"},+}+_CARD: Final = "4111 1111 1111 1111"+_CARD_PATTERN: Final = re.compile(r"\b(?:\d{4} ){3}\d{4}\b")+_MASK: Final = "****"+_GUARD_PATH: Final = "/beta/litellm_basic_guardrail_api"+_PNG: Final = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="+_JSON: Final = TypeAdapter(JsonValue)+_UNAPPLIABLE: Final = "rewrote the request in a way this endpoint cannot apply"+_ADDED_TOOL: Final = {"type": "function", "function": {"name": "retrieve", "parameters": {"type": "object"}}}+_TOOL_CONFIG: Final = {+ "tools": [+ {+ "toolSpec": {+ "name": "lookup_card",+ "description": f"Looks up cards like {_CARD}",+ "inputSchema": {+ "json": {+ "type": "object",+ "properties": {"card": {"type": "string", "description": f"for example {_CARD}"}},+ }+ },+ }+ },+ {"cachePoint": {"type": "default"}},+ {+ "toolSpec": {+ "name": "refund",+ "description": "Refunds an order",+ "inputSchema": {"json": {"type": "object"}},+ }+ },+ ]+}+++class _Vendor(str, Enum):+ MASKS_ROWS_ONLY = "masks-rows-only"+ MASKS_ROWS_AND_BLANKS_EMPTY_CONTENT = "masks-rows-and-blanks-empty-content"+ JOINS_MASKED_ROWS = "joins-masked-rows"+ ECHOES_ROWS = "echoes-rows"+ RESPACES_UNMASKED_ROWS = "respaces-unmasked-rows"+ COMPACTS_TOOL_RESULTS = "compacts-tool-results"+ DROPS_A_ROW = "drops-a-row"+ MASKS_TEXTS_AND_ROW_CONTENT = "masks-texts-and-row-content"+ CLEARS_CARD_TEXTS = "clears-card-texts"+ MASKS_TEXTS_ONLY = "masks-texts-only"+ BLOCKS = "blocks"+ MASKS_TOOLS = "masks-tools"+ DROPS_A_TOOL = "drops-a-tool"+ ADDS_A_TOOL = "adds-a-tool"+ RENAMES_A_TOOL = "renames-a-tool"+ ECHOES_TOOLS_AS_NOT_STRICT = "echoes-tools-as-not-strict"+ JUDGES_LATEST_USER_MESSAGE = "judges-latest-user-message"+++@dataclass(frozen=True, slots=True)+class _Rig:+ gateway: Gateway+ vendor: Wire+ bedrock: Wire+ keys: Mapping[str, str]+++def _masked(value: JsonValue) -> JsonValue:+ return _JSON.validate_json(_CARD_PATTERN.sub(_MASK, json.dumps(value)))+++def _flattened(row: Mapping[str, JsonValue]) -> dict[str, JsonValue]:+ content: Final = row.get("content")+ if not isinstance(content, list):+ return dict(row)+ parts: Final = tuple(object_value(part).get("text") for part in content)+ return {**row, "content": "\n".join(part for part in parts if isinstance(part, str))}+++def _normalised_first_part(row: Mapping[str, JsonValue]) -> dict[str, JsonValue]:+ content: Final = row.get("content")+ if not isinstance(content, list) or not content:+ return dict(row)+ first: Final = object_value(content[0])+ text: Final = first.get("text")+ if not isinstance(text, str):+ return dict(row)+ return {**row, "content": [{**first, "text": text.strip() + " "}, *content[1:]]}+++def _blank_content(row: Mapping[str, JsonValue]) -> dict[str, JsonValue]:+ return {**row, "content": ""} if row.get("content") is None else dict(row)+++def _card_cleared(value: JsonValue) -> JsonValue:+ match value:+ case str() if _CARD_PATTERN.search(value):+ return ""+ case list():+ return [_card_cleared(item) for item in value]+ case dict():+ return {key: _card_cleared(item) for key, item in value.items()}+ case _:+ return value+++def _compacted(row: Mapping[str, JsonValue]) -> dict[str, JsonValue]:+ return {**row, "content": f"compacted: {row.get('content')}"} if row.get("role") == "tool" else dict(row)+++def _content_masked(row: Mapping[str, JsonValue]) -> dict[str, JsonValue]:+ return {**row, "content": _masked(row.get("content"))}+++def _latest_user_message(body: Mapping[str, JsonValue]) -> JsonValue:+ rows: Final = tuple(object_value(row) for row in list_value(body.get("structured_messages") or []))+ users: Final = tuple(row for row in rows if row.get("role") == "user")+ return users[-1] if users else body.get("texts")+++def _verdict(vendor: _Vendor, body: Mapping[str, JsonValue]) -> dict[str, JsonValue]:+ if _CARD_PATTERN.search(json.dumps(body)) is None:+ return {"action": "NONE"}+ texts: Final = _masked(list_value(body.get("texts") or []))+ sent_rows: Final = tuple(object_value(row) for row in list_value(body.get("structured_messages") or []))+ rows: Final = tuple(object_value(row) for row in list_value(_masked([dict(row) for row in sent_rows])))+ tools: Final = list(list_value(_masked(list_value(body.get("tools") or []))))+ match vendor:+ case _Vendor.MASKS_ROWS_ONLY:+ return {"action": "GUARDRAIL_INTERVENED", "structured_messages": [dict(row) for row in rows]}+ case _Vendor.MASKS_ROWS_AND_BLANKS_EMPTY_CONTENT:+ return {+ "action": "GUARDRAIL_INTERVENED",+ "texts": texts,+ "structured_messages": list(map(_blank_content, rows)),+ }+ case _Vendor.JOINS_MASKED_ROWS:+ return {+ "action": "GUARDRAIL_INTERVENED",+ "texts": texts,+ "structured_messages": list(map(_flattened, rows)),+ }+ case _Vendor.ECHOES_ROWS:+ return {"action": "GUARDRAIL_INTERVENED", "texts": texts, "structured_messages": list(map(dict, sent_rows))}+ case _Vendor.RESPACES_UNMASKED_ROWS:+ return {+ "action": "GUARDRAIL_INTERVENED",+ "texts": texts,+ "structured_messages": list(map(_normalised_first_part, sent_rows)),+ }+ case _Vendor.COMPACTS_TOOL_RESULTS:+ return {"action": "GUARDRAIL_INTERVENED", "structured_messages": list(map(_compacted, rows))}+ case _Vendor.DROPS_A_ROW:+ return {"action": "GUARDRAIL_INTERVENED", "texts": texts, "structured_messages": list(map(dict, rows[:-1]))}+ case _Vendor.MASKS_TEXTS_AND_ROW_CONTENT:+ return {+ "action": "GUARDRAIL_INTERVENED",+ "texts": texts,+ "structured_messages": list(map(_content_masked, sent_rows)),+ }+ case _Vendor.CLEARS_CARD_TEXTS:+ return {+ "action": "GUARDRAIL_INTERVENED",+ "texts": _card_cleared(list_value(body.get("texts") or [])),+ "structured_messages": _card_cleared([dict(row) for row in sent_rows]),+ }+ case _Vendor.MASKS_TEXTS_ONLY:+ return {"action": "GUARDRAIL_INTERVENED", "texts": texts}+ case _Vendor.BLOCKS:+ return {"action": "BLOCKED", "blocked_reason": "card number"}+ case _Vendor.MASKS_TOOLS:+ return {"action": "GUARDRAIL_INTERVENED", "texts": texts, "tools": tools}+ case _Vendor.DROPS_A_TOOL:+ return {"action": "GUARDRAIL_INTERVENED", "texts": texts, "tools": tools[1:]}+ case _Vendor.ADDS_A_TOOL:+ return {"action": "GUARDRAIL_INTERVENED", "texts": texts, "tools": [*tools, _ADDED_TOOL]}+ case _Vendor.RENAMES_A_TOOL:+ renamed: Final = object_value(tools[0])+ function: Final = object_value(renamed.get("function"))+ return {+ "action": "GUARDRAIL_INTERVENED",+ "texts": texts,+ "tools": [{**renamed, "function": {**function, "name": "lookup_card_v2"}}, *tools[1:]],+ }+ case _Vendor.ECHOES_TOOLS_AS_NOT_STRICT:+ echoed: Final = tuple(object_value(tool) for tool in tools)+ return {+ "action": "GUARDRAIL_INTERVENED",+ "texts": texts,+ "tools": [+ {**tool, "function": {**object_value(tool.get("function")), "strict": False}} for tool in echoed+ ],+ }+ case _Vendor.JUDGES_LATEST_USER_MESSAGE:+ if _CARD_PATTERN.search(json.dumps(_latest_user_message(body))) is None:+ return {"action": "NONE"}+ return {"action": "BLOCKED", "blocked_reason": "card number"}+++def _vendor(request: Request) -> Reply:+ vendor: Final = _Vendor(request.target.removeprefix("/gga/").removesuffix(_GUARD_PATH))+ return Reply(body=json.dumps(_verdict(vendor, JSON_OBJECT.validate_json(request.body))).encode())+++def _bedrock(request: Request) -> Reply:+ assert request.target == f"/model/{_MODEL_ID}/converse", request.target+ return Reply(+ body=json.dumps(+ {+ "output": {"message": {"role": "assistant", "content": [{"text": "guarded reply"}]}},+ "stopReason": "end_turn",+ "usage": {"inputTokens": 7, "outputTokens": 2, "totalTokens": 9},+ "metrics": {"latencyMs": 1},+ }+ ).encode()+ )+++def _guardrail(name: str, params: Mapping[str, JsonValue]) -> dict[str, JsonValue]:+ return {"guardrail_name": name, "litellm_params": {"mode": "pre_call", "default_on": False, **params}}+++def _generic(vendor: _Vendor) -> str:+ return f"gga-{vendor.value}"+++def _guardrails(vendor_url: str) -> tuple[dict[str, JsonValue], ...]:+ generic: Final = {"guardrail": "generic_guardrail_api", "api_key": "synthetic-guardrail-key"}+ return (+ *(+ _guardrail(_generic(vendor), {**generic, "api_base": f"{vendor_url}/gga/{vendor.value}"})+ for vendor in _Vendor+ ),+ _guardrail("mcp-end-user", {"guardrail": "mcp_end_user_permission"}),+ _guardrail(+ "gga-block-skip-tool",+ {**generic, "api_base": f"{vendor_url}/gga/{_Vendor.BLOCKS.value}", "skip_tool_message_in_guardrail": True},+ ),+ _guardrail(+ "gga-mask-tool-only",+ {+ **generic,+ "api_base": f"{vendor_url}/gga/{_Vendor.MASKS_TEXTS_ONLY.value}",+ "scan_only_tool_results": True,+ },+ ),+ _guardrail("tool-policy", {"guardrail": "tool_policy"}),+ )+++def _config(directory: Path, guardrails: tuple[dict[str, JsonValue], ...], bedrock: Wire) -> Path:+ configuration: Final = yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())+ configuration["model_list"] = [+ *configuration["model_list"],+ *(+ {+ "model_name": model_name,+ "litellm_params": {+ "model": f"bedrock/{_MODEL_ID}",+ "api_base": bedrock.url,+ "aws_access_key_id": "AKIASCRIPTEDPROVIDER",+ "aws_secret_access_key": "scripted-secret",+ "aws_region_name": "us-east-1",+ },+ }+ for model_name in (_MODEL, *_PIPELINED_ACTIONS)+ ),+ ]+ configuration["guardrails"] = list(guardrails)+ configuration["policies"] = {+ model_name: {+ "guardrails": {"add": [_generic(_Vendor.DROPS_A_ROW)]},+ "pipeline": {+ "mode": "pre_call",+ "steps": [{"guardrail": _generic(_Vendor.DROPS_A_ROW), "on_pass": "next", **actions}],+ },+ }+ for model_name, actions in _PIPELINED_ACTIONS.items()+ }+ configuration["policy_attachments"] = [+ {"policy": model_name, "models": [model_name]} for model_name in _PIPELINED_ACTIONS+ ]+ path: Final = directory / "converse-guardrails.yaml"+ path.write_text(yaml.safe_dump(configuration))+ return path++[email protected](scope="module")+def rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[_Rig]:+ directory: Final = tmp_path_factory.mktemp("converse-guardrail-rewrites")+ with (+ gateway_from_environment() as gateway,+ wire_server(_vendor) as vendor,+ wire_server(_bedrock) as bedrock,+ ):+ guardrails: Final = _guardrails(vendor.url)+ names: Final = tuple(str(guardrail["guardrail_name"]) for guardrail in guardrails)+ with (+ owned_proxy(gateway, directory, {}, config=_config(directory, guardrails, bedrock), workers=2) as owned,+ owned.scenario() as scenario,+ ):+ keys: Final = {name: scenario.key(guardrails=[name]) for name in names}+ tool_remover_then_masker: Final = ["mcp-end-user", "gga-mask-tool-only"]+ yield _Rig(+ owned,+ vendor,+ bedrock,+ {**keys, "+".join(tool_remover_then_masker): scenario.key(guardrails=tool_remover_then_masker)},+ )++[email protected](autouse=True)+def _drained(rig: _Rig) -> Iterator[None]:+ rig.vendor.drain()+ rig.bedrock.drain()+ yield+ rig.vendor.drain()+ rig.bedrock.drain()+++def _converse(rig: _Rig, guardrail: str, body: Mapping[str, JsonValue]) -> httpx.Response:+ return rig.gateway.request("POST", f"/bedrock/model/{_MODEL}/converse", body, key=rig.keys[guardrail])+++def _forwarded(rig: _Rig, response: httpx.Response) -> dict[str, JsonValue]:+ assert response.status_code == 200, response.text+ sent: Final = rig.bedrock.drain()+ assert len(sent) == 1, response.text+ return JSON_OBJECT.validate_json(sent[0].body)+++def _refused(rig: _Rig, response: httpx.Response) -> str:+ assert response.status_code >= 400, response.text+ assert rig.bedrock.drain() == (), response.text+ return response.text+++def _vendor_bodies(rig: _Rig) -> tuple[dict[str, JsonValue], ...]:+ return tuple(JSON_OBJECT.validate_json(request.body) for request in rig.vendor.drain())+++def _user(*blocks: JsonValue) -> dict[str, JsonValue]:+ return {"role": "user", "content": list(blocks)}+++def _assistant(*blocks: JsonValue) -> dict[str, JsonValue]:+ return {"role": "assistant", "content": list(blocks)}+++def _tool_use(card: str) -> dict[str, JsonValue]:+ return {"toolUse": {"toolUseId": "tooluse_lookup", "name": "lookup_card", "input": {"card": card, "limit": 2}}}+++def _tool_result(*content: JsonValue) -> dict[str, JsonValue]:+ return {"toolResult": {"toolUseId": "tooluse_lookup", "content": list(content), "status": "success"}}+++def _tool_loop(card_line: str, tool_call_card: str) -> dict[str, JsonValue]:+ return {+ "messages": [+ _user({"text": card_line}),+ _assistant(_tool_use(tool_call_card)),+ _user(_tool_result({"text": "card is active"})),+ ]+ }+++def test_card_the_vendor_masks_only_in_messages_reaches_bedrock_masked(rig: _Rig) -> None:+ body: Final = {"messages": [_user({"text": f"Card {_CARD} please."})]}+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.MASKS_ROWS_ONLY), body))+ assert sent["messages"] == [_user({"text": f"Card {_MASK} please."})]+++def test_message_masks_reach_every_block_of_an_agent_loop_with_the_image_intact(rig: _Rig) -> None:+ image: Final = {"image": {"format": "png", "source": {"bytes": _PNG}}}+ body: Final = {+ "system": [{"text": f"Card on file {_CARD}."}],+ "messages": [+ _user({"text": "Check this."}, {"guardContent": {"text": {"text": f"Card {_CARD}."}}}),+ _assistant(_tool_use(_CARD)),+ _user(_tool_result({"text": f"found {_CARD}"}, image, {"json": {"card": _CARD, "status": "active"}})),+ ],+ }+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.MASKS_ROWS_AND_BLANKS_EMPTY_CONTENT), body))+ assert sent == _masked(body)+++def test_flattened_messages_reach_bedrock_masked_in_their_original_blocks(rig: _Rig) -> None:+ body: Final = {+ "system": [{"text": "You are a billing assistant."}, {"text": f"Card on file {_CARD}."}],+ "messages": [_user({"text": "Order details below."}, {"text": f"Card {_CARD} please."})],+ }+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.JOINS_MASKED_ROWS), body))+ assert sent == _masked(body)+++def test_echoed_messages_keep_the_text_mask(rig: _Rig) -> None:+ body: Final = {"messages": [_user({"text": f"Card {_CARD} please."})]}+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.ECHOES_ROWS), body))+ assert sent["messages"] == [_user({"text": f"Card {_MASK} please."})]+++def test_text_mask_wins_over_a_message_change_that_left_the_card(rig: _Rig) -> None:+ body: Final = {"messages": [_user({"text": f"Card {_CARD} on file."}, {"text": "Thanks."})]}+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.RESPACES_UNMASKED_ROWS), body))+ assert sent["messages"] == [_user({"text": f"Card {_MASK} on file."}, {"text": "Thanks."})]+++def test_compacted_tool_result_reaches_bedrock_as_one_text_block_with_the_image_in_place(rig: _Rig) -> None:+ image: Final = {"image": {"format": "png", "source": {"bytes": _PNG}}}+ body: Final = {+ "messages": [+ _user({"text": "Look up my card."}),+ _assistant(_tool_use("last four 1111")),+ _user(_tool_result({"text": f"found {_CARD}"}, image, {"json": {"card": _CARD, "status": "active"}})),+ ]+ }+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.COMPACTS_TOOL_RESULTS), body))+ compacted: Final = f"compacted: found {_MASK}\n{json.dumps({'card': _MASK, 'status': 'active'})}"+ assert sent["messages"] == [+ _user({"text": "Look up my card."}),+ _assistant(_tool_use("last four 1111")),+ _user(_tool_result({"text": compacted}, image)),+ ]+++ ("user_text", "request_fields"),+ [+ (f"Card {_CARD} please.", {"thinking": {"type": "enabled", "budget_tokens": 1024}}),+ (f"Card {_CARD} please.", {"anthropic_beta": ["interleaved-thinking-2025-05-14"]}),+ ("Hello.", {"system": f"Card {_CARD} please."}),+ ],+ ids=["card-next-to-thinking", "card-next-to-anthropic-beta", "card-in-a-request-field"],+)+def test_guardrail_judging_the_latest_user_message_reads_it_with_the_request_fields(+ rig: _Rig, user_text: str, request_fields: Mapping[str, JsonValue]+) -> None:+ body: Final = {"messages": [_user({"text": user_text})], "additionalModelRequestFields": dict(request_fields)}+ assert "card number" in _refused(rig, _converse(rig, _generic(_Vendor.JUDGES_LATEST_USER_MESSAGE), body))+++def test_dropped_message_is_refused_before_bedrock(rig: _Rig) -> None:+ body: Final = {"messages": [_user({"text": "Hello."}), _assistant({"text": "Hi."}), _user({"text": f"{_CARD}"})]}+ assert _UNAPPLIABLE in _refused(rig, _converse(rig, _generic(_Vendor.DROPS_A_ROW), body))+++def test_text_mask_the_messages_leave_out_of_a_tool_call_is_refused_before_bedrock(rig: _Rig) -> None:+ body: Final = _tool_loop(f"Charge card {_CARD}.", _CARD)+ assert _UNAPPLIABLE in _refused(rig, _converse(rig, _generic(_Vendor.MASKS_TEXTS_AND_ROW_CONTENT), body))++[email protected]("model_name", tuple(_PIPELINED_ACTIONS))+def test_pipeline_step_refuses_a_rewrite_it_cannot_apply_whatever_its_actions(rig: _Rig, model_name: str) -> None:+ body: Final = {"messages": [_user({"text": "Hello."}), _assistant({"text": "Hi."}), _user({"text": f"{_CARD}"})]}+ response: Final = rig.gateway.request("POST", f"/bedrock/model/{model_name}/converse", body)+ assert _UNAPPLIABLE in _refused(rig, response)+++def test_skip_tool_messages_keeps_tool_call_arguments_away_from_the_guardrail(rig: _Rig) -> None:+ body: Final = _tool_loop("Check my card.", _CARD)+ sent: Final = _forwarded(rig, _converse(rig, "gga-block-skip-tool", body))+ assert sent["messages"] == body["messages"]+ assert all(_CARD not in json.dumps(scanned) for scanned in _vendor_bodies(rig))+++def test_tool_only_guardrail_scans_and_masks_only_tool_results(rig: _Rig) -> None:+ body: Final = {+ "messages": [+ _user({"text": f"My card is {_CARD}."}),+ _assistant(_tool_use("lookup")),+ _user(_tool_result({"text": f"found {_CARD}"})),+ ],+ "toolConfig": _TOOL_CONFIG,+ }+ sent: Final = _forwarded(rig, _converse(rig, "gga-mask-tool-only", body))+ scanned: Final = _vendor_bodies(rig)+ assert [(payload["texts"], payload.get("tools")) for payload in scanned] == [([f"found {_CARD}"], None)]+ assert scanned[0]["structured_messages"] == [+ {"role": "tool", "tool_call_id": "tooluse_lookup", "content": f"found {_CARD}"}+ ]+ assert sent == {**body, "messages": [*body["messages"][:2], _user(_tool_result({"text": f"found {_MASK}"}))]}+++def test_masked_tool_definitions_reach_bedrock_masked(rig: _Rig) -> None:+ body: Final = {"messages": [_user({"text": "Which cards are on file?"})], "toolConfig": _TOOL_CONFIG}+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.MASKS_TOOLS), body))+ assert sent == _masked(body)+++def test_tool_the_guardrail_removed_never_reaches_bedrock_nor_does_its_cache_point(rig: _Rig) -> None:+ body: Final = {"messages": [_user({"text": "Which cards are on file?"})], "toolConfig": _TOOL_CONFIG}+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.DROPS_A_TOOL), body))+ assert sent["toolConfig"] == {"tools": _TOOL_CONFIG["tools"][2:]}+++def test_tool_choice_the_guardrail_removed_is_refused_before_bedrock(rig: _Rig) -> None:+ body: Final = {+ "messages": [_user({"text": "Which cards are on file?"})],+ "toolConfig": {**_TOOL_CONFIG, "toolChoice": {"tool": {"name": "lookup_card"}}},+ }+ assert _UNAPPLIABLE in _refused(rig, _converse(rig, _generic(_Vendor.DROPS_A_TOOL), body))+++def _converted_tool(name: str, description: str, properties: Mapping[str, JsonValue]) -> dict[str, JsonValue]:+ schema: Final = {"type": "object", "properties": dict(properties), "required": []}+ return {"toolSpec": {"name": name, "description": description, "inputSchema": {"json": schema}}}+++def _masked_lookup(name: str) -> dict[str, JsonValue]:+ properties: Final = {"card": {"type": "string", "description": f"for example {_MASK}"}}+ return _converted_tool(name, f"Looks up cards like {_MASK}", properties)+++def test_tool_the_guardrail_added_reaches_bedrock_after_the_others(rig: _Rig) -> None:+ body: Final = {"messages": [_user({"text": "Which cards are on file?"})], "toolConfig": _TOOL_CONFIG}+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.ADDS_A_TOOL), body))+ assert sent["toolConfig"] == {+ "tools": [+ *list_value(object_value(_masked(_TOOL_CONFIG))["tools"]),+ _converted_tool("retrieve", "retrieve", {}),+ ]+ }+++def test_tool_the_guardrail_added_to_a_request_without_tools_reaches_bedrock(rig: _Rig) -> None:+ body: Final = {"messages": [_user({"text": f"Card {_CARD} please."})]}+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.ADDS_A_TOOL), body))+ assert sent == {+ "messages": [_user({"text": f"Card {_MASK} please."})],+ "toolConfig": {"tools": [_converted_tool("retrieve", "retrieve", {})]},+ }+++def test_tool_the_guardrail_renamed_reaches_bedrock_without_the_old_cache_point(rig: _Rig) -> None:+ body: Final = {"messages": [_user({"text": "Which cards are on file?"})], "toolConfig": _TOOL_CONFIG}+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.RENAMES_A_TOOL), body))+ assert sent["toolConfig"] == {"tools": [_masked_lookup("lookup_card_v2"), _TOOL_CONFIG["tools"][2]]}+++def test_tools_echoed_with_an_added_key_are_rebuilt_and_keep_their_cache_point(rig: _Rig) -> None:+ body: Final = {"messages": [_user({"text": "Which cards are on file?"})], "toolConfig": _TOOL_CONFIG}+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.ECHOES_TOOLS_AS_NOT_STRICT), body))+ assert sent["toolConfig"] == {+ "tools": [+ _masked_lookup("lookup_card"),+ {"cachePoint": {"type": "default"}},+ _converted_tool("refund", "Refunds an order", {}),+ ]+ }+++def test_text_block_the_guardrail_cleared_is_dropped_before_bedrock(rig: _Rig) -> None:+ body: Final = {"messages": [_user({"text": "Order details below."}, {"text": f"Card {_CARD} please."})]}+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.CLEARS_CARD_TEXTS), body))+ assert sent["messages"] == [_user({"text": "Order details below."})]+++def test_turn_the_guardrail_cleared_entirely_is_sent_as_written(rig: _Rig) -> None:+ body: Final = {"messages": [_user({"text": f"Card {_CARD} please."})]}+ sent: Final = _forwarded(rig, _converse(rig, _generic(_Vendor.CLEARS_CARD_TEXTS), body))+ assert sent["messages"] == [_user({"text": ""})]+++def test_deeply_nested_tool_result_json_reaches_bedrock_with_the_message_mask(rig: _Rig) -> None:+ nested: JsonValue = "status active"+ for _ in range(500):+ nested = {"k": nested}+ body: Final = {+ "messages": [+ _user({"text": "Look up my card."}),+ _assistant(_tool_use("last four 1111")),+ _user(_tool_result({"json": nested}), {"text": f"Card {_CARD} please."}),+ ]+ }+ response: Final = _converse(rig, _generic(_Vendor.MASKS_ROWS_AND_BLANKS_EMPTY_CONTENT), body)+ assert response.status_code == 200, response.text+ sent: Final = rig.bedrock.drain()+ assert len(sent) == 1, response.text+ forwarded: object = json.loads(sent[0].body)+ assert forwarded == {+ "messages": [+ _user({"text": "Look up my card."}),+ _assistant(_tool_use("last four 1111")),+ _user(_tool_result({"json": nested}), {"text": f"Card {_MASK} please."}),+ ]+ }+++def _named_tools(*names: str) -> dict[str, JsonValue]:+ return {"tools": [{"toolSpec": {"name": name, "inputSchema": {"json": {"type": "object"}}}} for name in names]}+++def test_tool_policy_refuses_a_converse_tool_whose_input_policy_is_blocked(rig: _Rig) -> None:+ blocked: Final = f"converse_blocked_{uuid.uuid4().hex[:8]}"+ rig.gateway.post("/v1/tool/policy", {"tool_name": blocked, "input_policy": "blocked"})+ body: Final = {"messages": [_user({"text": "Refund my order."})], "toolConfig": _named_tools(blocked, "refund")}+ held(lambda: _converse(rig, "tool-policy", body).status_code, lambda status: status == 400, holding=2, seconds=60)+ rig.bedrock.drain()+ assert "Violated tool policy" in _refused(rig, _converse(rig, "tool-policy", body))+++def _end_user_on_github_only(rig: _Rig) -> dict[str, str]:+ end_user: Final = f"converse-mcp-{uuid.uuid4().hex[:8]}"+ rig.gateway.post("/customer/new", {"user_id": end_user, "object_permission": {"mcp_servers": ["github"]}})+ return {"x-litellm-end-user-id": end_user}+++def test_mcp_end_user_permission_drops_tools_of_servers_the_end_user_cannot_use(rig: _Rig) -> None:+ body: Final = {+ "messages": [_user({"text": "File the bug."})],+ "toolConfig": _named_tools("github-create_issue", "slack-post_message", "get_weather"),+ }+ response: Final = rig.gateway.request(+ "POST",+ f"/bedrock/model/{_MODEL}/converse",+ body,+ key=rig.keys["mcp-end-user"],+ headers=_end_user_on_github_only(rig),+ )+ assert _forwarded(rig, response)["toolConfig"] == _named_tools("github-create_issue", "get_weather")+++ "guardrail_config",+ [{}, {"guardrailConfig": {"guardrailIdentifier": "gr-scripted", "guardrailVersion": "1"}}],+ ids=["plain", "with-guardrail-config"],+)+def test_mcp_end_user_permission_removing_every_tool_drops_the_tool_config_and_turns_tool_history_into_text(+ rig: _Rig, guardrail_config: Mapping[str, JsonValue]+) -> None:+ tool_use: Final = {"toolUseId": "tooluse_post", "name": "slack-post_message", "input": {"channel": "#ops"}}+ body: Final = {+ **guardrail_config,+ "messages": [+ _user({"text": "Post the update."}),+ _assistant({"toolUse": tool_use}),+ _user(+ {"toolResult": {"toolUseId": "tooluse_post", "content": [{"text": "posted to #ops"}]}},+ {"text": "Again."},+ ),+ ],+ "toolConfig": {**_named_tools("slack-post_message"), "toolChoice": {"any": {}}},+ }+ response: Final = rig.gateway.request(+ "POST",+ f"/bedrock/model/{_MODEL}/converse",+ body,+ key=rig.keys["mcp-end-user"],+ headers=_end_user_on_github_only(rig),+ )+ assert _forwarded(rig, response) == {+ **guardrail_config,+ "messages": [+ _user({"text": "Post the update."}),+ _assistant({"text": '[tool call tooluse_post: slack-post_message({"channel": "#ops"})]'}),+ _user({"text": "[tool result for tooluse_post: posted to #ops]"}, {"text": "Again."}),+ ],+ }+++def test_tool_result_of_a_tool_mcp_end_user_permission_removed_is_masked_by_a_later_tool_results_only_guardrail(+ rig: _Rig,+) -> None:+ tool_use: Final = {"toolUseId": "tooluse_post", "name": "slack-post_message", "input": {"channel": "#ops"}}+ body: Final = {+ "messages": [+ _user({"text": "Post the update."}),+ _assistant({"toolUse": tool_use}),+ _user(+ {"toolResult": {"toolUseId": "tooluse_post", "content": [{"text": f"posted card {_CARD}"}]}},+ {"text": "Again."},+ ),+ ],+ "toolConfig": _named_tools("slack-post_message"),+ }+ response: Final = rig.gateway.request(+ "POST",+ f"/bedrock/model/{_MODEL}/converse",+ body,+ key=rig.keys["mcp-end-user+gga-mask-tool-only"],+ headers=_end_user_on_github_only(rig),+ )+ sent: Final = _forwarded(rig, response)+ assert "toolConfig" not in sent+ assert sent["messages"][-1] == _user(+ {"text": f"[tool result for tooluse_post: posted card {_MASK}]"}, {"text": "Again."}+ )diff --git a/tests/unit/llms/bedrock/passthrough/guardrail_translation/test_handler.py b/tests/unit/llms/bedrock/passthrough/guardrail_translation/test_handler.pyindex 85de558a8b2..5aaee1f0ee4 100644--- a/tests/unit/llms/bedrock/passthrough/guardrail_translation/test_handler.py+++ b/tests/unit/llms/bedrock/passthrough/guardrail_translation/test_handler.py@@ -10,12 +10,18 @@ Validates that:"""import copy+import importlib.utilimport json-from collections.abc import Mapping, Sequence+import sys+import time+import types+from collections.abc import Callable, Mapping, Sequencefrom datetime import datetime-from typing import Literal, TypeAlias-from unittest.mock import AsyncMock, MagicMock+from itertools import chain+from typing import ClassVar, Literal, TypeAlias+from unittest.mock import AsyncMock, MagicMock, patch+import httpximport pytestimport respxfrom pydantic import JsonValue@@ -25,12 +31,31 @@ import litellmfrom litellm.caching.caching import DualCachefrom litellm.integrations.custom_guardrail import CustomGuardrailfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandlerfrom litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy.guardrails.guardrail_hooks.airia.airia import AiriaGuardrail+from litellm.proxy.guardrails.guardrail_hooks.akto.akto import AktoGuardrail+from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import BedrockGuardrail+from litellm.proxy.guardrails.guardrail_hooks.conduct import conduct as conduct_module+from litellm.proxy.guardrails.guardrail_hooks.crowdstrike_aidr.crowdstrike_aidr import CrowdStrikeAIDRHandler+from litellm.proxy.guardrails.guardrail_hooks.headroom.headroom import HeadroomGuardrail+from litellm.proxy.guardrails.guardrail_hooks.hiddenlayer.hiddenlayer import (+ HiddenlayerGuardrail,+ HiddenlayerGuardrailV2,+)+from litellm.proxy.guardrails.guardrail_hooks.llm_as_a_judge import LLMAsAJudgeGuardrail+from litellm.proxy.guardrails.guardrail_hooks.openai.moderations import OpenAIModerationGuardrail+from litellm.proxy.guardrails.guardrail_hooks.panw_prisma_airs.panw_prisma_airs import PanwPrismaAirsHandler+from litellm.proxy.guardrails.guardrail_hooks.prompt_security.prompt_security import PromptSecurityGuardrail+from litellm.proxy.guardrails.guardrail_hooks.promptguard.promptguard import PromptGuardGuardrail+from litellm.proxy.guardrails.guardrail_hooks.qualifire.qualifire import QualifireGuardrail+from litellm.proxy.guardrails.guardrail_hooks.singulr.singulr import SingulrGuardrailfrom litellm.proxy.guardrails.guardrail_hooks.noma import NomaV2Guardrailfrom litellm.proxy.utils import ProxyLoggingfrom litellm.types.guardrails import GuardrailEventHooksfrom litellm.types.utils import GenericGuardrailAPIInputs+from litellm.llms.base_llm.guardrail_translation.utils import UnappliableRequestRewritefrom litellm.llms.bedrock.passthrough.guardrail_translation.handler import (BedrockPassthroughGuardrailHandler,_extract_converse_texts,@@ -1355,6 +1380,1137 @@ class TestDeAnonymizeConverseStream:assert result is stream_bytes+class _ScriptedGuardrail(CustomGuardrail):+ def __init__(+ self,+ reply: Callable[[GenericGuardrailAPIInputs], Mapping[str, object]],+ *,+ skip_system: bool = False,+ scan_only_tool_results: bool = False,+ ) -> None:+ super().__init__(guardrail_name="test-guard")+ self.reply = reply+ self.skip_system_message_in_guardrail = skip_system+ self.scan_only_tool_results = scan_only_tool_results+ self.received: tuple[GenericGuardrailAPIInputs, ...] = ()++ async def apply_guardrail(+ self,+ inputs: GenericGuardrailAPIInputs,+ request_data: dict,+ input_type: Literal["request", "response"],+ logging_obj: LiteLLMLoggingObj | None = None,+ ) -> Mapping[str, object]:+ self.received = (*self.received, copy.deepcopy(inputs))+ return self.reply(inputs)+++def _replying(result: Mapping[str, object]) -> _ScriptedGuardrail:+ return _ScriptedGuardrail(lambda _: result)+++def _with_structured_text(inputs: GenericGuardrailAPIInputs, old: str, new: str) -> GenericGuardrailAPIInputs:+ rows = [+ {**row, "content": [{**part, "text": part["text"].replace(old, new)} for part in row["content"]]}+ if isinstance(row["content"], list)+ else row+ for row in inputs["structured_messages"]+ ]+ return {**inputs, "structured_messages": rows}+++def _masked_texts(inputs: GenericGuardrailAPIInputs) -> list[str]:+ return [text.replace("4111", "[CARD]") for text in inputs["texts"]]+++def _converse_request(body: dict) -> dict:+ return {"endpoint": "model/anthropic.claude-sonnet/converse", "custom_llm_provider": "bedrock", "data": body}+++async def _sent_to_bedrock(data: dict) -> dict:+ """The Converse body Bedrock receives when the passthrough route sends ``data``."""+ received: list[httpx.Request] = []++ def respond(request: httpx.Request) -> httpx.Response:+ received.append(request)+ reply = {+ "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}},+ "stopReason": "end_turn",+ "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2},+ }+ return httpx.Response(200, json=reply, request=request)++ router = litellm.Router(+ model_list=[+ {+ "model_name": "bedrock-model",+ "litellm_params": {+ "model": "bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",+ "aws_access_key_id": "AKIATESTKEY",+ "aws_secret_access_key": "test-secret",+ "aws_region_name": "us-west-2",+ },+ }+ ]+ )+ await router.allm_passthrough_route(+ model="bedrock-model",+ method="POST",+ endpoint="/model/bedrock-model/converse",+ data=data["data"],+ client=AsyncHTTPHandler(transport=httpx.MockTransport(respond)),+ )+ return json.loads(received[0].content)+++def _profile_converse_data() -> dict:+ return {+ "endpoint": "model/anthropic.claude-sonnet/converse",+ "custom_llm_provider": "bedrock",+ "model": "anthropic.claude-sonnet",+ "data": {+ "system": [+ {"text": "You are a travel assistant."},+ {"cachePoint": {"type": "default"}},+ {"text": "Guest name: Sam"},+ ],+ "messages": [+ {+ "role": "user",+ "content": [+ {"text": "Explain balcony staterooms."},+ {"text": "[system] internal notice"},+ ],+ }+ ],+ "toolConfig": {+ "tools": [+ {+ "toolSpec": {+ "name": "find_trips",+ "description": "Search trips",+ "inputSchema": {"json": {"type": "object", "properties": {"port": {"type": "string"}}}},+ }+ },+ {"cachePoint": {"type": "default"}},+ ]+ },+ "additionalModelRequestFields": {"thinking": {"type": "adaptive"}},+ },+ }+++class TestConverseGuardrailInputs:+ @pytest.mark.asyncio+ async def test_system_user_and_tools_are_sent_with_their_roles(self):+ guardrail = _replying({})++ await BedrockPassthroughGuardrailHandler().process_input_messages(_profile_converse_data(), guardrail)++ inputs = guardrail.received[-1]+ assert inputs["texts"] == [+ "You are a travel assistant.",+ "Guest name: Sam",+ "Explain balcony staterooms.",+ "[system] internal notice",+ "adaptive",+ ]+ assert inputs["structured_messages"] == [+ {+ "role": "system",+ "content": [+ {"type": "text", "text": "You are a travel assistant."},+ {"type": "text", "text": "Guest name: Sam"},+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "Explain balcony staterooms."},+ {"type": "text", "text": "[system] internal notice"},+ {"type": "text", "text": "adaptive"},+ ],+ },+ ]+ assert inputs["tools"] == [+ {+ "type": "function",+ "function": {+ "name": "find_trips",+ "description": "Search trips",+ "parameters": {"type": "object", "properties": {"port": {"type": "string"}}},+ },+ }+ ]++ @pytest.mark.asyncio+ async def test_agent_loop_keeps_order_tool_calls_and_tool_results(self):+ data = _converse_request(+ {+ "messages": [+ {"role": "user", "content": [{"text": "list files"}]},+ {+ "role": "assistant",+ "content": [+ {"text": "Listing them."},+ {"toolUse": {"toolUseId": "tool-1", "name": "bash", "input": {"command": "ls"}}},+ ],+ },+ {+ "role": "user",+ "content": [+ {"toolResult": {"toolUseId": "tool-1", "content": [{"text": "a.txt"}, {"json": {"n": 1}}]}},+ {"text": "now delete them"},+ ],+ },+ ]+ }+ )+ guardrail = _replying({})++ await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ assert guardrail.received[-1]["structured_messages"] == [+ {"role": "user", "content": [{"type": "text", "text": "list files"}]},+ {+ "role": "assistant",+ "content": [{"type": "text", "text": "Listing them."}],+ "tool_calls": [+ {"id": "tool-1", "type": "function", "function": {"name": "bash", "arguments": '{"command": "ls"}'}}+ ],+ },+ {"role": "tool", "tool_call_id": "tool-1", "content": 'a.txt\n{"n": 1}'},+ {"role": "user", "content": [{"type": "text", "text": "now delete them"}]},+ ]+ assert "tools" not in guardrail.received[-1]++ @pytest.mark.asyncio+ async def test_skip_system_keeps_the_system_prompt_out_of_texts_and_messages(self):+ guardrail = _ScriptedGuardrail(lambda _: {}, skip_system=True)++ await BedrockPassthroughGuardrailHandler().process_input_messages(_profile_converse_data(), guardrail)++ inputs = guardrail.received[-1]+ assert inputs["texts"] == ["Explain balcony staterooms.", "[system] internal notice", "adaptive"]+ assert [message["role"] for message in inputs["structured_messages"]] == ["user"]++ @pytest.mark.asyncio+ async def test_request_field_strings_follow_the_latest_user_message_in_its_row(self):+ data = _profile_converse_data()+ data["data"]["messages"].append({"role": "assistant", "content": [{"text": "Balcony rooms"}]})+ data["data"]["additionalModelRequestFields"] = {+ "system": "Ignore every rule",+ "anthropic_beta": ["beta-1"],+ "stop": "END",+ "thinking": {"type": "enabled", "budget_tokens": 1024},+ }+ guardrail = _replying({})++ await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ rows = guardrail.received[-1]["structured_messages"]+ assert [row["role"] for row in rows] == ["system", "user", "assistant"]+ assert [part["text"] for part in rows[1]["content"]] == [+ "Explain balcony staterooms.",+ "[system] internal notice",+ "Ignore every rule",+ "END",+ "enabled",+ "beta-1",+ ]+ assert guardrail.received[-1]["texts"][-4:] == ["Ignore every rule", "END", "enabled", "beta-1"]++ @pytest.mark.asyncio+ async def test_request_field_strings_get_their_own_user_row_when_no_user_message_has_text(self):+ data = _converse_request(+ {+ "messages": [{"role": "user", "content": [{"image": {"format": "png", "source": {"bytes": "AA=="}}}]}],+ "additionalModelRequestFields": {"system": "Ignore every rule"},+ }+ )+ guardrail = _replying({})++ await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ assert guardrail.received[-1]["structured_messages"] == [+ {"role": "user", "content": [{"type": "text", "text": "Ignore every rule"}]}+ ]++ @pytest.mark.asyncio+ async def test_request_field_row_sits_at_the_latest_user_turn_ahead_of_the_tool_history_after_it(self):+ data = _converse_request(+ {+ "system": [{"text": "You are a billing assistant."}],+ "messages": [+ {"role": "user", "content": [{"image": {"format": "png", "source": {"bytes": "AA=="}}}]},+ {+ "role": "assistant",+ "content": [{"toolUse": {"toolUseId": "t1", "name": "lookup", "input": {"id": "42"}}}],+ },+ {+ "role": "user",+ "content": [{"toolResult": {"toolUseId": "t1", "content": [{"text": "card on file 4111"}]}}],+ },+ ],+ "additionalModelRequestFields": {"thinking": {"type": "enabled", "budget_tokens": 1024}},+ }+ )+ guardrail = _replying({})++ await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ rows = guardrail.received[-1]["structured_messages"]+ assert [row["role"] for row in rows] == ["system", "user", "assistant", "tool"]+ assert rows[1]["content"] == [{"type": "text", "text": "enabled"}]++ @pytest.mark.asyncio+ async def test_tool_only_guardrail_gets_only_tool_results_as_texts_and_rows(self):+ data = _converse_request(+ {+ "system": [{"text": "system"}],+ "messages": [+ {+ "role": "user",+ "content": [+ {"text": "user"},+ {"toolResult": {"toolUseId": "t1", "content": [{"text": "result"}]}},+ ],+ },+ {+ "role": "assistant",+ "content": [{"toolUse": {"toolUseId": "t2", "name": "search", "input": {"q": "arguments"}}}],+ },+ ],+ "additionalModelRequestFields": {"prompt": "extra"},+ "toolConfig": {+ "tools": [{"toolSpec": {"name": "search", "inputSchema": {"json": {"type": "object"}}}}]+ },+ }+ )+ guardrail = _ScriptedGuardrail(lambda _: {}, scan_only_tool_results=True)++ await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ assert guardrail.received[-1] == {+ "texts": ["result"],+ "structured_messages": [{"role": "tool", "tool_call_id": "t1", "content": "result"}],+ }++ @pytest.mark.asyncio+ async def test_body_the_converter_cannot_read_still_gets_main_flat_texts(self):+ data = _converse_request({"messages": [{"role": "user", "content": [{"text": "4111"}, "not a block"]}]})+ guardrail = _replying({"texts": ["[CARD]"], "structured_messages": [{"role": "user", "content": "[CARD]"}]})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ assert guardrail.received[-1] == {"texts": ["4111"]}+ assert result["data"]["messages"][0]["content"] == [{"text": "[CARD]"}, "not a block"]+++def _pay_turn(arguments: Mapping[str, object]) -> dict:+ return {"role": "assistant", "content": [{"toolUse": {"toolUseId": "t1", "name": "pay", "input": dict(arguments)}}]}+++def _pay_row(+ arguments: str = '{"card": "[CARD]", "tags": ["a"]}', *, call_id: str = "t1", name: str = "pay", content=None+) -> dict:+ call = {"id": call_id, "type": "function", "function": {"name": name, "arguments": arguments}}+ return {"role": "assistant", "content": content, "tool_calls": [call]}+++_CARD_TOOL_CALL = {"card": "4111", "tags": ["a"]}+++class TestConverseRowEditWriteBack:+ @pytest.mark.asyncio+ async def test_row_mask_of_a_request_field_is_written_back_into_that_field(self):+ data = _profile_converse_data()+ data["data"]["additionalModelRequestFields"] = {"system": "card 4111 1111 1111 1111", "top_k": 5}+ expected = copy.deepcopy(data["data"])+ expected["additionalModelRequestFields"]["system"] = "card [CARD]"+ guardrail = _ScriptedGuardrail(lambda inputs: _with_structured_text(inputs, "4111 1111 1111 1111", "[CARD]"))++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ assert result["data"] == expected++ @pytest.mark.asyncio+ async def test_row_mask_on_a_tool_call_argument_keeps_the_text_mask_on_its_sibling(self):+ data = _converse_request({"messages": [_pay_turn({"card": "4111", "name": "Alice"})]})+ guardrail = _replying(+ {"texts": ["[CARD]", "Alice"], "structured_messages": [_pay_row('{"card": "4111", "name": "[NAME]"}')]}+ )++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ assert result["data"]["messages"] == [_pay_turn({"card": "[CARD]", "name": "[NAME]"})]++ @pytest.mark.asyncio+ async def test_system_text_the_guardrail_cleared_is_dropped_and_an_emptied_system_is_removed(self):+ def cleared(*prefixes: str) -> _ScriptedGuardrail:+ return _ScriptedGuardrail(+ lambda inputs: {"texts": ["" if text.startswith(prefixes) else text for text in inputs["texts"]]}+ )++ handler = BedrockPassthroughGuardrailHandler()++ result = await handler.process_input_messages(_profile_converse_data(), cleared("Guest"))+ emptied = await handler.process_input_messages(_profile_converse_data(), cleared("Guest", "You are"))++ assert result["data"]["system"] == [+ {"text": "You are a travel assistant."},+ {"cachePoint": {"type": "default"}},+ ]+ assert "system" not in emptied["data"]+ assert emptied["data"]["messages"] == _profile_converse_data()["data"]["messages"]++ @pytest.mark.asyncio+ async def test_blank_text_the_client_sent_is_left_in_place(self):+ data = _converse_request({"messages": [{"role": "user", "content": [{"text": " "}, {"text": "card 4111"}]}]})+ guardrail = _ScriptedGuardrail(lambda inputs: {"texts": _masked_texts(inputs)})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ assert result["data"]["messages"][0]["content"] == [{"text": " "}, {"text": "card [CARD]"}]++ @pytest.mark.asyncio+ async def test_text_mask_written_into_the_sent_texts_list_still_wins(self):+ data = _converse_request({"messages": [{"role": "user", "content": [{"text": "ssn 123 email [email protected]"}]}]})++ def mask_in_place(inputs: dict) -> dict:+ inputs["texts"][0] = "ssn [SSN] email [email protected]"+ return _with_structured_text(copy.deepcopy(inputs), "[email protected]", "[EMAIL]")++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(+ data, _ScriptedGuardrail(mask_in_place)+ )++ assert result["data"]["messages"][0]["content"] == [{"text": "ssn [SSN] email [email protected]"}]++ @pytest.mark.asyncio+ async def test_structured_messages_that_are_not_rows_fall_back_to_texts(self):+ data = _converse_request({"messages": [{"role": "user", "content": [{"text": "4111"}]}]})+ guardrail = _replying({"texts": ["[CARD]"], "structured_messages": {"evaluation": {"action": "Redact"}}})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ assert result["data"]["messages"][0]["content"] == [{"text": "[CARD]"}]++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("messages", "rows"),+ [+ pytest.param(+ [{"role": "user", "content": [{"text": "card 4111"}]}],+ [{"role": "assistant", "content": [{"type": "text", "text": "card [CARD]"}]}],+ id="role-changed",+ ),+ pytest.param(+ [{"role": "user", "content": [{"text": "card\n4111"}, {"text": "thanks"}]}],+ [{"role": "user", "content": "card\n[CARD] thanks"}],+ id="blocks-that-hold-newlines-joined-with-a-space",+ ),+ pytest.param(+ [{"role": "user", "content": [{"text": "card 4111"}, {"text": "thanks"}, {"text": "bye"}]}],+ [{"role": "user", "content": "card [CARD]\nthanks"}],+ id="newline-joined-blocks-with-one-missing",+ ),+ pytest.param([_pay_turn(_CARD_TOOL_CALL)], [_pay_row(content="added text")], id="text-added-to-a-call"),+ pytest.param([_pay_turn(_CARD_TOOL_CALL)], [_pay_row(call_id="t2")], id="tool-call-id-changed"),+ pytest.param([_pay_turn(_CARD_TOOL_CALL)], [_pay_row(name="refund")], id="tool-renamed"),+ pytest.param([_pay_turn(_CARD_TOOL_CALL)], [_pay_row("not json")], id="arguments-not-json"),+ pytest.param(+ [_pay_turn(_CARD_TOOL_CALL)], [_pay_row('{"number": "[CARD]", "tags": ["a"]}')], id="argument-renamed"+ ),+ pytest.param(+ [_pay_turn(_CARD_TOOL_CALL)], [_pay_row('{"card": "[CARD]", "tags": ["a", "b"]}')], id="list-grew"+ ),+ pytest.param([_pay_turn(_CARD_TOOL_CALL)], [{**_pay_row(), "tool_calls": []}], id="tool-call-dropped"),+ pytest.param(+ [+ {+ "role": "user",+ "content": [{"toolResult": {"toolUseId": "t1", "content": [{"text": "found 4111"}]}}],+ }+ ],+ [{"role": "tool", "tool_call_id": "t2", "content": "found [CARD]"}],+ id="tool-result-id-changed",+ ),+ ],+ )+ async def test_row_edit_that_cannot_be_placed_fails_closed_without_mutation(self, messages, rows):+ data = _converse_request({"messages": messages})+ original = copy.deepcopy(data["data"])++ with pytest.raises(UnappliableRequestRewrite):+ await BedrockPassthroughGuardrailHandler().process_input_messages(+ data, _replying({"structured_messages": rows})+ )++ assert data["data"] == original++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("last_block", "masked_last_block"),+ [+ ({"text": "thanks 4111"}, {"text": "thanks [CARD]"}),+ ({"guardContent": {"text": {"text": "thanks 4111"}}}, {"guardContent": {"text": {"text": "thanks [CARD]"}}}),+ ],+ ids=["text", "guard-content"],+ )+ async def test_row_joined_with_newlines_is_split_back_into_its_blocks(self, last_block, masked_last_block):+ cache_point = {"cachePoint": {"type": "default"}}+ data = _converse_request(+ {"messages": [{"role": "user", "content": [{"text": "card 4111"}, cache_point, last_block]}]}+ )++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(+ data, _replying({"structured_messages": [{"role": "user", "content": "card [CARD]\nthanks [CARD]"}]})+ )++ assert result["data"]["messages"] == [+ {"role": "user", "content": [{"text": "card [CARD]"}, cache_point, masked_last_block]}+ ]++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("content", "blanked", "forwarded"),+ [+ ([{"text": " 4111 1111 1111 1111 "}], " ", [{"text": " "}]),+ (+ [{"text": "card 4111"}, {"cachePoint": {"type": "default"}}],+ "",+ [{"text": ""}, {"cachePoint": {"type": "default"}}],+ ),+ ],+ ids=["whitespace-left", "nothing-left-before-a-cache-point"],+ )+ async def test_turn_the_guardrail_blanks_entirely_is_forwarded_as_written(self, content, blanked, forwarded):+ data = _converse_request({"messages": [{"role": "user", "content": content}]})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(+ data, _replying({"structured_messages": [{"role": "user", "content": blanked}]})+ )++ assert result["data"]["messages"] == [{"role": "user", "content": forwarded}]++ @pytest.mark.asyncio+ async def test_single_block_row_keeps_a_newline_the_guardrail_wrote(self):+ data = _converse_request({"messages": [{"role": "user", "content": [{"text": "card 4111"}]}]})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(+ data, _replying({"structured_messages": [{"role": "user", "content": "card\n[CARD]"}]})+ )++ assert result["data"]["messages"] == [{"role": "user", "content": [{"text": "card\n[CARD]"}]}]++ @pytest.mark.asyncio+ @pytest.mark.parametrize("content", [None, "", []], ids=["none", "empty-string", "empty-list"])+ async def test_tool_call_argument_mask_in_a_row_is_written_back(self, content):+ data = _converse_request({"messages": [_pay_turn(_CARD_TOOL_CALL)]})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(+ data, _replying({"structured_messages": [_pay_row(content=content)]})+ )++ assert result["data"]["messages"] == [_pay_turn({"card": "[CARD]", "tags": ["a"]})]++ @pytest.mark.asyncio+ @pytest.mark.parametrize("role", ["system", "user"])+ async def test_flattened_multi_block_row_is_written_back_block_by_block(self, role):+ blocks = [{"text": "Order details."}, {"text": "card 4111"}]+ hello = {"role": "user", "content": [{"text": "hi"}]}+ body = (+ {"system": blocks, "messages": [hello]}+ if role == "system"+ else {"messages": [hello, {"role": "user", "content": blocks}]}+ )+ flattened = {"role": role, "content": "Order details.\ncard [CARD]"}+ hello_row = {"role": "user", "content": [{"type": "text", "text": "hi"}]}+ rows = [flattened, hello_row] if role == "system" else [hello_row, flattened]+ guardrail = _ScriptedGuardrail(lambda inputs: {"texts": _masked_texts(inputs), "structured_messages": rows})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(_converse_request(body), guardrail)++ written = result["data"]["system"] if role == "system" else result["data"]["messages"][1]["content"]+ assert written == [{"text": "Order details."}, {"text": "card [CARD]"}]++ @pytest.mark.asyncio+ async def test_reshaped_tool_result_row_is_sent_as_one_text_block_where_its_text_parts_were(self):+ image = {"image": {"format": "png", "source": {"bytes": "iVBORw0KGgo="}}}+ tool_result = {"toolUseId": "t1", "content": [image, {"text": "found 4111"}, {"json": {"rows": [1]}}]}+ data = _converse_request({"messages": [{"role": "user", "content": [{"toolResult": tool_result}]}]})+ guardrail = _replying({"structured_messages": [{"role": "tool", "tool_call_id": "t1", "content": "1 row"}]})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ assert result["data"]["messages"][0]["content"] == [+ {"toolResult": {"toolUseId": "t1", "content": [image, {"text": "1 row"}]}}+ ]+++def _card_on_file_data() -> dict:+ return _converse_request(+ {+ "system": [{"text": "Card 4111 on file."}],+ "messages": [{"role": "user", "content": [{"text": "My card is 4111."}]}],+ }+ )+++def _card_rows_masked(inputs: GenericGuardrailAPIInputs) -> list:+ return json.loads(json.dumps(inputs["structured_messages"]).replace("4111", "****"))+++class TestConverseTextsNextToRewrittenRows:+ @pytest.mark.asyncio+ @pytest.mark.parametrize("texts", [[], ["", "My card is ****."]], ids=["no-texts", "texts-emptying-a-row"])+ async def test_texts_without_a_mask_of_their_own_give_way_to_the_rewritten_rows(self, texts):+ guardrail = _ScriptedGuardrail(+ lambda inputs: {"texts": texts, "structured_messages": _card_rows_masked(inputs)}+ )++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(_card_on_file_data(), guardrail)++ assert result["data"] == {+ "system": [{"text": "Card **** on file."}],+ "messages": [{"role": "user", "content": [{"text": "My card is ****."}]}],+ }++ @pytest.mark.asyncio+ async def test_fewer_texts_with_a_mask_the_rows_do_not_hold_fail_closed(self):+ guardrail = _ScriptedGuardrail(+ lambda inputs: {"texts": ["Card [CARD] on file."], "structured_messages": _card_rows_masked(inputs)}+ )++ with pytest.raises(UnappliableRequestRewrite):+ await BedrockPassthroughGuardrailHandler().process_input_messages(_card_on_file_data(), guardrail)+++def _tool_config_data() -> dict:+ lookup = {+ "name": "lookup",+ "description": "Card 4111 on file",+ "inputSchema": {"json": {"type": "object", "properties": {"card": {"type": "string"}}}},+ }+ return _converse_request(+ {+ "messages": [{"role": "user", "content": [{"text": "Card 4111 please"}]}],+ "toolConfig": {+ "tools": [+ {"toolSpec": lookup},+ {"cachePoint": {"type": "default"}},+ {"toolSpec": {"name": "refund", "inputSchema": {"json": {"type": "object"}}}},+ ],+ "toolChoice": {"auto": {}},+ },+ }+ )+++_REFUND = {"toolSpec": {"name": "refund", "inputSchema": {"json": {"type": "object"}}}}+++def _without_the_first_tool(inputs: GenericGuardrailAPIInputs) -> Mapping[str, object]:+ return {"texts": inputs["texts"], "tools": inputs["tools"][1:]}+++def _masked_tools(inputs: GenericGuardrailAPIInputs) -> list:+ return json.loads(json.dumps(inputs["tools"]).replace("4111", "[CARD]"))+++def _converted(name: str, description: str, properties: dict) -> dict:+ schema = {"type": "object", "properties": properties, "required": []}+ return {"toolSpec": {"name": name, "description": description, "inputSchema": {"json": schema}}}+++_CACHE_POINT = {"cachePoint": {"type": "default"}}+_LOOKUP_MASKED = {+ "toolSpec": {+ "name": "lookup",+ "description": "Card [CARD] on file",+ "inputSchema": {"json": {"type": "object", "properties": {"card": {"type": "string"}}}},+ }+}+_RETRIEVE = {"type": "function", "function": {"name": "retrieve", "parameters": {"type": "object"}}}+++class TestConverseToolListRewrites:+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("rewrite", "expected_tools"),+ [+ (lambda tools: tools, [_LOOKUP_MASKED, _CACHE_POINT, _REFUND]),+ (+ lambda tools: [*tools, _RETRIEVE],+ [_LOOKUP_MASKED, _CACHE_POINT, _REFUND, _converted("retrieve", "retrieve", {})],+ ),+ (+ lambda tools: [{**tools[0], "function": {**tools[0]["function"], "name": "lookup_v2"}}, *tools[1:]],+ [_converted("lookup_v2", "Card [CARD] on file", {"card": {"type": "string"}}), _REFUND],+ ),+ (lambda tools: tools[::-1], [_REFUND, _LOOKUP_MASKED, _CACHE_POINT]),+ (+ lambda tools: [{**tool, "function": {**tool["function"], "strict": False}} for tool in tools],+ [+ _converted("lookup", "Card [CARD] on file", {"card": {"type": "string"}}),+ _CACHE_POINT,+ _converted("refund", "refund", {}),+ ],+ ),+ ],+ ids=["masked", "added", "renamed", "reordered", "strict-echoed"],+ )+ async def test_tool_list_bedrock_gets_is_built_from_what_the_guardrail_returned(self, rewrite, expected_tools):+ guardrail = _ScriptedGuardrail(+ lambda inputs: {"texts": _masked_texts(inputs), "tools": rewrite(_masked_tools(inputs))}+ )++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(_tool_config_data(), guardrail)++ assert result["data"]["toolConfig"] == {"tools": expected_tools, "toolChoice": {"auto": {}}}+ assert result["data"]["messages"] == [{"role": "user", "content": [{"text": "Card [CARD] please"}]}]++ @pytest.mark.asyncio+ async def test_removing_the_tool_tool_choice_names_fails_closed_without_mutation(self):+ data = _tool_config_data()+ data["data"]["toolConfig"]["toolChoice"] = {"tool": {"name": "lookup"}}+ original = copy.deepcopy(data["data"])++ with pytest.raises(UnappliableRequestRewrite):+ await BedrockPassthroughGuardrailHandler().process_input_messages(+ data, _ScriptedGuardrail(_without_the_first_tool)+ )++ assert data["data"] == original++ @pytest.mark.asyncio+ async def test_tool_choice_naming_a_kept_tool_survives_the_removal(self):+ data = _tool_config_data()+ data["data"]["toolConfig"]["toolChoice"] = {"tool": {"name": "refund"}}++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(+ data, _ScriptedGuardrail(_without_the_first_tool)+ )++ assert result["data"]["toolConfig"] == {"tools": [_REFUND], "toolChoice": {"tool": {"name": "refund"}}}++ @pytest.mark.asyncio+ async def test_entry_the_guardrail_never_saw_outlives_the_tool_it_followed(self):+ data = _tool_config_data()+ system_tool = {"systemTool": {"name": "nova_grounding"}}+ data["data"]["toolConfig"]["tools"].insert(1, system_tool)++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(+ data, _ScriptedGuardrail(_without_the_first_tool)+ )++ assert result["data"]["toolConfig"] == {"tools": [_REFUND, system_tool], "toolChoice": {"auto": {}}}++ @pytest.mark.asyncio+ async def test_every_tool_removed_reaches_bedrock_without_tool_config_and_with_tool_history_as_text(self):+ data = _tool_config_data()+ data["data"]["messages"] = [+ {+ "role": "assistant",+ "content": [+ {"text": "Checking."},+ {"toolUse": {"toolUseId": "t1", "name": "lookup", "input": {"card": "4111"}}},+ {"toolUse": {"toolUseId": "t2", "name": "refund", "input": {}}},+ ],+ },+ {+ "role": "user",+ "content": [+ {"toolResult": {"toolUseId": "t1", "content": [{"text": "on file"}, {"json": {"status": "4111"}}]}},+ {+ "toolResult": {+ "toolUseId": "t2",+ "content": [{"image": {"format": "png", "source": {"bytes": "iVBO"}}}],+ }+ },+ {"text": "thanks"},+ ],+ },+ ]+ guardrail = _ScriptedGuardrail(lambda inputs: {"texts": _masked_texts(inputs), "tools": []})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ assert result["data"]["toolConfig"] == {"tools": [], "toolChoice": {"auto": {}}}+ assert await _sent_to_bedrock(result) == {+ "messages": [+ {+ "role": "assistant",+ "content": [+ {"text": "Checking."},+ {"text": '[tool call t1: lookup({"card": "[CARD]"})]'},+ {"text": "[tool call t2: refund({})]"},+ ],+ },+ {+ "role": "user",+ "content": [+ {"text": '[tool result for t1: on file\n{"status": "[CARD]"}]'},+ {"text": "[tool result for t2: <non-text tool result omitted>]"},+ {"text": "thanks"},+ ],+ },+ ]+ }++ @pytest.mark.asyncio+ async def test_returned_tool_named_by_a_non_string_fails_closed_without_mutation(self):+ data = _tool_config_data()+ original = copy.deepcopy(data["data"])++ def misnamed(inputs: GenericGuardrailAPIInputs) -> Mapping[str, object]:+ first, *rest = inputs["tools"]+ renamed = {**first, "function": {**first["function"], "name": ["lookup"]}}+ return {"texts": inputs["texts"], "tools": [renamed, *rest]}++ with pytest.raises(UnappliableRequestRewrite):+ await BedrockPassthroughGuardrailHandler().process_input_messages(data, _ScriptedGuardrail(misnamed))++ assert data["data"] == original+++class _CountingName(str):+ """A tool name that records every equality check made on it."""++ checks: ClassVar[list[str]] = []+ __hash__ = str.__hash__++ def __eq__(self, other: object) -> bool:+ self.checks.append(str(self))+ return str.__eq__(self, other)+++def _counted_names(inputs: GenericGuardrailAPIInputs) -> Mapping[str, object]:+ tools = [+ {**tool, "function": {**tool["function"], "name": _CountingName(tool["function"]["name"])}}+ for tool in inputs["tools"]+ ]+ return {"texts": inputs["texts"], "tools": tools}+++class TestConverseRewritesOfWideRequests:+ @pytest.mark.asyncio+ async def test_each_returned_tool_is_matched_to_its_original_by_one_lookup(self):+ tools = [+ {"toolSpec": {"name": f"tool_{index}", "inputSchema": {"json": {"type": "object"}}}}+ for index in range(2_000)+ ]+ data = _converse_request(+ {"messages": [{"role": "user", "content": [{"text": "hi"}]}], "toolConfig": {"tools": tools}}+ )+ sent = copy.deepcopy(data["data"])+ _CountingName.checks.clear()++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(+ data, _ScriptedGuardrail(_counted_names)+ )++ assert result["data"] == sent+ assert len(_CountingName.checks) <= 4 * len(tools)++ @pytest.mark.asyncio+ async def test_row_masks_in_thirty_thousand_request_fields_are_all_written_back(self):+ data = _converse_request(+ {+ "messages": [{"role": "user", "content": [{"text": "hi"}]}],+ "additionalModelRequestFields": {f"field_{index}": "card 4111" for index in range(30_000)},+ }+ )+ guardrail = _ScriptedGuardrail(+ lambda inputs: {"texts": inputs["texts"], "structured_messages": _card_rows_masked(inputs)}+ )+ handler = BedrockPassthroughGuardrailHandler()+ await handler.process_input_messages(_card_on_file_data(), guardrail)++ started = time.perf_counter()+ result = await handler.process_input_messages(data, guardrail)+ elapsed = time.perf_counter() - started++ assert result["data"]["additionalModelRequestFields"] == {+ f"field_{index}": "card ****" for index in range(30_000)+ }+ assert elapsed < 10+++class _ConductPluginGuard(CustomGuardrail):+ def __init__(self, *, guardrail_name: str, unreachable_fallback: str | None = None) -> None:+ super().__init__(guardrail_name=guardrail_name)+ self.unreachable_fallback = unreachable_fallback+++def _conduct_with_its_plugin() -> CustomGuardrail:+ plugin = types.ModuleType("conduct_litellm_guard.guardrail")+ plugin.__dict__.update(ConductGuard=_ConductPluginGuard, ConductGuardBlocked=RuntimeError)+ spec = importlib.util.spec_from_file_location("conduct_with_its_plugin", conduct_module.__file__)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ with patch.dict(+ sys.modules,+ {"conduct_litellm_guard": types.ModuleType("conduct_litellm_guard"), "conduct_litellm_guard.guardrail": plugin},+ ):+ spec.loader.exec_module(module)+ guardrail = vars(module)["ConductGuardrail"](guardrail_name="conduct")+ assert isinstance(guardrail, CustomGuardrail)+ return guardrail+++_FLAT_TEXT_READERS: tuple[Callable[[], CustomGuardrail], ...] = (+ lambda: OpenAIModerationGuardrail(guardrail_name="moderation", api_key="sk-test"),+ lambda: LLMAsAJudgeGuardrail(+ guardrail_name="judge", judge_model="gpt-judge", criteria=[{"name": "safe", "description": "is safe"}]+ ),+ lambda: CrowdStrikeAIDRHandler(guardrail_name="crowdstrike", api_key="cs-test", api_base="http://127.0.0.1:9"),+ lambda: PromptSecurityGuardrail(guardrail_name="prompt-security", api_key="ps-test", api_base="http://127.0.0.1:9"),+ lambda: PanwPrismaAirsHandler(+ guardrail_name="panw", profile_name="default", api_key="panw-test", api_base="http://127.0.0.1:9"+ ),+ lambda: HiddenlayerGuardrail(guardrail_name="hiddenlayer", api_base="http://127.0.0.1:9"),+ lambda: HiddenlayerGuardrailV2(guardrail_name="hiddenlayer-v2", api_base="http://127.0.0.1:9"),+ lambda: BedrockGuardrail(+ guardrail_name="bedrock",+ guardrailIdentifier="gr-test",+ guardrailVersion="DRAFT",+ experimental_use_latest_role_message_only=True,+ ),+ lambda: AktoGuardrail(akto_base_url="http://127.0.0.1:9", akto_api_key="akto-test", guardrail_name="akto"),+ lambda: PromptGuardGuardrail(guardrail_name="promptguard", api_key="pg-test", api_base="http://127.0.0.1:9"),+ lambda: SingulrGuardrail(+ guardrail_name="singulr",+ singulr_api_key="singulr-test",+ singulr_api_base="http://127.0.0.1:9",+ singulr_application_id="app-test",+ singulr_guardrail_id="gr-test",+ ),+ lambda: QualifireGuardrail(+ guardrail_name="qualifire", api_key="qf-test", api_base="http://127.0.0.1:9", evaluation_id="eval-test"+ ),+ _conduct_with_its_plugin,+ lambda: AiriaGuardrail(guardrail_name="airia", api_key="airia-test", api_base="http://127.0.0.1:9"),+)+++def _card_in_every_turn_data() -> dict:+ data = _tool_config_data()+ data["data"].update(+ {+ "system": [{"text": "Billing card 4111 1111 1111 1111."}],+ "messages": [+ {"role": "user", "content": [{"text": "My card is 4111 1111 1111 1111."}]},+ {+ "role": "assistant",+ "content": [+ {"toolUse": {"toolUseId": "t1", "name": "pay", "input": {"card": "4111 1111 1111 1111"}}}+ ],+ },+ {+ "role": "user",+ "content": [+ {"toolResult": {"toolUseId": "t1", "content": [{"text": "paid with 4111 1111 1111 1111"}]}},+ {"text": "Thanks, what next?"},+ ],+ },+ ],+ "additionalModelRequestFields": {"system": "Answer briefly."},+ }+ )+ return data+++class _FlatTextsOnlyGuardrail(_ScriptedGuardrail):+ def supports_structured_messages(self) -> bool:+ return False+++class TestConverseGuardrailsThatReadFlatTextsOnly:+ @pytest.mark.parametrize(+ "make_guardrail",+ _FLAT_TEXT_READERS,+ ids=[+ "openai-moderation",+ "llm-as-a-judge",+ "crowdstrike-aidr",+ "prompt-security",+ "panw-prisma-airs",+ "hiddenlayer",+ "hiddenlayer-v2",+ "bedrock-latest-user",+ "akto",+ "promptguard",+ "singulr",+ "qualifire",+ "conduct",+ "airia",+ ],+ )+ def test_guardrail_opts_out_of_converse_rows_and_tools(self, make_guardrail):+ assert make_guardrail().supports_structured_messages() is False++ @pytest.mark.asyncio+ async def test_headroom_gets_no_rows_so_it_never_calls_its_service(self):+ data = _card_in_every_turn_data()+ sent = copy.deepcopy(data["data"])++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(+ data, HeadroomGuardrail(api_base="http://127.0.0.1:9", guardrail_name="headroom")+ )++ assert result["data"] == sent++ @pytest.mark.asyncio+ async def test_flat_texts_only_guardrail_gets_main_flat_texts_and_its_mask_reaches_every_turn(self):+ guardrail = _FlatTextsOnlyGuardrail(lambda inputs: {"texts": _masked_texts(inputs)})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(+ _card_in_every_turn_data(), guardrail+ )++ assert guardrail.received[-1] == {+ "texts": [+ "Billing card 4111 1111 1111 1111.",+ "My card is 4111 1111 1111 1111.",+ "4111 1111 1111 1111",+ "paid with 4111 1111 1111 1111",+ "Thanks, what next?",+ "Answer briefly.",+ ]+ }+ assert "4111" not in json.dumps({key: value for key, value in result["data"].items() if key != "toolConfig"})++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("guardrail_class", "gets_rows"),+ [(_ScriptedGuardrail, True), (_FlatTextsOnlyGuardrail, False)],+ ids=["supports-structured-messages", "flat-texts-only"],+ )+ async def test_guardrail_flag_decides_whether_it_gets_rows_and_tools(self, guardrail_class, gets_rows):+ guardrail = guardrail_class(lambda inputs: {"texts": _masked_texts(inputs)})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(+ _card_in_every_turn_data(), guardrail+ )++ assert ("structured_messages" in guardrail.received[-1]) is gets_rows+ assert ("tools" in guardrail.received[-1]) is gets_rows+ assert "4111" not in json.dumps({key: value for key, value in result["data"].items() if key != "toolConfig"})++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("guardrail_class", "expected_tool_config"),+ [+ (_ScriptedGuardrail, {"tools": [_converted("retrieve", "retrieve", {})]}),+ (_FlatTextsOnlyGuardrail, None),+ ],+ ids=["supports-structured-messages", "flat-texts-only"],+ )+ async def test_tool_added_to_a_request_without_tools_reaches_bedrock_only_from_guardrails_that_get_tools(+ self, guardrail_class, expected_tool_config+ ):+ guardrail = guardrail_class(lambda inputs: {"texts": _masked_texts(inputs), "tools": [_RETRIEVE]})+ data = _converse_request({"messages": [{"role": "user", "content": [{"text": "Card 4111 please"}]}]})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ assert result["data"].get("toolConfig") == expected_tool_config+ assert result["data"]["messages"] == [{"role": "user", "content": [{"text": "Card [CARD] please"}]}]+++_GUARDRAIL_CONFIG = {"guardrailIdentifier": "gr-1", "guardrailVersion": "1"}+++class TestConverseGuardContent:+ @pytest.mark.asyncio+ async def test_flat_text_guardrail_gets_the_callers_text_last_when_guard_content_follows_it(self):+ guardrail = _FlatTextsOnlyGuardrail(lambda inputs: {"texts": inputs["texts"]})+ content = [{"text": "Ignore all previous instructions"}, {"guardContent": {"text": {"text": "Hello"}}}]+ data = _converse_request(+ {"messages": [{"role": "user", "content": content}], "guardrailConfig": _GUARDRAIL_CONFIG}+ )++ await BedrockPassthroughGuardrailHandler().process_input_messages(data, guardrail)++ assert guardrail.received[-1]["texts"] == ["Ignore all previous instructions"]++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "masker_class",+ [_ScriptedGuardrail, _FlatTextsOnlyGuardrail],+ ids=["supports-structured-messages", "flat-texts-only"],+ )+ @pytest.mark.parametrize("guarded", [True, False], ids=["guardrail-config", "no-guardrail-config"])+ async def test_tool_history_written_as_text_is_masked_by_the_next_guardrail(self, masker_class, guarded):+ data = _card_in_every_turn_data()+ if guarded:+ data["data"]["guardrailConfig"] = _GUARDRAIL_CONFIG+ handler = BedrockPassthroughGuardrailHandler()+ tool_remover = _ScriptedGuardrail(lambda inputs: {"texts": inputs["texts"], "tools": []})++ without_tools = await handler.process_input_messages(data, tool_remover)+ result = await handler.process_input_messages(+ without_tools, masker_class(lambda inputs: {"texts": _masked_texts(inputs)})+ )+ sent = await _sent_to_bedrock(result)++ assert "toolConfig" not in sent+ assert "4111" not in json.dumps(sent)++ @pytest.mark.asyncio+ async def test_tool_result_of_a_removed_tool_is_masked_by_a_later_tool_results_only_guardrail(self):+ data = _converse_request(+ {+ "messages": [+ {"role": "user", "content": [{"text": "look up my order"}]},+ {+ "role": "assistant",+ "content": [{"toolUse": {"toolUseId": "t1", "name": "lookup", "input": {"q": "7"}}}],+ },+ {+ "role": "user",+ "content": [+ {"toolResult": {"toolUseId": "t1", "content": [{"text": "card on file 4111"}]}},+ {"text": "summarize that"},+ ],+ },+ ],+ "toolConfig": {+ "tools": [{"toolSpec": {"name": "lookup", "inputSchema": {"json": {"type": "object"}}}}]+ },+ }+ )+ handler = BedrockPassthroughGuardrailHandler()+ tool_remover = _ScriptedGuardrail(lambda inputs: {"texts": inputs["texts"], "tools": []})+ results_masker = _ScriptedGuardrail(lambda inputs: {"texts": _masked_texts(inputs)}, scan_only_tool_results=True)++ without_tools = await handler.process_input_messages(data, tool_remover)+ result = await handler.process_input_messages(without_tools, results_masker)++ assert results_masker.received[-1]["texts"] == ["card on file 4111"]+ assert (await _sent_to_bedrock(result))["messages"][-1] == {+ "role": "user",+ "content": [{"text": "[tool result for t1: card on file [CARD]]"}, {"text": "summarize that"}],+ }++ @pytest.mark.asyncio+ async def test_tool_history_written_as_text_adds_no_guard_content_block(self):+ data = _card_in_every_turn_data()+ data["data"]["guardrailConfig"] = _GUARDRAIL_CONFIG+ tool_remover = _ScriptedGuardrail(lambda inputs: {"texts": inputs["texts"], "tools": []})++ result = await BedrockPassthroughGuardrailHandler().process_input_messages(data, tool_remover)+ sent = await _sent_to_bedrock(result)++ blocks = tuple(chain.from_iterable(message["content"] for message in sent["messages"]))+ assert all(block.keys() == {"text"} for block in blocks), (+ "a guardContent block makes Bedrock's own guardrail skip every plain text block",+ blocks,+ )++def _decoded_frames(raw: bytes) -> list[tuple[str, str, dict]]:import jsonfrom botocore.eventstream import EventStreamBufferdiff --git a/tests/unit/proxy/policy_engine/test_pipeline_executor.py b/tests/unit/proxy/policy_engine/test_pipeline_executor.pyindex 8dbab66ff3d..c42878bd4f7 100644--- a/tests/unit/proxy/policy_engine/test_pipeline_executor.py+++ b/tests/unit/proxy/policy_engine/test_pipeline_executor.py@@ -15,6 +15,7 @@ import pytestimport litellmfrom litellm.caching.dual_cache import DualCachefrom litellm.integrations.custom_guardrail import CustomGuardrail+from litellm.llms.base_llm.guardrail_translation.utils import UnappliableRequestRewritefrom litellm.proxy._types import UserAPIKeyAuthfrom litellm.proxy.guardrails.guardrail_hooks.custom_code.custom_code_guardrail import (CustomCodeGuardrail,@@ -61,6 +62,25 @@ class AlwaysFailGuardrail(CustomGuardrail):raise HTTPException(status_code=400, detail="Content policy violation")+class UnappliableRewriteGuardrail(CustomGuardrail):+ """Raises the error an endpoint translation raises for a rewrite it cannot apply."""++ def __init__(self, guardrail_name: str):+ super().__init__(+ guardrail_name=guardrail_name,+ event_hook="pre_call",+ default_on=True,+ )+ self.calls = 0++ def should_run_guardrail(self, data, event_type) -> bool:+ return True++ async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):+ self.calls += 1+ raise UnappliableRequestRewrite(self.guardrail_name)++class HttpStatusGuardrail(CustomGuardrail):"""Raises HTTPException with a configurable status (e.g. 503 for API outage)."""@@ -795,6 +815,38 @@ async def test_on_error_next_fallback_on_api_outage_on_fail_blocks_content(monkeassert result.step_results[1].outcome == "pass"+ "on_fail, on_error",+ [("block", "allow"), ("next", "block"), ("allow", "block"), ("allow", "allow"), ("next", "next"), ("next", None)],+)+async def test_unappliable_rewrite_blocks_whatever_on_fail_and_on_error_say(monkeypatch, on_fail, on_error):+ """+ A rewrite the endpoint cannot apply blocks the pipeline, so no on_fail or on_error action sends the original request on.+ """+ rewriter = UnappliableRewriteGuardrail("rewriter")+ later = AlwaysPassGuardrail("later-step")+ monkeypatch.setattr(litellm, "callbacks", [rewriter, later])++ result = await PipelineExecutor.execute_steps(+ steps=[+ PipelineStep(guardrail="rewriter", on_pass="next", on_fail=on_fail, on_error=on_error),+ PipelineStep(guardrail="later-step", on_pass="allow", on_fail="block"),+ ],+ mode="pre_call",+ data={"messages": [{"role": "user", "content": "card 4111 1111 1111 1111"}]},+ user_api_key_dict=MagicMock(),+ call_type="completion",+ policy_name="rewrite-policy",+ )++ assert rewriter.calls == 1+ assert later.calls == 0+ assert result.terminal_action == "block"+ assert result.step_results[0].action_taken == "block"+ assert isinstance(result.original_exception, UnappliableRequestRewrite)++@pytest.mark.skipif(HTTPException is None, reason="fastapi not installed")@pytest.mark.asyncioasync def test_on_fail_next_on_content_on_error_block_stops_api_fallback(monkeypatch):