구조화 출력 (Structured outputs)
구조화 출력 (Structured outputs)
모델 응답을 JSON 형태로 강제하고 싶다면 구조화 출력을 써요. JSON 스키마를 하나 정의해 주면, Gemini가 그 스키마에 맞는 예측 가능하고 타입이 보장된 결과만 내놓습니다. 비정형 텍스트에서 데이터를 뽑아내거나 분류하는 작업처럼 '정해진 모양'이 필요한 곳에 딱 맞아요.
언제 유용한가
- 데이터 추출: 텍스트에서 이름·날짜 같은 특정 정보를 뽑을 때
- 구조적 분류: 텍스트를 미리 정의된 카테고리로 나눌 때
- 에이전트 워크플로: 도구나 API용 구조화된 입력을 생성할 때
REST API에서는 JSON Schema를 직접 쓰고, Google GenAI SDK에서는 Python의 Pydantic, JavaScript의 Zod로 스키마를 정의할 수 있어요.
기본 예시: 레시피 추출
텍스트에서 재료와 조리 단계를 추출해 구조화된 레시피로 만드는 예시를 볼게요. Pydantic으로 Recipe 모델을 정의하고, 요청의 response_format에 그 스키마를 실어 보냅니다.
from google import genai
from pydantic import BaseModel, Field
from typing import List, Optional
class Ingredient(BaseModel):
name: str = Field(description="Name of the ingredient.")
quantity: str = Field(description="Quantity of the ingredient, including units.")
class Recipe(BaseModel):
recipe_name: str = Field(description="The name of the recipe.")
prep_time_minutes: Optional[int] = Field(description="Optional time in minutes to prepare the recipe.")
ingredients: List[Ingredient]
instructions: List[str]
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Please extract the recipe from the following text...",
response_format={
"type": "text",
"mime_type": "application/json",
"schema": Recipe.model_json_schema()
},
)
recipe = Recipe.model_validate_json(interaction.output_text)
print(recipe)
REST에서도 같은 방식이에요. response_format 안에 mime_type: "application/json"과 schema를 넣으면 모델이 그 스키마에 맞는 JSON을 반환합니다.
JSON 스키마 지원 범위
구조화 출력은 JSON Schema 사양의 일부를 지원해요. type으로는 string, number, integer, boolean, object, array를 쓸 수 있고, 속성이 null이 되게 하려면 {"type": ["string", "null"]}처럼 타입 배열에 "null"을 포함하면 됩니다.
타입별 특화 속성도 지원해요.
- object:
properties(속성별 스키마),required(필수 속성),additionalProperties(미등록 속성 허용 여부) - string:
enum(분류용 허용 문자열),format(date-time,date,time등 문법 지정) - number / integer:
enum,minimum,maximum - array:
items(원소 스키마),prefixItems(튜플형 구조),minItems,maxItems
title과 description은 모델을 안내하는 데 도움을 주는 설명 속성이에요.
구조화 출력 vs 함수 호출
| 기능 | 주 사용처 |
|---|---|
| 구조화 출력 | 최종 응답의 형식을 지정. 모델의 답이 특정 형식이길 바랄 때 |
| 함수 호출 | 대화 중 행동을 취함. 모델이 최종 답 전에 어떤 작업을 수행해 달라고 요청할 때 |
모범 사례와 한계
모범 사례를 몇 가지 짚어 보면, description 필드로 모델을 충분히 안내하고, integer·string·enum처럼 구체적인 타입을 쓰며, 프롬프트에서 원하는 출력을 명확히 말해 주는 게 좋아요. JSON은 문법적으로 올바르게 나와도 값 자체는 어긋날 수 있으니, 애플리케이션에서 반드시 검증하세요.
한계도 있어요. 모든 JSON Schema 기능이 지원되는 건 아니고, 아주 크거나 깊게 중첩된 스키마는 거부될 수 있습니다.