Guardrails - Schnelleinstieg
Einrichtung von Prompt-Injection-Erkennung, PII-Maskierung auf dem LiteLLM Proxy (KI-Gateway)
1. Definieren Sie Guardrails in Ihrer LiteLLM config.yaml
Legen Sie Ihre Guardrails im Abschnitt guardrails fest.
model_list:
- model_name: gpt-3.5-turbo
litellm_params:
model: openai/gpt-3.5-turbo
api_key: os.environ/OPENAI_API_KEY
guardrails:
- guardrail_name: general-guard
litellm_params:
guardrail: aim
mode: [pre_call, post_call]
api_key: os.environ/AIM_API_KEY
api_base: os.environ/AIM_API_BASE
default_on: true # Optional
- guardrail_name: "aporia-pre-guard"
litellm_params:
guardrail: aporia # supported values: "aporia", "lakera"
mode: "during_call"
api_key: os.environ/APORIA_API_KEY_1
api_base: os.environ/APORIA_API_BASE_1
- guardrail_name: "aporia-post-guard"
litellm_params:
guardrail: aporia # supported values: "aporia", "lakera"
mode: "post_call"
api_key: os.environ/APORIA_API_KEY_2
api_base: os.environ/APORIA_API_BASE_2
guardrail_info: # Optional field, info is returned on GET /guardrails/list
# you can enter any fields under info for consumers of your guardrail
params:
- name: "toxicity_score"
type: "float"
description: "Score between 0-1 indicating content toxicity level"
- name: "pii_detection"
type: "boolean"
Unterstützte Werte für mode (Event Hooks)
pre_callVor dem LLM-Aufruf, auf der Eingabe ausführenpost_callNach dem LLM-Aufruf, auf der Eingabe & Ausgabe ausführenduring_callWährend des LLM-Aufrufs, auf der Eingabe ausführen. Gleichtpre_call, läuft aber parallel zum LLM-Aufruf. Die Antwort wird erst zurückgegeben, wenn die Guardrail-Prüfung abgeschlossen ist.- Eine Liste der obigen Werte, um mehrere Modi auszuführen, z. B.
mode: [pre_call, post_call]
2. LiteLLM Gateway starten
litellm --config config.yaml --detailed_debug
3. Anfrage testen
Langchain, OpenAI SDK Anwendungsbeispiele
- Fehlgeschlagener Aufruf
- Erfolgreicher Aufruf
Dies sollte fehlschlagen, da ishaan@berri.ai in der Anfrage PII ist.
curl -i https://:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-npnwjPQciVRok5yNZgKmFQ" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": "hi my email is ishaan@berri.ai"}
],
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}'
Erwartete Antwort bei Fehler
{
"error": {
"message": {
"error": "Violated guardrail policy",
"aporia_ai_response": {
"action": "block",
"revised_prompt": null,
"revised_response": "Aporia detected and blocked PII",
"explain_log": null
}
},
"type": "None",
"param": "None",
"code": "400"
}
}
curl -i https://:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-npnwjPQciVRok5yNZgKmFQ" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": "hi what is the weather"}
],
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}'
Standardmäßig aktivierte Guardrails
Setzen Sie default_on: true in Ihrer Guardrail-Konfiguration, um die Guardrail bei jeder Anfrage auszuführen. Dies ist nützlich, wenn Sie eine Guardrail bei jeder Anfrage ausführen möchten, ohne dass der Benutzer sie angeben muss.
Hinweis: Diese werden auch ausgeführt, wenn der Benutzer eine andere Guardrail oder ein leeres Guardrail-Array angibt.
guardrails:
- guardrail_name: "aporia-pre-guard"
litellm_params:
guardrail: aporia
mode: "pre_call"
default_on: true
Testanfrage
In dieser Anfrage wird die Guardrail aporia-pre-guard bei jeder Anfrage ausgeführt, da default_on: true gesetzt ist.
curl -i https://:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-npnwjPQciVRok5yNZgKmFQ" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": "hi my email is ishaan@berri.ai"}
]
}'
Erwartete Antwort
Ihre Antwort-Header enthalten x-litellm-applied-guardrails mit der angewendeten Guardrail.
x-litellm-applied-guardrails: aporia-pre-guard
Guardrails auf der Client-Seite verwenden
Selbst testen (OSS)
Übergeben Sie guardrails an Ihren Request-Body, um ihn zu testen.
curl -i https://:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-npnwjPQciVRok5yNZgKmFQ" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": "hi my email is ishaan@berri.ai"}
],
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}'
Für Ihre Benutzer verfügbar machen (Enterprise)
Befolgen Sie diesen einfachen Workflow, um Guardrails zu implementieren und zu optimieren.
1. ✨ Verfügbare Guardrails anzeigen
✨ Dies ist eine Funktion nur für Enterprise-Kunden. Kostenlose Testversion erhalten
Überprüfen Sie zuerst, welche Guardrails verfügbar sind und welche Parameter sie haben.
Rufen Sie /guardrails/list auf, um verfügbare Guardrails und Informationen zu den Guardrails (unterstützte Parameter, Beschreibung usw.) anzuzeigen.
curl -X GET 'http://0.0.0.0:4000/guardrails/list'
Erwartete Antwort
{
"guardrails": [
{
"guardrail_name": "aporia-post-guard",
"guardrail_info": {
"params": [
{
"name": "toxicity_score",
"type": "float",
"description": "Score between 0-1 indicating content toxicity level"
},
{
"name": "pii_detection",
"type": "boolean"
}
]
}
}
]
}
Diese Konfiguration gibt die Antwort
/guardrails/listoben zurück. Das Feldguardrail_infoist optional, und Sie können beliebige Felder unter info für Konsumenten Ihrer Guardrail hinzufügen.- guardrail_name: "aporia-post-guard"
litellm_params:
guardrail: aporia # supported values: "aporia", "lakera"
mode: "post_call"
api_key: os.environ/APORIA_API_KEY_2
api_base: os.environ/APORIA_API_BASE_2
guardrail_info: # Optional field, info is returned on GET /guardrails/list
# you can enter any fields under info for consumers of your guardrail
params:
- name: "toxicity_score"
type: "float"
description: "Score between 0-1 indicating content toxicity level"
- name: "pii_detection"
type: "boolean"
2. Guardrails anwenden
Fügen Sie ausgewählte Guardrails zu Ihrer Chat-Completion-Anfrage hinzu.
curl -i https://:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "your message"}],
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}'
3. Mit Mock-LLM-Completions testen
Senden Sie mock_response, um Guardrails zu testen, ohne einen LLM-Aufruf durchzuführen. Weitere Informationen zu mock_response finden Sie hier.
curl -i https://:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-npnwjPQciVRok5yNZgKmFQ" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [
{"role": "user", "content": "hi my email is ishaan@berri.ai"}
],
"mock_response": "This is a mock response",
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}'
4. ✨ Dynamische Parameter an Guardrail übergeben
✨ Dies ist eine Funktion nur für Enterprise-Kunden. Kostenlose Testversion erhalten
Verwenden Sie dies, um zusätzliche Parameter an den Guardrail-API-Aufruf zu übergeben. z. B. Dinge wie eine Erfolgsschwelle. Siehe guardrails-Spezifikation für weitere Details
- OpenAI Python v1.0.0+
- Curl-Anfrage
Setzen Sie guardrails={"aporia-pre-guard": {"extra_body": {"success_threshold": 0.9}}}, um zusätzliche Parameter an die Guardrail zu übergeben.
In diesem Beispiel wird success_threshold=0.9 an den Request-Body der Guardrail aporia-pre-guard übergeben.
import openai
client = openai.OpenAI(
api_key="anything",
base_url="http://0.0.0.0:4000"
)
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages = [
{
"role": "user",
"content": "this is a test request, write a short poem"
}
],
extra_body={
"guardrails": [
"aporia-pre-guard": {
"extra_body": {
"success_threshold": 0.9
}
}
]
}
)
print(response)
curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Content-Type: application/json' \
--data '{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": "what llm are you"
}
],
"guardrails": [
"aporia-pre-guard": {
"extra_body": {
"success_threshold": 0.9
}
}
]
}'
Proxy-Admin-Steuerelemente
✨ Guardrails überwachen
Überwachen Sie, welche Guardrails ausgeführt wurden und ob sie bestanden oder fehlgeschlagen sind. z. B. wenn eine Guardrail außer Kontrolle gerät und Anfragen fehlschlägt, die wir nicht fehlschlagen lassen wollen.
✨ Dies ist eine Funktion nur für Enterprise-Kunden. Kostenlose Testversion erhalten
Einrichtung
- Verbinden Sie LiteLLM mit einem unterstützten Logging-Anbieter.
- Führen Sie eine Anfrage mit einem
guardrails-Parameter aus. - Überprüfen Sie Ihren Logging-Anbieter auf den Guardrail-Trace.
Erfolgreiche Guardrail-Nachverfolgung
Fehlgeschlagene Guardrail-Nachverfolgung
✨ Guardrails pro API-Schlüssel steuern
✨ Dies ist eine Funktion nur für Enterprise-Kunden. Kostenlose Testversion erhalten
Verwenden Sie dies, um zu steuern, welche Guardrails pro API-Schlüssel ausgeführt werden. In diesem Tutorial sollen nur die folgenden Guardrails für 1 API-Schlüssel ausgeführt werden.
guardrails: ["aporia-pre-guard", "aporia-post-guard"]
Schritt 1 Schlüssel mit Guardrail-Einstellungen erstellen
- /key/generate
- /key/update
curl -X POST 'http://0.0.0.0:4000/key/generate' \
-H 'Authorization: Bearer sk-1234' \
-H 'Content-Type: application/json' \
-D '{
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}
}'
curl --location 'http://0.0.0.0:4000/key/update' \
--header 'Authorization: Bearer sk-1234' \
--header 'Content-Type: application/json' \
--data '{
"key": "sk-jNm1Zar7XfNdZXp49Z1kSQ",
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}
}'
Schritt 2 Mit neuem Schlüssel testen
curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Authorization: Bearer sk-jNm1Zar7XfNdZXp49Z1kSQ' \
--header 'Content-Type: application/json' \
--data '{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": "my email is ishaan@berri.ai"
}
]
}'
✨ Verhindern, dass das Team Guardrails aktiviert/deaktiviert
✨ Dies ist eine Funktion nur für Enterprise-Kunden. Kostenlose Testversion erhalten
1. Verhindern Sie, dass das Team Guardrails modifiziert
curl -X POST 'http://0.0.0.0:4000/team/update' \
-H 'Authorization: Bearer sk-1234' \
-H 'Content-Type: application/json' \
-D '{
"team_id": "4198d93c-d375-4c83-8d5a-71e7c5473e50",
"metadata": {"guardrails": {"modify_guardrails": false}}
}'
2. Versuchen Sie, Guardrails für einen Aufruf zu deaktivieren
curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer $LITELLM_VIRTUAL_KEY' \
--data '{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": "Think of 10 random colors."
}
],
"metadata": {"guardrails": {"hide_secrets": false}}
}'
3. 403-Fehler erhalten
{
"error": {
"message": {
"error": "Your team does not have permission to modify guardrails."
},
"type": "auth_error",
"param": "None",
"code": 403
}
}
Erwarten Sie, dass +1 412-612-9992 NICHT in Ihren Serverprotokollen bei Ihrem Callback angezeigt wird.
Die Guardrail pii_masking wurde bei dieser Anfrage ausgeführt, da der API-Schlüssel = sk-jNm1Zar7XfNdZXp49Z1kSQ über "permissions": {"pii_masking": true} verfügt.
Spezifikation
guardrails-Konfiguration in YAML
guardrails:
- guardrail_name: string # Required: Name of the guardrail
litellm_params: # Required: Configuration parameters
guardrail: string # Required: One of "aporia", "bedrock", "guardrails_ai", "lakera", "presidio", "hide-secrets"
mode: Union[string, List[string]] # Required: One or more of "pre_call", "post_call", "during_call", "logging_only"
api_key: string # Required: API key for the guardrail service
api_base: string # Optional: Base URL for the guardrail service
default_on: boolean # Optional: Default False. When set to True, will run on every request, does not need client to specify guardrail in request
guardrail_info: # Optional[Dict]: Additional information about the guardrail
guardrails-Request-Parameter
Der Parameter guardrails kann an jeden LiteLLM Proxy-Endpunkt übergeben werden (/chat/completions, /completions, /embeddings).
Formatoptionen
- Einfaches Listenformat
"guardrails": [
"aporia-pre-guard",
"aporia-post-guard"
]
- Erweitertes Dictionary-Format
In diesem Format ist der Dictionary-Schlüssel der guardrail_name, den Sie ausführen möchten.
"guardrails": {
"aporia-pre-guard": {
"extra_body": {
"success_threshold": 0.9,
"other_param": "value"
}
}
}
Typdefinition
guardrails: Union[
List[str], # Simple list of guardrail names
Dict[str, DynamicGuardrailParams] # Advanced configuration
]
class DynamicGuardrailParams:
extra_body: Dict[str, Any] # Additional parameters for the guardrail