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(guardrails): Add per-request profile overrides to PANW Prisma AIRS (#16069)
Jason Roberts667225076971
diff --git a/docs/my-website/docs/proxy/guardrails/panw_prisma_airs.md b/docs/my-website/docs/proxy/guardrails/panw_prisma_airs.mdindex 97f3e7efe54..e1d6ddf5928 100644--- a/docs/my-website/docs/proxy/guardrails/panw_prisma_airs.md+++ b/docs/my-website/docs/proxy/guardrails/panw_prisma_airs.md@@ -199,10 +199,44 @@ Expected successful response:| Parameter | Required | Description | Default ||-----------|----------|-------------|---------|| `api_key` | Yes | Your PANW Prisma AIRS API key from Strata Cloud Manager | - |-| `profile_name` | Yes | Security profile name configured in Strata Cloud Manager | - |+| `profile_name` | No | Security profile name configured in Strata Cloud Manager. Optional if API key has linked profile | - |+| `app_name` | No | Application identifier for tracking in Prisma AIRS analytics (will be prefixed with "LiteLLM-") | `LiteLLM` || `api_base` | No | Custom API base URL (without /v1/scan/sync/request path) | `https://service.api.aisecurity.paloaltonetworks.com` || `mode` | No | When to run the guardrail | `pre_call` |+## Per-Request Metadata Overrides++You can override guardrail settings on a per-request basis using the `metadata` field:++```json+{+ "model": "gpt-4",+ "messages": [...],+ "metadata": {+ "profile_name": "dev-allow-all", // Override profile name+ "profile_id": "uuid-here", // Override profile ID (takes precedence)+ "user_ip": "192.168.1.100", // Track user IP+ "app_name": "MyApp" // Custom app name (becomes "LiteLLM-MyApp")+ }+}+```++**Supported Metadata Fields:**++| Field | Description | Priority |+|-------|-------------|----------|+| `profile_name` | PANW AI security profile name | Per-request > config |+| `profile_id` | PANW AI security profile ID (takes precedence over profile_name) | Per-request only |+| `user_ip` | User IP address for tracking in Prisma AIRS | Per-request only |+| `app_name` | Application identifier (prefixed with "LiteLLM-") | Per-request > config > "LiteLLM" |++:::info Profile Resolution+- If both `profile_id` and `profile_name` are provided, PANW API uses `profile_id` (it takes precedence)+- If no profile is specified in metadata, uses the config `profile_name`+- If no profile is specified at all, PANW API will use the profile linked to your API key in Strata Cloud Manager+- **Note:** If your API key is not linked to a profile, you must provide `profile_name` or `profile_id`+:::+## Environment Variables```bash@@ -235,6 +269,43 @@ guardrails:profile_name: "permissive-policy" # Lower security profile```+### Multiple API Keys (Multi-Tenant)++For multi-tenant deployments where different customers need different PANW API keys, create separate guardrail instances:++```yaml+guardrails:+ - guardrail_name: "panw-customer-a"+ litellm_params:+ guardrail: panw_prisma_airs+ mode: "pre_call"+ api_key: os.environ/PANW_CUSTOMER_A_KEY # Linked to Customer A profile in SCM++ - guardrail_name: "panw-customer-b"+ litellm_params:+ guardrail: panw_prisma_airs+ mode: "pre_call"+ api_key: os.environ/PANW_CUSTOMER_B_KEY # Linked to Customer B profile in SCM+```++Then route requests to the appropriate guardrail:++```bash+curl -X POST http://localhost:4000/v1/chat/completions \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer sk-1234" \+ -d '{+ "model": "gpt-4",+ "messages": [{"role": "user", "content": "Hello"}],+ "guardrails": ["panw-customer-a"]+ }'+```++**Use Cases:**+- **Multi-tenant deployments**: Different customers with different security policies+- **Environment-specific policies**: Dev/staging/prod with different API keys and profiles+- **A/B testing**: Compare different security profiles side-by-side+### Content MaskingPANW Prisma AIRS can automatically mask sensitive content (PII, credit cards, SSNs, etc.) instead of blocking requests. This allows your application to continue functioning while protecting sensitive data.diff --git a/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/__init__.pyindex e69077401e9..05e6ee49a23 100644--- a/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/__init__.py+++ b/litellm/proxy/guardrails/guardrail_hooks/panw_prisma_airs/__init__.py@@ -1,4 +1,4 @@-from typing import TYPE_CHECKING, Optional, cast+from typing import TYPE_CHECKINGfrom litellm.types.guardrails import SupportedGuardrailIntegrations@@ -12,11 +12,8 @@ def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"import litellmguardrail_name = guardrail.get("guardrail_name")- profile_name = cast(Optional[str], getattr(litellm_params, "profile_name", None))-- # Note: api_key can be None here - handler will fallback to PANW_PRISMA_AIRS_API_KEY env var- if not profile_name:- raise ValueError("PANW Prisma AIRS: profile_name is required")++ # Note: api_key and profile_name can be None - handler will use env vars or API key's linked profileif not guardrail_name:raise ValueError("PANW Prisma AIRS: guardrail_name is required")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 c6d2543f9f4..814fb6deb2c 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@@ -7,6 +7,7 @@ Provides real-time threat detection, DLP, URL filtering, content masking, and poimport osfrom litellm._uuid import uuid+from litellm.caching import DualCachefrom typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Typefrom fastapi import HTTPException@@ -38,7 +39,8 @@ class PanwPrismaAirsHandler(CustomGuardrail):guardrail_name: Name of the guardrail instanceapi_key: PANW Prisma AIRS API keyapi_base: PANW Prisma AIRS API endpoint (default: https://service.api.aisecurity.paloaltonetworks.com)- profile_name: PANW security profile name+ profile_name: PANW security profile name (optional if API key has linked profile)+ app_name: Application name for tracking in Prisma AIRS analytics (default: "LiteLLM")mask_request_content: Apply masking to prompts (default: False)mask_response_content: Apply masking to responses (default: False)mask_on_block: Backwards compatible flag that enables both request and response masking@@ -47,13 +49,14 @@ class PanwPrismaAirsHandler(CustomGuardrail):def __init__(self,guardrail_name: str,- profile_name: str,+ profile_name: Optional[str] = None,api_key: Optional[str] = None,api_base: Optional[str] = None,default_on: bool = True,mask_on_block: bool = False,mask_request_content: bool = False,mask_response_content: bool = False,+ app_name: Optional[str] = None,**kwargs,):"""Initialize PANW Prisma AIRS guardrail handler."""@@ -69,7 +72,7 @@ class PanwPrismaAirsHandler(CustomGuardrail):default_on=default_on,mask_request_content=_mask_request_content,mask_response_content=_mask_response_content,- **kwargs+ **kwargs,)# Store configuration with env var fallbacks@@ -80,7 +83,13 @@ class PanwPrismaAirsHandler(CustomGuardrail):or "https://service.api.aisecurity.paloaltonetworks.com")self.profile_name = profile_name-++ # Handle app_name: Default to "LiteLLM", or prefix user's app_name with "LiteLLM-"+ if app_name:+ self.app_name = f"LiteLLM-{app_name}"+ else:+ self.app_name = "LiteLLM"+# Validate required configurationif not self.api_key:raise ValueError(@@ -88,9 +97,19 @@ class PanwPrismaAirsHandler(CustomGuardrail):"Set it via config or PANW_PRISMA_AIRS_API_KEY environment variable.")+ # Warn if no profile is configured (user must have API key with linked profile)+ if not self.profile_name:+ verbose_proxy_logger.warning(+ f"PANW Prisma AIRS Guardrail '{guardrail_name}': No profile_name configured. "+ f"Ensure your API key has a linked profile in Strata Cloud Manager, "+ f"or provide 'profile_name'/'profile_id' via config or per-request metadata. "+ f"Requests will fail if the API key is not linked to a profile."+ )+verbose_proxy_logger.info(f"Initialized PANW Prisma AIRS Guardrail: {guardrail_name} "- f"(mask_request={self.mask_request_content}, mask_response={self.mask_response_content})"+ f"(profile={self.profile_name or 'API-key-linked'}, "+ f"mask_request={self.mask_request_content}, mask_response={self.mask_response_content})")def _extract_text_from_messages(self, messages: List[Dict[str, Any]]) -> str:@@ -136,27 +155,37 @@ class PanwPrismaAirsHandler(CustomGuardrail):"""try:from litellm.types.utils import Choices-+text_parts = []-+if hasattr(response, "choices") and response.choices:for choice in response.choices:if isinstance(choice, Choices):# Extract message contentif choice.message.content:text_parts.append(str(choice.message.content))-+# Extract tool call arguments- if hasattr(choice.message, "tool_calls") and choice.message.tool_calls:+ if (+ hasattr(choice.message, "tool_calls")+ and choice.message.tool_calls+ ):for tool_call in choice.message.tool_calls:- if hasattr(tool_call, "function") and hasattr(tool_call.function, "arguments"):+ if hasattr(tool_call, "function") and hasattr(+ tool_call.function, "arguments"+ ):text_parts.append(str(tool_call.function.arguments))-+# Extract function call arguments (legacy)- if hasattr(choice.message, "function_call") and choice.message.function_call:+ if (+ hasattr(choice.message, "function_call")+ and choice.message.function_call+ ):if hasattr(choice.message.function_call, "arguments"):- text_parts.append(str(choice.message.function_call.arguments))-+ text_parts.append(+ str(choice.message.function_call.arguments)+ )+return " ".join(text_parts) if text_parts else ""except (AttributeError, IndexError) as e:verbose_proxy_logger.error(@@ -164,35 +193,76 @@ class PanwPrismaAirsHandler(CustomGuardrail):)return ""- async def _call_panw_api(+ async def _call_panw_api( # noqa: PLR0915self,content: str,is_response: bool = False,metadata: Optional[Dict[str, Any]] = None,+ call_id: Optional[str] = None,) -> Dict[str, Any]:"""Call PANW Prisma AIRS API to scan content."""if not content.strip():return {"action": "allow", "category": "empty"}- # Build request payload- transaction_id = (- f"litellm-{'resp' if is_response else 'req'}-{uuid.uuid4().hex[:8]}"- )+ # Use litellm_call_id if provided, fallback to generating UUID+ litellm_call_id = call_id or str(uuid.uuid4())++ # Build transaction ID with prompt/response prefix + full call_id for correlation+ transaction_id = f"litellm-{'resp' if is_response else 'req'}-{litellm_call_id}"++ # Build Prisma AIRS API metadata+ # Handle app_name: LiteLLM by default, or LiteLLM-{user_app_name} if user provides one+ user_app_name = metadata.get("app_name") if metadata else None+ if user_app_name:+ app_name_value = f"LiteLLM-{user_app_name}"+ else:+ app_name_value = self.app_name # Defaults to "LiteLLM"++ panw_metadata = {+ "app_user": (+ metadata.get("user", "litellm_user") if metadata else "litellm_user"+ ),+ "ai_model": metadata.get("model", "unknown") if metadata else "unknown",+ "app_name": app_name_value,+ "source": "litellm_builtin_guardrail",+ }++ # Include user_ip if available (from LiteLLM metadata or request)+ if metadata and metadata.get("user_ip"):+ panw_metadata["user_ip"] = metadata["user_ip"]+ elif metadata and metadata.get("requester_ip_address"):+ panw_metadata["user_ip"] = metadata["requester_ip_address"]payload = {"tr_id": transaction_id,- "ai_profile": {"profile_name": self.profile_name},- "metadata": {- "app_user": (- metadata.get("user", "litellm_user") if metadata else "litellm_user"- ),- "ai_model": metadata.get("model", "unknown") if metadata else "unknown",- "source": "litellm_builtin_guardrail",- },+ "metadata": panw_metadata,"contents": [{"response" if is_response else "prompt": content}],}+ # Build ai_profile object per PANW API schema+ # Priority: per-request profile_id > per-request profile_name > config profile_name+ # Note: If both are provided, PANW API uses profile_id (profile_id takes precedence)+ profile_name = None+ profile_id = None++ if metadata:+ profile_id = metadata.get("profile_id")+ profile_name = metadata.get("profile_name", self.profile_name)+ else:+ profile_name = self.profile_name++ # Add ai_profile to payload if profile is specified+ # If neither profile_name nor profile_id is provided, PANW API will use the+ # profile linked to the API key (if configured in Strata Cloud Manager)+ if profile_name or profile_id:+ ai_profile = {}+ if profile_id:+ ai_profile["profile_id"] = profile_id+ if profile_name:+ ai_profile["profile_name"] = profile_name+ payload["ai_profile"] = ai_profile+if is_response:payload["metadata"]["is_response"] = True # type: ignore[index]@@ -225,16 +295,51 @@ class PanwPrismaAirsHandler(CustomGuardrail):)return {"action": "block", "category": "api_error"}+ # Check for profile-related errors from PANW API+ if result.get("action") == "block" and "error" in result:+ error_msg = str(result.get("error", "")).lower()+ if "profile" in error_msg and (+ "not found" in error_msg+ or "required" in error_msg+ or "invalid" in error_msg+ ):+ verbose_proxy_logger.error(+ f"PANW Prisma AIRS: Profile configuration error. "+ f"Ensure your API key has a linked profile in Strata Cloud Manager, "+ f"or provide 'profile_name' or 'profile_id' in config/metadata. "+ f"PANW API response: {result}"+ )+verbose_proxy_logger.debug(f"PANW Prisma AIRS: Scan result - Action: {result.get('action')}, Category: {result.get('category', 'unknown')}")return resultexcept Exception as e:- verbose_proxy_logger.error(f"PANW Prisma AIRS: API call failed: {str(e)}")+ error_msg = str(e).lower()++ # Check for profile-related errors in HTTP error responses+ if "profile" in error_msg and (+ "not found" in error_msg+ or "required" in error_msg+ or "invalid" in error_msg+ ):+ verbose_proxy_logger.error(+ f"PANW Prisma AIRS: Profile configuration error - {str(e)}. "+ f"Your API key may not be linked to a profile. "+ f"Either link your API key to a profile in Strata Cloud Manager, "+ f"or provide 'profile_name'/'profile_id' in your guardrail config or request metadata."+ )+ else:+ verbose_proxy_logger.error(+ f"PANW Prisma AIRS: API call failed: {str(e)}"+ )+return {"action": "block", "category": "api_error"}- def _get_masked_text(self, scan_result: Dict[str, Any], is_response: bool = False) -> Optional[str]:+ def _get_masked_text(+ self, scan_result: Dict[str, Any], is_response: bool = False+ ) -> Optional[str]:"""Extract masked text from PANW scan result."""masked_key = "response_masked_data" if is_response else "prompt_masked_data"masked_data = scan_result.get(masked_key)@@ -243,9 +348,7 @@ class PanwPrismaAirsHandler(CustomGuardrail):return Nonedef _apply_masking_to_messages(- self,- messages: List[Dict[str, Any]],- masked_text: str+ self, messages: List[Dict[str, Any]], masked_text: str) -> List[Dict[str, Any]]:"""Apply masked text to the last user message."""if not messages:@@ -255,7 +358,7 @@ class PanwPrismaAirsHandler(CustomGuardrail):if message.get("role") == "user":new_message = message.copy()content = message.get("content")-+if isinstance(content, str):new_message["content"] = masked_textelif isinstance(content, list):@@ -266,16 +369,14 @@ class PanwPrismaAirsHandler(CustomGuardrail):else:new_content.append(part)new_message["content"] = new_content-+idx = len(messages) - i - 1- return messages[:idx] + [new_message] + messages[idx+1:]-+ return messages[:idx] + [new_message] + messages[idx + 1 :]+return messagesdef _apply_masking_to_response(- self,- response: ModelResponse,- masked_text: str+ self, response: ModelResponse, masked_text: str) -> None:"""Apply masked text to all content in response in-place.@@ -283,10 +384,10 @@ class PanwPrismaAirsHandler(CustomGuardrail):Preserves list-based content structure (e.g., multimodal messages)."""from litellm.types.utils import Choices-+if not hasattr(response, "choices") or not response.choices:return-+for choice in response.choices:if isinstance(choice, Choices):# Mask message content - handle both string and list formats@@ -299,20 +400,27 @@ class PanwPrismaAirsHandler(CustomGuardrail):new_content = []for part in content: # type: ignoreif isinstance(part, dict) and part.get("type") == "text":- new_content.append({"type": "text", "text": masked_text})+ new_content.append(+ {"type": "text", "text": masked_text}+ )else:# Preserve non-text parts (images, etc.)new_content.append(part)choice.message.content = new_content # type: ignore-+# Mask tool call argumentsif hasattr(choice.message, "tool_calls") and choice.message.tool_calls:for tool_call in choice.message.tool_calls:- if hasattr(tool_call, "function") and hasattr(tool_call.function, "arguments"):+ if hasattr(tool_call, "function") and hasattr(+ tool_call.function, "arguments"+ ):tool_call.function.arguments = masked_text-+# Mask function call arguments (legacy)- if hasattr(choice.message, "function_call") and choice.message.function_call:+ if (+ hasattr(choice.message, "function_call")+ and choice.message.function_call+ ):if hasattr(choice.message.function_call, "arguments"):choice.message.function_call.arguments = masked_text@@ -355,11 +463,46 @@ class PanwPrismaAirsHandler(CustomGuardrail):return error_detail+ def _prepare_metadata_from_request(self, data: Dict[str, Any]) -> Dict[str, Any]:+ """+ Extract and prepare metadata from request data for PANW API call.++ Supported metadata fields (from request.metadata):+ - profile_name: AI security profile name (PANW API field)+ - profile_id: AI security profile ID (PANW API field, takes precedence)+ - user_ip: User IP address for tracking+ - app_name: Application identifier (will be prefixed with "LiteLLM-")++ Note: If neither profile_name nor profile_id is provided, PANW API will use+ the profile linked to the API key (configured in Strata Cloud Manager).+ If both are provided, PANW API uses profile_id (profile_id takes precedence).+ """+ user_metadata = data.get("metadata", {}) or {}+ metadata = {+ "user": data.get("user") or "litellm_user",+ "model": data.get("model") or "unknown",+ }++ # Pass through PANW API fields+ if "profile_name" in user_metadata:+ metadata["profile_name"] = user_metadata["profile_name"]++ if "profile_id" in user_metadata:+ metadata["profile_id"] = user_metadata["profile_id"]++ if "user_ip" in user_metadata:+ metadata["user_ip"] = user_metadata["user_ip"]++ if "app_name" in user_metadata:+ metadata["app_name"] = user_metadata["app_name"]++ return metadata+@log_guardrail_informationasync def async_pre_call_hook(self,user_api_key_dict: UserAPIKeyAuth,- cache: Any,+ cache: DualCache,data: Dict[str, Any],call_type: Literal["completion",@@ -371,6 +514,7 @@ class PanwPrismaAirsHandler(CustomGuardrail):"pass_through_endpoint","rerank","mcp_call",+ "anthropic_messages",],) -> Optional[Dict[str, Any]]:"""@@ -394,7 +538,7 @@ class PanwPrismaAirsHandler(CustomGuardrail):# Extract prompt text from messages (chat completion) or prompt (text completion)messages = data.get("messages", [])prompt_text = self._extract_text_from_messages(messages)-+# Fallback to prompt field for text completion requestsif not prompt_text:prompt_value = data.get("prompt")@@ -412,15 +556,15 @@ class PanwPrismaAirsHandler(CustomGuardrail):)return None- # Prepare metadata- metadata = {- "user": data.get("user") or "litellm_user",- "model": data.get("model") or "unknown",- }+ # Prepare metadata - include user's metadata for profile override+ metadata = self._prepare_metadata_from_request(data)# Scan prompt with PANW Prisma AIRSscan_result = await self._call_panw_api(- content=prompt_text, is_response=False, metadata=metadata+ content=prompt_text,+ is_response=False,+ metadata=metadata,+ call_id=data.get("litellm_call_id"),)action = scan_result.get("action", "block")@@ -431,7 +575,9 @@ class PanwPrismaAirsHandler(CustomGuardrail):if action == "allow":if masked_text:if messages:- data["messages"] = self._apply_masking_to_messages(messages, masked_text)+ data["messages"] = self._apply_masking_to_messages(+ messages, masked_text+ )elif "prompt" in data:data["prompt"] = masked_textverbose_proxy_logger.info(@@ -449,7 +595,9 @@ class PanwPrismaAirsHandler(CustomGuardrail):# Action is "block" - check if we should mask instead of blockingif masked_text and self.mask_request_content:if messages:- data["messages"] = self._apply_masking_to_messages(messages, masked_text)+ data["messages"] = self._apply_masking_to_messages(+ messages, masked_text+ )elif "prompt" in data:data["prompt"] = masked_textverbose_proxy_logger.warning(@@ -475,13 +623,13 @@ class PanwPrismaAirsHandler(CustomGuardrail):status_code=500,detail={"error": {- "message": "Security scan failed - request blocked for safety",- "type": "guardrail_scan_error",- "code": "panw_prisma_airs_scan_failed",- "guardrail": self.guardrail_name,- }+ "message": "Security scan failed - request blocked for safety",+ "type": "guardrail_scan_error",+ "code": "panw_prisma_airs_scan_failed",+ "guardrail": self.guardrail_name,}- )+ },+ )@log_guardrail_informationasync def async_post_call_success_hook(@@ -521,15 +669,15 @@ class PanwPrismaAirsHandler(CustomGuardrail):)return response- # Prepare metadata- metadata = {- "user": data.get("user") or "litellm_user",- "model": data.get("model") or "unknown",- }+ # Prepare metadata - include user's metadata for profile override+ metadata = self._prepare_metadata_from_request(data)# Scan response with PANW Prisma AIRSscan_result = await self._call_panw_api(- content=response_text, is_response=True, metadata=metadata+ content=response_text,+ is_response=True,+ metadata=metadata,+ call_id=data.get("litellm_call_id"),)action = scan_result.get("action", "block")@@ -583,7 +731,7 @@ class PanwPrismaAirsHandler(CustomGuardrail):"code": "panw_prisma_airs_scan_failed","guardrail": self.guardrail_name,}- }+ },)async def _scan_and_process_streaming_response(@@ -597,25 +745,27 @@ class PanwPrismaAirsHandler(CustomGuardrail):"""content_was_modified = Falseresponse_text = self._extract_response_text(assembled_model_response)-+if not response_text or not response_text.strip():- verbose_proxy_logger.info("PANW Prisma AIRS: No content to scan in streaming response")+ verbose_proxy_logger.info(+ "PANW Prisma AIRS: No content to scan in streaming response"+ )return content_was_modified, assembled_model_response-- # Prepare metadata and scan- metadata = {- "user": request_data.get("user") or "litellm_user",- "model": request_data.get("model") or "unknown",- }-++ # Prepare metadata - include user's metadata for profile override+ metadata = self._prepare_metadata_from_request(request_data)+scan_result = await self._call_panw_api(- content=response_text, is_response=True, metadata=metadata+ content=response_text,+ is_response=True,+ metadata=metadata,+ call_id=request_data.get("litellm_call_id"),)-+action = scan_result.get("action", "block")category = scan_result.get("category", "unknown")masked_text = self._get_masked_text(scan_result, is_response=True)-+# Handle scan resultsif action == "allow":if masked_text:@@ -640,7 +790,7 @@ class PanwPrismaAirsHandler(CustomGuardrail):f"PANW Prisma AIRS: {error_detail['error']['message']}")raise HTTPException(status_code=400, detail=error_detail)-+return content_was_modified, assembled_model_response@log_guardrail_information@@ -658,45 +808,50 @@ class PanwPrismaAirsHandler(CustomGuardrail):from litellm.proxy.common_utils.callback_utils import (add_guardrail_to_applied_guardrails_header,)-+# Check if guardrail should run for this requestfrom litellm.types.guardrails import GuardrailEventHooks as EventHooks-+if not self.should_run_guardrail(data=request_data, event_type=EventHooks.post_call):async for chunk in response:yield chunkreturn-+verbose_proxy_logger.info("PANW Prisma AIRS: Running post-call streaming scan")-+all_chunks = []content_was_modified = False-+try:# Collect all chunksasync for chunk in response:all_chunks.append(chunk)-+# Assemble complete response from chunksassembled_model_response = stream_chunk_builder(chunks=all_chunks)-+if isinstance(assembled_model_response, ModelResponse):# Scan and process the assembled response- content_was_modified, assembled_model_response = await self._scan_and_process_streaming_response(+ (+ content_was_modified,+ assembled_model_response,+ ) = await self._scan_and_process_streaming_response(assembled_model_response, request_data)-+# Add guardrail to applied guardrails header for observabilityadd_guardrail_to_applied_guardrails_header(request_data=request_data, guardrail_name=self.guardrail_name)-+# Only use MockResponseIterator if content was modified# Otherwise, yield original chunks to preserve streaming behaviorif content_was_modified:- mock_response = MockResponseIterator(model_response=assembled_model_response)+ mock_response = MockResponseIterator(+ model_response=assembled_model_response+ )async for chunk in mock_response:yield chunkelse:@@ -706,7 +861,7 @@ class PanwPrismaAirsHandler(CustomGuardrail):# If not a ModelResponse, just yield original chunksfor chunk in all_chunks:yield chunk-+except HTTPException:raiseexcept Exception as e:@@ -720,7 +875,7 @@ class PanwPrismaAirsHandler(CustomGuardrail):"code": "panw_prisma_airs_scan_failed","guardrail": self.guardrail_name,}- }+ },)@staticmethoddiff --git a/litellm/types/proxy/guardrails/guardrail_hooks/panw_prisma_airs.py b/litellm/types/proxy/guardrails/guardrail_hooks/panw_prisma_airs.pyindex c23c1542674..cd5fd4fc08c 100644--- a/litellm/types/proxy/guardrails/guardrail_hooks/panw_prisma_airs.py+++ b/litellm/types/proxy/guardrails/guardrail_hooks/panw_prisma_airs.py@@ -15,8 +15,14 @@ class PanwPrismaAirsGuardrailConfigModel(GuardrailConfigModel):description="The API base for the PANW Prisma AIRS guardrail. Defaults to https://service.api.aisecurity.paloaltonetworks.com. If not provided, the `PANW_PRISMA_AIRS_API_BASE` environment variable is checked.",)- profile_name: str = Field(- description="PANW Prisma AIRS security profile name configured in Strata Cloud Manager. Required.",+ profile_name: Optional[str] = Field(+ default=None,+ description="PANW Prisma AIRS security profile name configured in Strata Cloud Manager. Optional if API key has a linked profile.",+ )++ app_name: Optional[str] = Field(+ default=None,+ description="Application name for tracking this LiteLLM instance in Prisma AIRS analytics and dashboards. Defaults to 'LiteLLM' if not specified.",)mask_on_block: bool = Field(diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_panw_prisma_airs.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_panw_prisma_airs.pyindex 4d351c80da1..101a1d8275a 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_panw_prisma_airs.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_panw_prisma_airs.py@@ -9,7 +9,6 @@ This test file follows LiteLLM's testing patterns and covers:- Configuration validation"""-from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patchimport pytest@@ -61,6 +60,7 @@ class TestPanwAirsInitialization:assert isinstance(handler, PanwPrismaAirsHandler)assert handler.guardrail_name == "test_guardrail"+ @patch.dict("os.environ", {}, clear=True)def test_missing_api_key_raises_error(self):"""Test that missing API key raises ValueError."""# Test direct handler initialization without api_key or env var@@ -72,18 +72,17 @@ class TestPanwAirsInitialization:default_on=True,)- def test_missing_profile_name_raises_error(self):- """Test that missing profile name raises ValueError."""- litellm_params = SimpleNamespace(- api_key="test_key",- api_base=None,+ def test_api_key_with_linked_profile(self):+ """Test initialization with API key that has a linked profile (no explicit profile_name needed)."""+ # profile_name is optional when API key has linked profile+ handler = PanwPrismaAirsHandler(+ guardrail_name="test_panw_airs",+ api_key="test_api_key_with_linked_profile",+ profile_name=None, # Optional when API key has linked profiledefault_on=True,- profile_name=None,)- guardrail_config = {"guardrail_name": "test_guardrail"}-- with pytest.raises(ValueError, match="profile_name is required"):- initialize_guardrail(litellm_params, guardrail_config)+ assert handler.api_key == "test_api_key_with_linked_profile"+ assert handler.profile_name is None # Should be None, PANW API will use linked profileclass TestPanwAirsPromptScanning: