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 branch 'litellm_internal_staging' into litellm_model_armor_logging_only_streaming
yucheng7a083353a8e3
diff --cc tests/test_litellm/integrations/test_custom_guardrail.pyindex bdb7fad21b3,1644d78ae37..8cd719bfd55--- a/tests/test_litellm/integrations/test_custom_guardrail.py+++ b/tests/test_litellm/integrations/test_custom_guardrail.py@@@ -2831,50 -2831,129 +2831,178 @@@ class TestCustomGuardrailPostCallSuccesassert len(_guardrail_entries(request_data)) == 1+class _NativeLifecycleLoggingGuardrail(CustomGuardrail):+ """Native lifecycle guardrail that also implements apply_guardrail, like the azure guards."""++ use_native_lifecycle_hooks: ClassVar[bool] = True++ def __init__(self):+ from litellm.types.guardrails import GuardrailEventHooks++ super().__init__(+ guardrail_name="native-logging-guardrail",+ event_hook=GuardrailEventHooks.logging_only,+ )+ self.calls: list = []++ async def apply_guardrail(self, inputs, request_data, input_type, logging_obj=None):+ self.calls.append((input_type, list(inputs.get("texts") or [])))+ return inputs+++async def test_native_lifecycle_guardrail_logging_only_scans_assembled_response():+ """A use_native_lifecycle_hooks guardrail accepts mode logging_only and its+ async_logging_hook scans kwargs["async_complete_streaming_response"], not the raw result."""+ from litellm.types.utils import Choices, Message, ModelResponse++ guardrail = _NativeLifecycleLoggingGuardrail()+ assembled = ModelResponse(+ choices=[Choices(message=Message(role="assistant", content="assembled stream text"))]+ )+ sentinel_result = object()+ kwargs = {+ "model": "gpt-5.4-mini",+ "messages": [{"role": "user", "content": "hi"}],+ "litellm_call_id": "call-1",+ "litellm_params": {"metadata": {}},+ "optional_params": {},+ "standard_logging_object": {"guardrail_information": None},+ "async_complete_streaming_response": assembled,+ }++ out_kwargs, out_result = await guardrail.async_logging_hook(+ kwargs=kwargs, result=sentinel_result, call_type=CallTypes.acompletion.value+ )++ assert out_result is sentinel_result+ assert ("response", ["assembled stream text"]) in guardrail.calls+ assert out_kwargs["standard_logging_object"]["guardrail_information"]+++++ class TestPreCallHookResponseIsNotLoggedVerbatim:+ """Regression for LIT-6935: a pre_call hook returning the request payload leaked the prompt+ into ``guardrail_response`` and from there onto OTEL guardrail spans."""++ @staticmethod+ def _logged_response(request_data: dict[str, object]) -> object:+ metadata = request_data["litellm_metadata"]+ assert isinstance(metadata, dict)+ entries = metadata["standard_logging_guardrail_information"]+ assert len(entries) == 1+ return entries[0]["guardrail_response"]++ @staticmethod+ def _request() -> dict[str, object]:+ return {+ "model": "gpt-4.1-mini",+ "input": "SECRET_PROMPT",+ "messages": [{"role": "user", "content": "SECRET_PROMPT"}],+ "litellm_metadata": {},+ }++ @pytest.mark.asyncio+ async def test_pre_call_hook_returning_request_logs_allow(self):+ class PassthroughGuardrail(CustomGuardrail):+ @log_guardrail_information+ async def async_pre_call_hook(+ self,+ user_api_key_dict: UserAPIKeyAuth,+ cache: object,+ data: dict[str, object],+ call_type: str,+ ) -> dict[str, object]:+ return data++ data = self._request()+ await PassthroughGuardrail(guardrail_name="g").async_pre_call_hook(+ user_api_key_dict=UserAPIKeyAuth(), cache=None, data=data, call_type="aresponses"+ )++ assert self._logged_response(data) == "allow"++ @pytest.mark.asyncio+ async def test_pre_call_hook_returning_modified_copy_logs_mask(self):+ class MaskingGuardrail(CustomGuardrail):+ @log_guardrail_information+ async def async_pre_call_hook(+ self,+ user_api_key_dict: UserAPIKeyAuth,+ cache: object,+ data: dict[str, object],+ call_type: str,+ ) -> dict[str, object]:+ return {**data, "input": "[MASKED]"}++ data = self._request()+ await MaskingGuardrail(guardrail_name="g").async_pre_call_hook(+ user_api_key_dict=UserAPIKeyAuth(), cache=None, data=data, call_type="aresponses"+ )++ assert self._logged_response(data) == "mask"++ @pytest.mark.asyncio+ async def test_pre_call_hook_mutating_request_in_place_logs_mask(self):+ class InPlaceMaskingGuardrail(CustomGuardrail):+ @log_guardrail_information+ async def async_pre_call_hook(+ self,+ user_api_key_dict: UserAPIKeyAuth,+ cache: object,+ data: dict[str, object],+ call_type: str,+ ) -> dict[str, object]:+ messages = data["messages"]+ assert isinstance(messages, list)+ messages[0]["content"] = "[MASKED]"+ return data++ data = self._request()+ await InPlaceMaskingGuardrail(guardrail_name="g").async_pre_call_hook(+ user_api_key_dict=UserAPIKeyAuth(), cache=None, data=data, call_type="acompletion"+ )++ assert self._logged_response(data) == "mask"++ @pytest.mark.asyncio+ async def test_pre_call_hook_returning_rejection_string_logs_that_string(self):+ class RejectingGuardrail(CustomGuardrail):+ @log_guardrail_information+ async def async_pre_call_hook(+ self,+ user_api_key_dict: UserAPIKeyAuth,+ cache: object,+ data: dict[str, object],+ call_type: str,+ ) -> str:+ return "Blocked by policy"++ data = self._request()+ result = await RejectingGuardrail(guardrail_name="g").async_pre_call_hook(+ user_api_key_dict=UserAPIKeyAuth(), cache=None, data=data, call_type="acompletion"+ )++ assert result == "Blocked by policy"+ assert self._logged_response(data) == "Blocked by policy"++ @pytest.mark.asyncio+ async def test_pre_call_hook_removing_legacy_functions_in_place_logs_mask(self):+ class FunctionStrippingGuardrail(CustomGuardrail):+ @log_guardrail_information+ async def async_pre_call_hook(+ self,+ user_api_key_dict: UserAPIKeyAuth,+ cache: object,+ data: dict[str, object],+ call_type: str,+ ) -> dict[str, object]:+ data["functions"] = []+ data["function_call"] = "none"+ return data++ data = {**self._request(), "functions": [{"name": "delete_db"}], "function_call": "auto"}+ await FunctionStrippingGuardrail(guardrail_name="g").async_pre_call_hook(+ user_api_key_dict=UserAPIKeyAuth(), cache=None, data=data, call_type="acompletion"+ )++ assert self._logged_response(data) == "mask"