가드레일 공급자: 커스텀 코드 가드레일

가드레일 공급자: 커스텀 코드 가드레일 (Custom Code Guardrail)

자체 Python 코드로 커스텀 가드레일을 작성해 LiteLLM에 등록해요. 이는 프롬프트/응답을 검사하는 서드파티 API가 없이 조직 내부 로직을 실행해야 할 때 사용해요.

출처: 문서

본문

개요 (Overview)

커스텀 코드 가드레일은 CustomGuardrail 클래스를 서브클래싱해 LiteLLM이 호출 훅에서 호출하는 메서드를 정의해요. pre_call(요청 검사), post_call(응답 검사), during_call 등 모드에 따라 호출 시점을 제어할 수 있어요.

빠른 시작 (Quick Start)

1. 커스텀 가드레일 파일 생성

custom_guardrail.py 파일을 만들고 CustomGuardrail을 상속해 검사 로직을 구현하세요:

from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.proxy._types import UserAPIKeyAuth
from litellm.types.utils import CallTypesLiteral
from fastapi import HTTPException

class MyCustomGuardrail(CustomGuardrail):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    async def async_pre_call_hook(
        self,
        data: dict,
        user_api_key_dict: UserAPIKeyAuth,
        call_type: CallTypesLiteral,
    ):
        messages = data["messages"]
        # 여기에 검사 로직 추가
        if "blocked phrase" in str(messages):
            raise HTTPException(
                status_code=400, detail={"error": "Blocked content detected"}
            )

2. 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: "my-custom-guardrail"
    litellm_params:
      guardrail: custom_guardrail.MyCustomGuardrail  # {file_name}.{class_name}
      mode: "pre_call"
      default_on: true

3. LiteLLM 게이트웨이 시작 및 테스트

litellm --config config.yaml
curl -i http://localhost:4000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.6-luna",
    "messages": [
      {"role": "user", "content": "test request"}
    ],
    "guardrails": ["my-custom-guardrail"]
  }'

지원되는 훅 (Supported hooks)

  • async_pre_call_hook - LLM 호출 전 입력 검사
  • async_post_call_success_hook - 성공 응답 검사
  • async_post_call_failure_hook - 실패 응답 검사
  • async_moderation_hook - LLM 호출과 병행 중재 검사

참고 사항 (Notes)

  • mode에 따라 pre_call, post_call, during_call을 지정하세요.
  • guardrail 필드는 <파일명>.<클래스명> 형식이에요.
  • 자세한 정의, 파라미터, 응답 처리 방식은 원문 문서를 참고하세요.