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] Add Guardrails for /v1/messages and /v1/responses API (#15686)

Ishaan Jaffcea318330e52
diff --git a/docs/my-website/docs/anthropic_unified.md b/docs/my-website/docs/anthropic_unified.md
index 03ba8a68847..62dea7051b0 100644
--- a/docs/my-website/docs/anthropic_unified.md
+++ b/docs/my-website/docs/anthropic_unified.md
@@ -16,6 +16,7 @@ Use LiteLLM to call all your LLM APIs in the Anthropic `v1/messages` format.
| Streaming | ✅ | |
| Fallbacks | ✅ | between supported models |
| Loadbalancing | ✅ | between supported models |
+| Guardrails | ✅ | |
| Support llm providers | **All LiteLLM supported providers** | `openai`, `anthropic`, `bedrock`, `vertex_ai`, `gemini`, `azure`, `azure_ai`, etc. |
## Usage
diff --git a/docs/my-website/docs/response_api.md b/docs/my-website/docs/response_api.md
index 80bd2ba6f7b..7b7db32fc6a 100644
--- a/docs/my-website/docs/response_api.md
+++ b/docs/my-website/docs/response_api.md
@@ -17,6 +17,7 @@ Requests to /chat/completions may be bridged here automatically when the provide
| Image Generation Streaming | ✅ | Progressive image generation with partial images (1-3) |
| Fallbacks | ✅ | Works between supported models |
| Loadbalancing | ✅ | Works between supported models |
+| Guardrails | ✅ | |
| Supported operations | Create a response, Get a response, Delete a response | |
| Supported LiteLLM Versions | 1.63.8+ | |
| Supported LLM providers | **All LiteLLM supported providers** | `openai`, `anthropic`, `bedrock`, `vertex_ai`, `gemini`, `azure`, `azure_ai` etc. |
diff --git a/enterprise/enterprise_hooks/aporia_ai.py b/enterprise/enterprise_hooks/aporia_ai.py
index de741aa6ca7..55ba6071820 100644
--- a/enterprise/enterprise_hooks/aporia_ai.py
+++ b/enterprise/enterprise_hooks/aporia_ai.py
@@ -174,6 +174,7 @@ class AporiaGuardrail(CustomGuardrail):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
from litellm.proxy.common_utils.callback_utils import (
diff --git a/enterprise/enterprise_hooks/google_text_moderation.py b/enterprise/enterprise_hooks/google_text_moderation.py
index 61987af7532..c1c932dcb04 100644
--- a/enterprise/enterprise_hooks/google_text_moderation.py
+++ b/enterprise/enterprise_hooks/google_text_moderation.py
@@ -6,13 +6,14 @@
# +-----------------------------------------------+
# Thank you users! We ❤️ you! - Krrish & Ishaan
-
from typing import Literal
-import litellm
-from litellm.proxy._types import UserAPIKeyAuth
-from litellm.integrations.custom_logger import CustomLogger
+
from fastapi import HTTPException
+
+import litellm
from litellm._logging import verbose_proxy_logger
+from litellm.integrations.custom_logger import CustomLogger
+from litellm.proxy._types import UserAPIKeyAuth
class _ENTERPRISE_GoogleTextModeration(CustomLogger):
@@ -96,6 +97,7 @@ class _ENTERPRISE_GoogleTextModeration(CustomLogger):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
"""
diff --git a/enterprise/enterprise_hooks/openai_moderation.py b/enterprise/enterprise_hooks/openai_moderation.py
index 0b6f34018b4..4464fff25c9 100644
--- a/enterprise/enterprise_hooks/openai_moderation.py
+++ b/enterprise/enterprise_hooks/openai_moderation.py
@@ -43,6 +43,7 @@ class _ENTERPRISE_OpenAI_Moderation(CustomLogger):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
text = ""
@@ -61,7 +62,7 @@ class _ENTERPRISE_OpenAI_Moderation(CustomLogger):
)
verbose_proxy_logger.debug("Moderation response: %s", moderation_response)
- if moderation_response.results[0].flagged is True:
+ if moderation_response and moderation_response.results[0].flagged is True:
raise HTTPException(
status_code=403, detail={"error": "Violated content safety policy"}
)
diff --git a/enterprise/litellm_enterprise/enterprise_callbacks/llama_guard.py b/enterprise/litellm_enterprise/enterprise_callbacks/llama_guard.py
index ea428b51b8e..80de7a396a4 100644
--- a/enterprise/litellm_enterprise/enterprise_callbacks/llama_guard.py
+++ b/enterprise/litellm_enterprise/enterprise_callbacks/llama_guard.py
@@ -106,6 +106,7 @@ class _ENTERPRISE_LlamaGuard(CustomLogger):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
"""
diff --git a/enterprise/litellm_enterprise/enterprise_callbacks/llm_guard.py b/enterprise/litellm_enterprise/enterprise_callbacks/llm_guard.py
index e290013248d..6f07250a61a 100644
--- a/enterprise/litellm_enterprise/enterprise_callbacks/llm_guard.py
+++ b/enterprise/litellm_enterprise/enterprise_callbacks/llm_guard.py
@@ -128,6 +128,7 @@ class _ENTERPRISE_LLMGuard(CustomLogger):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
"""
diff --git a/enterprise/litellm_enterprise/enterprise_callbacks/pagerduty/pagerduty.py b/enterprise/litellm_enterprise/enterprise_callbacks/pagerduty/pagerduty.py
index 8db0fcf752c..3162c2f12f8 100644
--- a/enterprise/litellm_enterprise/enterprise_callbacks/pagerduty/pagerduty.py
+++ b/enterprise/litellm_enterprise/enterprise_callbacks/pagerduty/pagerduty.py
@@ -152,6 +152,7 @@ class PagerDutyAlerting(SlackAlerting):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[Union[Exception, str, dict]]:
"""
diff --git a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
index e2963f8fb87..1dfa746b4f0 100644
--- a/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
+++ b/enterprise/litellm_enterprise/proxy/hooks/managed_files.py
@@ -4,12 +4,12 @@
import asyncio
import base64
import json
-from litellm._uuid import uuid
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union, cast
from fastapi import HTTPException
from litellm import Router, verbose_logger
+from litellm._uuid import uuid
from litellm.caching.caching import DualCache
from litellm.integrations.custom_logger import CustomLogger
from litellm.litellm_core_utils.prompt_templates.common_utils import extract_file_data
@@ -291,6 +291,7 @@ class _PROXY_LiteLLMManagedFiles(CustomLogger, BaseFileEndpoints):
"alist_fine_tuning_jobs",
"acancel_fine_tuning_job",
"mcp_call",
+ "anthropic_messages",
],
) -> Union[Exception, str, Dict, None]:
"""
diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.py
index 22e652e1d7b..86eed1747be 100644
--- a/litellm/integrations/custom_guardrail.py
+++ b/litellm/integrations/custom_guardrail.py
@@ -11,6 +11,9 @@ from litellm.types.guardrails import (
Mode,
PiiEntityType,
)
+from litellm.types.llms.openai import (
+ AllMessageValues,
+)
from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel
from litellm.types.utils import (
CallTypes,
@@ -492,6 +495,43 @@ class CustomGuardrail(CustomLogger):
"""
for key, value in vars(litellm_params).items():
setattr(self, key, value)
+
+ def get_guardrails_messages_for_call_type(self, call_type: CallTypes, data: Optional[dict] = None) -> Optional[List[AllMessageValues]]:
+ """
+ Returns the messages for the given call type and data
+ """
+ if call_type is None or data is None:
+ return None
+
+ #########################################################
+ # /chat/completions
+ # /messages
+ # Both endpoints store the messages in the "messages" key
+ #########################################################
+ if call_type == CallTypes.completion.value or call_type == CallTypes.acompletion.value or call_type == CallTypes.anthropic_messages.value:
+ return data.get("messages")
+
+ #########################################################
+ # /responses
+ # User/System messages are stored in the "input" key, use litellm transformation to get the messages
+ #########################################################
+ if call_type == CallTypes.responses.value or call_type == CallTypes.aresponses.value:
+ from typing import cast
+
+ from litellm.responses.litellm_completion_transformation.transformation import (
+ LiteLLMCompletionResponsesConfig,
+ )
+
+ input_data = data.get("input")
+ if input_data is None:
+ return None
+
+ messages = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(
+ input=input_data,
+ responses_api_request=data,
+ )
+ return cast(List[AllMessageValues], messages)
+ return None
def log_guardrail_information(func):
diff --git a/litellm/integrations/custom_logger.py b/litellm/integrations/custom_logger.py
index 615e64b97f9..d631c466865 100644
--- a/litellm/integrations/custom_logger.py
+++ b/litellm/integrations/custom_logger.py
@@ -293,6 +293,7 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbac
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[
Union[Exception, str, dict]
@@ -340,6 +341,7 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbac
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
) -> Any:
pass
diff --git a/litellm/proxy/anthropic_endpoints/endpoints.py b/litellm/proxy/anthropic_endpoints/endpoints.py
index e7ce5e888c0..c450b655a2c 100644
--- a/litellm/proxy/anthropic_endpoints/endpoints.py
+++ b/litellm/proxy/anthropic_endpoints/endpoints.py
@@ -87,7 +87,7 @@ async def anthropic_response( # noqa: PLR0915
### CALL HOOKS ### - modify incoming data before calling the model
data = await proxy_logging_obj.pre_call_hook( # type: ignore
- user_api_key_dict=user_api_key_dict, data=data, call_type="text_completion"
+ user_api_key_dict=user_api_key_dict, data=data, call_type=CallTypes.anthropic_messages.value
)
tasks = []
diff --git a/litellm/proxy/example_config_yaml/custom_callbacks1.py b/litellm/proxy/example_config_yaml/custom_callbacks1.py
index d84980f42d7..7e7f8133f4d 100644
--- a/litellm/proxy/example_config_yaml/custom_callbacks1.py
+++ b/litellm/proxy/example_config_yaml/custom_callbacks1.py
@@ -31,6 +31,7 @@ class MyCustomHandler(
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
):
return data
@@ -65,6 +66,7 @@ class MyCustomHandler(
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
pass
diff --git a/litellm/proxy/example_config_yaml/custom_guardrail.py b/litellm/proxy/example_config_yaml/custom_guardrail.py
index b05498eae5f..95324583158 100644
--- a/litellm/proxy/example_config_yaml/custom_guardrail.py
+++ b/litellm/proxy/example_config_yaml/custom_guardrail.py
@@ -33,6 +33,7 @@ class myCustomGuardrail(CustomGuardrail):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[Union[Exception, str, dict]]:
"""
@@ -69,6 +70,7 @@ class myCustomGuardrail(CustomGuardrail):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
"""
diff --git a/litellm/proxy/guardrails/guardrail_hooks/aim/aim.py b/litellm/proxy/guardrails/guardrail_hooks/aim/aim.py
index c95c41ee1d0..fd9b89d0834 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/aim/aim.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/aim/aim.py
@@ -77,6 +77,7 @@ class AimGuardrail(CustomGuardrail):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Union[Exception, str, dict, None]:
verbose_proxy_logger.debug("Inside AIM Pre-Call Hook")
@@ -96,6 +97,7 @@ class AimGuardrail(CustomGuardrail):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
) -> Union[Exception, str, dict, None]:
verbose_proxy_logger.debug("Inside AIM Moderation Hook")
diff --git a/litellm/proxy/guardrails/guardrail_hooks/aporia_ai/aporia_ai.py b/litellm/proxy/guardrails/guardrail_hooks/aporia_ai/aporia_ai.py
index 0d41e40e833..35f776e5bd1 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/aporia_ai/aporia_ai.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/aporia_ai/aporia_ai.py
@@ -189,6 +189,7 @@ class AporiaGuardrail(CustomGuardrail):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
from litellm.proxy.common_utils.callback_utils import (
diff --git a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py
index 7479c9dfcf9..99f3e4cf243 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py
@@ -14,7 +14,7 @@ sys.path.insert(
) # Adds the parent directory to the system path
import json
import sys
-from typing import Any, AsyncGenerator, List, Literal, Optional, Tuple, Union
+from typing import Any, AsyncGenerator, List, Literal, Optional, Tuple, Union, cast
import httpx
from fastapi import HTTPException
@@ -40,6 +40,7 @@ from litellm.types.proxy.guardrails.guardrail_hooks.bedrock_guardrails import (
BedrockTextContent,
)
from litellm.types.utils import (
+ CallTypes,
Choices,
GuardrailStatus,
ModelResponse,
@@ -600,9 +601,10 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Union[Exception, str, dict, None]:
- verbose_proxy_logger.debug("Inside AIM Pre-Call Hook")
+ verbose_proxy_logger.debug("Inside Bedrock Pre-Call Hook for call_type: %s", call_type)
from litellm.proxy.common_utils.callback_utils import (
add_guardrail_to_applied_guardrails_header,
@@ -611,19 +613,24 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):
event_type: GuardrailEventHooks = GuardrailEventHooks.pre_call
if self.should_run_guardrail(data=data, event_type=event_type) is not True:
return data
-
- new_messages: Optional[List[AllMessageValues]] = data.get("messages")
+
+ new_messages = self.get_guardrails_messages_for_call_type(
+ call_type=cast(CallTypes, call_type),
+ data=data,
+ )
+
+ # Handle None case
if new_messages is None:
- verbose_proxy_logger.warning(
- "Bedrock AI: not running guardrail. No messages in data"
- )
+ verbose_proxy_logger.debug("No messages found for call_type, skipping guardrail")
return data
-
+
#########################################################
########## 1. Make the Bedrock API request ##########
#########################################################
bedrock_guardrail_response = await self.make_bedrock_api_request(
- source="INPUT", messages=new_messages, request_data=data
+ source="INPUT",
+ messages=new_messages,
+ request_data=data,
)
#########################################################
@@ -657,6 +664,7 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
from litellm.proxy.common_utils.callback_utils import (
@@ -667,7 +675,11 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):
if self.should_run_guardrail(data=data, event_type=event_type) is not True:
return
- new_messages: Optional[List[AllMessageValues]] = data.get("messages")
+ new_messages = self.get_guardrails_messages_for_call_type(
+ call_type=cast(CallTypes, call_type),
+ data=data,
+ )
+
if new_messages is None:
verbose_proxy_logger.warning(
"Bedrock AI: not running guardrail. No messages in data"
diff --git a/litellm/proxy/guardrails/guardrail_hooks/custom_guardrail.py b/litellm/proxy/guardrails/guardrail_hooks/custom_guardrail.py
index 91878ad0f0d..bb4a74efc82 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/custom_guardrail.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/custom_guardrail.py
@@ -36,6 +36,7 @@ class myCustomGuardrail(CustomGuardrail):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[Union[Exception, str, dict]]:
"""
@@ -73,6 +74,7 @@ class myCustomGuardrail(CustomGuardrail):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
"""
diff --git a/litellm/proxy/guardrails/guardrail_hooks/enkryptai/enkryptai.py b/litellm/proxy/guardrails/guardrail_hooks/enkryptai/enkryptai.py
index 39e658355e8..bbff5419374 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/enkryptai/enkryptai.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/enkryptai/enkryptai.py
@@ -291,6 +291,7 @@ class EnkryptAIGuardrails(CustomGuardrail):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Union[Exception, str, dict, None]:
"""
@@ -348,6 +349,7 @@ class EnkryptAIGuardrails(CustomGuardrail):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
"""
diff --git a/litellm/proxy/guardrails/guardrail_hooks/javelin/javelin.py b/litellm/proxy/guardrails/guardrail_hooks/javelin/javelin.py
index 36b5700713b..9c82b511f56 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/javelin/javelin.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/javelin/javelin.py
@@ -175,6 +175,7 @@ class JavelinGuardrail(CustomGuardrail):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[Union[Exception, str, Dict]]:
"""
diff --git a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai.py b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai.py
index bd0a9eba7d5..a530682ae4f 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai.py
@@ -136,6 +136,7 @@ class lakeraAI_Moderation(CustomGuardrail):
"rerank",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
if (
@@ -315,6 +316,7 @@ class lakeraAI_Moderation(CustomGuardrail):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[Union[Exception, str, Dict]]:
from litellm.types.guardrails import GuardrailEventHooks
@@ -350,6 +352,7 @@ class lakeraAI_Moderation(CustomGuardrail):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
if self.event_hook is None:
diff --git a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py
index 0a75328f4da..9a0b21e6859 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py
@@ -193,6 +193,7 @@ class LakeraAIGuardrail(CustomGuardrail):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[Union[Exception, str, Dict]]:
from litellm.proxy.common_utils.callback_utils import (
@@ -264,6 +265,7 @@ class LakeraAIGuardrail(CustomGuardrail):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
from litellm.proxy.common_utils.callback_utils import (
diff --git a/litellm/proxy/guardrails/guardrail_hooks/lasso/lasso.py b/litellm/proxy/guardrails/guardrail_hooks/lasso/lasso.py
index cddbdc010d5..d4b7c03c7ab 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/lasso/lasso.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/lasso/lasso.py
@@ -83,6 +83,7 @@ class LassoGuardrail(CustomGuardrail):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Union[Exception, str, dict, None]:
verbose_proxy_logger.debug("Inside Lasso Pre-Call Hook")
@@ -101,6 +102,7 @@ class LassoGuardrail(CustomGuardrail):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
):
"""
diff --git a/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py b/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py
index e9ddca31777..82245f2ce0a 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py
@@ -360,6 +360,7 @@ class ModelArmorGuardrail(CustomGuardrail, VertexBase):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Union[Exception, str, dict, None]:
"""Pre-call hook to sanitize user prompts."""
diff --git a/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py b/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py
index 782c785ce58..7073a4341fb 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py
@@ -585,6 +585,7 @@ class NomaGuardrail(CustomGuardrail):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[Union[Exception, str, dict]]:
verbose_proxy_logger.debug("Running Noma pre-call hook")
@@ -646,6 +647,7 @@ class NomaGuardrail(CustomGuardrail):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
) -> Union[Exception, str, dict, None]:
event_type: GuardrailEventHooks = GuardrailEventHooks.during_call
diff --git a/litellm/proxy/guardrails/guardrail_hooks/pillar/pillar.py b/litellm/proxy/guardrails/guardrail_hooks/pillar/pillar.py
index e19125ed031..537b6038b53 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/pillar/pillar.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/pillar/pillar.py
@@ -15,6 +15,7 @@ from fastapi import HTTPException
# LiteLLM imports
from litellm import DualCache
from litellm._logging import verbose_proxy_logger
+from litellm._version import version as litellm_version
from litellm.integrations.custom_guardrail import (
CustomGuardrail,
log_guardrail_information,
@@ -30,8 +31,6 @@ from litellm.proxy.common_utils.callback_utils import (
)
from litellm.types.guardrails import GuardrailEventHooks
from litellm.types.utils import LLMResponseTypes
-from litellm._version import version as litellm_version
-
if TYPE_CHECKING:
from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel
@@ -172,6 +171,7 @@ class PillarGuardrail(CustomGuardrail):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[Union[Exception, str, dict]]:
"""
@@ -219,6 +219,7 @@ class PillarGuardrail(CustomGuardrail):
"audio_transcription",
"responses",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[Union[Exception, str, dict]]:
"""
diff --git a/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py b/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py
index 7519f0fa479..97f8dd76bd4 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py
@@ -1,10 +1,9 @@
-from fastapi import HTTPException
-
import re
from typing import Any, AsyncGenerator, Dict, List, Literal, Optional, Union
-from litellm import ChatCompletionToolParam
+from fastapi import HTTPException
+from litellm import ChatCompletionToolParam
from litellm._logging import verbose_proxy_logger
from litellm.caching.dual_cache import DualCache
from litellm.exceptions import GuardrailRaisedException
@@ -23,11 +22,11 @@ from litellm.types.proxy.guardrails.guardrail_hooks.tool_permission import (
ToolResult,
)
from litellm.types.utils import (
+ ChatCompletionMessageToolCall,
+ Choices,
+ LLMResponseTypes,
ModelResponse,
ModelResponseStream,
- LLMResponseTypes,
- Choices,
- ChatCompletionMessageToolCall,
)
GUARDRAIL_NAME = "tool_permission"
@@ -282,6 +281,7 @@ class ToolPermissionGuardrail(CustomGuardrail):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Union[Exception, str, dict, None]:
""" """
diff --git a/litellm/proxy/hooks/dynamic_rate_limiter.py b/litellm/proxy/hooks/dynamic_rate_limiter.py
index 6c72b4c9d24..4e0eea1eab8 100644
--- a/litellm/proxy/hooks/dynamic_rate_limiter.py
+++ b/litellm/proxy/hooks/dynamic_rate_limiter.py
@@ -198,6 +198,7 @@ class _PROXY_DynamicRateLimitHandler(CustomLogger):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[
Union[Exception, str, dict]
diff --git a/litellm/proxy/hooks/dynamic_rate_limiter_v3.py b/litellm/proxy/hooks/dynamic_rate_limiter_v3.py
index b3ea2510ce5..92b8dcf7ec3 100644
--- a/litellm/proxy/hooks/dynamic_rate_limiter_v3.py
+++ b/litellm/proxy/hooks/dynamic_rate_limiter_v3.py
@@ -459,6 +459,7 @@ class _PROXY_DynamicRateLimitHandlerV3(CustomLogger):
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[Union[Exception, str, dict]]:
"""
diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yaml
index fc32eb65f27..2e8ebd15f58 100644
--- a/litellm/proxy/proxy_config.yaml
+++ b/litellm/proxy/proxy_config.yaml
@@ -1,58 +1,20 @@
model_list:
- - model_name: mistral/*
- litellm_params:
- model: mistral/*
- - model_name: special-bedrock-model
- litellm_params:
- model: bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0
- aws_region_name: us-west-2
- custom_llm_provider: bedrock
- model_name: aws/anthropic/bedrock-claude-3-5-sonnet-v1
litellm_params:
model: bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0
- aws_region_name: us-west-2
+ aws_region_name: us-east-1
custom_llm_provider: bedrock
- # Load balancing test - multiple deployments with same model_name
- - model_name: load-balanced-claude
+ - model_name: aws/anthropic/bedrock-claude-3-5-sonnet-v1
litellm_params:
model: bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0
aws_region_name: us-west-2
custom_llm_provider: bedrock
- - model_name: load-balanced-claude
- litellm_params:
- model: bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0
- aws_region_name: us-east-1
- custom_llm_provider: bedrock
- - model_name: fake-openai-endpoint
- - model_name: bedrock/batch-anthropic.claude-3-5-sonnet-20240620-v1:0
- litellm_params:
- model: bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0
- #########################################################
- ########## batch specific params ########################
- s3_bucket_name: litellm-proxy
- s3_region_name: us-west-2
- s3_access_key_id: os.environ/AWS_ACCESS_KEY_ID
- s3_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY
- aws_batch_role_arn: arn:aws:iam::888602223428:role/service-role/AmazonBedrockExecutionRoleForAgents_BB9HNW6V4CV
- model_info:
- mode: batch
- - model_name: anthropic/*
- litellm_params:
- model: anthropic/*
- api_key: os.environ/ANTHROPIC_API_KEY
- - model_name: openai/*
- litellm_params:
- model: openai/*
- api_key: os.environ/OPENAI_API_KEY
- - model_name: gemini/*
- litellm_params:
- model: gemini/*
- api_key: os.environ/GEMINI_API_KEY
- - model_name: vertex-gemini-2.5-flash
- litellm_params:
- model: vertex_ai/gemini-2.5-flash
- vertex_project: "your-gcp-project-id"
- vertex_location: "us-central1"
- vertex_credentials: "path/to/your/service-account-key.json"
-
+
+guardrails:
+ - guardrail_name: "bedrock-pre-guard"
+ litellm_params:
+ guardrail: bedrock # supported values: "aporia", "bedrock", "lakera"
+ mode: "pre_call"
+ guardrailIdentifier: ff6ujrregl1q
+ guardrailVersion: "DRAFT"
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index 803c9c1a4ff..0065edeb0e9 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -22,6 +22,7 @@ from typing import (
overload,
)
+from litellm import _custom_logger_compatible_callbacks_literal
from litellm.constants import DEFAULT_MODEL_CREATED_AT_TIME, MAX_TEAM_LIST_LIMIT
from litellm.proxy._types import (
DB_CONNECTION_ERROR_TYPES,
@@ -32,6 +33,7 @@ from litellm.proxy._types import (
SpendLogsPayload,
)
from litellm.types.guardrails import GuardrailEventHooks
+from litellm.types.utils import CallTypes
try:
import backoff
@@ -93,7 +95,7 @@ from litellm.types.mcp import (
MCPPreCallRequestObject,
MCPPreCallResponseObject,
)
-from litellm.types.utils import CallTypes, LLMResponseTypes, LoggedLiteLLMParams
+from litellm.types.utils import LLMResponseTypes, LoggedLiteLLMParams
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
@@ -391,7 +393,7 @@ class ProxyLogging:
for callback in litellm.callbacks:
if isinstance(callback, str):
callback = litellm.litellm_core_utils.litellm_logging._init_custom_logger_compatible_class( # type: ignore
- callback,
+ cast(_custom_logger_compatible_callbacks_literal, callback),
internal_usage_cache=self.internal_usage_cache.dual_cache,
llm_router=llm_router,
)
@@ -799,6 +801,7 @@ class ProxyLogging:
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> None:
pass
@@ -818,6 +821,7 @@ class ProxyLogging:
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> dict:
pass
@@ -836,6 +840,7 @@ class ProxyLogging:
"pass_through_endpoint",
"rerank",
"mcp_call",
+ "anthropic_messages",
],
) -> Optional[dict]:
"""
@@ -902,7 +907,7 @@ class ProxyLogging:
_callback = None
if isinstance(callback, str):
_callback = litellm.litellm_core_utils.litellm_logging.get_custom_logger_compatible_class(
- callback
+ cast(_custom_logger_compatible_callbacks_literal, callback)
)
else:
_callback = callback # type: ignore
@@ -1241,7 +1246,7 @@ class ProxyLogging:
_callback: Optional[CustomLogger] = None
if isinstance(callback, str):
_callback = litellm.litellm_core_utils.litellm_logging.get_custom_logger_compatible_class(
- callback
+ cast(_custom_logger_compatible_callbacks_literal, callback)
)
else:
_callback = callback # type: ignore
@@ -1404,7 +1409,7 @@ class ProxyLogging:
_callback: Optional[CustomLogger] = None
if isinstance(callback, str):
_callback = litellm.litellm_core_utils.litellm_logging.get_custom_logger_compatible_class(
- callback
+ cast(_custom_logger_compatible_callbacks_literal, callback)
)
else:
_callback = callback # type: ignore
@@ -1486,7 +1491,7 @@ class ProxyLogging:
continue
if isinstance(callback, str):
_callback = litellm.litellm_core_utils.litellm_logging.get_custom_logger_compatible_class(
- callback
+ cast(_custom_logger_compatible_callbacks_literal, callback)
)
else:
_callback = callback # type: ignore
@@ -1526,7 +1531,7 @@ class ProxyLogging:
_callback: Optional[CustomLogger] = None
if isinstance(callback, str):
_callback = litellm.litellm_core_utils.litellm_logging.get_custom_logger_compatible_class(
- callback
+ cast(_custom_logger_compatible_callbacks_literal, callback)
)
else:
_callback = callback # type: ignore
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index c31d27214b5..d744bb9d38b 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -220,7 +220,7 @@ class GenericStreamingChunk(TypedDict, total=False):
from enum import Enum
-class CallTypes(Enum):
+class CallTypes(str, Enum):
embedding = "embedding"
aembedding = "aembedding"
completion = "completion"
diff --git a/tests/guardrails_tests/test_bedrock_guardrails.py b/tests/guardrails_tests/test_bedrock_guardrails.py
index 7ca78d83ae9..b0e192c00a7 100644
--- a/tests/guardrails_tests/test_bedrock_guardrails.py
+++ b/tests/guardrails_tests/test_bedrock_guardrails.py
@@ -86,6 +86,87 @@ async def test_bedrock_guardrails_pii_masking_content_list():
+async def test_bedrock_guardrails_block_messages_api():
+ """
+ Test that guardrails block messages API requests containing 'coffee' and raise the expected exception.
+ """
+ from fastapi import HTTPException
+
+ # Create proper mock objects
+ mock_user_api_key_dict = UserAPIKeyAuth()
+
+ guardrail = BedrockGuardrail(
+ guardrailIdentifier="ff6ujrregl1q",
+ guardrailVersion="DRAFT",
+ )
+
+ request_data = {
+ "model": "claude-3-5-sonnet-20240620",
+ "messages": [
+ {"role": "user", "content": [
+ {"type": "text", "text": "Hello, my phone number is +1 412 555 1212"},
+ {"type": "text", "text": "what time is it?"},
+ ]},
+ {
+ "role": "user",
+ "content": "tell me about coffee"
+ }
+ ],
+ }
+
+ with pytest.raises(HTTPException) as exc_info:
+ await guardrail.async_pre_call_hook(
+ data=request_data,
+ user_api_key_dict=mock_user_api_key_dict,
+ call_type="anthropic_messages",
+ cache=MagicMock(spec=DualCache),
+ )
+
+ exception = exc_info.value
+ assert exception.status_code == 400
+ detail = exception.detail
+ assert isinstance(detail, dict)
+ assert detail["error"] == "Violated guardrail policy"
+ assert detail["bedrock_guardrail_response"] == "Sorry, the model cannot answer this question. coffee guardrail applied "
+
+async def test_bedrock_guardrails_block_responses_api():
+ """
+ Test that guardrails block responses API requests containing 'coffee' and raise the expected exception.
+ """
+ from fastapi import HTTPException
+
+ # Create proper mock objects
+ mock_user_api_key_dict = UserAPIKeyAuth()
+
+ guardrail = BedrockGuardrail(
+ guardrailIdentifier="ff6ujrregl1q",
+ guardrailVersion="DRAFT",
+ )
+
+ request_data = {
+ "model": "gpt-4.1",
+ "input": "Tell me a three sentence bedtime story about a unicorn drinking coffee",
+ "stream": False,
+ }
+
+ with pytest.raises(HTTPException) as exc_info:
+ await guardrail.async_pre_call_hook(
+ data=request_data,
+ user_api_key_dict=mock_user_api_key_dict,
+ call_type="responses",
+ cache=MagicMock(spec=DualCache),
+ )
+
+ exception = exc_info.value
+ assert exception.status_code == 400
+ detail = exception.detail
+ assert isinstance(detail, dict)
+ assert detail["error"] == "Violated guardrail policy"
+ assert detail["bedrock_guardrail_response"] == "Sorry, the model cannot answer this question. coffee guardrail applied "
+
+
@pytest.mark.asyncio
async def test_bedrock_guardrails_with_streaming():