본문 바로가기
C.W.K.
Stream
Lesson 02 of 04 · published

구조화 출력 / JSON

~14 min · json, schema, pydantic, structured-output

Level 0불씨
0 XP0/35 lessons0/10 achievements
0/140 XP to next level140 XP to go0% complete

모델이 올바른 JSON만 내놓게 강제하기

response_mime_type='application/json'을 설정하면 모델이 JSON을 만들어. response_schema까지 넣으면 그 스키마를 따르게 돼. 스키마에는 Pydantic 모델, TypedDict, 일반 dict를 쓸 수 있어.

자동으로 정리되는 두 가지

  1. 출력을 감싸는 마크다운 코드 펜스(```json ... ```)가 붙지 않아.
  2. "여기 JSON이야: ..." 같은 앞뒤 설명이 붙지 않아.

response.text에는 바로 파싱할 수 있는 깨끗한 문자열이 들어가고, Pydantic을 썼다면 response.parsed에는 역직렬화된 객체가 들어가.

함수 호출과는 다른 기능이야

  • 구조화 출력최종 응답 형식을 정해. 모델이 JSON으로 답하는 거야.
  • 함수 호출은 대화 도중 모델이 애플리케이션 코드를 실행해 달라고 요청하는 거야. 함수 호출 자체가 응답이지만 최종 답변은 아니야.

구조화 출력은 추출, 분류, 양식 채우기에 써. 함수 호출은 시스템에서 실제 행동이 필요할 때 써.

Code

Pydantic 스키마 — 가장 쉬운 방법·python
from pydantic import BaseModel
from google import genai
from google.genai import types

client = genai.Client()

class Recipe(BaseModel):
    recipe_name: str
    ingredients: list[str]
    instructions: list[str]
    prep_minutes: int

response = client.models.generate_content(
    model='gemini-2.5-flash',
    contents='Give me a 30-minute chocolate chip cookie recipe.',
    config=types.GenerateContentConfig(
        response_mime_type='application/json',
        response_schema=Recipe,
    ),
)

# Parsed instance
recipe: Recipe = response.parsed
print(recipe.recipe_name, recipe.prep_minutes)
print(recipe.ingredients)
객체 목록·python
class Recipe(BaseModel):
    recipe_name: str
    ingredients: list[str]

response = client.models.generate_content(
    model='gemini-2.5-flash',
    contents='Give me 3 cookie recipes.',
    config=types.GenerateContentConfig(
        response_mime_type='application/json',
        response_schema=list[Recipe],  # list of
    ),
)
recipes: list[Recipe] = response.parsed
TypeScript — 같은 개념·typescript
import { GoogleGenAI, Type } from '@google/genai';

const ai = new GoogleGenAI({});

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Give me 3 cookie recipes.',
  config: {
    responseMimeType: 'application/json',
    responseSchema: {
      type: Type.ARRAY,
      items: {
        type: Type.OBJECT,
        properties: {
          recipeName:  { type: Type.STRING },
          ingredients: { type: Type.ARRAY, items: { type: Type.STRING } },
          prepMinutes: { type: Type.INTEGER },
        },
        required: ['recipeName', 'ingredients'],
      },
    },
  },
});

const recipes = JSON.parse(response.text);

External links

Exercise

영화 리뷰용 Pydantic 스키마를 작성해. title(str), year(int), rating(1–10의 int), positives(list[str]), negatives(list[str]), one_line_summary(str)을 넣어. Flash에 서로 다른 영화 제목 세 개를 보내 구조화된 리뷰를 요청하고, response.parsed가 형식이 정해진 인스턴스를 주는지 확인해. 그다음 Gemini가 만족할 수 없는 잘못된 스키마를 넣어 어떤 식으로 실패하는지 관찰해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.