Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Merge origin/litellm_internal_staging into litellm_fix_anthropic_midturn_interjections

mateo-berri78dd81c014de
diff --cc litellm/llms/anthropic/chat/guardrail_translation/handler.py
index 82707e741c0,88db9fae912..3747e03660d
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@@ -13,8 -13,11 +13,12 @@@ Pattern Overview
"""
import json
+ from collections.abc import Mapping
+from copy import deepcopy
- from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, cast
+ from dataclasses import dataclass
+ from typing import TYPE_CHECKING, Any, Final, cast
+
+ from typing_extensions import assert_never
from litellm._logging import verbose_proxy_logger
from litellm.llms.anthropic.chat.transformation import AnthropicConfig
@@@ -58,11 -65,59 +66,55 @@@ if TYPE_CHECKING
)
+ @dataclass(frozen=True, slots=True)
+ class MessageContentTarget:
+ msg_idx: int
+
+
+ @dataclass(frozen=True, slots=True)
+ class ContentBlockTextTarget:
+ msg_idx: int
+ content_idx: int
+
+
+ @dataclass(frozen=True, slots=True)
+ class ToolResultStringTarget:
+ msg_idx: int
+ content_idx: int
+
+
+ @dataclass(frozen=True, slots=True)
+ class ToolResultBlockTextTarget:
+ msg_idx: int
+ content_idx: int
+ block_idx: int
+
+
+ InputWriteBackTarget = (
+ MessageContentTarget | ContentBlockTextTarget | ToolResultStringTarget | ToolResultBlockTextTarget
+ )
+
+
+ @dataclass(frozen=True, slots=True)
+ class ScannedText:
+ text: str
+ target: InputWriteBackTarget
+
+
+ @dataclass(frozen=True, slots=True)
+ class ExtractedInput:
+ scanned: tuple[ScannedText, ...]
+ images: tuple[str, ...]
+
+
+ EMPTY_EXTRACTED_INPUT: Final = ExtractedInput(scanned=(), images=())
+
+
class AnthropicMessagesHandler(BaseTranslation):
- """
- Handler for processing Anthropic messages with guardrails.
-
- This class provides methods to:
- 1. Process input messages (pre-call hook)
- 2. Process output responses (post-call hook)
+ """Process Anthropic messages with guardrails.
- Methods can be overridden to customize behavior for different message formats.
+ In-sequence system entries are untrusted client input. This handler scans and preserves
+ them through guardrail rewrites; downstream provider handling is out of scope.
"""
def __init__(self):
@@@ -272,39 -327,30 +324,44 @@@
if messages is None:
return data
- skip_system = effective_skip_system_message_for_guardrail(guardrail_to_apply)
- skip_tool = effective_skip_tool_message_for_guardrail(guardrail_to_apply)
+ skip_system: Final = effective_skip_system_message_for_guardrail(guardrail_to_apply)
+ skip_tool: Final = effective_skip_tool_message_for_guardrail(guardrail_to_apply)
+ scan_only_tool_results: Final = effective_scan_only_tool_results_for_guardrail(guardrail_to_apply)
- chat_completion_compatible_request: Final = self._translate_to_openai(data)
+ # Exclude only the trusted top-level prompt. In-sequence system entries are untrusted
+ # and must stay aligned with texts_to_check for positional masking. When the top-level
+ # prompt is included, the pre-existing count mismatch disables positional masking.
- translation_source = { # mutable-ok: API message payload
++ translation_source: Final = { # mutable-ok: API message payload
+ key: value for key, value in data.items() if key != "system"
- } # mutable-ok: API message payload
- chat_completion_compatible_request = self._translate_to_openai(translation_source)
++ }
++ chat_completion_compatible_request: Final = self._translate_to_openai(translation_source)
- structured_messages = cast(
- List[AllMessageValues],
+ full_structured_messages: Final = cast(
+ list[AllMessageValues],
chat_completion_compatible_request.get("messages", []),
)
- has_midturn_system_message = any(
- str(message.get("role") or "").lower() == "system" for message in structured_messages
++ has_midturn_system_message: Final = any(
++ str(message.get("role") or "").lower() == "system" for message in full_structured_messages
++ )
++ hoisted_system_message: Final = None if skip_system else self._hoisted_top_level_system_message(data)
++ if hoisted_system_message is not None:
++ full_structured_messages.insert(0, hoisted_system_message)
++ # skip_system already excluded the trusted top-level prompt (it is simply not hoisted);
++ # in-sequence system entries are untrusted and always stay in scope.
+ scoped_message_indices: Final = scoped_structured_message_indices(
+ full_structured_messages,
+ scan_only_tool_results=scan_only_tool_results,
- skip_system=skip_system,
++ skip_system=False,
+ skip_tool=skip_tool,
+ )
+ structured_messages: Final = [full_structured_messages[index] for index in scoped_message_indices]
+
+ tools_to_check: Final[list[ChatCompletionToolParam]] = (
+ [] if scan_only_tool_results else chat_completion_compatible_request.get("tools", [])
)
- hoisted_system_message: AllMessageValues | None = None
- if not skip_system:
- hoisted_system_message = self._hoisted_top_level_system_message(data)
- if hoisted_system_message is not None:
- structured_messages.insert(0, hoisted_system_message)
- if skip_tool:
- structured_messages = openai_messages_without_tool(structured_messages)
-
- texts_to_check: List[str] = []
- images_to_check: List[str] = []
- tools_to_check: List[ChatCompletionToolParam] = chat_completion_compatible_request.get("tools", [])
- task_mappings: List[Tuple[int, Optional[int]]] = []
# Step 1: Extract all text content and images
- for msg_idx, message in enumerate(messages):
+ extracted: Final = tuple(
self._extract_input_text_and_images(
message=message,
msg_idx=msg_idx,
@@@ -356,9 -415,13 +426,15 @@@
):
self._write_back_structured_messages(
data,
- guardrailed_structured_messages,
+ guardrailed_structured_messages
+ if guardrail_to_apply.structured_messages_cover_full_request()
+ else merge_guardrailed_scoped_messages(
+ full_messages=full_structured_messages,
+ scoped_indices=scoped_message_indices,
+ guardrailed_scoped=guardrailed_structured_messages,
+ ),
+ hoisted_system_message=hoisted_system_message,
+ preserve_system_messages=has_midturn_system_message,
)
else:
# Step 3: Map guardrail responses back to original message structure
@@@ -372,120 -435,36 +448,114 @@@
return data
+ def _hoisted_top_level_system_message(
+ self, data: dict
+ ) -> AllMessageValues | None: # mutable-ok: API message payload
+ """Return the system message produced by translating the top-level prompt."""
- system = data.get("system")
++ system: Final = data.get("system")
+ if not system:
+ return None
- probe = self._translate_to_openai(
++ probe: Final = self._translate_to_openai(
+ { # mutable-ok: API message payload
+ "model": data.get("model") or "",
+ "messages": [], # mutable-ok: API message payload
+ "system": system,
+ }
+ )
- hoisted = probe.get("messages") or [] # mutable-ok: API message payload
++ hoisted: Final = probe.get("messages") or [] # mutable-ok: API message payload
+ return hoisted[0] if hoisted else None
+
@staticmethod
- def _write_back_structured_messages(data: dict, structured_messages: list) -> None:
- """Convert compressed structured_messages back to Anthropic format and write to data.
-
- ``anthropic_messages_pt`` merges every run of consecutive user/tool rows
- into a single message, so a turn carrying only tool results and the user
- turn that follows it come back fused, and the request the model sees no
- longer has the boundaries the client sent. Converting a row at a time
- would keep them apart but breaks tool pairing: an assistant row whose
- tool results sit outside its own call reads as an orphaned tool call,
- and under ``modify_params`` the sanitizer answers it with a synthetic
- "tool execution skipped" result and drops the real one. Converting each
- assistant row together with the tool rows that answer it, and every
- other row on its own, satisfies both.
- """
+ def _openai_system_message_to_anthropic(
+ message: dict[str, Any],
+ ) -> dict[str, Any] | None: # mutable-ok: API message payload
+ """Convert an OpenAI system message to the client's Anthropic-shaped entry."""
- content = message.get("content")
++ content: Final = message.get("content")
+ if isinstance(content, str):
+ return (
+ {"role": "system", "content": content} if content else None # mutable-ok: API message payload
+ ) # mutable-ok: API message payload
+ if not isinstance(content, list):
+ return None
- blocks: list[dict[str, Any]] = [] # mutable-ok: API message payload
++ blocks: Final[list[dict[str, Any]]] = [] # mutable-ok: API message payload
+ for block in content:
+ if not isinstance(block, dict) or block.get("type") != "text":
+ continue
+ text = block.get("text")
+ if not isinstance(text, str) or not text:
+ continue
+ anthropic_block: dict[str, Any] = { # mutable-ok: API message payload
+ "type": "text",
+ "text": text,
+ } # mutable-ok: API message payload
+ cache_control = block.get("cache_control")
+ if cache_control:
+ anthropic_block["cache_control"] = deepcopy(cache_control)
+ blocks.append(anthropic_block)
+ return (
+ {"role": "system", "content": blocks} if blocks else None # mutable-ok: API message payload
+ ) # mutable-ok: API message payload
+
+ @staticmethod
- def _is_hoisted_top_level_system(message: Any, hoisted_system_message: Any) -> bool:
++ def _is_hoisted_top_level_system(message: object, hoisted_system_message: object) -> bool:
+ """Match the hoisted prompt by identity, or by value after serialization."""
+ if hoisted_system_message is None:
+ return False
+ if message is hoisted_system_message:
+ return True
+ return (
+ isinstance(message, dict) and isinstance(hoisted_system_message, dict) and message == hoisted_system_message
+ )
+
+ @staticmethod
+ def _write_back_structured_messages(
+ data: dict, # mutable-ok: API message payload
+ structured_messages: list, # mutable-ok: API message payload
- hoisted_system_message: Any = None,
++ hoisted_system_message: object = None,
+ preserve_system_messages: bool = False,
+ ) -> None:
+ """Write a guardrail's structured-message rewrite back without losing corrections."""
from litellm.litellm_core_utils.prompt_templates.factory import (
anthropic_messages_pt,
group_tool_exchanges,
)
- def _is_system(message: Any) -> bool:
++ def _is_system(message: object) -> bool:
+ return isinstance(message, dict) and str(message.get("role") or "").lower() == "system"
+
- model = str(data.get("model") or "")
- converted: list = [] # mutable-ok: API message payload
+ model: Final = str(data.get("model") or "")
- non_system: Final = [m for m in structured_messages if m.get("role") != "system"]
- groups: Final = tuple([non_system[index] for index in group] for group in group_tool_exchanges(non_system)) or (
- non_system,
- )
- converted: Final = [
- message
- for group in groups
- for message in anthropic_messages_pt(messages=group, model=model, llm_provider="anthropic")
- ]
++ converted: Final[list] = [] # mutable-ok: API message payload
+
+ def _convert_run(run: list) -> None: # mutable-ok: API message payload
+ for group in group_tool_exchanges(run):
+ converted.extend(
+ anthropic_messages_pt(
- messages=[ # mutable-ok: API message payload
- run[index] for index in group
- ], # mutable-ok: API message payload
++ messages=[run[index] for index in group], # mutable-ok: API message payload
+ model=model,
+ llm_provider="anthropic",
+ )
+ )
+
- run: list = [] # mutable-ok: API message payload
- hoisted_dropped = False
++ run: Final[list] = [] # mutable-ok: API message payload
++ hoisted_dropped = False # rebind-ok: flips once the hoisted prompt is dropped
+ for message in structured_messages:
+ if not _is_system(message):
+ run.append(message)
+ continue
+ _convert_run(run)
- run = [] # mutable-ok: API message payload
++ run.clear()
+ if not hoisted_dropped and AnthropicMessagesHandler._is_hoisted_top_level_system(
+ message, hoisted_system_message
+ ):
+ hoisted_dropped = True
+ continue
+ if preserve_system_messages:
+ anthropic_system = AnthropicMessagesHandler._openai_system_message_to_anthropic(message)
+ if anthropic_system is not None:
+ converted.append(anthropic_system)
+ _convert_run(run)
+ if not any(not _is_system(message) for message in converted):
- converted.extend(
- anthropic_messages_pt(
- messages=[], model=model, llm_provider="anthropic"
- ) # mutable-ok: API message payload
- ) # mutable-ok: API message payload
++ converted.extend(anthropic_messages_pt(messages=[], model=model, llm_provider="anthropic"))
for msg in converted:
content = msg.get("content")
if isinstance(content, list):
@@@ -494,105 -473,118 +564,149 @@@
block.pop("cache_control", None)
data["messages"] = converted
+ @staticmethod
+ def _extract_midturn_system_text(
+ message: dict[str, Any], # mutable-ok: API message payload
+ msg_idx: int,
- texts_to_check: list[str], # mutable-ok: API message payload
- task_mappings: list[tuple[int, int | None]], # mutable-ok: API message payload
- ) -> None:
- content = message.get("content")
++ ) -> ExtractedInput:
++ """Match the adapter's filtering so positional guardrail write-back stays aligned."""
++ content: Final = message.get("content")
+ if isinstance(content, str):
- if content:
- texts_to_check.append(content)
- task_mappings.append((msg_idx, None))
- return
++ if not content:
++ return EMPTY_EXTRACTED_INPUT
++ return ExtractedInput(scanned=(ScannedText(content, MessageContentTarget(msg_idx)),), images=())
+ if not isinstance(content, list):
- return
- for content_idx, content_item in enumerate(content):
- if not isinstance(content_item, dict) or content_item.get("type") != "text":
- continue
- text_str = content_item.get("text")
- if isinstance(text_str, str) and text_str:
- texts_to_check.append(text_str)
- task_mappings.append((msg_idx, content_idx))
++ return EMPTY_EXTRACTED_INPUT
++ return ExtractedInput(
++ scanned=tuple(
++ ScannedText(text_str, ContentBlockTextTarget(msg_idx, content_idx))
++ for content_idx, content_item in enumerate(content)
++ if isinstance(content_item, dict)
++ and content_item.get("type") == "text"
++ and isinstance(text_str := content_item.get("text"), str)
++ and text_str
++ ),
++ images=(),
++ )
+
- def extract_request_tool_names(self, data: dict) -> List[str]:
+ def extract_request_tool_names(self, data: dict) -> list[str]:
"""Extract tool names from Anthropic messages request (tools[].name)."""
- names: List[str] = []
+ names: Final[list[str]] = []
for tool in data.get("tools") or []:
if isinstance(tool, dict) and tool.get("name"):
names.append(str(tool["name"]))
return names
+ @classmethod
def _extract_input_text_and_images(
- self,
- message: Dict[str, Any],
+ cls,
+ message: dict[str, Any],
msg_idx: int,
- texts_to_check: List[str],
- images_to_check: List[str],
- task_mappings: List[Tuple[int, Optional[int]]],
skip_system_message: bool = False,
skip_tool_message: bool = False,
- ) -> None:
- """Extract text content and images from a message."""
- role = str(message.get("role") or "")
+ scan_only_tool_results: bool = False,
+ ) -> ExtractedInput:
++ """Extract text content and images from a message.
++
++ In-sequence system entries are scanned even when ``skip_system_message`` is set:
++ that flag covers only the trusted top-level prompt, which never appears here.
+ """
- Extract text content and images from a message.
- """
- role: Final = str(message.get("role") or "").lower()
- if (skip_system_message and role == "system") or (skip_tool_message and role == "tool"):
++ role: Final = str(message.get("role") or "")
+ if role == "system":
- # Match the adapter's filtering so positional guardrail write-back stays aligned.
- self._extract_midturn_system_text(
- message=message,
++ if scan_only_tool_results:
++ return EMPTY_EXTRACTED_INPUT
++ return cls._extract_midturn_system_text(message=message, msg_idx=msg_idx)
++ if skip_tool_message and role.lower() == "tool":
+ return EMPTY_EXTRACTED_INPUT
+
+ content: Final = message.get("content", None)
+ if isinstance(content, str):
+ if scan_only_tool_results:
+ return EMPTY_EXTRACTED_INPUT
+ return ExtractedInput(scanned=(ScannedText(content, MessageContentTarget(msg_idx)),), images=())
+ if not isinstance(content, list):
+ return EMPTY_EXTRACTED_INPUT
+
+ blocks: Final = tuple(
+ cls._extract_content_block(
+ content_item=content_item,
msg_idx=msg_idx,
- texts_to_check=texts_to_check,
- task_mappings=task_mappings,
+ content_idx=content_idx,
+ skip_tool_message=skip_tool_message,
+ scan_only_tool_results=scan_only_tool_results,
)
- return
- if skip_tool_message and role.lower() == "tool":
- return
-
- content = message.get("content", None)
- tools = message.get("tools", None)
- if content is None and tools is None:
- return
-
- ## CHECK FOR TEXT + IMAGES
- if content is not None and isinstance(content, str):
- # Simple string content
- texts_to_check.append(content)
- task_mappings.append((msg_idx, None))
-
- elif content is not None and isinstance(content, list):
- # List content (e.g., multimodal with text and images)
- for content_idx, content_item in enumerate(content):
- # Extract text
- text_str = content_item.get("text", None)
- if text_str is not None:
- texts_to_check.append(text_str)
- task_mappings.append((msg_idx, int(content_idx)))
-
- # Extract images
- if content_item.get("type") == "image":
- source = content_item.get("source", {})
- if isinstance(source, dict):
- # Could be base64 or url
- data = source.get("data")
- if data:
- images_to_check.append(data)
-
- def _extract_input_tools(
- self,
- tools: List[Dict[str, Any]],
- tools_to_check: List[ChatCompletionToolParam],
- ) -> None:
- """
- Extract tools from a message.
- """
- ## CHECK FOR TOOLS
- if tools is not None and isinstance(tools, list):
- # TRANSFORM ANTHROPIC TOOLS TO OPENAI TOOLS
- openai_tools = self.adapter.translate_anthropic_tools_to_openai(
- tools=cast(List[AllAnthropicToolsValues], tools)
+ for content_idx, content_item in enumerate(content)
+ if isinstance(content_item, dict)
+ )
+ return ExtractedInput(
+ scanned=tuple(item for block in blocks for item in block.scanned),
+ images=tuple(image for block in blocks for image in block.images),
+ )
+
+ @classmethod
+ def _extract_content_block(
+ cls,
+ content_item: Mapping[str, Any],
+ msg_idx: int,
+ content_idx: int,
+ skip_tool_message: bool,
+ scan_only_tool_results: bool = False,
+ ) -> ExtractedInput:
+ if content_item.get("type") == "tool_result":
+ if skip_tool_message:
+ return EMPTY_EXTRACTED_INPUT
+ return cls._extract_tool_result(content_item=content_item, msg_idx=msg_idx, content_idx=content_idx)
+
+ if scan_only_tool_results:
+ return EMPTY_EXTRACTED_INPUT
+
+ text_str: Final = content_item.get("text", None)
+ return ExtractedInput(
+ scanned=(
+ () if text_str is None else (ScannedText(text_str, ContentBlockTextTarget(msg_idx, content_idx)),)
+ ),
+ images=cls._image_sources(content_item) if content_item.get("type") == "image" else (),
+ )
+
+ @classmethod
+ def _extract_tool_result(
+ cls,
+ content_item: Mapping[str, Any],
+ msg_idx: int,
+ content_idx: int,
+ ) -> ExtractedInput:
+ tool_result_content: Final = content_item.get("content")
+
+ if isinstance(tool_result_content, str):
+ return ExtractedInput(
+ scanned=(ScannedText(tool_result_content, ToolResultStringTarget(msg_idx, content_idx)),),
+ images=(),
)
- tools_to_check.extend(openai_tools) # type: ignore
+ if not isinstance(tool_result_content, list):
+ return EMPTY_EXTRACTED_INPUT
+
+ blocks: Final = tuple(
+ (block_idx, block) for block_idx, block in enumerate(tool_result_content) if isinstance(block, dict)
+ )
+ return ExtractedInput(
+ scanned=tuple(
+ ScannedText(block["text"], ToolResultBlockTextTarget(msg_idx, content_idx, block_idx))
+ for block_idx, block in blocks
+ if isinstance(block.get("text"), str)
+ ),
+ images=tuple(
+ image for _, block in blocks if block.get("type") == "image" for image in cls._image_sources(block)
+ ),
+ )
+
+ @staticmethod
+ def _image_sources(block: Mapping[str, Any]) -> tuple[str, ...]:
+ source: Final = block.get("source")
+ if not isinstance(source, Mapping):
+ return ()
+ # Could be base64 or url
+ data: Final = source.get("data")
+ return (data,) if data else ()
async def _apply_guardrail_responses_to_input(
self,
diff --cc litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
index 707d53e9006,22f9bfd30ea..92a32cafde3
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
@@@ -354,19 -343,14 +343,19 @@@ class LiteLLMAnthropicMessagesAdapter
def translate_anthropic_messages_to_openai(
self,
- messages: List[AllAnthropicPassThroughMessageValues], # mutable-ok: API message payload
- model: Optional[str] = None,
- ) -> List:
- new_messages: List[AllMessageValues] = []
- messages: list[AnthropicMessagesUserMessageParam | AnthopicMessagesAssistantMessageParam],
++ messages: list[AllAnthropicPassThroughMessageValues],
+ model: str | None = None,
+ ) -> list:
+ new_messages: Final[list[AllMessageValues]] = []
for m in messages:
- user_message: Optional[ChatCompletionUserMessage] = None
- tool_message_list: List[ChatCompletionToolMessage] = []
- new_user_content_list: List[Union[ChatCompletionTextObject, ChatCompletionImageObject]] = []
+ user_message: ChatCompletionUserMessage | None = None
+ tool_message_list: list[ChatCompletionToolMessage] = []
+ new_user_content_list: list[ChatCompletionTextObject | ChatCompletionImageObject] = []
+ if m["role"] == "system":
+ system_message = self._translate_midturn_system_message_to_openai(m, model)
+ if system_message is not None:
+ new_messages.append(system_message)
+ continue
## USER MESSAGE ##
if m["role"] == "user":
## translate user message
@@@ -867,32 -848,9 +853,32 @@@
for def_schema in schema[key].values():
LiteLLMAnthropicMessagesAdapter._add_additional_properties_false(def_schema)
+ def _translate_midturn_system_message_to_openai(
+ self,
+ message: AnthropicMessagesSystemMessageParam,
+ model: str | None,
+ ) -> ChatCompletionSystemMessage | None:
+ """Translate an in-sequence system entry without changing its role or position."""
- content = message.get("content")
++ content: Final = message.get("content")
+ if isinstance(content, str):
+ return ChatCompletionSystemMessage(role="system", content=content) if content else None
+ if not isinstance(content, list):
+ return None
- text_parts: list[ChatCompletionTextObject] = [] # mutable-ok: API message payload
++ text_parts: Final[list[ChatCompletionTextObject]] = [] # mutable-ok: API message payload
+ for block in content:
- if not isinstance(block, dict) or block.get("type") != "text":
++ if not isinstance(block, dict) or block.get("type") != "text": # pyright: ignore[reportUnnecessaryIsInstance] # untrusted client payload
+ continue
+ text = block.get("text")
+ if not text:
+ continue
+ text_obj = ChatCompletionTextObject(type="text", text=text)
+ self._add_cache_control_if_applicable(block, text_obj, model)
+ text_parts.append(text_obj)
+ return ChatCompletionSystemMessage(role="system", content=text_parts) if text_parts else None
+
def _add_system_message_to_messages(
self,
- new_messages: List[AllMessageValues],
+ new_messages: list[AllMessageValues],
anthropic_message_request: AnthropicMessagesRequest,
) -> None:
"""Add system message to messages list if present in request."""
@@@ -1087,12 -1045,12 +1073,12 @@@
for tools that exceeded OpenAI's 64-char limit
"""
# Debug: Processing Anthropic message request
- new_messages: List[AllMessageValues] = []
- tool_name_mapping: Dict[str, str] = {}
+ new_messages: list[AllMessageValues] = []
+ tool_name_mapping: dict[str, str] = {}
## CONVERT ANTHROPIC MESSAGES TO OPENAI
- messages_list = cast(
- List[AllAnthropicPassThroughMessageValues],
- messages_list: Final[list[AnthropicMessagesUserMessageParam | AnthopicMessagesAssistantMessageParam]] = cast(
- list[AnthropicMessagesUserMessageParam | AnthopicMessagesAssistantMessageParam],
++ messages_list: Final[list[AllAnthropicPassThroughMessageValues]] = cast(
++ list[AllAnthropicPassThroughMessageValues],
anthropic_message_request["messages"],
)
new_messages = self.translate_anthropic_messages_to_openai(
diff --cc litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py
index cbe36100eb0,d0709b847c0..bf3f6153e7c
--- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py
@@@ -6,8 -6,7 +6,8 @@@ path used for OpenAI and Azure models
"""
import json
+from collections.abc import Iterable
- from typing import Any, Dict, List, Optional, Union, cast
+ from typing import Any, Final, cast
from litellm.litellm_core_utils.reasoning_effort_utils import (
reasoning_effort_from_thinking_budget,
@@@ -55,27 -72,10 +73,27 @@@ class LiteLLMAnthropicToResponsesAPIAda
return source.get("url")
return None
+ @staticmethod
+ def _translate_midturn_system_content_to_responses(
- content: Union[str, Iterable[AnthropicSystemMessageContent]],
++ content: str | Iterable[AnthropicSystemMessageContent],
+ ) -> list[dict[str, str]]: # mutable-ok: API message payload
+ """Convert in-sequence system content to Responses input-text parts."""
+ if isinstance(content, str):
+ return (
+ [{"type": "input_text", "text": content}] if content else [] # mutable-ok: API message payload
+ ) # mutable-ok: API message payload
+ if not isinstance(content, list):
+ return [] # mutable-ok: API message payload
+ return [ # mutable-ok: API message payload
+ {"type": "input_text", "text": text} # mutable-ok: API message payload
+ for block in content
- if isinstance(block, dict) and block.get("type") == "text" and (text := block.get("text"))
++ if isinstance(block, dict) and block.get("type") == "text" and (text := block.get("text")) # pyright: ignore[reportUnnecessaryIsInstance] # untrusted client payload
+ ]
+
def translate_messages_to_responses_input(
self,
- messages: List[AllAnthropicPassThroughMessageValues], # mutable-ok: API message payload
- ) -> List[Dict[str, Any]]:
- messages: list[AnthropicMessagesUserMessageParam | AnthopicMessagesAssistantMessageParam],
++ messages: list[AllAnthropicPassThroughMessageValues],
+ ) -> list[dict[str, Any]]:
"""
Convert Anthropic messages list to Responses API `input` items.
@@@ -87,21 -86,9 +105,21 @@@
assistant text -> message(role=assistant, output_text)
assistant tool_use -> function_call
"""
- input_items: List[Dict[str, Any]] = []
+ input_items: Final[list[dict[str, Any]]] = []
for m in messages:
+ if m["role"] == "system":
+ system_parts = self._translate_midturn_system_content_to_responses(m.get("content"))
+ if system_parts:
+ input_items.append(
+ { # mutable-ok: API message payload
+ "type": "message",
+ "role": "system",
+ "content": system_parts,
+ }
+ )
+ continue
+
role = m["role"]
content = m.get("content")
@@@ -311,9 -298,9 +329,9 @@@
Translate a full Anthropic /v1/messages request dict to
litellm.responses() / litellm.aresponses() kwargs.
"""
- model: str = anthropic_request["model"]
- messages_list = cast(
- List[AllAnthropicPassThroughMessageValues],
+ model: Final[str] = anthropic_request["model"]
+ messages_list: Final = cast(
- list[AnthropicMessagesUserMessageParam | AnthopicMessagesAssistantMessageParam],
++ list[AllAnthropicPassThroughMessageValues],
anthropic_request["messages"],
)
diff --cc litellm/types/llms/anthropic.py
index 29faf500b3d,bb861030d86..69d291eebd0
--- a/litellm/types/llms/anthropic.py
+++ b/litellm/types/llms/anthropic.py
@@@ -1,8 -1,9 +1,9 @@@
+ from collections.abc import Iterable
from enum import Enum
- from typing import Any, Dict, Iterable, List, Optional, Union
-from typing import Any, Final, Literal
++from typing import Any, Final, Literal, TypeAlias
from pydantic import BaseModel, ConfigDict
- from typing_extensions import Literal, NotRequired, Required, TypedDict
+ from typing_extensions import NotRequired, Required, TypedDict
from .openai import (
ChatCompletionCachedContent,
@@@ -362,45 -345,33 +345,43 @@@ class AnthropicMetadata(TypedDict, tota
class AnthropicSystemMessageContent(TypedDict, total=False):
type: str
text: str
- cache_control: Optional[Union[dict, ChatCompletionCachedContent]]
+ cache_control: dict | ChatCompletionCachedContent | None
+class AnthropicMessagesSystemMessageParam(TypedDict, total=False):
+ role: Required[Literal["system"]]
- content: Required[Union[str, Iterable[AnthropicSystemMessageContent]]]
++ content: Required[str | Iterable[AnthropicSystemMessageContent]]
+
+
- AllAnthropicMessageValues = Union[AnthropicMessagesUserMessageParam, AnthopicMessagesAssistantMessageParam]
+ AllAnthropicMessageValues = AnthropicMessagesUserMessageParam | AnthopicMessagesAssistantMessageParam
+# System is not a native Anthropic message role; only pass-through adapters use this union.
- AllAnthropicPassThroughMessageValues = Union[
- AnthropicMessagesUserMessageParam,
- AnthopicMessagesAssistantMessageParam,
- AnthropicMessagesSystemMessageParam,
- ]
++AllAnthropicPassThroughMessageValues: TypeAlias = (
++ AnthropicMessagesUserMessageParam | AnthopicMessagesAssistantMessageParam | AnthropicMessagesSystemMessageParam
++)
+
class AnthropicMessagesRequestOptionalParams(TypedDict, total=False):
- max_tokens: Optional[int]
- metadata: Optional[Union[AnthropicMetadata, Dict]]
- stop_sequences: Optional[List[str]]
- stream: Optional[bool]
- system: Optional[Union[str, List]]
- temperature: Optional[float]
- thinking: Optional[Dict]
- tool_choice: Optional[Union[AnthropicMessagesToolChoice, Dict]]
- tools: Optional[List[Union[AllAnthropicToolsValues, Dict]]]
- top_k: Optional[int]
- inference_geo: Optional[str]
- top_p: Optional[float]
- mcp_servers: Optional[List[AnthropicMcpServerTool]]
- context_management: Optional[Dict[str, Any]]
- container: Optional[Dict[str, Any]] # Container config with skills for code execution
- output_format: Optional[AnthropicOutputSchema] # Structured outputs support
- speed: Optional[str] # Fast mode support for Opus models
- output_config: Optional[AnthropicOutputConfig] # Configuration for Claude's output behavior
- cache_control: Optional[Dict[str, Any]] # Automatic prompt caching
- reasoning_effort: Optional[str]
+ max_tokens: int | None
+ metadata: AnthropicMetadata | dict | None
+ stop_sequences: list[str] | None
+ stream: bool | None
+ system: str | list | None
+ temperature: float | None
+ thinking: dict | None
+ tool_choice: AnthropicMessagesToolChoice | dict | None
+ tools: list[AllAnthropicToolsValues | dict] | None
+ top_k: int | None
+ inference_geo: str | None
+ top_p: float | None
+ mcp_servers: list[AnthropicMcpServerTool] | None
+ context_management: dict[str, Any] | None
+ container: dict[str, Any] | None # Container config with skills for code execution
+ output_format: AnthropicOutputSchema | None # Structured outputs support
+ speed: str | None # Fast mode support for Opus models
+ output_config: AnthropicOutputConfig | None # Configuration for Claude's output behavior
+ cache_control: dict[str, Any] | None # Automatic prompt caching
+ reasoning_effort: str | None
class AnthropicMessagesRequest(AnthropicMessagesRequestOptionalParams, total=False):
diff --cc tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
index 7757b0fa5a4,c7a30f7f954..1470056fd93
--- a/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
+++ b/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
@@@ -255,660 -211,6 +256,663 @@@ class TestAnthropicMessagesHandlerInput
assert data.get("litellm_metadata", {}).get("guardrails")
assert guardrail.dynamic_params == {"policy_id": "policy-123"}
+ @pytest.mark.asyncio
+ async def test_midturn_system_correction_is_guardrailed_when_top_level_system_is_skipped(
+ self,
+ ):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockMaskingGuardrail()
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "system": "trusted top-level system prompt",
+ "messages": [
+ {"role": "user", "content": "safe text"},
+ {
+ "role": "system",
+ "content": [
+ {"type": "unsupported", "text": "discarded text"},
+ {"type": "text", "text": "prohibited correction"},
+ ],
+ },
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.inputs is not None
+ assert guardrail.inputs["texts"] == ["safe text", "prohibited correction"]
+ assert "trusted top-level system prompt" not in guardrail.inputs["texts"]
+ assert data["messages"][1]["content"][0]["text"] == "discarded text"
+ assert data["messages"][1]["content"][1]["text"] == "[MASKED]"
+
+ @pytest.mark.asyncio
+ async def test_string_midturn_system_correction_is_guardrailed(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockMaskingGuardrail()
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "messages": [{"role": "system", "content": "prohibited correction"}],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.inputs is not None
+ assert guardrail.inputs["texts"] == ["prohibited correction"]
+ assert data["messages"][0]["content"] == "[MASKED]"
+
+ @pytest.mark.asyncio
+ async def test_unsupported_midturn_system_content_is_not_guardrailed(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockMaskingGuardrail()
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "messages": [
+ {
+ "role": "system",
+ "content": [{"type": "image", "source": {"type": "url"}}],
+ }
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.inputs is None
+
+ @pytest.mark.asyncio
+ async def test_skip_system_message_excludes_only_hoisted_top_level_system(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockMaskingGuardrail()
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "system": "trusted top-level system prompt",
+ "messages": [
+ {"role": "user", "content": "safe text"},
+ {"role": "system", "content": "prohibited correction"},
+ {"role": "user", "content": "continue"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.inputs is not None
+ structured = guardrail.inputs["structured_messages"]
+ assert [m["role"] for m in structured] == ["user", "system", "user"]
+ assert structured[1]["content"] == "prohibited correction"
+
+ @pytest.mark.asyncio
+ async def test_default_skip_false_scans_midturn_system_and_hoists_top_level_system(
+ self,
+ ):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockMaskingGuardrail(skip_system_message_in_guardrail=None)
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "system": "trusted top-level system prompt",
+ "messages": [
+ {"role": "user", "content": "safe text"},
+ {"role": "system", "content": "prohibited correction"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.inputs is not None
+ assert guardrail.inputs["texts"] == ["safe text", "prohibited correction"]
+ structured = guardrail.inputs["structured_messages"]
+ assert [m["role"] for m in structured] == ["system", "user", "system"]
+ assert structured[0]["content"] == "trusted top-level system prompt"
+ assert data["messages"][1]["content"] == "[MASKED]"
+
+ @pytest.mark.asyncio
+ async def test_bedrock_masking_slice_is_unavailable_when_top_level_system_is_included(
+ self,
+ ):
+ from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import (
+ BedrockGuardrail,
+ )
+
+ handler = AnthropicMessagesHandler()
+ guardrail = MockMaskingGuardrail(skip_system_message_in_guardrail=None)
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "system": "trusted top-level system prompt",
+ "messages": [
+ {"role": "user", "content": "safe text"},
+ {"role": "system", "content": "prohibited correction"},
+ {"role": "user", "content": "latest question"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.inputs is not None
+ texts = guardrail.inputs["texts"]
+ structured = guardrail.inputs["structured_messages"]
+
+ bedrock = BedrockGuardrail(guardrailIdentifier="gi", guardrailVersion="1")
+ assert sum(bedrock._count_message_texts(m) for m in structured) == len(texts) + 1
+ latest_user_index = bedrock._find_latest_message_index(structured, target_role="user")
+ assert (
+ bedrock._locate_message_texts_slice(
+ structured_messages=structured,
+ target_index=latest_user_index,
+ texts=texts,
+ )
+ is None
+ )
+ assert (
+ bedrock._merge_masked_texts(
+ masked_texts=["{MASKED}"],
+ texts=texts,
+ scanned_slice=None,
+ scanned_role_subset=True,
+ )
+ == texts
+ )
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("skip_system_message_in_guardrail", [True, None])
+ async def test_midturn_system_text_extraction_matches_translation_in_both_skip_modes(
+ self,
+ skip_system_message_in_guardrail: Optional[bool],
+ ):
+ from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import (
+ BedrockGuardrail,
+ )
+
+ handler = AnthropicMessagesHandler()
+ guardrail = MockMaskingGuardrail(skip_system_message_in_guardrail=skip_system_message_in_guardrail)
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "messages": [
+ {"role": "user", "content": "safe text"},
+ {
+ "role": "system",
+ "content": [
+ {"type": "text", "text": ""},
+ {"type": "image", "source": {"type": "url", "url": "https://example.com/a.png"}},
+ {"type": "text", "text": "prohibited correction"},
+ ],
+ },
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.inputs is not None
+ texts = guardrail.inputs["texts"]
+ structured = guardrail.inputs["structured_messages"]
+ assert texts == ["safe text", "prohibited correction"]
+ bedrock = BedrockGuardrail(guardrailIdentifier="gi", guardrailVersion="1")
+ assert sum(bedrock._count_message_texts(m) for m in structured) == len(texts)
+ assert data["messages"][1]["content"][2]["text"] == "[MASKED]"
+
+ @pytest.mark.asyncio
+ async def test_bedrock_masking_slice_stays_aligned_with_midturn_system(self):
+ from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import (
+ BedrockGuardrail,
+ )
+
+ handler = AnthropicMessagesHandler()
+ guardrail = MockMaskingGuardrail()
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "system": "trusted top-level system prompt",
+ "messages": [
+ {"role": "user", "content": "safe text"},
+ {
+ "role": "system",
+ "content": [
+ {"type": "text", "text": "prohibited correction"},
+ {"type": "text", "text": "second correction"},
+ ],
+ },
+ {"role": "user", "content": "latest question"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.inputs is not None
+ texts = guardrail.inputs["texts"]
+ structured = guardrail.inputs["structured_messages"]
+
+ bedrock = BedrockGuardrail(guardrailIdentifier="gi", guardrailVersion="1")
+ total = sum(bedrock._count_message_texts(m) for m in structured)
+ assert total == len(texts)
+
+ latest_user_index = bedrock._find_latest_message_index(structured, target_role="user")
+ assert latest_user_index == 2
+ scanned_slice = bedrock._locate_message_texts_slice(
+ structured_messages=structured,
+ target_index=latest_user_index,
+ texts=texts,
+ )
+ assert scanned_slice == (3, 1)
+
+ merged = bedrock._merge_masked_texts(
+ masked_texts=["{MASKED}"],
+ texts=texts,
+ scanned_slice=scanned_slice,
+ scanned_role_subset=True,
+ )
+ assert merged == [
+ "safe text",
+ "prohibited correction",
+ "second correction",
+ "{MASKED}",
+ ]
+
+ @pytest.mark.asyncio
+ async def test_compaction_rewrite_keeps_midturn_system_messages(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockCompactingGuardrail(
+ replacement_messages=[
+ {"role": "user", "content": "compacted history"},
+ {
+ "role": "system",
+ "content": [{"type": "text", "text": "use the corrected result"}],
+ },
+ {"role": "user", "content": "continue"},
+ ]
+ )
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "system": "trusted top-level system prompt",
+ "messages": [
+ {"role": "user", "content": "original history"},
+ {"role": "system", "content": "use the corrected result"},
+ {"role": "user", "content": "continue"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert [m["role"] for m in data["messages"]] == ["user", "system", "user"]
+ assert data["messages"][1]["content"] == [{"type": "text", "text": "use the corrected result"}]
+ assert data["messages"][0]["content"] == [{"type": "text", "text": "compacted history"}]
+ assert data["messages"][2]["content"] == [{"type": "text", "text": "continue"}]
+ assert data["system"] == "trusted top-level system prompt"
+
+ @pytest.mark.asyncio
+ async def test_compaction_rewrite_does_not_duplicate_hoisted_top_level_system(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockCompactingGuardrail(
+ replacement_messages=[
+ {"role": "system", "content": "trusted top-level system prompt"},
+ {"role": "user", "content": "compacted history"},
+ {"role": "system", "content": "use the corrected result"},
+ ]
+ )
+ guardrail.skip_system_message_in_guardrail = None
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "system": "trusted top-level system prompt",
+ "messages": [
+ {"role": "user", "content": "original history"},
+ {"role": "system", "content": "use the corrected result"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert [m["role"] for m in data["messages"]] == ["user", "system"]
+ assert data["messages"][1]["content"] == "use the corrected result"
+ assert data["system"] == "trusted top-level system prompt"
+
+ @pytest.mark.asyncio
+ async def test_compaction_rewrite_keeps_leading_midturn_system_when_system_is_skipped(
+ self,
+ ):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockCompactingGuardrail(
+ replacement_messages=[
+ {"role": "system", "content": "use the corrected result"},
+ {"role": "user", "content": "compacted history"},
+ ]
+ )
+ guardrail.skip_system_message_in_guardrail = True
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "system": "trusted top-level system prompt",
+ "messages": [
+ {"role": "system", "content": "use the corrected result"},
+ {"role": "user", "content": "original history"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert [m["role"] for m in data["messages"]] == ["system", "user"]
+ assert data["messages"][0]["content"] == "use the corrected result"
+
+ @pytest.mark.asyncio
+ async def test_compaction_rewrite_keeps_leading_correction_when_top_level_system_hoists_nothing(
+ self,
+ ):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockCompactingGuardrail(
+ replacement_messages=[
+ {"role": "system", "content": "use the corrected result"},
+ {"role": "user", "content": "compacted history"},
+ ]
+ )
+ guardrail.skip_system_message_in_guardrail = None
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "system": [{"type": "image", "source": {"type": "url", "url": "https://example.com/a.png"}}],
+ "messages": [
+ {"role": "system", "content": "use the corrected result"},
+ {"role": "user", "content": "original history"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert [m["role"] for m in data["messages"]] == ["system", "user"]
+ assert data["messages"][0]["content"] == "use the corrected result"
+
+ @pytest.mark.asyncio
+ async def test_compaction_rewrite_keeps_leading_correction_when_hoisted_prompt_is_dropped(
+ self,
+ ):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockCompactingGuardrail(
+ replacement_messages=[
+ {"role": "system", "content": "CLIENT CORRECTION"},
+ {"role": "user", "content": "compacted history"},
+ ]
+ )
+ guardrail.skip_system_message_in_guardrail = None
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "system": "TRUSTED",
+ "messages": [
+ {"role": "system", "content": "CLIENT CORRECTION"},
+ {"role": "user", "content": "original history"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.inputs is not None
+ assert guardrail.inputs["structured_messages"][0] == {
+ "role": "system",
+ "content": "TRUSTED",
+ }
+ assert [m["role"] for m in data["messages"]] == ["system", "user"]
+ assert data["messages"][0]["content"] == "CLIENT CORRECTION"
+ assert data["system"] == "TRUSTED"
+
+ @pytest.mark.asyncio
+ async def test_compaction_rewrite_drops_hoisted_prompt_matched_by_content_copy(self):
+ import json
+
+ handler = AnthropicMessagesHandler()
+ guardrail = MockCompactingGuardrail(
+ replacement_messages=[
+ json.loads(json.dumps({"role": "system", "content": "TRUSTED"})),
+ {"role": "user", "content": "compacted history"},
+ {"role": "system", "content": "CLIENT CORRECTION"},
+ ]
+ )
+ guardrail.skip_system_message_in_guardrail = None
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "system": "TRUSTED",
+ "messages": [
+ {"role": "user", "content": "original history"},
+ {"role": "system", "content": "CLIENT CORRECTION"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert [m["role"] for m in data["messages"]] == ["user", "system"]
+ assert data["messages"][1]["content"] == "CLIENT CORRECTION"
+ assert data["system"] == "TRUSTED"
+
+ @pytest.mark.asyncio
+ async def test_compaction_rewrite_preserves_cache_control_on_system_blocks(self):
+ """
+ `cache_control` on an in-sequence system text block survives the write-back, and is
+ copied rather than aliased into the guardrail's own returned list.
+ """
+ handler = AnthropicMessagesHandler()
+ source_cache_control = {"type": "ephemeral"}
+ guardrail = MockCompactingGuardrail(
+ replacement_messages=[
+ {"role": "user", "content": "compacted history"},
+ {
+ "role": "system",
+ "content": [
+ {
+ "type": "text",
+ "text": "use the corrected result",
+ "cache_control": source_cache_control,
+ }
+ ],
+ },
+ ]
+ )
+ guardrail.skip_system_message_in_guardrail = True
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "messages": [
+ {"role": "user", "content": "original history"},
+ {"role": "system", "content": "use the corrected result"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert data["messages"][1]["content"] == [
+ {
+ "type": "text",
+ "text": "use the corrected result",
+ "cache_control": {"type": "ephemeral"},
+ }
+ ]
+ assert data["messages"][1]["content"][0]["cache_control"] is not source_cache_control
+
+ @pytest.mark.asyncio
+ async def test_compaction_rewrite_rstrips_trailing_assistant_in_each_run(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockCompactingGuardrail(
+ replacement_messages=[
+ {"role": "user", "content": "compacted history"},
+ {"role": "assistant", "content": "earlier "},
+ {"role": "system", "content": "use the corrected result"},
+ {"role": "user", "content": "continue"},
+ {"role": "assistant", "content": "prefill "},
+ ]
+ )
+ guardrail.skip_system_message_in_guardrail = True
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "messages": [
+ {"role": "user", "content": "original history"},
+ {"role": "system", "content": "use the corrected result"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert [m["role"] for m in data["messages"]] == [
+ "user",
+ "assistant",
+ "system",
+ "user",
+ "assistant",
+ ]
+ assert data["messages"][1]["content"] == [{"type": "text", "text": "earlier"}]
+ assert data["messages"][-1]["content"] == [{"type": "text", "text": "prefill"}]
+
+ @pytest.mark.asyncio
+ async def test_compaction_rewrite_drops_text_free_system_message(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockCompactingGuardrail(
+ replacement_messages=[
+ {"role": "user", "content": "compacted history"},
+ {"role": "system", "content": [{"type": "text", "text": ""}]},
+ {"role": "system", "content": ""},
+ {"role": "user", "content": "continue"},
+ ]
+ )
+ guardrail.skip_system_message_in_guardrail = True
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "messages": [
+ {"role": "user", "content": "original history"},
+ {"role": "system", "content": "use the corrected result"},
+ {"role": "user", "content": "continue"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert [m["role"] for m in data["messages"]] == ["user", "user"]
+ assert data["messages"][0]["content"] == [{"type": "text", "text": "compacted history"}]
+ assert data["messages"][1]["content"] == [{"type": "text", "text": "continue"}]
+
+ @pytest.mark.asyncio
+ async def test_noncanonical_system_role_casing_is_still_scanned(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockMaskingGuardrail()
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "messages": [
+ {"role": "user", "content": "safe text"},
+ {"role": "System", "content": "prohibited correction"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.inputs is not None
+ assert "prohibited correction" in guardrail.inputs["texts"]
+ assert data["messages"][1]["content"] == "[MASKED]"
+
+ @pytest.mark.asyncio
- async def test_tool_result_turns_have_a_preexisting_alignment_gap(self):
++ async def test_midturn_system_keeps_tool_result_turns_aligned_for_masking(self):
++ """Tool-result texts are scanned (LIT-5251), so counts align and the latest-user
++ masking slice is locatable; a mid-turn system entry only shifts it by its own text."""
+ from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import (
+ BedrockGuardrail,
+ )
+
+ handler = AnthropicMessagesHandler()
+ bedrock = BedrockGuardrail(guardrailIdentifier="gi", guardrailVersion="1")
+ tool_loop = [
+ {"role": "user", "content": "call the tool"},
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "tu_1", "name": "get", "input": {"a": 1}}],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "tu_1",
+ "content": [{"type": "text", "text": "tool output"}],
+ }
+ ],
+ },
+ ]
+
+ async def _slice_for(messages: list):
+ guardrail = MockMaskingGuardrail()
+ data = {"model": "claude-3-5-sonnet-20241022", "messages": messages}
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+ assert guardrail.inputs is not None
+ texts = guardrail.inputs["texts"]
+ structured = guardrail.inputs["structured_messages"]
+ target_index = bedrock._find_latest_message_index(structured, target_role="user")
+ return (
+ sum(bedrock._count_message_texts(m) for m in structured) - len(texts),
+ bedrock._locate_message_texts_slice(
+ structured_messages=structured,
+ target_index=target_index,
+ texts=texts,
+ ),
+ )
+
+ with_system = await _slice_for(
+ tool_loop
+ + [
+ {"role": "system", "content": "use the corrected result"},
+ {"role": "user", "content": "latest question"},
+ ]
+ )
+ without_system = await _slice_for(tool_loop + [{"role": "user", "content": "latest question"}])
+
- assert with_system == without_system == (1, None)
++ assert with_system == (0, (3, 1))
++ assert without_system == (0, (2, 1))
+
+ @pytest.mark.asyncio
+ async def test_compaction_rewrite_to_only_system_messages_is_rejected(self):
+ import litellm
+
+ handler = AnthropicMessagesHandler()
+ guardrail = MockCompactingGuardrail(
+ replacement_messages=[{"role": "system", "content": "use the corrected result"}]
+ )
+ guardrail.skip_system_message_in_guardrail = True
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "messages": [
+ {"role": "user", "content": "original history"},
+ {"role": "system", "content": "use the corrected result"},
+ ],
+ }
+
+ with patch.object(litellm, "modify_params", False):
+ with pytest.raises(litellm.BadRequestError, match="at least one non-system message"):
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ @pytest.mark.asyncio
+ async def test_compaction_rewrite_to_only_system_messages_repaired_with_modify_params(
+ self,
+ ):
+ import litellm
+
+ handler = AnthropicMessagesHandler()
+ guardrail = MockCompactingGuardrail(
+ replacement_messages=[{"role": "system", "content": "use the corrected result"}]
+ )
+ guardrail.skip_system_message_in_guardrail = True
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "messages": [
+ {"role": "user", "content": "original history"},
+ {"role": "system", "content": "use the corrected result"},
+ ],
+ }
+
+ with patch.object(litellm, "modify_params", True):
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert [m["role"] for m in data["messages"]] == ["system", "user"]
+ assert data["messages"][0]["content"] == "use the corrected result"
+
+ @pytest.mark.asyncio
+ async def test_compaction_rewrite_without_system_messages_is_unchanged(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = MockCompactingGuardrail(replacement_messages=[{"role": "user", "content": "compacted history"}])
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "messages": [
+ {"role": "user", "content": "a"},
+ {"role": "assistant", "content": "b"},
+ {"role": "user", "content": "c"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert data["messages"] == [{"role": "user", "content": [{"type": "text", "text": "compacted history"}]}]
+
@pytest.mark.asyncio
async def test_process_output_streaming_response_empty_choices(self):
"""Test that streaming response with empty choices doesn't raise IndexError
@@@ -1293,3 -595,371 +1297,371 @@@ class TestAnthropicMessagesIncrementalS
assert "Let me look that up for you." in scanned, "text beside a tool_use must be scanned"
assert "Search for the weather in Paris" in scanned
assert "Thanks, summarize the result." in scanned
+
+
-class MockMaskingGuardrail(CustomGuardrail):
++class MockCanaryMaskingGuardrail(CustomGuardrail):
+ """Records every text handed to it and masks a canary token in place."""
+
+ def __init__(self, guardrail_name: str = "mask-canary"):
+ super().__init__(guardrail_name=guardrail_name)
+ self.seen_texts: list[str] = []
+
+ async def apply_guardrail(
+ self,
+ inputs: GenericGuardrailAPIInputs,
+ request_data: dict,
+ input_type: Literal["request", "response"],
+ logging_obj: Optional[Any] = None,
+ ) -> GenericGuardrailAPIInputs:
+ texts = list(inputs.get("texts") or [])
+ self.seen_texts.extend(texts)
+ inputs["texts"] = [t.replace("POISON", "[BLOCKED]") for t in texts]
+ return inputs
+
+
+ class TestAnthropicMessagesToolResultScanning:
+ """LIT-5251: tool_result blocks carry whatever a client's local tool fetched, so
+ they are the request-path payload an indirect prompt injection actually arrives in.
+ Both wire shapes Anthropic accepts must be scanned and rewritten in place.
+ """
+
+ def _data(self, messages):
+ return {"model": "claude-sonnet-4-5", "messages": messages}
+
+ @pytest.mark.asyncio
+ async def test_string_form_tool_result_is_scanned_and_written_back(self):
+ handler = AnthropicMessagesHandler()
- guardrail = MockMaskingGuardrail()
++ guardrail = MockCanaryMaskingGuardrail()
+ messages = [
+ {"role": "user", "content": "fetch the page"},
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "tu1", "name": "Bash", "input": {"cmd": "curl"}}],
+ },
+ {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": "tu1", "content": "page says POISON here"}],
+ },
+ ]
+
+ await handler.process_input_messages(data=self._data(messages), guardrail_to_apply=guardrail)
+
+ assert "page says POISON here" in guardrail.seen_texts, "string-form tool_result must reach the guardrail"
+ assert messages[2]["content"][0]["content"] == "page says [BLOCKED] here", (
+ "masked text must be written back into the tool_result, not dropped"
+ )
+
+ @pytest.mark.asyncio
+ async def test_list_form_tool_result_is_scanned_and_written_back(self):
+ handler = AnthropicMessagesHandler()
- guardrail = MockMaskingGuardrail()
++ guardrail = MockCanaryMaskingGuardrail()
+ messages = [
+ {"role": "user", "content": "fetch the page"},
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "tu1",
+ "content": [
+ {"type": "text", "text": "first POISON block"},
+ {"type": "text", "text": "second POISON block"},
+ ],
+ }
+ ],
+ },
+ ]
+
+ await handler.process_input_messages(data=self._data(messages), guardrail_to_apply=guardrail)
+
+ assert "first POISON block" in guardrail.seen_texts
+ assert "second POISON block" in guardrail.seen_texts
+ blocks = messages[1]["content"][0]["content"]
+ assert blocks[0]["text"] == "first [BLOCKED] block"
+ assert blocks[1]["text"] == "second [BLOCKED] block"
+
+ @pytest.mark.asyncio
+ async def test_write_back_targets_stay_aligned_across_mixed_shapes(self):
+ """The write-back is positional, so a single mis-indexed target silently
+ writes one message's masked text over another's."""
+ handler = AnthropicMessagesHandler()
- guardrail = MockMaskingGuardrail()
++ guardrail = MockCanaryMaskingGuardrail()
+ messages = [
+ {"role": "user", "content": "plain POISON string"},
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "sibling POISON text"},
+ {"type": "tool_result", "tool_use_id": "tu1", "content": "string POISON result"},
+ {
+ "type": "tool_result",
+ "tool_use_id": "tu2",
+ "content": [{"type": "text", "text": "nested POISON result"}],
+ },
+ ],
+ },
+ {"role": "user", "content": "trailing POISON string"},
+ ]
+
+ await handler.process_input_messages(data=self._data(messages), guardrail_to_apply=guardrail)
+
+ assert messages[0]["content"] == "plain [BLOCKED] string"
+ assert messages[1]["content"][0]["text"] == "sibling [BLOCKED] text"
+ assert messages[1]["content"][1]["content"] == "string [BLOCKED] result"
+ assert messages[1]["content"][2]["content"][0]["text"] == "nested [BLOCKED] result"
+ assert messages[2]["content"] == "trailing [BLOCKED] string"
+
+ @pytest.mark.asyncio
+ async def test_image_inside_tool_result_is_collected(self):
+ handler = AnthropicMessagesHandler()
+
- class ImageRecordingGuardrail(MockMaskingGuardrail):
++ class ImageRecordingGuardrail(MockCanaryMaskingGuardrail):
+ def __init__(self):
+ super().__init__()
+ self.seen_images: list[str] = []
+
+ async def apply_guardrail(self, inputs, request_data, input_type, logging_obj=None):
+ self.seen_images.extend(inputs.get("images") or [])
+ return await super().apply_guardrail(inputs, request_data, input_type, logging_obj)
+
+ guardrail = ImageRecordingGuardrail()
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "tu1",
+ "content": [
+ {"type": "text", "text": "screenshot POISON"},
+ {"type": "image", "source": {"type": "base64", "data": "SCREENSHOT_BYTES"}},
+ ],
+ }
+ ],
+ }
+ ]
+
+ await handler.process_input_messages(data=self._data(messages), guardrail_to_apply=guardrail)
+
+ assert "SCREENSHOT_BYTES" in guardrail.seen_images, "images nested in a tool_result must be scanned too"
+
+ @pytest.mark.asyncio
+ async def test_tool_result_is_skipped_when_guardrail_skips_tool_messages(self):
+ handler = AnthropicMessagesHandler()
- guardrail = MockMaskingGuardrail()
++ guardrail = MockCanaryMaskingGuardrail()
+ guardrail.skip_tool_message_in_guardrail = True
+ messages = [
+ {"role": "user", "content": "keep me POISON"},
+ {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": "tu1", "content": "skip me POISON"}],
+ },
+ ]
+
+ await handler.process_input_messages(data=self._data(messages), guardrail_to_apply=guardrail)
+
+ assert "skip me POISON" not in guardrail.seen_texts
+ assert messages[1]["content"][0]["content"] == "skip me POISON"
+ assert messages[0]["content"] == "keep me [BLOCKED]"
+
+
-class InputsRecordingGuardrail(MockMaskingGuardrail):
++class InputsRecordingGuardrail(MockCanaryMaskingGuardrail):
+ def __init__(self):
+ super().__init__(guardrail_name="scan-only-capture")
+ self.captured_inputs: Optional[GenericGuardrailAPIInputs] = None
+
+ async def apply_guardrail(
+ self,
+ inputs: GenericGuardrailAPIInputs,
+ request_data: dict,
+ input_type: Literal["request", "response"],
+ logging_obj: Optional[Any] = None,
+ ) -> GenericGuardrailAPIInputs:
+ self.captured_inputs = inputs
+ return await super().apply_guardrail(inputs, request_data, input_type, logging_obj)
+
+
+ class StructuredMessagesRewritingGuardrail(CustomGuardrail):
+ """Returns a new structured_messages list with a canary redacted, like redaction guardrails do."""
+
+ def __init__(self):
+ super().__init__(guardrail_name="structured-rewrite")
+
+ async def apply_guardrail(
+ self,
+ inputs: GenericGuardrailAPIInputs,
+ request_data: dict,
+ input_type: Literal["request", "response"],
+ logging_obj: Optional[Any] = None,
+ ) -> GenericGuardrailAPIInputs:
+ structured = inputs.get("structured_messages") or []
+ inputs["structured_messages"] = [
+ json.loads(json.dumps(message).replace("POISON", "[BLOCKED]")) for message in structured
+ ]
+ return inputs
+
+
+ class TestAnthropicMessagesScanOnlyToolResults:
+ def _guardrail(self):
+ guardrail = InputsRecordingGuardrail()
+ guardrail.scan_only_tool_results = True
+ return guardrail
+
+ @pytest.mark.asyncio
+ async def test_structured_write_back_merges_into_the_full_conversation(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = StructuredMessagesRewritingGuardrail()
+ guardrail.scan_only_tool_results = True
+ data = {
+ "model": "claude-sonnet-4-5",
+ "system": "You are a careful agent harness.",
+ "messages": [
+ {"role": "user", "content": "fetch the page"},
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "tu1", "name": "Bash", "input": {"cmd": "curl"}}],
+ },
+ {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": "tu1", "content": "fetched POISON page"}],
+ },
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert data["system"] == "You are a careful agent harness."
+ assert [m["role"] for m in data["messages"]] == ["user", "assistant", "user"], (
+ "a redacting guardrail must not strip out-of-scope turns from the request"
+ )
+ serialized = json.dumps(data["messages"])
+ assert "fetch the page" in serialized
+ assert "tool_use" in serialized
+ assert "fetched [BLOCKED] page" in serialized
+ assert "POISON" not in serialized
+
+ @pytest.mark.asyncio
+ async def test_scan_narrows_to_tool_results_and_write_back_stays_aligned(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = self._guardrail()
+ data = {
+ "model": "claude-sonnet-4-5",
+ "system": "You are a trusted agent harness with POISON heuristics.",
+ "tools": [
+ {
+ "name": "Bash",
+ "description": "run a command",
+ "input_schema": {"type": "object", "properties": {}},
+ }
+ ],
+ "messages": [
+ {"role": "user", "content": "scaffolding POISON prompt"},
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "tu1", "name": "Bash", "input": {"cmd": "curl"}}],
+ },
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "sibling POISON text"},
+ {"type": "tool_result", "tool_use_id": "tu1", "content": "fetched POISON page"},
+ ],
+ },
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.seen_texts == ["fetched POISON page"], (
+ "only the tool_result payload may reach the guardrail"
+ )
+ assert guardrail.captured_inputs is not None
+ assert guardrail.captured_inputs.get("tools") is None
+ assert [m["role"] for m in guardrail.captured_inputs["structured_messages"]] == ["tool"]
+ assert data["messages"][2]["content"][1]["content"] == "fetched [BLOCKED] page"
+ assert data["messages"][0]["content"] == "scaffolding POISON prompt", (
+ "out-of-scope content must come back untouched, not masked or dropped"
+ )
+ assert data["messages"][2]["content"][0]["text"] == "sibling POISON text"
+
+ @pytest.mark.asyncio
+ async def test_guardrail_synthesized_tools_are_appended_without_replacing_request_tools(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = ToolAppendingGuardrail(guardrail_name="tool-appending")
+ guardrail.scan_only_tool_results = True
+ original_tools = [
+ {
+ "name": "get_weather",
+ "description": "Get the weather at a specific location",
+ "input_schema": {"type": "object", "properties": {"location": {"type": "string"}}},
+ }
+ ]
+ data = {
+ "model": "claude-sonnet-4-5",
+ "tools": original_tools,
+ "messages": [
+ {"role": "user", "content": "what's the weather?"},
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "tu1", "name": "get_weather", "input": {}}],
+ },
+ {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": "tu1", "content": "sunny"}],
+ },
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert [t["name"] for t in data["tools"]] == ["get_weather", "injected_tool"], (
+ "a tool the guardrail synthesized must reach the model, converted to Anthropic format, "
+ "without the request's own tools being replaced or dropped"
+ )
+ assert data["tools"][0] == original_tools[0]
+
+ @pytest.mark.asyncio
+ async def test_guardrail_is_not_called_when_the_request_has_no_tool_results(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = self._guardrail()
+ data = {
+ "model": "claude-sonnet-4-5",
+ "messages": [{"role": "user", "content": "What is 2 plus 2?"}],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.captured_inputs is None
+ assert guardrail.seen_texts == []
+
+ @pytest.mark.asyncio
+ async def test_images_are_scoped_the_same_way_as_texts(self):
+ handler = AnthropicMessagesHandler()
+ guardrail = self._guardrail()
+ data = {
+ "model": "claude-sonnet-4-5",
+ "messages": [
+ {
+ "role": "user",
+ "content": [{"type": "image", "source": {"type": "base64", "data": "USER_IMG"}}],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "tu1",
+ "content": [
+ {"type": "text", "text": "screenshot POISON"},
+ {"type": "image", "source": {"type": "base64", "data": "TOOL_IMG"}},
+ ],
+ }
+ ],
+ },
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert guardrail.captured_inputs is not None
+ assert guardrail.captured_inputs.get("images") == ["TOOL_IMG"]