C.W.K.
Stream
Lesson 02 of 04 · published

Structured Output / JSON

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

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

모델이 valid JSON emit 강제

response_mime_type='application/json' 세팅하면 모델이 JSON 생산. response_schema 추가하면 JSON 이 그 schema 따름. Schema 는 Pydantic 모델, TypedDict, raw dict 가능.

자동으로 처리해 주는 두 가지 cleanup

  1. 출력 wrap 하는 markdown fence (```json ... ```) X.
  2. Trailing prose ("여기 JSON: ...") X.

response.text 에 깔끔한 parse 가능 문자열, (Pydantic 사용 시) response.parsed 에 deserialize 된 객체.

Function calling 과 같은 거 X

  • Structured output = 최종 response 포맷. 모델이 JSON 으로 너한테 답함.
  • Function calling = 모델이 conversation mid 에 코드 호출 원함. Function call 이 response, 최종 답변 X.

Structured output 사용처: 추출, 분류, form-filling. Function calling 사용처: 너 시스템에서 action 요구하는 거.

Code

Pydantic schema — 가장 쉬운 길·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)
Object 의 list·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 schema 작성: title (str), year (int), rating (int 1-10), positives (list[str]), negatives (list[str]), one_line_summary (str). Flash 에 다른 영화 제목 셋 보내고 구조화된 리뷰 요청. response.parsed 가 typed instance 주는지 확인. 그 다음 malformed schema (Gemini 가 만족 못 하는 거) 도입하고 어떻게 실패하는지 관찰.

Progress

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

댓글 0

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

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