가드레일 - 빠른 시작
가드레일 - 빠른 시작 (Guardrails - Quick Start)
LiteLLM 프록시(AI 게이트웨이)에서 프롬프트 인젝션 감지, PII 마스킹 같은 가드레일을 설정하는 방법을 다루는 문서예요. config.yaml에 가드레일을 정의하고, 요청에 적용하며, 관리하는 전체 흐름을 살펴볼 수 있답니다.
출처: 문서
본문
1. LiteLLM config.yaml에 가드레일 정의하기
가드레일은 guardrails 섹션 아래에 정의해요.
model_list:
- model_name: gpt-5.6-luna
litellm_params:
model: openai/gpt-5.6-luna
api_key: os.environ/OPENAI_API_KEY
guardrails:
- guardrail_name: general-guard
litellm_params:
guardrail: cato_networks
mode: [pre_call, post_call]
api_key: os.environ/CATO_API_KEY
api_base: os.environ/CATO_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"
mode에서 지원하는 값 (Event Hooks)
가드레일 평가에서 시스템 메시지 건너뛰기
role: system 콘텐츠는 가드레일이 검사하지 않으면서도 전체 messages 목록은 모델로 전송하도록 할 수 있어요.
글로벌하게는 litellm_settings에서:
litellm_settings:
skip_system_message_in_guardrail: true
가드레일별로는 해당 가드레일의 litellm_params 아래에 skip_system_message_in_guardrail: true 또는 false를 설정해요. 생략하면 글로벌 litellm_settings 값이 사용되며, 가드레일별 false는 글로벌 플래그가 true여도 시스템 메시지를 검사에 포함시켜요.
LiteLLM UI에서는 어드민 대시보드에서 가드레일을 만들거나 수정할 때 "Skip system messages in guardrail" 옵션으로 설정할 수 있어요.
| UI 옵션 | 효과 |
|---|---|
| Use global default | 프록시 설정의 litellm_settings.skip_system_message_in_guardrail 사용 |
| Yes — exclude from guardrail scan | 가드레일별 skip_system_message_in_guardrail: true 설정 |
| No — always include in scan | 가드레일별 skip_system_message_in_guardrail: false 설정 (글로벌 스킵 재정의) |
가드레일 평가에서 도구 메시지 건너뛰기
role: tool 콘텐츠에 대해서도 동일한 아이디어예요. 도구 호출 결과는 가드레일이 검사하지 않으면서도 전체 messages 목록은 모델로 전송해요.
글로벌(litellm_settings):
litellm_settings:
skip_tool_message_in_guardrail: true
가드레일별로는 해당 가드레일의 litellm_params 아래에 skip_tool_message_in_guardrail: true 또는 false를 설정하며, 시스템 메시지 플래그와 동일한 우선순위 규칙을 따라요.
LiteLLM UI에서도 위 시스템 메시지 드롭다운 바로 아래에서 "Skip tool messages in guardrail"을 동일하게 설정할 수 있어요.
스킵 플래그가 적용되는 곳
적용 대상: 통합 가드레일 경로(apply_guardrail을 구현하고 LiteLLM의 메시지 변환 계층을 거치는 프로바이더)의 OpenAI Chat Completions(/v1/chat/completions)와 Anthropic Messages(/v1/messages). Presidio, Bedrock guardrails, litellm_content_filter, OpenAI Moderation, Generic Guardrail API, 그리고 apply_guardrail을 정의하는 커스텀 코드 가드레일 등이 해당돼요. Lakera v2도 직접 훅 대신 이 통합 경로를 거치므로 두 플래그를 모두 존중해요.
적용 안 되는 곳: 원시 요청에서 직접 훅으로만 동작하는 다른 가드레일(Aporia, DynamoAI, Javelin, Lasso, Pangea, Model Armor, Azure Content Safety 훅, Guardrails AI, AIM, Cato Networks, tool permission, MCP security 등). 이 플래그들은 해당 엔드포인트가 같은 변환 계층을 사용할 때까지 다른 라우트(Responses API, embeddings, speech 등)에는 적용되지 않아요.
가드레일 로드 밸런싱
여러 계정이나 지역에 가드레일 요청을 분산해야 하나요? 가드레일 로드 밸런싱 문서를 참고하세요.
2. LiteLLM 게이트웨이 시작하기
litellm --config config.yaml --detailed_debug
3. 테스트 요청
Langchain, OpenAI SDK 사용 예시.
요청에 [email protected](PII)가 포함되어 실패할 것으로 예상되는 요청:
curl -i http://localhost:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ***" \
-d '{
"model": "gpt-5.6-luna",
"messages": [
{"role": "user", "content": "hi my email is [email protected]"}
],
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}'
실패 시 예상 응답:
{
"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 http://localhost:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ***" \
-d '{
"model": "gpt-5.6-luna",
"messages": [
{"role": "user", "content": "hi what is the weather"}
],
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}'
기본 실행 가드레일 (Default On Guardrails)
가드레일 설정에 default_on: true를 설정하면 모든 요청에서 가드레일이 실행돼요. 사용자가 가드레일을 지정하지 않아도 매 요청마다 가드레일을 실행하고 싶을 때 유용해요.
참고: 사용자가 다른 가드레일이나 빈 guardrails 배열을 지정해도 이 가드레일은 실행돼요.
guardrails:
- guardrail_name: "aporia-pre-guard"
litellm_params:
guardrail: aporia
mode: "pre_call"
default_on: true
테스트 요청. default_on: true가 설정되어 있으므로 aporia-pre-guard 가드레일이 모든 요청에서 실행돼요.
curl -i http://localhost:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ***" \
-d '{
"model": "gpt-5.6-luna",
"messages": [
{"role": "user", "content": "hi my email is [email protected]"}
]
}'
예상 응답. 응답 헤더에 적용된 가드레일을 나타내는 x-litellm-applied-guardrails가 포함돼요.
x-litellm-applied-guardrails: aporia-pre-guard
가드레일 정책 (Guardrail Policies)
더 세밀한 제어가 필요하다면 가드레일 정책을 사용하세요.
클라이언트 측에서 가드레일 사용하기 (Using Guardrails Client Side)
직접 테스트해 보기 (OSS)
요청 본문에 가드레일을 전달해서 테스트해요.
curl -i http://localhost:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ***" \
-d '{
"model": "gpt-5.6-luna",
"messages": [
{"role": "user", "content": "hi my email is [email protected]"}
],
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}'
응답에서 가드레일 결과 검사하기 (OSS)
요청 본문에 include_guardrail_response: true를 설정하면 가드레일 실행 기록이 최상위 guardrail_information 목록으로 응답에 포함돼요. 이 플래그 없이는 응답 본문이 변하지 않으므로 기존 클라이언트에는 영향이 없어요. 이 플래그는 프로바이더에 도달하기 전에 제거돼요.
curl -i http://localhost:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ***" \
-d '{
"model": "gpt-5.6-luna",
"messages": [{"role": "user", "content": "Reply OK"}],
"guardrails": ["aporia-pre-guard"],
"include_guardrail_response": true
}'
예상 응답(다른 필드는 생략):
{
"id": "chatcmpl-EQjb0XEZzNUUGhbbYLfB2FApCuPJc",
"choices": [{"message": {"role": "assistant", "content": "OK"}}],
"guardrail_information": [
{
"guardrail_name": "aporia-pre-guard",
"guardrail_provider": "aporia",
"guardrail_mode": "pre_call",
"guardrail_status": "success",
"guardrail_response": [],
"start_time": 1790040506.278482,
"end_time": 1790040506.278695,
"duration": 0.000214,
"masked_entity_count": {}
}
]
}
각 항목은 StandardLoggingPayload의 guardrail_information과 같은 형태예요. 요청에서 가드레일이 실행되지 않으면 guardrail_information은 []예요. 정확히 JSON true 불리언만 활성화하며, "true"나 1은 꺼짐으로 처리돼요. 스트리밍 응답에는 이 필드가 포함되지 않아요. guardrail_response 내부의 keyword, snippet, match, regex 값은 "[REDACTED]"로 반환되어 마스킹된 콘텐츠가 호출자에게 다시 에코되지 않아요.
사용자에게 노출하기 (Enterprise)
가드레일 구현과 조정을 위한 간단한 워크플로예요.
1. 사용 가능한 가드레일 보기
먼저 어떤 가드레일이 있는지와 그 파라미터를 확인하세요.
/guardrails/list를 호출하면 사용 가능한 가드레일과 가드레일 정보(지원 파라미터, 설명 등)를 볼 수 있어요.
curl -X GET 'http://0.0.0.0:4000/guardrails/list'
예상 응답:
{
"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"
}
]
}
}
]
}
이 설정은 위 /guardrails/list 응답을 반환해요. guardrail_info 필드는 선택 사항이며 가드레일 사용자를 위해 info 아래에 원하는 필드를 추가할 수 있어요.
- 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. 가드레일 적용하기
선택한 가드레일을 채팅 완성 요청에 추가해요.
curl -i http://localhost:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.6-luna",
"messages": [{"role": "user", "content": "your message"}],
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}'
3. Mock LLM 완성으로 테스트하기
LLM을 호출하지 않고 가드레일을 테스트하려면 mock_response를 보내세요.
curl -i http://localhost:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ***" \
-d '{
"model": "gpt-5.6-luna",
"messages": [
{"role": "user", "content": "hi my email is [email protected]"}
],
"mock_response": "This is a mock response",
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}'
4. 가드레일에 동적 파라미터 전달하기
이 기능은 LiteLLM Enterprise 라이선스가 필요해요. 30일 무료 체험판을 시작하거나 데모를 예약하세요.
가드레일 API 호출에 추가 파라미터(예: success threshold)를 전달할 때 사용해요. guardrails={"aporia-pre-guard": {"extra_body": {"success_threshold": 0.9}}}로 설정하면 success_threshold=0.9가 aporia-pre-guard 가드레일 요청 본문에 전달돼요.
import openai
client = openai.OpenAI(
api_key="anything",
base_url="http://0.0.0.0:4000"
)
response = client.chat.completions.create(
model="gpt-5.6-luna",
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-5.6-luna",
"messages": [
{
"role": "user",
"content": "what llm are you"
}
],
"guardrails": {
"aporia-pre-guard": {
"extra_body": {
"success_threshold": 0.9
}
}
}
}'
프록시 관리자 제어 (Proxy Admin Controls)
가드레일 모니터링
어떤 가드레일이 실행되었고 통과/실패했는지 모니터링해요. 예를 들어 가드레일이 오작동해서 의도치 않게 요청을 실패시키는 경우를 감지할 수 있어요.
설정 (Setup)
추적된 가드레일 성공 (Traced Guardrail Success)
추적된 가드레일 실패 (Traced Guardrail Failure)
API 키별 가드레일 제어하기
이 기능은 LiteLLM Enterprise 라이선스가 필요해요.
API 키별로 실행할 가드레일을 제어할 수 있어요. 이 예시에서는 1개의 API 키에 대해서만 특정 가드레일이 실행되도록 해요.
1단계. 가드레일 설정으로 키 생성하기.
curl -X POST 'http://0.0.0.0:4000/key/generate' \
-H "Authorization: Bearer ***" \
-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 ***" \
--header 'Content-Type: application/json' \
--data '{
"key": "sk-jNm...1kSQ",
"guardrails": ["aporia-pre-guard", "aporia-post-guard"]
}'
2단계. 새 키로 테스트하기.
curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Authorization: Bearer ***' \
--header 'Content-Type: application/json' \
--data '{
"model": "gpt-5.6-luna",
"messages": [
{
"role": "user",
"content": "my email is [email protected]"
}
]
}'
태그 기반 가드레일 모드
이 기능은 LiteLLM Enterprise 라이선스가 필요해요.
user-agent 헤더를 기준으로 가드레일을 실행해요. OpenWebUI에서는 사전 호출 검사를 실행하고 Claude CLI에서는 로그에서만 마스킹하는 경우에 유용해요.
default와 tag 값 모두 단일 모드 문자열이거나 모드 목록일 수 있어요.
model_list:
- model_name: gpt-5.6-luna
litellm_params:
model: gpt-5.6-luna
api_key: os.environ/OPENAI_API_KEY
guardrails:
- guardrail_name: "guardrails_ai-guard"
litellm_params:
guardrail: guardrails_ai
guard_name: "pii_detect" # 👈 Guardrail AI guard name
mode:
tags:
"User-Agent: claude-cli": "logging_only" # Claude CLI - only mask in logs
default: "pre_call" # Default mode when no tags match
api_base: os.environ/GUARDRAILS_AI_API_BASE # 👈 Guardrails AI API Base. Defaults to "http://0.0.0.0:8000"
default_on: true # run on every request
가드레일별:
model_list:
- model_name: gpt-5.6-luna
litellm_params:
model: gpt-5.6-luna
api_key: os.environ/OPENAI_API_KEY
guardrails:
- guardrail_name: "guardrails_ai-guard"
litellm_params:
guardrail: guardrails_ai
guard_name: "pii_detect"
mode:
tags:
"User-Agent: claude-cli": "logging_only"
default: ["pre_call", "post_call"] # Run on both pre and post call when no tags match
api_base: os.environ/GUARDRAILS_AI_API_BASE
default_on: true
model_list:
- model_name: gpt-5.6-luna
litellm_params:
model: gpt-5.6-luna
api_key: os.environ/OPENAI_API_KEY
guardrails:
- guardrail_name: "guardrails_ai-guard"
litellm_params:
guardrail: guardrails_ai
guard_name: "pii_detect"
mode:
tags:
"User-Agent: claude-cli": ["pre_call", "post_call"] # Run both pre and post call for claude-cli
default: "logging_only" # Default to logging only when no tags match
api_base: os.environ/GUARDRAILS_AI_API_BASE
default_on: true
모델 수준 가드레일
이 기능은 LiteLLM Enterprise 라이선스가 필요해요.
온프레미스와 호스팅 모델이 함께 있을 때, 호스팅 모델로 PII가 전송되는 것을 막고 싶은 경우에 유용해요.
model_list:
- model_name: claude-sonnet-5
litellm_params:
model: anthropic/claude-sonnet-5
api_key: os.environ/ANTHROPIC_API_KEY
api_base: https://api.anthropic.com/v1
guardrails: ["azure-text-moderation"]
- model_name: openai-gpt-4o
litellm_params:
model: openai/gpt-5.6-terra
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
mode: "post_call"
api_key: os.environ/AZURE_GUARDRAIL_API_KEY
api_base: os.environ/AZURE_GUARDRAIL_API_BASE
팀이 가드레일을 켜고 끄지 못하게 하기
이 기능은 LiteLLM Enterprise 라이선스가 필요해요.
1. 팀이 가드레일을 수정하지 못하게 하기
curl -X POST 'http://0.0.0.0:4000/team/update' \
-H "Authorization: Bearer ***" \
-H 'Content-Type: application/json' \
-d '{
"team_id": "4198d93c-d375-4c83-8d5a-71e7c5473e50",
"metadata": {"guardrails": {"modify_guardrails": false}}
}'
2. 호출에 대해 가드레일 비활성화 시도하기
curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer $LITEL..._KEY' \
--data '{
"model": "gpt-5.6-luna",
"messages": [
{
"role": "user",
"content": "Think of 10 random colors."
}
],
"metadata": {"guardrails": {"hide_secrets": false}}
}'
3. 403 오류 받기
{
"error": {
"message": {
"error": "Your team does not have permission to modify guardrails."
},
"type": "auth_error",
"param": "None",
"code": 403
}
}
콜백의 서버 로그에 +1 412-612-9992가 나타나지 않을 것으로 예상해요. pii_masking 가드레일이 실행된 이유는 api key=sk-jNm...1kSQ에 "permissions": {"pii_masking": true}가 있기 때문이에요.
명세 (Specification)
YAML의 guardrails 구성
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], Mode] # 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
Mode 명세. default와 tag 값 모두 단일 문자열 또는 문자열 목록을 받을 수 있어요.
from litellm.types.guardrails import Mode
# Single default mode
mode = Mode(
tags={"User-Agent: claude-cli": "logging_only"},
default="logging_only"
)
# Multiple default modes
mode = Mode(
tags={"User-Agent: claude-cli": "logging_only"},
default=["pre_call", "post_call"]
)
# Multiple modes on a tag value
mode = Mode(
tags={"User-Agent: claude-cli": ["pre_call", "post_call"]},
default="logging_only"
)
guardrails 요청 파라미터
guardrails 파라미터는 모든 LiteLLM 프록시 엔드포인트(/chat/completions, /completions, /embeddings)에 전달할 수 있어요.
형식 옵션
{"guardrails": [
"aporia-pre-guard",
"aporia-post-guard"
]}
이 형식에서 사전의 키는 실행하려는 guardrail_name이에요.
{"guardrails": {
"aporia-pre-guard": {
"extra_body": {
"success_threshold": 0.9,
"other_param": "value"
}
}
}}
타입 정의
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