LiteLLM 콘텐츠 필터

LiteLLM 콘텐츠 필터 (빌트인 가드레일) (LiteLLM Content Filter (Built-in Guardrails))

regex 패턴과 키워드 매칭을 사용해 민감 정보를 감지·필터링하는 빌트인 가드레일이에요. 외부 의존성이 없어요. 민감 정보를 감지하는 데 ML 모델이 필요 없는 경우에 좋아요.

출처: 문서

본문

개요 (Overview)

속성 세부
설명 regex 패턴과 키워드 매칭으로 민감 정보를 감지·필터링하는 온디바이스 가드레일. 외부 의존성 없이 LiteLLM에 내장
가드레일 이름 litellm_content_filter
감지 방법 사전 구축 regex 패턴, 커스텀 regex, 키워드 매칭
동작 BLOCK (요청 거부), MASK (콘텐츠 교정)
지원 모드 pre_call, post_call, during_call (스트리밍)
성능 빠름 - 로컬에서 실행, 외부 API 호출 없음

빠른 시작 (Quick Start)

LiteLLM UI

  1. "Add New Guardrail"을 클릭하고 가드레일 공급자로 "LiteLLM Content Filter"를 선택하세요.
  2. 차단하거나 마스킹할 사전 구축 엔티티를 선택하세요. 이 예시에서는 "Email"을 선택해 이메일 주소를 감지·차단해요. 커스텀 엔티티를 차단해야 한다면 "Add custom regex"를 클릭해 커스텀 regex 패턴을 추가할 수 있어요.
  3. 차단할 특정 키워드를 입력하세요. 특정 단어나 문구를 차단하는 정책이 있을 때 유용해요.
  4. 가드레일을 만든 후 "Test Playground"로 이동해 테스트하세요.
    • 차단 키워드 테스트: "blue"를 차단 키워드로 설정했으므로 "hi blue" 입력 시 차단
    • 패턴 감지 테스트: "Hi [email protected]" 입력 시 email 패턴 감지기 발동

LiteLLM Config.yaml 설정

1단계: config.yaml에 가드레일 정의

config.yaml:

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: "harmful-content-filter"
    litellm_params:
      guardrail: litellm_content_filter
      mode: "pre_call"
      # Enable harmful content categories
      categories:
        - category: "harmful_self_harm"
          enabled: true
          action: "BLOCK"
          severity_threshold: "medium"
        - category: "harmful_violence"
          enabled: true
          action: "BLOCK"
          severity_threshold: "medium"
        - category: "harmful_illegal_weapons"
          enabled: true
          action: "BLOCK"
          severity_threshold: "medium"

2단계: LiteLLM 게이트웨이 시작

litellm --config config.yaml

3단계: 테스트 요청

SSN 차단:

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": "My SSN is 123-45-6789"}
    ],
    "guardrails": ["content-filter-pre"]
  }'

응답: HTTP 400 Error

{
  "error": {
    "message": {
      "error": "Content blocked: us_ssn pattern detected",
      "pattern": "us_ssn"
    },
    "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": "Contact me at [email protected]"}
    ],
    "guardrails": ["content-filter-pre"]
  }'

요청이 이메일이 마스킹된 채로 LLM에 전송돼요: Contact me at [EMAIL_REDACTED]

구성 (Configuration)

지원 모드 (Supported Modes):

  • pre_call - LLM 호출 전 실행, 입력 메시지 필터
  • post_call - LLM 호출 후 실행, 출력 응답 필터
  • during_call - 스트리밍 중 실행, 각 청크 실시간 필터

동작 (Actions):

  • BLOCK - HTTP 400 오류로 요청 거부
  • MASK - 민감 콘텐츠를 교정 태그로 대체 (예: [EMAIL_REDACTED])

사전 구축 패턴 (Prebuilt Patterns):

패턴 이름 설명 예시
us_ssn 미국 사회보장번호 123-45-6789
email 이메일 주소 [email protected]
phone 전화번호 +1-555-123-4567
visa Visa 신용카드 4532-1234-5678-9010
mastercard Mastercard 신용카드 5425-2334-3010-9903
amex American Express 카드 3782-822463-10005
aws_access_key AWS 액세스 키 AKIAIOSFODNN7EXAMPLE
aws_secret_key AWS 시크릿 키 wJalrXUtnFEMI/K7MDENG/bPxRfi...
github_token GitHub 토큰 example-github-token-123

