출력 타입(Output Types) 정의하기

출력 타입(Output Types) 정의하기

Outlines의 장점은 출력 구조를 간단하고 직관적으로 정의할 수 있다는 점이에요. 기본 파이썬 타입, 여러 선택지, JSON 스키마, 정규식, 문맥 자유 문법까지 지원해요. 모델을 호출할 때 prompt와 함께 output_type을 넘기면, 그 타입에 맞는 출력이 강제돼요.

기본 아이디어는 함수의 반환 타입 힌트를 넣을 자리에 output type을 넣는다고 생각하면 돼요. 예를 들어 int, Literal, Pydantic 클래스를 output type으로 쓰면 그에 맞는 텍스트가 나와요.

from typing import Dict, List, Literal, Union
from pydantic import BaseModel

class Character(BaseModel):
    name: str
    skills: Union[Dict, List[str]]

model("How many minutes are there in one hour", int)  # "60"
model("Pizza or burger", Literal["pizza", "burger"])  # "pizza"
model("Create a character", Character, max_new_tokens=100)

출처: https://dottxt-ai.github.io/outlines/latest/features/core/output_types/

반환은 항상 문자열

주의할 점이 하나 있어요. Outlines generator는 항상 문자열을 반환해요. 원하는 타입으로 쓰려면 직접 캐스팅해야 해요. 예를 들어 Pydantic 클래스라면 Character.model_validate_json(result)처럼 파싱합니다.

result = model("Create a character", Character, max_new_tokens=100)
casted_result = Character.model_validate_json(result)

기본 파이썬 타입

int, float, bool 같은 기본 타입과 typingDict, Union, Optional, List, Tuple 등을 조합해 복잡한 출력 형태를 만들 수 있어요.

from typing import Dict
output_type = float        # 예: "0.05"
output_type = bool         # 예: "True"
output_type = Dict[int, str]  # 예: "{1: 'hello', 2: 'there'}"

여러 선택지 (Multiple Choices)

Literal이나 Enum 타입으로 선택지 분류를 할 수 있어요. 목록이 동적으로 변하는 상황이라면 Outlines 전용 Choice 타입을 써요.

from enum import Enum
from typing import Literal

class PizzaOrBurger(Enum):
    pizza = "pizza"
    burger = "burger"

output_type = Literal["pizza", "burger"]
output_type = PizzaOrBurger

JSON 스키마

JSON 스키마를 만족하는 출력을 원한다면, Pydantic 클래스·데이터클래스·TypedDict·호출 가능한 함수(파라미터가 키, 타입 힌트가 값 타입)를 쓸 수 있어요. JSON 스키마 문자열이나 딕셔너리를 직접 줄 땐 모호하므로 outlines.types.JsonSchema로 감싸야 해요.

from outlines.types import JsonSchema

schema_string = '{"type": "object", "properties": {"answer": {"type": "number"}}}'
output_type = JsonSchema(schema_string)

JsonSchemawhitespace_pattern(기본 None)과 ensure_ascii(기본 True) 두 선택 파라미터를 받아요.

정규식 패턴

정규식 문자열로 제한하고 싶으면 outlines.types.Regex로 감싸요. outlines.types 모듈에는 문장·이메일·ISBN 같은 흔한 패턴 변수도 준비돼 있어요.

from outlines.types import Regex
regex = r"[0-9]{3}"
output_type = Regex(regex)

문맥 자유 문법 (CFG)

Lark 문법으로 문맥 자유 문법을 정의해 출력을 강제할 수도 있어요. 큰 문법 문자열은 outlines.types.CFG로 감싸야 해요.

from outlines.types import CFG
grammar_string = """start: expr
expr: "{" expr "}" | "[" expr "]" | """
output_type = CFG(grammar_string)

출력 타입 가용성

주의할 점은 모든 출력 타입이 모든 모델에서 지원되는 건 아니라는 거예요. 어떤 모델은 구조화 출력을 제한적으로만 지원하니, 쓰는 모델의 문서에서 지원 범위를 확인해야 해요.

더 알아보기