Structured Outputs 실습 — cookbook으로 스키마 검증 익히기

Structured Outputs 실습

공식 cookbook의 structured_outputs_intro는 Structured Outputs를 처음 접할 때 좋은 실습 자료예요. 1) 모델 호출, 2) JSON Schema 제공, 3) 응답 검증 순서로 손에 익힐 수 있어요.

핵심 흐름

  1. 원하는 출력의 JSON Schema를 정의해요.
  2. API 호출 시 response_format에 스키마(strict)를 넘겨요.
  3. 반환된 응답을 JSON으로 파싱해 애플리케이션에서 그대로 사용해요.
from openai import OpenAI

client = OpenAI()
response = client.chat.completions.create(
    model="gpt-4o",
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "event",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "date": {"type": "string"},
                },
                "required": ["name", "date"],
                "additionalProperties": False,
            },
        },
    },
    messages=[{"role": "user", "content": "Extract event info."}],
)

왜 스키마가 중요한가

애플리케이션이 출력을 신뢰할 수 있게 되면, 그다음 단계(DB 저장·UI 렌더링·다른 모델 입력)를 훨씬 안전하게 자동화할 수 있어요. 바로 이 지점이 Structured Outputs의 핵심 가치예요.

더 알아보기