사전 구축 패턴 사용:

guardrails:
  - guardrail_name: "pii-filter"
    litellm_params:
      guardrail: litellm_content_filter
      mode: "pre_call"
      patterns:
        - pattern_type: "prebuilt"
          pattern_name: "us_ssn"
          action: "BLOCK"
        - pattern_type: "prebuilt"
          pattern_name: "email"
          action: "MASK"
        - pattern_type: "prebuilt"
          pattern_name: "aws_access_key"
          action: "BLOCK"

커스텀 regex 패턴 (Custom Regex Patterns):

도메인 특화 민감 데이터에 대한 자체 regex 패턴 정의:

guardrails:
  - guardrail_name: "custom-patterns"
    litellm_params:
      guardrail: litellm_content_filter
      mode: "pre_call"
      patterns:
        # Custom employee ID format
        - pattern_type: "regex"
          pattern: '\b[A-Z]{3}-\d{4}\b'
          name: "employee_id"
          action: "MASK"
        # Custom project code format
        - pattern_type: "regex"
          pattern: 'PROJECT-\d{6}'
          name: "project_code"
          action: "BLOCK"

키워드 필터링 (Keyword Filtering):

특정 키워드 차단/마스킹:

guardrails:
  - guardrail_name: "keyword-filter"
    litellm_params:
      guardrail: litellm_content_filter
      mode: "pre_call"
      blocked_words:
        - keyword: "confidential"
          action: "BLOCK"
          description: "Internal confidential information"
        - keyword: "proprietary"
          action: "MASK"
          description: "Proprietary company data"
        - keyword: "secret_project"
          action: "BLOCK"

파일에서 키워드 로드 (Loading Keywords from File):

대규모 키워드 목록에는 YAML 파일 사용:

guardrails:
  - guardrail_name: "keyword-file-filter"
    litellm_params:
      guardrail: litellm_content_filter
      mode: "pre_call"
      blocked_words_file: "/path/to/sensitive_keywords.yaml"

sensitive_keywords.yaml:

blocked_words:
  - keyword: "project_apollo"
    action: "BLOCK"
    description: "Confidential project codename"
  - keyword: "internal_api"
    action: "MASK"
    description: "Internal API references"
  - keyword: "customer_database"
    action: "BLOCK"
    description: "Protected database name"

스트리밍 지원 (Streaming Support)

콘텐츠 필터는 스트리밍 응답에서 각 청크를 확인해서 동작해요:

guardrails:
  - guardrail_name: "streaming-filter"
    litellm_params:
      guardrail: litellm_content_filter
      mode: "during_call"  # Check each streaming chunk
      patterns:
        - pattern_type: "prebuilt"
          pattern_name: "email"
          action: "MASK"
import openai
client = openai.OpenAI(
    api_key="sk-<your-litellm-api-key>",
    base_url="http://localhost:4000")
response = client.chat.completions.create(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me about yourself"}],
    stream=True,
    extra_body={"guardrails": ["streaming-filter"]})
for chunk in response:
    print(chunk.choices[0].delta.content)
    # Emails automatically masked in real-time

이미지 콘텐츠 필터링 (Image Content Filtering)

콘텐츠 필터는 설명을 생성하고 텍스트 설명에 필터를 적용해 이미지를 분석할 수 있어요.

warning

이는 요청에 상당한 지연을 도입할 수 있어요 - 비전 가능 모델의 속도에 따라 다름. 이미지를 포함한 각 요청이 비전 가능 모델에 보내져 설명을 생성하기 때문이에요.

config.yaml:

model_list:
  - model_name: gpt-4-vision
    litellm_params:
      model: openai/gpt-5.6-terra
      api_key: os.environ/OPENAI_API_KEY
guardrails:
  - guardrail_name: "image-filter"
    litellm_params:
      guardrail: litellm_content_filter
      mode: "pre_call"
      image_model: "gpt-4-vision"  # value is `model_name` of the vision-capable model
      # Apply same filters to image descriptions
      categories:
        - category: "harmful_violence"
          enabled: true
          action: "BLOCK"
          severity_threshold: "medium"
      patterns:
        - pattern_type: "prebuilt"
          pattern_name: "email"
          action: "MASK"

이미지가 비전 모델로 보내져 텍스트 설명이 생성되고, 콘텐츠 필터가 설명에 적용되며, 유해 콘텐츠가 감지되면 이미지에 대한 컨텍스트와 함께 요청이 차단돼요.

