Structured Outputs (Pydantic / JSON)
Enforcing a JSON Schema / Pydantic type at token-decoding time so responses always parse cleanly.
What It Is
Structured outputs constrain the LLM's token sampler using a JSON Schema or Pydantic model so the generated text is guaranteed to conform to exact field names, enums, and types. Instead of writing fragile `JSON.parse()` fallbacks or regex hacks around markdown code fences, every response arrives as type-safe application data.
Protobuf / Zod schema validation built directly into the model's output stream.
How It Works (Step-by-Step)
- 01Define your target data structure with Pydantic (`BaseModel`) or TypeScript/Zod (`z.object(...)`).
- 02Pass the schema in the API config (`response_schema` + `application/json`).
- 03The inference engine masks invalid tokens during decoding so syntax errors and missing required keys cannot happen.
- 04Parse and validate directly into your typed app object.
Real-World Scenario
Extracting `{ vendor, invoice_date, total_usd, line_items[] }` from uploaded PDF receipts straight into your billing database without a single markdown-backtick parsing crash.
When to Use vs. When NOT to Use
Use at every AI-to-code boundary: database inserts, UI cards, routing labels, and extraction jobs.
Do not force rigid schemas on long-form creative writing or open-ended conversational explanations.
Common Beginner Mistakes
- Relying only on 'Please reply in valid JSON' in the prompt text instead of schema-constrained decoding.
- Over-constraining freeform user-facing chat answers into rigid JSON when streaming prose is better UX.
Code Example
from typing import Literal
from pydantic import BaseModel
from google import genai
class BugTriage(BaseModel):
component: str
severity: Literal["sev1", "sev2", "sev3"]
needs_escalation: bool
summary: str
client = genai.Client()
res = client.models.generate_content(
model="gemini-2.5-flash",
contents="Checkout returning 502s for 40% of EU traffic since 14:05 UTC.",
config={
"response_mime_type": "application/json",
"response_schema": BugTriage,
"temperature": 0.0,
},
)
triage = BugTriage.model_validate_json(res.text)
print(triage.severity, triage.needs_escalation)