Gemini API structured output으로 JSON 스키마 강제하기
Gemini API의 response_format에 JSON Schema를 넘기면 모델 응답을 타입 안전한 JSON으로 고정할 수 있어요. Python은 Pydantic, JavaScript는 Zod로 스키마를 정의하면 파싱까지 한 번에 처리돼요.
Gemini API structured output으로 JSON 스키마 강제하기
회사 워크플로에 LLM을 연동할 때 가장 흔한 문제는 응답 형식이 매번 달라진다는 점이다. Gemini API의 structured output 기능은 response_format 파라미터에 JSON Schema를 지정해 모델이 반드시 그 구조로 응답하도록 강제한다.
동작 원리
response_format 객체에 type: "text", mime_type: "application/json", schema 세 필드를 함께 넘기면 된다. 모델은 스키마를 벗어난 응답을 생성하지 않는다. Python SDK는 Pydantic 모델을, JavaScript SDK는 Zod 스키마를 직접 받아 JSON Schema로 변환해준다.
Python 예시 (Pydantic)
아래는 예시 코드다.
import os
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
prep_time_minutes: Optional[int] = None
ingredients: List[Ingredient]
instructions: List[str]
client = genai.Client() # GEMINI_API_KEY 환경변수 사용
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="레시피 텍스트를 추출해줘: ...",
response_format={
"type": "text",
"mime_type": "application/json",
"schema": Recipe.model_json_schema()
},
)
recipe = Recipe.model_validate_json(interaction.output_text)
print(recipe)
GEMINI_API_KEY는 환경변수로 주입한다. 코드에 직접 넣지 않는다.
지원 타입과 제약
Gemini structured output이 지원하는 JSON Schema 타입은 string, number, integer, boolean, object, array, null이다. null을 허용하려면 {"type": ["string", "null"]} 형태로 배열로 지정한다.
분류 작업에는 enum을 쓴다. 예를 들어 스팸 유형을 ["phishing", "scam", "unsolicited promotion", "other"]로 고정하면 모델이 그 외 값을 반환하지 않는다. 조건부 구조가 필요하면 anyOf로 두 스키마 중 하나를 선택하게 할 수 있다.
재귀 구조도 지원한다. 조직도처럼 같은 타입이 중첩되는 경우 "$ref": "#"으로 자기 참조 스키마를 정의한다.
스트리밍
stream: true를 추가하면 응답을 청크 단위로 받을 수 있다. 각 청크는 유효한 부분 JSON 문자열이며, 이어 붙이면 최종 JSON 객체가 된다. 긴 응답을 처리할 때 첫 토큰 지연을 줄이는 데 유용하다.
도구와 함께 쓰기
Gemini 3 시리즈 모델에서는 structured output을 Google Search, URL Context, Code Execution 같은 내장 도구와 함께 쓸 수 있다. tools 배열과 response_format을 동시에 지정하면 도구 호출 결과를 지정한 스키마로 정리해 돌려준다. 공식 문서 기준 이 기능은 Gemini 3 시리즈 한정 프리뷰다.
주의할 점
JSON Schema 전체 명세를 지원하지는 않는다. 스키마가 지나치게 크거나 깊이 중첩되면 요청이 거부될 수 있다. 모델이 스키마를 구문상 준수하더라도 값의 의미가 맞는지는 애플리케이션에서 별도로 검증해야 한다. description 필드를 충분히 작성해두면 모델이 의도에 맞는 값을 채울 가능성이 높아진다.