예시:

import openai
client = openai.OpenAI(
    api_key="sk-<your-litellm-api-key>",
    base_url="http://localhost:4000")
response = client.chat.completions.create(
    model="gpt-4-vision",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What's in this image?"},
            {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
        ]
    }],
    extra_body={"guardrails": ["image-filter"]})

이미지 설명이 필터링된 콘텐츠를 포함하면:

{
  "error": "Content blocked: harmful_violence category keyword 'weapon' detected (severity: high) (Image description): The image shows..."
}

교정 태그 사용자 지정 (Customizing Redaction Tags)

MASK 동작 사용 시 민감 콘텐츠가 교정 태그로 대체돼요. 태그 표시를 사용자 지정할 수 있어요.

  • 기본 동작 (패턴): 각 패턴 유형은 패턴 이름 기반 자체 태그를 갖음 "My email is [email protected] and SSN is 123-45-6789""My email is [EMAIL_REDACTED] and SSN is [US_SSN_REDACTED]"
  • 키워드: 모든 키워드가 같은 일반 태그 사용 "This is confidential and proprietary information""This is [KEYWORD_REDACTED] and [KEYWORD_REDACTED] information"

pattern_redaction_formatkeyword_redaction_tag로 교정 형식을 변경:

config.yaml:

guardrails:
  - guardrail_name: "custom-redaction"
    litellm_params:
      guardrail: litellm_content_filter
      mode: "pre_call"
      pattern_redaction_format: "***{pattern_name}***"  # Use {pattern_name} placeholder
      keyword_redaction_tag: "***REDACTED***"
      patterns:
        - pattern_type: "prebuilt"
          pattern_name: "email"
          action: "MASK"
        - pattern_type: "prebuilt"
          pattern_name: "us_ssn"
          action: "MASK"
      blocked_words:
        - keyword: "confidential"
          action: "MASK"

출력: "Email [email protected], SSN 123-45-6789, confidential data""Email ***EMAIL***, SSN ***US_SSN***, ***REDACTED*** data"

핵심 사항:

  • pattern_redaction_format{pattern_name} 플레이스홀더를 포함해야 함
  • 패턴 이름은 자동 대문자화됨 (예: emailEMAIL)
  • keyword_redaction_tag는 고정 문자열 (플레이스홀더 없음)

콘텐츠 카테고리 (Content Categories)

사전 구축 카테고리는 유해 콘텐츠, 편향, 부적절한 조언을 감지하기 위해 키워드 매칭을 사용해요. 키워드는 단어 경계(단어 하나) 또는 하위 문자열(여러 단어 문구)로 일치하며, 대소문자 구분 없이 매칭돼요.

이름으로 아래 카테고리를 참조하면 돼요. category_file:은 필요 없어요.

카테고리 설명
유해 콘텐츠 (Harmful Content)
harmful_self_harm 자해, 자살, 섭식 장애
harmful_violence 폭력, 범죄 계획, 공격
harmful_illegal_weapons 불법 무기, 폭발물, 위험 물질
harmful_child_safety 미성년자 관련 부적절한 콘텐츠
편향 / 고용 차별 (Bias / Employment Discrimination)
bias_gender 성별 기반 차별, 고정관념
bias_sexual_orientation LGBTQ+ 차별, 혐오·관타포비아
bias_racial 인종/민족 차별, 증오 발언
bias_religious 종교 차별, 고정관념
age_discrimination 연령 기반 고용 차별
disability 장애인 고용 차별
gender_sexual_orientation 성별·성·성적 지향 고용 차별
거부 조언 (Denied Advice)
denied_financial_advice 개인화된 금융 조언, 투자 권유
denied_medical_advice 의료 조언, 진단, 치료 권유
denied_legal_advice 법률 조언, 대리, 법적 전략
denied_insults 모욕, 욕설, 인신 공격
프롬프트 인젝션 (Prompt Injection)
prompt_injection_jailbreak 젤브레이크 시도 (DAN, 롤플레이 공격, 안전 우회)
prompt_injection_system_prompt 시스템 프롬프트 추출·노출·재정의 시도
prompt_injection_sql 프롬프트에 내장된 SQL 인젝션
prompt_injection_malicious_code 프롬프트를 통한 악성 코드 인젝션
prompt_injection_data_exfiltration 훈련 데이터 또는 내부 정보 추출 시도
클레임 오용 (Claims Abuse)
claims_fraud_coaching 사기 보험 클레임 코칭
claims_medical_advice 클레임 맥락의 의료 조언
claims_phi_disclosure 무단 PHI 공개 / HIPAA 위반
claims_prior_auth_gaming 사전 승인 게임 시도
claims_system_override 클레임 시스템 재정의 / 역할 사칭 시도

