Guardrails API — Guard.use와 on_fail 동작
Guardrails API
Guardrails의 핵심 타입은 Guard예요. 여기에 validator를 붙이고, 검증 실패 시 어떻게 다룰지를 on_fail로 정합니다.
Guard.use로 validator 조합
from guardrails import Guard, OnFailAction
from guardrails_ai.competitor_check import CompetitorCheck
from guardrails_ai.toxic_language import ToxicLanguage
guard = Guard().use(
CompetitorCheck(["Apple", "Microsoft", "Google"], on_fail=OnFailAction.EXCEPTION),
ToxicLanguage(threshold=0.5, validation_method="sentence", on_fail=OnFailAction.EXCEPTION),
)
guard.validate(
"An apple a day keeps a doctor away. This is good advice for keeping your health."
) # 두 가드레일 모두 통과
try:
guard.validate(
"Shut the hell up! Apple just released a new iPhone."
) # 둘 다 실패 → Exception
except Exception as e:
print(e)
OnFailAction.EXCEPTION은 검증 실패 시 예외를 던지도록 만드는 동작이에요. 그 외에도 재시도·고정(fix)·차단 등 여러 정책을 validator 단위로 지정할 수 있어요.
핵심 파라미터
threshold: 독성 점수의 허용 기준validation_method: 문장 단위("sentence")인지 전체("full")인지on_fail: 실패 시 대응 (OnFailAction.EXCEPTION,REASK,FIX등)
검증 흐름
- LLM이 응답 생성
Guard가 응답 파싱- 등록된 각 validator 실행
- 결과 따라 통과 / 예외 / 재시도 처리
이 흐름 덕분에 '모델이 뭘 내놓든 상관없다'가 아니라 '정해진 규칙을 지키는 응답만 통과'시키는 앱을 만들 수 있어요.