앱에 Guardrails 임베딩하기
앱에 Guardrails 임베딩하기 (시작하기)
Guardrails를 내 애플리케이션 안에 심어 쓰는 가장 기본적인 길을 따라가볼게요. 설치부터 validator 하나를 guard에 얹고, LLM 출력을 구조화하는 데까지 한 번에 이어지는 흐름이에요. 어떤 언어 모델이든 조합해서 쓸 수 있다는 게 눈에 띄는 특징이죠. 아직 감이 안 잡히면 이 페이지 하나로 시작해도 충분해요.
소개
Guardrails는 언어 모델의 출력 데이터를 검증하고 구조화하는 프레임워크예요. 검증 범위는 regex 매칭처럼 단순한 것부터 경쟁사 분석처럼 복잡한 것까지 다양하죠. 그리고 어떤 언어 모델과도 함께 쓸 수 있어요.
설치
Guardrails 다운로드 (필수)
먼저 원하는 언어에 맞춰 Guardrails를 설치해요.
pip install guardrails-ai
Guardrails CLI 설정 (선택)
CLI는 아래 명령으로 설정해요.
guardrails configure
설정 과정에서 익명 메트릭 보고를 켜고 싶은지 물어봐요.
validator 설치
LLM 출력을 검증하려면 용도에 맞는 validator를 설치해야 해요. validator는 guardrails-ai-<name> 이름으로 공개 PyPI에 배포되고 pip로 설치할 수 있어요. 예를 들어 Detect PII validator는 이렇게 설치해요.
pip install guardrails-ai-detect-pii
사용법
설치한 validator로 Guard 만들기
먼저 PyPI에서 원하는 validator를 설치해요.
pip install guardrails-ai-regex-match
그다음 guardrails_ai 네임스페이스에서 validator를 import 해 Guard를 구성해요.
# Import Guard and Validator
from guardrails_ai.regex_match import RegexMatch
from guardrails import Guard
# Initialize the Guard with
guard = Guard().use(
RegexMatch(regex="^[A-Z][a-z]*$")
)
print(guard.parse("Caesar").validation_passed) # Guardrail Passes
print(
guard.parse("Caesar Salad")
.validation_passed
) # Guardrail Fails
하나의 Guard에서 validator 여러 개 실행하기
필요한 validator들을 먼저 PyPI에서 설치하고,
pip install guardrails-ai-regex-match guardrails-ai-valid-length
그다음 설치한 validator들로 Guard를 만들어요.
from guardrails_ai.regex_match import RegexMatch
from guardrails_ai.valid_length import ValidLength
from guardrails import Guard
guard = Guard().use(
RegexMatch(regex="^[A-Z][a-z]*$"),
ValidLength(min=1, max=12)
)
print(guard.parse("Caesar").validation_passed) # Guardrail Passes
print(
guard.parse("Caesar Salad")
.validation_passed
) # Guardrail Fails due to regex match
print(
guard.parse("Caesarisagreatleader")
.validation_passed
) # Guardrail Fails due to length
구조화된 데이터 생성과 검증
이번엔 LLM에게 가상의 반려동물 이름을 만들도록 시키는 예시를 볼게요.
- 원하는 출력 구조를 나타내는 Pydantic BaseModel을 만들고,
from pydantic import BaseModel, Field
class Pet(BaseModel):
pet_type: str = Field(description="Species of pet")
name: str = Field(description="a unique pet name")
Pet클래스로 Guard를 만들어요. Guard로 LLM을 호출하면 출력이Pet클래스 형식으로 맞춰져요. 내부적으로는 두 가지 방법 중 하나가 쓰이죠.
(1) 함수 호출(function calling): 함수 호출을 지원하는 LLM이면, 함수 호출 문법으로 구조화된 데이터를 생성해요.
(2) 프롬프트 최적화: 함수 호출을 지원하지 않는 LLM이면, 예상 출력 스키마를 프롬프트에 넣어 LLM이 구조화된 데이터를 만들게 해요.
from guardrails import Guard
prompt = """
What kind of pet should I get and what should I name it?
${gr.complete_json_suffix_v2}
"""
guard = Guard.for_pydantic(output_class=Pet)
res = guard(
model="gpt-3.5-turbo",
messages=[{
"role": "user",
"content": prompt
}]
)
print(f"{res.validated_output}")
출력은 이렇게 나와요.
{
"pet_type": "dog",
"name": "Buddy"
}
심화 설치 방법
Javascript 라이브러리 설치하기
참고: Javascript 라이브러리는 I/O 브리지를 통해 내부적으로 파이썬 라이브러리를 실행해요. Javascript 라이브러리를 쓰려면 시스템에 Python 3.10 이상이 설치돼 있어야 해요.
npm i @guardrails-ai/core
특정 버전 설치하기
파이썬에서 특정 버전을 설치하려면 이렇게 해요.
# pip install guardrails-ai==[version-number]
# Example:
pip install guardrails-ai==0.5.0a13
GitHub에서 직접 설치하기
아직 릴리스로 잘리지 않은 변경이 담긴 브랜치가 필요할 때 GitHub에서 직접 설치하면 돼요. 비출시 버전은 breaking change가 포함될 수 있고 테스트 커버리지가 완전하지 않을 수 있으니, 가능하면 출시된 버전을 쓰는 걸 권장해요.
# pip install git+https://github.com/guardrails-ai/guardrails.git@[branch/commit/tag]
# Example:
pip install git+https://github.com/guardrails-ai/guardrails.git@main
npm i git+https://github.com/guardrails-ai/guardrails-js.git
더 알아보기
- Guard 객체: guard를 초기화한 뒤 호출하거나 parse하는 핵심 흐름을 봐요.
- Validators: 검증 기준을 정의하는 validator가 어떻게 동작하는지 봐요.
- 지원하는 여러 LLM에서 검증하기: 100개 이상의 LLM을 함께 쓰는 방법을 알아봐요.