GrepBoard/매뉴얼
605 편 ·

Gemini 응답을 JSON 스키마로 고정하기

·시험 환경 Gemini API 공식 문서 기준 · 2026-10 · jsonschema 4.10.3 로 응답 검증·시험 범위 ↓·6 단계

Gemini API 에 mime_type 과 JSON 스키마를 함께 보내 응답을 정해진 JSON 으로 받는 방법입니다. 지원하는 스키마 키워드와 한계, 받은 값 검증까지 다룹니다.

프롬프트에 「JSON 으로 답해」라고 쓰는 대신, 요청에 스키마를 실어 응답 모양을 API 쪽에서 고정합니다. 프롬프트로 형식을 맞추는 방법은 Gemini 답 형식을 시스템 지시와 예시로 고정하기 를 먼저 보세요.

[1] 요청에 두 값을 넣습니다. MIME 타입 application/json 과 JSON 스키마입니다. 공식 문서의 Recipe Extractor 예제에서 필드를 줄인 것으로, 현재 문서는 Interactions API 의 response_format 을 씁니다(문서).

request.json
{  "model": "gemini-3.8-flash",  "input": "Please extract the recipe from the following text. ...",  "response_format": {    "type": "text",    "mime_type": "application/json",    "schema": {      "type": "object",      "properties": {        "recipe_name": { "type": "string", "description": "The name of the recipe." },        "ingredients": {          "type": "array",          "items": {            "type": "object",            "properties": { "name": { "type": "string" }, "quantity": { "type": "string" } },            "required": ["name", "quantity"]          }        }      },      "required": ["recipe_name", "ingredients"]    }  }}
console
# model 값은 문서 예제의 것입니다. 쓰는 모델로 바꿉니다.$ curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \    -H "x-goog-api-key: $GEMINI_API_KEY" \    -H 'Content-Type: application/json' \    -d @request.json

[2] 응답을 읽습니다. 문서의 예시 응답은 이렇게 생겼습니다(일부).

output
{  "recipe_name": "Delicious Chocolate Chip Cookies",  "ingredients": [    { "name": "all-purpose flour", "quantity": "2 and 1/4 cups" },    ...  ],  ...}

Python SDK 에서는 interaction.output_text 가 이 JSON 문자열입니다. 문서는 Pydantic 클래스에서 스키마를 만들고(Recipe.model_json_schema()) 이 문자열을 Recipe.model_validate_json() 으로 객체로 바꿉니다.

[3] 기존 generateContent 코드라면 필드 이름이 다릅니다. 마이그레이션 문서의 「Before」 예제는 generationConfig 안에 responseMimeType 과 responseSchema 를 넣습니다. 이 예제의 스키마는 type 을 OBJECT · STRING 처럼 대문자로 씁니다.

generate-content.json
"generationConfig": {  "responseMimeType": "application/json",  "responseSchema": {    "type": "OBJECT",    "properties": {      "recipe_name": { "type": "STRING" },      "ingredients": { "type": "ARRAY", "items": { "type": "STRING" } }    },    "required": ["recipe_name", "ingredients"]  }}

[4] 스키마에 쓸 수 있는 키워드를 확인합니다. JSON Schema 중 일부만 지원합니다.

대상지원 항목
typestring · number · integer · boolean · object · array · null
설명title · description
objectproperties · required · additionalProperties
stringenum · format(date-time · date · time)
number · integerenum · minimum · maximum
arrayitems · prefixItems · minItems · maxItems

후보가 정해진 값은 enum 으로 좁힙니다(문서의 모더레이션 예제는 spam_type 을 phishing · scam · unsolicited promotion · other 로 제한). null 을 허용하려면 {"type": ["string", "null"]} 처럼 타입 배열에 "null" 을 넣습니다. 2025-11 구글 블로그는 anyOf · $ref · prefixItems 지원 추가와 함께, 응답의 키 순서가 스키마의 키 순서를 따르게 됐다고 알립니다(글).

[5] 프롬프트에는 할 일을, 필드 설명은 description 에 씁니다. 문서의 모범 사례가 그렇게 안내합니다. 「Use the description field to guide the model」 「Clearly state what you want the model to do」. 스키마 내용을 프롬프트에 되풀이해 적으라는 안내는 이 문서에서 찾지 못했습니다.

[6] 받은 값은 그래도 검증합니다. 문서가 「출력은 문법상 올바른 JSON 이지만 값은 애플리케이션에서 검증하라」고 하기 때문입니다. check.py 는 jsonschema 의 Draft202012Validator 로 응답 파일을 스키마에 맞춰 봅니다. 시험용 schema.json 은 1단계 스키마와 다른 파일입니다. prep_time_minutes(정수 또는 null)와 instructions(문자열 배열)가 있고, recipe_name · ingredients · instructions 가 필수입니다.

schema.json
{  "type": "object",  "properties": {    "recipe_name": { "type": "string" },    "prep_time_minutes": { "type": ["integer", "null"] },    "ingredients": {      "type": "array",      "items": {        "type": "object",        "properties": { "name": { "type": "string" }, "quantity": { "type": "string" } },        "required": ["name", "quantity"]      }    },    "instructions": { "type": "array", "items": { "type": "string" } }  },  "required": ["recipe_name", "ingredients", "instructions"]}

스키마를 지킨 good.json 과, 타입을 어기고 instructions 를 뺀 bad.json 을 넣었습니다.

bad.json
{"recipe_name":"Cookies","ingredients":[{"name":"large eggs","quantity":2}],"prep_time_minutes":"10"}
console
$ python3 -I check.py schema.json good.json bad.jsongood.json OKbad.json FAIL   prep_time_minutes - '10' is not of type 'integer', 'null'   ingredients/0/quantity - 2 is not of type 'string'   (root) - 'instructions' is a required property

JSON · YAML 정리 · 변환 도구로 바로 확인 ↗ — 브라우저 안에서 계산합니다.

#gemini#json#structured-output