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]

feat(proxy/utils.py): support model level guardrails on stream event

Krrish Dholakiae5d68e522220
diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.py
index 5bf84bd8ce4..b6792354334 100644
--- a/litellm/integrations/custom_guardrail.py
+++ b/litellm/integrations/custom_guardrail.py
@@ -129,6 +129,7 @@ class CustomGuardrail(CustomLogger):
self,
requested_guardrails: Union[List[str], List[Dict[str, DynamicGuardrailParams]]],
) -> bool:
+
for _guardrail in requested_guardrails:
if isinstance(_guardrail, dict):
if self.guardrail_name in _guardrail:
diff --git a/litellm/proxy/_experimental/out/model_hub_table/index.html b/litellm/proxy/_experimental/out/model_hub_table/index.html
new file mode 100644
index 00000000000..155cf9b802a
--- /dev/null
+++ b/litellm/proxy/_experimental/out/model_hub_table/index.html
@@ -0,0 +1 @@
+<!DOCTYPE html><html id="__next_error__"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="preload" as="script" fetchPriority="low" href="/litellm-asset-prefix/_next/static/chunks/webpack-a426aae3231a8df1.js"/><script src="/litellm-asset-prefix/_next/static/chunks/fd9d1056-205af899b895cbac.js" async=""></script><script src="/litellm-asset-prefix/_next/static/chunks/117-a0da667066d322b6.js" async=""></script><script src="/litellm-asset-prefix/_next/static/chunks/main-app-475d6efe4080647d.js" async=""></script><title>LiteLLM Dashboard</title><meta name="description" content="LiteLLM Proxy Admin UI"/><link rel="icon" href="/favicon.ico" type="image/x-icon" sizes="16x16"/><link rel="icon" href="./favicon.ico"/><meta name="next-size-adjust"/><script src="/litellm-asset-prefix/_next/static/chunks/polyfills-42372ed130431b0a.js" noModule=""></script></head><body><script src="/litellm-asset-prefix/_next/static/chunks/webpack-a426aae3231a8df1.js" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0]);self.__next_f.push([2,null])</script><script>self.__next_f.push([1,"1:HL[\"/litellm-asset-prefix/_next/static/media/e4af272ccee01ff0-s.p.woff2\",\"font\",{\"crossOrigin\":\"\",\"type\":\"font/woff2\"}]\n2:HL[\"/litellm-asset-prefix/_next/static/css/31b7f215e119031e.css\",\"style\"]\n3:HL[\"/litellm-asset-prefix/_next/static/css/dd3d607f47531000.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"4:I[12846,[],\"\"]\n6:I[19107,[],\"ClientPageRoot\"]\n7:I[22775,[\"445\",\"static/chunks/445-e14a4d059f7305d5.js\",\"152\",\"static/chunks/152-c78d9bb44a92a615.js\",\"634\",\"static/chunks/634-74ee1cee62277068.js\",\"475\",\"static/chunks/475-4e66b9c01db4c006.js\",\"338\",\"static/chunks/338-58247f2bc5fc3b51.js\",\"162\",\"static/chunks/162-e1f42f86a1eb3286.js\",\"172\",\"static/chunks/172-b2d8ff2740510f56.js\",\"25\",\"static/chunks/app/model_hub_table/page-f3fc1d21cad686db.js\"],\"default\",1]\n8:I[4707,[],\"\"]\n9:I[36423,[],\"\"]\nb:I[61060,[],\"\"]\nc:[]\n"])</script><script>self.__next_f.push([1,"0:[\"$\",\"$L4\",null,{\"buildId\":\"-NrHJ0b9HqrHBQ9wRZS8v\",\"assetPrefix\":\"/litellm-asset-prefix\",\"urlParts\":[\"\",\"model_hub_table\"],\"initialTree\":[\"\",{\"children\":[\"model_hub_table\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",true],\"initialSeedData\":[\"\",{\"children\":[\"model_hub_table\",{\"children\":[\"__PAGE__\",{},[[\"$L5\",[\"$\",\"$L6\",null,{\"props\":{\"params\":{},\"searchParams\":{}},\"Component\":\"$7\"}],null],null],null]},[null,[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\",\"model_hub_table\",\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"notFoundStyles\":\"$undefined\"}]],null]},[[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/litellm-asset-prefix/_next/static/css/31b7f215e119031e.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}],[\"$\",\"link\",\"1\",{\"rel\":\"stylesheet\",\"href\":\"/litellm-asset-prefix/_next/static/css/dd3d607f47531000.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"children\":[\"$\",\"body\",null,{\"className\":\"__className_b0dd8a\",\"children\":[\"$\",\"$L8\",null,{\"parallelRouterKey\":\"children\",\"segmentPath\":[\"children\"],\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L9\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":\"404\"}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],\"notFoundStyles\":[]}]}]}]],null],null],\"couldBeIntercepted\":false,\"initialHead\":[null,\"$La\"],\"globalErrorComponent\":\"$b\",\"missingSlots\":\"$Wc\"}]\n"])</script><script>self.__next_f.push([1,"a:[[\"$\",\"meta\",\"0\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}],[\"$\",\"meta\",\"1\",{\"charSet\":\"utf-8\"}],[\"$\",\"title\",\"2\",{\"children\":\"LiteLLM Dashboard\"}],[\"$\",\"meta\",\"3\",{\"name\":\"description\",\"content\":\"LiteLLM Proxy Admin UI\"}],[\"$\",\"link\",\"4\",{\"rel\":\"icon\",\"href\":\"/favicon.ico\",\"type\":\"image/x-icon\",\"sizes\":\"16x16\"}],[\"$\",\"link\",\"5\",{\"rel\":\"icon\",\"href\":\"./favicon.ico\"}],[\"$\",\"meta\",\"6\",{\"name\":\"next-size-adjust\"}]]\n5:null\n"])</script></body></html>
\ No newline at end of file
diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yaml
index c249da05345..c9d8c4f7f51 100644
--- a/litellm/proxy/_new_secret_config.yaml
+++ b/litellm/proxy/_new_secret_config.yaml
@@ -10,13 +10,6 @@ model_list:
model: openai/gpt-4o
guardrails:
- - guardrail_name: "presidio-pii"
- litellm_params:
- guardrail: presidio # supported values: "aporia", "bedrock", "lakera", "presidio"
- mode: "pre_call"
- presidio_language: "en" # optional: set default language for PII analysis
- pii_entities_config:
- PERSON: "BLOCK" # Will mask credit card numbers
- guardrail_name: azure-text-moderation
litellm_params:
guardrail: azure/text_moderations
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index 655b50cfc20..02b7e14229c 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -1077,6 +1077,8 @@ class ProxyLogging:
Covers:
1. /chat/completions
"""
+ from litellm.proxy.proxy_server import llm_router
+
response_str: Optional[str] = None
if isinstance(response, (ModelResponse, ModelResponseStream)):
response_str = litellm.get_response_string(response_obj=response)
@@ -1088,9 +1090,15 @@ class ProxyLogging:
# Main - V2 Guardrails implementation
from litellm.types.guardrails import GuardrailEventHooks
+ ## CHECK FOR MODEL-LEVEL GUARDRAILS
+ modified_data = _check_and_merge_model_level_guardrails(
+ data=data, llm_router=llm_router
+ )
+
if (
callback.should_run_guardrail(
- data=data, event_type=GuardrailEventHooks.post_call
+ data=modified_data,
+ event_type=GuardrailEventHooks.post_call,
)
is not True
):
@@ -3012,6 +3020,74 @@ def _to_ns(dt):
return int(dt.timestamp() * 1e9)
+def _check_and_merge_model_level_guardrails(
+ data: dict, llm_router: Optional[Router]
+) -> dict:
+ """
+ Check if the model has guardrails defined and merge them with existing guardrails in the request data.
+
+ Args:
+ data: The request data dict
+ llm_router: The LLM router instance to get deployment info from
+
+ Returns:
+ Modified data dict with merged guardrails (if any model-level guardrails exist)
+ """
+ if llm_router is None:
+ return data
+
+ # Get the model ID from the data
+ metadata = data.get("metadata") or {}
+ model_info = metadata.get("model_info") or {}
+ model_id = model_info.get("id", None)
+
+ if model_id is None:
+ return data
+
+ # Check if the model has guardrails
+ deployment = llm_router.get_deployment(model_id=model_id)
+ if deployment is None:
+ return data
+
+ model_level_guardrails = deployment.litellm_params.get("guardrails")
+
+ if model_level_guardrails is None:
+ return data
+
+ # Merge model-level guardrails with existing ones
+ return _merge_guardrails_with_existing(data, model_level_guardrails)
+
+
+def _merge_guardrails_with_existing(data: dict, model_level_guardrails: Any) -> dict:
+ """
+ Merge model-level guardrails with any existing guardrails in the request data.
+
+ Args:
+ data: The request data dict
+ model_level_guardrails: Guardrails defined at the model level
+
+ Returns:
+ Modified data dict with merged guardrails in metadata
+ """
+ modified_data = data.copy()
+ metadata = modified_data.setdefault("metadata", {})
+ existing_guardrails = metadata.get("guardrails", [])
+
+ # Ensure existing_guardrails is a list
+ if not isinstance(existing_guardrails, list):
+ existing_guardrails = [existing_guardrails] if existing_guardrails else []
+
+ # Ensure model_level_guardrails is a list
+ if not isinstance(model_level_guardrails, list):
+ model_level_guardrails = (
+ [model_level_guardrails] if model_level_guardrails else []
+ )
+
+ # Combine existing and model-level guardrails
+ metadata["guardrails"] = list(set(existing_guardrails + model_level_guardrails))
+ return modified_data
+
+
def get_error_message_str(e: Exception) -> str:
error_message = ""
if isinstance(e, HTTPException):
@@ -3194,6 +3270,7 @@ def is_valid_api_key(key: str) -> bool:
- Length between 20 and 100 characters
"""
import re
+
if not isinstance(key, str):
return False
if 3 <= len(key) <= 100: