지원하는 여러 LLM에서 검증하기

지원하는 여러 LLM에서 검증하기

Guardrails는 LiteLLM과의 통합으로 100개 이상의 LLM을 지원해요. 그 덕분에 Guardrails의 호출 API가 LiteLLM과 OpenAI가 쓰는 깔끔한 인터페이스를 그대로 사용할 수 있죠. 모델과 상호작용할 때는 원하는 LLM의 API KEY를 설정하고, model 프로퍼티로 모델을 지정하면 돼요.

출처: Use supported LLMs - Guardrails AI 공식 문서

OpenAI

기본 사용법

from guardrails import Guard
import os

os.environ["OPENAI_API_KEY"] = "YOUR_OPEN_AI_API_KEY"

guard = Guard()

result = guard(
    messages=[{"role":"user", "content":"How many moons does Jupiter have?"}],
    model="gpt-4o",
)

print(f"{result.validated_output}")

스트리밍

stream=True를 넘기면 청크 단위로 검증 결과를 받아볼 수 있어요. 각 청크의 validated_output이 순서대로 출력돼요.

from guardrails import Guard
import os

os.environ["OPENAI_API_KEY"] = "YOUR_OPEN_AI_API_KEY"

guard = Guard()

stream_chunk_generator = guard(
    messages=[{"role":"user", "content":"How many moons does Jupiter have?"}],
    model="gpt-4o",
    stream=True,
)

for chunk in stream_chunk_generator:
    print(f"{chunk.validated_output}")

Tools/함수 호출

구조화된 출력은 Pydantic 모델로 정의하고, guard.json_function_calling_tool([])로 함수 호출 도구를 만들어 넘겨요. tool_choice="required"로 함수 호출을 강제할 수 있죠.

from pydantic import BaseModel, Field
from typing import List
from guardrails import Guard
import os

os.environ["OPENAI_API_KEY"] = "YOUR_OPEN_AI_API_KEY"

class Fruit(BaseModel):
    name: str
    color: str

class Basket(BaseModel):
    fruits: List[Fruit]
    
guard = Guard.for_pydantic(Basket)

result = guard(
    messages=[{"role":"user", "content":"Generate a basket of 5 fruits"}],
    model="gpt-4o",
    tools=guard.json_function_calling_tool([]),
    tool_choice="required",
)

print(f"{result.validated_output}")

Anthropic

기본 사용법

from guardrails import Guard
import os

guard = Guard()

os.environ["ANTHROPIC_API_KEY"] = "your-api-key"

result = guard(
    messages=[{"role":"user", "content":"How many moons does Jupiter have?"}],
    model="claude-3-opus-20240229"
)

print(f"{result.validated_output}")

스트리밍

from guardrails import Guard
import os

os.environ["ANTHROPIC_API_KEY"] = "your-api-key"

guard = Guard()

stream_chunk_generator = guard(
    messages=[{"role":"user", "content":"How many moons does Jupiter have?"}],
    model="claude-3-opus-20240229",
    stream=True,
)

for chunk in stream_chunk_generator:
    print(f"{chunk.validated_output}")

Azure OpenAI

기본 사용법

Azure는 키, 베이스 URL, 버전을 각각 환경변수로 설정해요. 모델은 azure/<your_deployment_name> 형태로 지정하죠.

from guardrails import Guard
import os

os.environ["AZURE_API_KEY"] = "" # "my-azure-api-key"
os.environ["AZURE_API_BASE"] = "" # "https://example-endpoint.openai.azure.com"
os.environ["AZURE_API_VERSION"] = "" # "2023-05-15"

guard = Guard()

result = guard(
    model="azure/<your_deployment_name>",
    messages=[{"role":"user", "content":"How many moons does Jupiter have?"}],
)

print(f"{result.validated_output}")

스트리밍

from guardrails import Guard
import os

os.environ["AZURE_API_KEY"] = "" # "my-azure-api-key"
os.environ["AZURE_API_BASE"] = "" # "https://example-endpoint.openai.azure.com"
os.environ["AZURE_API_VERSION"] = "" # "2023-05-15"

guard = Guard()

stream_chunk_generator = guard(
    messages=[{"role":"user", "content":"How many moons does Jupiter have?"}],
    model="azure/<your_deployment_name>", 
    stream=True
)

for chunk in stream_chunk_generator:
    print(f"{chunk.validated_output}")

Tools/함수 호출

Azure에서는 guard.add_json_function_calling_tool([])로 함수 호출 도구를 만들어요.

from pydantic import BaseModel, Field
from typing import List
from guardrails import Guard
import os

os.environ["AZURE_API_KEY"] = "" # "my-azure-api-key"
os.environ["AZURE_API_BASE"] = "" # "https://example-endpoint.openai.azure.com"
os.environ["AZURE_API_VERSION"] = "" # "2023-05-15"

class Fruit(BaseModel):
    name: str
    color: str

class Basket(BaseModel):
    fruits: List[Fruit]
    
guard = Guard.for_pydantic(Basket)

result = guard(
    messages=[{"role":"user", "content":"Generate a basket of 5 fruits"}],
    model="azure/<your_deployment_name>", 
    tools=guard.add_json_function_calling_tool([]),
    tool_choice="required",
)

print(f"{result.validated_output}")

Gemini

기본 사용법

from guardrails import Guard
import os

os.environ['GEMINI_API_KEY'] = ""
guard = Guard()

result = guard(
    messages=[{"role":"user", "content":"How many moons does Jupiter have?"}],
    model="gemini/gemini-pro"
)

print(f"{result.validated_output}")

스트리밍

from guardrails import Guard
import os

os.environ['GEMINI_API_KEY'] = ""
guard = Guard()

stream_chunk_generator = guard(
    messages=[{"role":"user", "content":"How many moons does Jupiter have?"}],
    model="gemini/gemini-pro",
    stream=True
)

for chunk in stream_chunk_generator:
    print(f"{chunk.validated_output}")

Databricks

기본 사용법

from guardrails import Guard
import os

os.environ["DATABRICKS_API_KEY"] = "" # your databricks key
os.environ["DATABRICKS_API_BASE"] = "" # e.g.: https://abc-123ab12a-1234.cloud.databricks.com

guard = Guard()

result = guard(
    messages=[{"role":"user", "content":"How many moons does Jupiter have?"}],
    model="databricks/databricks-dbrx-instruct",
)

print(f"{result.validated_output}")

스트리밍

from guardrails import Guard
import os

os.environ["DATABRICKS_API_KEY"] = "" # your databricks key
os.environ["DATABRICKS_API_BASE"] = "" # e.g.: https://abc-123ab12a-1234.cloud.databricks.com

guard = Guard()

stream_chunk_generator = guard(
    messages=[{"role":"user", "content":"How many moons does Jupiter have?"}],
    model="databricks/databricks-dbrx-instruct",
    stream=True,
)

for chunk in stream_chunk_generator:
    print(f"{chunk.validated_output}")

다른 LLM

LiteLLM 통합을 통해 100개 이상의 LLM이 지원돼요. 대표적으로 이런 것들이 있어요.

  • Anthropic
  • AWS Bedrock
  • Anyscale
  • Huggingface
  • Mistral
  • Predibase
  • Fireworks

원하는 LLM을 LiteLLM 문서에서 찾은 뒤, 그 안내대로 같은 환경변수를 설정하세요. 다만 litellm 객체 대신 Guard 객체를 호출하면 돼요. Guardrails가 인자를 litellm으로 전달하고, 가딩(guarding) 과정을 거친 뒤 검증된 결과를 돌려줘요.

커스텀 LLM 래퍼

Guardrails가 네이티브로 지원하지 않는 LLM이고 LiteLLM도 쓰고 싶지 않다면, 커스텀 LLM API 래퍼를 직접 만들 수 있어요. 프롬프트를 문자열로 받는 위치 인자 하나와, 그 외 인자를 키워드 인자로 받는 함수를 만들고, LLM API의 출력을 문자열로 반환하게 하면 돼요.

pip install guardrails-ai-profanity-free
from guardrails import Guard
from guardrails_ai.profanity_free import ProfanityFree

# Create a Guard class
guard = Guard().use(ProfanityFree())

# Function that takes the prompt as a string and returns the LLM output as string
def my_llm_api(
    *,
    **kwargs
) -> str:
    """Custom LLM API wrapper.

    At least one of messages should be provided.

    Args:
        **kwargs: Any additional arguments to be passed to the LLM API

    Returns:
        str: The output of the LLM API
    """
    messages = kwargs.pop("messages", [])
    updated_messages = some_message_processing(messages)
    # Call your LLM API here
    # What you pass to the llm will depend on what arguments it accepts.
    llm_output = some_llm(updated_messages, **kwargs)

    return llm_output

# Wrap your LLM API call
validated_response = guard(
    my_llm_api,
    messages=[{"role":"user","content":"Can you generate a list of 10 things that are not food?"}],
    **kwargs,
)

더 알아보기

  • 시작하기 (앱에 Guardrails 임베딩): 설치부터 첫 guard 구성까지의 흐름을 따라가요.
  • Guard 객체: 호출을 감싸고 검증을 조율하는 핵심 객체를 봐요.
  • 왜 Guardrails AI를 쓸까요: 프레임워크의 핵심 강점을 정리해 봐요.