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
feat: Add api_key to GenericGuardrailAPI and set x-api-key header (#18647)
Krish Dholakiab5aa7d1838c7
diff --git a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.pyindex c762f0cbfc6..8d32d95f0ac 100644--- a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.py+++ b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/__init__.py@@ -13,6 +13,7 @@ def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"_generic_guardrail_api_callback = GenericGuardrailAPI(api_base=litellm_params.api_base,+ api_key=litellm_params.api_key,headers=getattr(litellm_params, "headers", None),additional_provider_specific_params=getattr(litellm_params, "additional_provider_specific_params", {}diff --git a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.pyindex 35a1e26fb28..0dd00bfe55d 100644--- a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py+++ b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py@@ -54,6 +54,7 @@ class GenericGuardrailAPI(CustomGuardrail):self,headers: Optional[Dict[str, Any]] = None,api_base: Optional[str] = None,+ api_key: Optional[str] = None,additional_provider_specific_params: Optional[Dict[str, Any]] = None,**kwargs,):@@ -61,6 +62,11 @@ class GenericGuardrailAPI(CustomGuardrail):llm_provider=httpxSpecialProvider.GuardrailCallback)self.headers = headers or {}++ # If api_key is provided, add it as x-api-key header+ if api_key:+ self.headers["x-api-key"] = api_key+base_url = api_base or os.environ.get("GENERIC_GUARDRAIL_API_BASE")if not base_url:diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.pyindex f3de89d6d6c..b65065be366 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_generic_guardrail_api.py@@ -158,6 +158,31 @@ class TestGenericGuardrailAPIConfiguration:== "https://api.test.guardrail.com/beta/litellm_basic_guardrail_api")+ def test_api_key_sets_x_api_key_header(self):+ """Test that api_key is set as x-api-key header"""+ guardrail = GenericGuardrailAPI(+ api_base="https://api.test.guardrail.com",+ api_key="test-api-key-123",+ )+ assert guardrail.headers.get("x-api-key") == "test-api-key-123"++ def test_api_key_with_existing_headers(self):+ """Test that api_key is added to existing headers"""+ guardrail = GenericGuardrailAPI(+ api_base="https://api.test.guardrail.com",+ api_key="test-api-key-456",+ headers={"Custom-Header": "custom-value"},+ )+ assert guardrail.headers.get("x-api-key") == "test-api-key-456"+ assert guardrail.headers.get("Custom-Header") == "custom-value"++ def test_no_api_key_no_x_api_key_header(self):+ """Test that x-api-key header is not set when api_key is not provided"""+ guardrail = GenericGuardrailAPI(+ api_base="https://api.test.guardrail.com",+ )+ assert "x-api-key" not in guardrail.headers+class TestMetadataExtraction:"""Test metadata extraction from request data"""@@ -446,6 +471,39 @@ class TestImageSupport:assert result_images == ["https://example.com/image.jpg"]+class TestApiKeyHeader:+ """Test API key header handling"""++ @pytest.mark.asyncio+ async def test_x_api_key_header_sent_in_request(self, mock_request_data_input):+ """Test that x-api-key header is sent in the API request when api_key is provided"""+ guardrail = GenericGuardrailAPI(+ api_base="https://api.test.guardrail.com",+ api_key="my-secret-api-key",+ )++ mock_response = MagicMock()+ mock_response.json.return_value = {+ "action": "NONE",+ "texts": ["test"],+ }+ mock_response.raise_for_status = MagicMock()++ with patch.object(+ guardrail.async_handler, "post", return_value=mock_response+ ) as mock_post:+ await guardrail.apply_guardrail(+ inputs={"texts": ["test"]},+ request_data=mock_request_data_input,+ input_type="request",+ )++ # Verify API was called with x-api-key header+ call_args = mock_post.call_args+ headers = call_args.kwargs["headers"]+ assert headers.get("x-api-key") == "my-secret-api-key"++class TestAdditionalParams:"""Test additional provider-specific parameters"""