편향 감지 고려 사항 (Bias Detection Considerations):

편향 감지는 복잡하고 컨텍스트에 의존적이에요. 규칙 기반 시스템은 명시적 차별 언어를 잡지만 정당한 논의에서 거짓 양성을 생성할 수 있어요. 높은 심각도 임계값으로 시작하고 철저히 테스트하세요. 임무 중요 편향 감지에는 AI 기반 가드레일(예: HiddenLayer, Lakera)과 결합하는 것을 고려하세요.

구성 (Configuration):

guardrails:
  - guardrail_name: "content-filter"
    litellm_params:
      guardrail: litellm_content_filter
      mode: "pre_call"
      categories:
        - category: "harmful_self_harm"
          enabled: true
          action: "BLOCK"
          severity_threshold: "medium"  # Blocks medium+ severity
        - category: "bias_gender"
          enabled: true
          action: "BLOCK"
          severity_threshold: "high"  # Only explicit discrimination
        - category: "denied_financial_advice"
          enabled: true
          action: "BLOCK"
          severity_threshold: "medium"

심각도 임계값:

  • "high" - 고심각도 항목만 차단
  • "medium" - 중간 및 고심각도 차단 (기본)
  • "low" - 모든 심각도 수준 차단

커스텀 카테고리 파일 (Custom Category Files)

내장 카테고리를 재정의하거나, 자체 키워드 목록으로 새 카테고리를 추가하세요.

config.yaml:

categories:
  - category: "<your-category-name>"
    enabled: true
    action: "BLOCK"
    severity_threshold: "medium"
    category_file: "<your-category-name>.yaml"

<your-category-name>.yaml:

category_name: "<your-category-name>"
description: "Short description of what this category detects"
default_action: "BLOCK"
keywords:
  - keyword: "example keyword"
    severity: "high"
exceptions:
  - "example exception phrase"

파일을 놓을 곳 (Where to put the file):

옵션 A: 기본 categories/ 디렉토리 안에 배치 (권장). 파일을 <site-packages>/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/categories/<your-category-name>.yaml에 마운트하고 category_file: 필드를 빼세요. 로더가 카테고리 이름으로 가져와요.

옵션 B: env var 옵트인과 함께 다른 경로. 프록시 pod에 LITELLM_CONTENT_FILTER_ALLOW_EXTERNAL_PATHS=true를 설정하고 절대 경로로 파일을 참조하세요. category_file을 쓸 수 있는 사람(프록시 구성, DB, Admin UI, 팀 범위 구성)이 모두 신뢰되는 경우에만 사용하세요. 플래그가 켜지면 category_file이 pod의 어떤 YAML 파싱 가능 파일이든 가리킬 수 있어요.

로드 확인 (Verifying it loaded):

프록시 시작 로그에서 확인:

  • content_filter.py: Loaded category <name>: N keywords, M always-block keywords ...
  • 또는 content_filter.py: Category <name>: invalid category_file path, skipping. ...

두 번째 줄은 파일이 거부되어 카테고리가 0개 규칙으로 실행됨을 의미해요. 위 두 옵션 중 하나로 고치세요.

사용 사례 (Use Cases)

  1. 유해 콘텐츠 감지: 유해, 불법, 위험한 콘텐츠를 포함한 요청 차단/감지
  2. 편향 및 차별 감지: 여러 차원에 걸친 편향, 차별, 증오 콘텐츠 감지·차단
  3. PII 보호: LLM에 보내기 전에 개인 식별 정보 차단/마스킹
  4. 자격 증명 감지: API 키와 시크릿 노출 방지
  5. 민감 내부 데이터 보호: 기밀 내부 프로젝트, 코드네임, 독점 정보 참조 차단/마스킹
  6. 소비자 앱 안전 AI: 소비자 지향 AI에 대한 유해 콘텐츠와 편향 감지 결합
  7. 컴플라이언스: 민감 데이터 유형 필터링으로 규제 컴플라이언스 보장