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] Model-Guardrails: Add on UI (#13006)

Krish Dholakia4b50566d6dcb
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 4c37b00396c..de410985ac0 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -3240,6 +3240,7 @@ async def async_data_generator(
verbose_proxy_logger.debug("inside generator")
try:
str_so_far = ""
+ error_message: Optional[str] = None
async for chunk in proxy_logging_obj.async_post_call_streaming_iterator_hook(
user_api_key_dict=user_api_key_dict,
response=response,
@@ -3265,6 +3266,9 @@ async def async_data_generator(
if isinstance(chunk, BaseModel):
chunk = chunk.model_dump_json(exclude_none=True, exclude_unset=True)
+ elif isinstance(chunk, str) and chunk.startswith("data: "):
+ error_message = chunk
+ break
try:
yield f"data: {chunk}\n\n"
@@ -3272,6 +3276,8 @@ async def async_data_generator(
yield f"data: {str(e)}\n\n"
# Streaming is done, yield the [DONE] chunk
+ if error_message is not None:
+ yield error_message
done_message = "[DONE]"
yield f"data: {done_message}\n\n"
except Exception as e:
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index fa5eee71979..9da305e19fc 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -1115,10 +1115,16 @@ class ProxyLogging:
complete_response = str_so_far + response_str
else:
complete_response = response_str
- await _callback.async_post_call_streaming_hook(
- user_api_key_dict=user_api_key_dict,
- response=complete_response,
+ potential_error_response = (
+ await _callback.async_post_call_streaming_hook(
+ user_api_key_dict=user_api_key_dict,
+ response=complete_response,
+ )
)
+ if isinstance(
+ potential_error_response, str
+ ) and potential_error_response.startswith("data: "):
+ return potential_error_response
except Exception as e:
raise e
return response
@@ -1157,27 +1163,6 @@ class ProxyLogging:
)
return response
- async def post_call_streaming_hook(
- self,
- response: str,
- user_api_key_dict: UserAPIKeyAuth,
- ):
- """
- - Check outgoing streaming response uptil that point
- - Run through moderation check
- - Reject request if it fails moderation check
- """
- new_response = copy.deepcopy(response)
- for callback in litellm.callbacks:
- try:
- if isinstance(callback, CustomLogger):
- await callback.async_post_call_streaming_hook(
- user_api_key_dict=user_api_key_dict, response=new_response
- )
- except Exception as e:
- raise e
- return new_response
-
def _init_response_taking_too_long_task(self, data: Optional[dict] = None):
"""
Initialize the response taking too long task if user is using slack alerting
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index c5677074f9b..a3e3b9e2f2d 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -2093,7 +2093,7 @@ all_litellm_params = [
"metadata",
"litellm_metadata",
"litellm_trace_id",
- "litellm_guardrails",
+ "guardrails",
"tags",
"acompletion",
"aimg_generation",
diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py
index a92a9104a3d..5840d52813f 100644
--- a/tests/test_litellm/proxy/test_proxy_server.py
+++ b/tests/test_litellm/proxy/test_proxy_server.py
@@ -940,3 +940,106 @@ async def test_write_config_to_file_when_store_model_in_db_false(monkeypatch):
mock_file_open.return_value.__enter__.return_value,
default_flow_style=False,
)
+
+
+async def test_async_data_generator_midstream_error():
+ """
+ Test async_data_generator handles midstream error from async_post_call_streaming_hook
+ Specifically testing the case where Azure Content Safety Guardrail returns an error
+ """
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.proxy.proxy_server import async_data_generator
+ from litellm.proxy.utils import ProxyLogging
+
+ # Create mock objects
+ mock_user_api_key_dict = MagicMock(spec=UserAPIKeyAuth)
+ mock_request_data = {
+ "model": "gpt-3.5-turbo",
+ "messages": [{"role": "user", "content": "test"}],
+ }
+
+ # Mock response chunks - simulating normal streaming that gets interrupted
+ mock_chunks = [
+ {"choices": [{"delta": {"content": "Hello"}}]},
+ {"choices": [{"delta": {"content": " world"}}]},
+ {"choices": [{"delta": {"content": " this"}}]},
+ ]
+
+ # Mock the proxy_logging_obj
+ mock_proxy_logging_obj = MagicMock(spec=ProxyLogging)
+
+ # Mock async_post_call_streaming_iterator_hook to yield chunks
+ async def mock_streaming_iterator(*args, **kwargs):
+ for chunk in mock_chunks:
+ yield chunk
+
+ mock_proxy_logging_obj.async_post_call_streaming_iterator_hook = (
+ mock_streaming_iterator
+ )
+
+ # Mock async_post_call_streaming_hook to return error on third chunk
+ def mock_streaming_hook(*args, **kwargs):
+ chunk = kwargs.get("response")
+ # Return error message for the third chunk (simulating guardrail trigger)
+ if chunk == mock_chunks[2]:
+ return 'data: {"error": {"error": "Azure Content Safety Guardrail: Hate crossed severity 2, Got severity: 2"}}'
+ # Return normal chunks for first two
+ return chunk
+
+ mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock(
+ side_effect=mock_streaming_hook
+ )
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+
+ # Mock the global proxy_logging_obj
+ with patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj):
+ # Create a mock response object
+ mock_response = MagicMock()
+
+ # Collect all yielded data from the generator
+ yielded_data = []
+ try:
+ async for data in async_data_generator(
+ mock_response, mock_user_api_key_dict, mock_request_data
+ ):
+ yielded_data.append(data)
+ except Exception as e:
+ # If there's an exception, that's also part of what we want to test
+ pass
+
+ # Verify the results
+ assert (
+ len(yielded_data) >= 3
+ ), f"Expected at least 3 chunks, got {len(yielded_data)}: {yielded_data}"
+
+ # First two chunks should be normal data
+ assert yielded_data[0].startswith(
+ "data: "
+ ), f"First chunk should start with 'data: ', got: {yielded_data[0]}"
+ assert yielded_data[1].startswith(
+ "data: "
+ ), f"Second chunk should start with 'data: ', got: {yielded_data[1]}"
+
+ # The error message should be yielded
+ error_found = False
+ done_found = False
+
+ for data in yielded_data:
+ if "Azure Content Safety Guardrail: Hate crossed severity 2" in data:
+ error_found = True
+ if "data: [DONE]" in data:
+ done_found = True
+
+ assert (
+ error_found
+ ), f"Error message should be found in yielded data. Got: {yielded_data}"
+ assert done_found, f"[DONE] message should be found at the end. Got: {yielded_data}"
+
+ # Verify that the streaming hook was called for each chunk
+ assert mock_proxy_logging_obj.async_post_call_streaming_hook.call_count == len(
+ mock_chunks
+ )
+
+ # Verify that post_call_failure_hook was NOT called (since this is not an exception case)
+ mock_proxy_logging_obj.post_call_failure_hook.assert_not_called()
diff --git a/ui/litellm-dashboard/src/components/add_model/add_model_tab.tsx b/ui/litellm-dashboard/src/components/add_model/add_model_tab.tsx
index 525ce142049..67c4ecb6335 100644
--- a/ui/litellm-dashboard/src/components/add_model/add_model_tab.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/add_model_tab.tsx
@@ -1,5 +1,5 @@
import React, { useEffect, useMemo, useState } from "react";
-import { Card, Form, Button, Tooltip, Typography, Select as AntdSelect, Modal } from "antd";
+import { Card, Form, Button, Tooltip, Typography, Select as AntdSelect, Modal, message } from "antd";
import type { FormInstance } from "antd";
import type { UploadProps } from "antd/es/upload";
import { TabGroup, TabList, Tab, TabPanels, TabPanel } from "@tremor/react";
@@ -9,7 +9,7 @@ import ProviderSpecificFields from "./provider_specific_fields";
import AdvancedSettings from "./advanced_settings";
import { Providers, providerLogoMap, getPlaceholder } from "../provider_info_helpers";
import type { Team } from "../key_team_helpers/key_list";
-import { CredentialItem, modelAvailableCall } from "../networking";
+import { CredentialItem, getGuardrailsList, modelAvailableCall } from "../networking";
import ConnectionErrorDisplay from "./model_connection_test";
import { TEST_MODES } from "./add_model_modes";
import { Row, Col } from "antd";
@@ -20,7 +20,7 @@ import AddAutoRouterTab from "./add_auto_router_tab";
import { handleAddAutoRouterSubmit } from "./handle_add_auto_router_submit";
interface AddModelTabProps {
- form: FormInstance;
+ form: FormInstance; // For the Add Model tab
handleOk: () => void;
selectedProvider: Providers;
setSelectedProvider: (provider: Providers) => void;
@@ -56,13 +56,34 @@ const AddModelTab: React.FC<AddModelTabProps> = ({
userRole,
premiumUser,
}) => {
+ // Create separate form instance for auto router
+ const [autoRouterForm] = Form.useForm();
// State for test mode and connection testing
const [testMode, setTestMode] = useState<string>("chat");
const [isResultModalVisible, setIsResultModalVisible] = useState<boolean>(false);
const [isTestingConnection, setIsTestingConnection] = useState<boolean>(false);
+ const [guardrailsList, setGuardrailsList] = useState<string[]>([]);
// Using a unique ID to force the ConnectionErrorDisplay to remount and run a fresh test
const [connectionTestId, setConnectionTestId] = useState<string>("");
+
+
+ useEffect(() => {
+ const fetchGuardrails = async () => {
+ try {
+ const response = await getGuardrailsList(accessToken);
+ const guardrailNames = response.guardrails.map(
+ (g: { guardrail_name: string }) => g.guardrail_name
+ );
+ setGuardrailsList(guardrailNames);
+ } catch (error) {
+ console.error("Failed to fetch guardrails:", error);
+ }
+ };
+
+ fetchGuardrails();
+ }, [accessToken]);
+
// Test connection when button is clicked
const handleTestConnection = async () => {
setIsTestingConnection(true);
@@ -89,10 +110,10 @@ const AddModelTab: React.FC<AddModelTabProps> = ({
const isAdmin = all_admin_roles.includes(userRole);
const handleAutoRouterOk = () => {
- form
+ autoRouterForm
.validateFields()
.then((values) => {
- handleAddAutoRouterSubmit(values, accessToken, form, handleOk);
+ handleAddAutoRouterSubmit(values, accessToken, autoRouterForm, handleOk);
})
.catch((error) => {
console.error("Validation failed:", error);
@@ -112,7 +133,13 @@ const AddModelTab: React.FC<AddModelTabProps> = ({
<Card>
<Form
form={form}
- onFinish={handleOk}
+ onFinish={(values) => {
+ console.log("🔥 Form onFinish triggered with values:", values);
+ handleOk();
+ }}
+ onFinishFailed={(errorInfo) => {
+ console.log("💥 Form onFinishFailed triggered:", errorInfo);
+ }}
labelCol={{ span: 10 }}
wrapperCol={{ span: 16 }}
labelAlign="left"
@@ -334,6 +361,7 @@ const AddModelTab: React.FC<AddModelTabProps> = ({
showAdvancedSettings={showAdvancedSettings}
setShowAdvancedSettings={setShowAdvancedSettings}
teams={teams}
+ guardrailsList={guardrailsList}
/>
<div className="flex justify-between items-center mb-4">
@@ -353,7 +381,7 @@ const AddModelTab: React.FC<AddModelTabProps> = ({
</TabPanel>
<TabPanel>
<AddAutoRouterTab
- form={form}
+ form={autoRouterForm}
handleOk={handleAutoRouterOk}
accessToken={accessToken}
userRole={userRole}
diff --git a/ui/litellm-dashboard/src/components/add_model/advanced_settings.tsx b/ui/litellm-dashboard/src/components/add_model/advanced_settings.tsx
index 8ced27cd629..85135f8f46d 100644
--- a/ui/litellm-dashboard/src/components/add_model/advanced_settings.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/advanced_settings.tsx
@@ -1,8 +1,9 @@
import React from "react";
-import { Form, Switch, Select, Input } from "antd";
+import { Form, Switch, Select, Input, Tooltip } from "antd";
import { Text, Button, Accordion, AccordionHeader, AccordionBody, TextInput } from "@tremor/react";
import { Row, Col, Typography, Card } from "antd";
import TextArea from "antd/es/input/TextArea";
+import { InfoCircleOutlined } from "@ant-design/icons";
import { Team } from "../key_team_helpers/key_list";
import TeamDropdown from "../common_components/team_dropdown";
import CacheControlSettings from "./cache_control_settings";
@@ -12,17 +13,21 @@ interface AdvancedSettingsProps {
showAdvancedSettings: boolean;
setShowAdvancedSettings: (show: boolean) => void;
teams?: Team[] | null;
+ guardrailsList: string[];
}
const AdvancedSettings: React.FC<AdvancedSettingsProps> = ({
showAdvancedSettings,
setShowAdvancedSettings,
teams,
+ guardrailsList,
}) => {
const [form] = Form.useForm();
const [customPricing, setCustomPricing] = React.useState(false);
const [pricingModel, setPricingModel] = React.useState<'per_token' | 'per_second'>('per_token');
const [showCacheControl, setShowCacheControl] = React.useState(false);
+
+
// Add validation function for numbers
const validateNumber = (_: any, value: string) => {
@@ -121,6 +126,35 @@ const AdvancedSettings: React.FC<AdvancedSettingsProps> = ({
<Switch onChange={handleCustomPricingChange} className="bg-gray-600" />
</Form.Item>
+ <Form.Item
+ label={
+ <span>
+ Guardrails{' '}
+ <Tooltip title="Apply safety guardrails to this key to filter content or enforce policies">
+ <a
+ href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start"
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={(e) => e.stopPropagation()} // Prevent accordion from collapsing when clicking link
+ >
+ <InfoCircleOutlined style={{ marginLeft: '4px' }} />
+ </a>
+ </Tooltip>
+ </span>
+ }
+ name="guardrails"
+ className="mt-4"
+ help="Select existing guardrails. Go to 'Guardrails' tab to create new guardrails."
+ >
+ <Select
+ mode="tags"
+ style={{ width: '100%' }}
+ placeholder="Select or enter guardrails"
+ options={guardrailsList.map(name => ({ value: name, label: name }))}
+ />
+ </Form.Item>
+
+
{customPricing && (
<div className="ml-6 pl-4 border-l-2 border-gray-200">
<Form.Item
diff --git a/ui/litellm-dashboard/src/components/add_model/conditional_public_model_name.tsx b/ui/litellm-dashboard/src/components/add_model/conditional_public_model_name.tsx
index 40a124264a7..c1dc4fc6abf 100644
--- a/ui/litellm-dashboard/src/components/add_model/conditional_public_model_name.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/conditional_public_model_name.tsx
@@ -105,7 +105,23 @@ const ConditionalPublicModelName: React.FC = () => {
labelCol={{ span: 10 }}
wrapperCol={{ span: 16 }}
labelAlign="left"
- required={true}
+ rules={[
+ {
+ required: true,
+ validator: async (_, value) => {
+ if (!value || value.length === 0) {
+ throw new Error('At least one model mapping is required');
+ }
+ // Check if all mappings have valid public names
+ const invalidMappings = value.filter((mapping: any) =>
+ !mapping.public_name || mapping.public_name.trim() === ''
+ );
+ if (invalidMappings.length > 0) {
+ throw new Error('All model mappings must have valid public names');
+ }
+ }
+ }
+ ]}
>
<Table
key={tableKey} // Add key to force re-render
diff --git a/ui/litellm-dashboard/src/components/model_dashboard.tsx b/ui/litellm-dashboard/src/components/model_dashboard.tsx
index 3a6641c58fe..98cc3b14305 100644
--- a/ui/litellm-dashboard/src/components/model_dashboard.tsx
+++ b/ui/litellm-dashboard/src/components/model_dashboard.tsx
@@ -135,7 +135,8 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
premiumUser,
teams,
}) => {
- const [form] = Form.useForm();
+ const [addModelForm] = Form.useForm();
+ const [autoRouterForm] = Form.useForm();
const [modelMap, setModelMap] = useState<any>(null);
const [lastRefreshed, setLastRefreshed] = useState("");
@@ -411,10 +412,10 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
console.log(
`Resetting vertex_credentials to JSON; jsonStr: ${jsonStr}`
);
- form.setFieldsValue({ vertex_credentials: jsonStr });
+ addModelForm.setFieldsValue({ vertex_credentials: jsonStr });
console.log(
"Form values right after setting:",
- form.getFieldsValue()
+ addModelForm.getFieldsValue()
);
}
};
@@ -425,7 +426,7 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
},
onChange(info) {
console.log("Upload onChange triggered with values:", info);
- console.log("Current form values:", form.getFieldsValue());
+ console.log("Current form values:", addModelForm.getFieldsValue());
if (info.file.status !== "uploading") {
console.log(info.file, info.fileList);
@@ -976,13 +977,22 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
};
const handleOk = () => {
- form
+ console.log("🚀 handleOk called from model dashboard!");
+ console.log("Current form values:", addModelForm.getFieldsValue());
+
+ addModelForm
.validateFields()
- .then((values) => {
- handleAddModelSubmit(values, accessToken, form, handleRefreshClick);
+ .then((values: any) => {
+ console.log("✅ Validation passed, submitting:", values);
+ handleAddModelSubmit(values, accessToken, addModelForm, handleRefreshClick);
})
- .catch((error) => {
- console.error("Validation failed:", error);
+ .catch((error: any) => {
+ console.error("❌ Validation failed:", error);
+ console.error("Form errors:", error.errorFields);
+ const errorMessages = error.errorFields?.map((field: any) => {
+ return `${field.name.join('.')}: ${field.errors.join(', ')}`;
+ }).join(' | ') || 'Unknown validation error';
+ message.error(`Please fill in the following required fields: ${errorMessages}`);
});
};
@@ -1399,7 +1409,7 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
</TabPanel>
<TabPanel className="h-full">
<AddModelTab
- form={form}
+ form={addModelForm}
handleOk={handleOk}
selectedProvider={selectedProvider}
setSelectedProvider={setSelectedProvider}
diff --git a/ui/litellm-dashboard/src/components/model_info_view.tsx b/ui/litellm-dashboard/src/components/model_info_view.tsx
index 62958ccb900..60d69687102 100644
--- a/ui/litellm-dashboard/src/components/model_info_view.tsx
+++ b/ui/litellm-dashboard/src/components/model_info_view.tsx
@@ -24,8 +24,10 @@ import {
modelInfoCall,
modelInfoV1Call,
modelPatchUpdateCall,
+ getGuardrailsList,
} from "./networking";
-import { Button, Form, Input, InputNumber, message, Select, Modal } from "antd";
+import { Button, Form, Input, InputNumber, message, Select, Modal, Tooltip } from "antd";
+import { InfoCircleOutlined } from "@ant-design/icons";
import EditModelModal from "./edit_model/edit_model_modal";
import { handleEditModelSubmit } from "./edit_model/edit_model_modal";
import { getProviderLogoAndName } from "./provider_info_helpers";
@@ -76,7 +78,7 @@ export default function ModelInfoView({
const [showCacheControl, setShowCacheControl] = useState(false);
const [copiedStates, setCopiedStates] = useState<Record<string, boolean>>({});
const [isAutoRouterModalOpen, setIsAutoRouterModalOpen] = useState(false);
-
+ const [guardrailsList, setGuardrailsList] = useState<string[]>([]);
const canEditModel =
userRole === "Admin" || modelData?.model_info?.created_by === userID;
const isAdmin = userRole === "Admin";
@@ -121,8 +123,23 @@ export default function ModelInfoView({
setShowCacheControl(true);
}
};
+
+ const fetchGuardrails = async () => {
+ if (!accessToken) return;
+ try {
+ const response = await getGuardrailsList(accessToken);
+ const guardrailNames = response.guardrails.map(
+ (g: { guardrail_name: string }) => g.guardrail_name
+ );
+ setGuardrailsList(guardrailNames);
+ } catch (error) {
+ console.error("Failed to fetch guardrails:", error);
+ }
+ };
+
getExistingCredential();
getModelInfo();
+ fetchGuardrails();
}, [accessToken, modelId]);
const handleReuseCredential = async (values: any) => {
@@ -165,6 +182,9 @@ export default function ModelInfoView({
input_cost_per_token: values.input_cost / 1_000_000,
output_cost_per_token: values.output_cost / 1_000_000,
};
+ if (values.guardrails) {
+ updatedLitellmParams.guardrails = values.guardrails;
+ }
// Handle cache control settings
if (
@@ -502,6 +522,11 @@ export default function ModelInfoView({
)
? localModelData.model_info.access_groups
: [],
+ guardrails: Array.isArray(
+ localModelData.litellm_params?.guardrails
+ )
+ ? localModelData.litellm_params.guardrails
+ : [],
}}
layout="vertical"
onValuesChange={() => setIsDirty(true)}
@@ -758,6 +783,67 @@ export default function ModelInfoView({
)}
</div>
+ <div>
+ <Text className="font-medium">
+ Guardrails{' '}
+ <Tooltip title="Apply safety guardrails to this model to filter content or enforce policies">
+ <a
+ href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start"
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <InfoCircleOutlined style={{ marginLeft: '4px' }} />
+ </a>
+ </Tooltip>
+ </Text>
+ {isEditing ? (
+ <Form.Item name="guardrails" className="mb-0">
+ <Select
+ mode="tags"
+ showSearch
+ placeholder="Select existing guardrails or type to create new ones"
+ optionFilterProp="children"
+ tokenSeparators={[","]}
+ maxTagCount="responsive"
+ allowClear
+ style={{ width: "100%" }}
+ options={guardrailsList.map((name) => ({
+ value: name,
+ label: name,
+ }))}
+ />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.litellm_params?.guardrails ? (
+ Array.isArray(localModelData.litellm_params.guardrails) ? (
+ localModelData.litellm_params.guardrails.length > 0 ? (
+ <div className="flex flex-wrap gap-1">
+ {localModelData.litellm_params.guardrails.map(
+ (guardrail: string, index: number) => (
+ <span
+ key={index}
+ className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800"
+ >
+ {guardrail}
+ </span>
+ )
+ )}
+ </div>
+ ) : (
+ "No guardrails assigned"
+ )
+ ) : (
+ localModelData.litellm_params.guardrails
+ )
+ ) : (
+ "Not Set"
+ )}
+ </div>
+ )}
+ </div>
+
{/* Cache Control Section */}
{isEditing ? (
<CacheControlSettings