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
Merge remote-tracking branch 'origin/main' into litellm_anthropic_guardrail_system_and_tool_use
mateo-berri04410967ff7b
diff --cc litellm/llms/anthropic/chat/guardrail_translation/handler.pyindex b8e179e7274,656e9978eff..1f4e1487316--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py@@@ -674,9 -571,11 +675,11 @@@ class AnthropicMessagesHandler(BaseTranpreserve_system_messages=has_midturn_system_message,)else:+ if guardrailed_texts and len(guardrailed_texts) != len(scanned):+ raise unappliable_request_rewrite(guardrail_to_apply.guardrail_name)# Step 3: Map guardrail responses back to original message structureawait self._apply_guardrail_responses_to_input(- messages=messages,+ data=data,responses=guardrailed_texts,scanned=scanned,)diff --cc tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.pyindex 32786fc5057,0882b329c49..1cacbb6be6b--- 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@@@ -2481,6 -2272,58 +2481,74 @@@ class TestAnthropicMessagesHandlerStreaassert ended_key != open_key+ class PerRowTextGuardrail(CustomGuardrail):+ """Answers one redacted text per chat row it was shown, the way a guardrail+ that scans per message does, and hands back only texts."""++ def __init__(self):+ super().__init__(guardrail_name="per-row-redactor")++ async def apply_guardrail(+ self,+ inputs: GenericGuardrailAPIInputs,+ request_data: dict,+ input_type: Literal["request", "response"],+ logging_obj: Optional[Any] = None,+ ) -> GenericGuardrailAPIInputs:+ rows = inputs.get("structured_messages") or []+ return {**inputs, "texts": [str(row.get("content")).replace("123-45-6789", "<US_SSN>") for row in rows]}+++ class TestPerMessageTextWriteBack:+ """Texts that no longer pair one-to-one with what the handler extracted must be+ rejected by name instead of sliding onto the wrong messages."""++ @pytest.mark.asyncio- async def test_one_text_per_row_over_a_system_prompt_is_rejected_by_name(self):++ async def test_one_text_per_row_over_a_system_prompt_is_applied(self):++ data = {++ "model": "claude-sonnet-4-5",++ "system": "Reply with exactly the SSN you were given.",++ "messages": [{"role": "user", "content": "My SSN is 123-45-6789."}],++ }++++ await AnthropicMessagesHandler().process_input_messages(data=data, guardrail_to_apply=PerRowTextGuardrail())++++ assert data["system"] == "Reply with exactly the SSN you were given."++ assert data["messages"] == [{"role": "user", "content": "My SSN is <US_SSN>."}]++++ @pytest.mark.asyncio++ async def test_one_text_per_row_over_a_multi_block_system_prompt_is_rejected_by_name(self):+ from litellm.llms.base_llm.guardrail_translation.utils import UnappliableRequestRewrite++ data = {+ "model": "claude-sonnet-4-5",- "system": "Reply with exactly the SSN you were given.",++ "system": [++ {"type": "text", "text": "Reply with exactly the SSN you were given."},++ {"type": "text", "text": "Never apologize."},++ ],+ "messages": [{"role": "user", "content": "My SSN is 123-45-6789."}],+ }+ original = json.loads(json.dumps(data))++ with pytest.raises(UnappliableRequestRewrite) as excinfo:+ await AnthropicMessagesHandler().process_input_messages(data=data, guardrail_to_apply=PerRowTextGuardrail())++ assert excinfo.value.guardrail_name == "per-row-redactor"+ assert data["system"] == original["system"], "a rejected rewrite must leave the request untouched"+ assert data["messages"] == original["messages"], "a rejected rewrite must leave the request untouched"++ @pytest.mark.asyncio+ async def test_one_text_per_row_without_a_system_prompt_is_applied(self):+ data = {+ "model": "claude-sonnet-4-5",+ "messages": [{"role": "user", "content": "My SSN is 123-45-6789."}],+ }++ await AnthropicMessagesHandler().process_input_messages(data=data, guardrail_to_apply=PerRowTextGuardrail())++ assert data["messages"] == [{"role": "user", "content": "My SSN is <US_SSN>."}]++class TestAnthropicMessagesHandlerPostCallHookResponse:def test_openai_shaped_stream_assembly_reaches_the_hook_as_a_messages_response(self):from litellm.types.utils import Choices, Message, ModelResponse, Usage