---
title: "Structured Outputs in ADK: Pydantic Output Schemas and output_key"
date: "2026-11-25T08:28:00+07:00"
description: "How to get typed, validated JSON out of an ADK agent — Pydantic output_schema, output_key, parsing behavior, error handling, and when to use structured output vs plain text."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-pydantic-response-schema-structured-outputs.jpg"
alt: "Pydantic model flowing through an agent into validated structured JSON"
tags: ['google-adk', 'pydantic', 'structured-outputs', 'output-schema', 'python']
---

Free-form text is a terrible interface between agents. The moment one agent's answer becomes another component's input — a classifier feeding a router, a researcher feeding a synthesizer, an agent feeding your application code — you want a typed object, not a paragraph you parse with hope. ADK's structured output support closes that gap: declare a Pydantic model, attach it as `output_schema`, and the agent's response comes back validated against it.

Two fields do the work: **`output_schema`** (what shape the response must have) and **`output_key`** (where to store it in session state). Understanding both — plus where they don't apply — is the subject of this post.

## The basic setup

```python
from pydantic import BaseModel, Field
from google.adk.agents import Agent

class SentimentResult(BaseModel):
    label: str = Field(description="positive, neutral, or negative")
    confidence: float = Field(ge=0.0, le=1.0)
    evidence: list[str] = Field(description="short quotes supporting the label")

sentiment_agent = Agent(
    model="gemini-flash-latest",
    name="sentiment_agent",
    instruction="Analyze the customer message's sentiment. Respond with the required structure.",
    output_schema=SentimentResult,
    output_key="sentiment",
)
```

What this buys you:

- **The model's response is constrained to the schema.** Structured output mode makes the API produce JSON conforming to the declared shape — much more reliable than "please return JSON" in prose.
- **Parsing happens once, centrally.** No ad-hoc `json.loads(try: ...)` scattered across callers.
- **`output_key` persists the result.** The validated object is written into session state under `sentiment`, so later stages — or the next turn — can read `state["sentiment"]` directly.

```python
# later, in another agent's tool or callback
sentiment = tool_context.state.get("sentiment")
if sentiment and sentiment["confidence"] < 0.5:
    ...  # route to human review
```

That state handoff is the backbone of [pipeline topologies](/blog/adk-design-patterns-single-pipeline-swarm): each stage's typed output becomes the next stage's typed input.

## Designing schemas that the model fills well

Schema quality is prompt quality. Field descriptions are read by the model, so write them as instructions:

```python
class TicketTriage(BaseModel):
    category: Literal["billing", "technical", "account", "other"]
    urgency: Literal["low", "medium", "high", "critical"]
    summary: str = Field(description="One sentence, max 25 words, no preamble")
    needs_human: bool = Field(description="true only if policy requires a person")
    suggested_reply_draft: str | None = Field(
        default=None, description="null when needs_human is false"
    )
```

Principles:

1. **Narrow types over wide ones.** `Literal` enums beat free `str` — the model can't drift into `"urgent"` vs `"high"` mismatches, and downstream code can switch exhaustively.
2. **Bound numbers explicitly.** `ge`/`le` on confidences and scores; unbounded floats are where validation errors breed.
3. **Describe the *content*, not the type.** `float` says nothing; "0.0–1.0, one decimal" is a usable instruction.
4. **Optional fields need a stated condition.** Tell the model *when* to leave it null, or it will invent filler.
5. **Keep it shallow.** Deeply nested schemas with many required fields increase the chance of a near-miss; flatten where you can.
6. **No contradictory constraints.** A required field that's "only sometimes relevant" guarantees either validation failures or fabricated data.

## Where the result lands: schema vs. key vs. state

Three distinct mechanisms, easy to conflate:

| Mechanism | Role |
|---|---|
| `output_schema` | Constrains the *shape of the model's response* |
| `output_key` | Copies the parsed result into *session state* after the turn |
| `state` (via `ctx.state`) | The shared, persistent scratchpad other components read |

`output_schema` without `output_key` still gives you structured events — you'd read the typed value from the emitted event's content. Add `output_key` when the value's purpose is to be *consumed downstream*. Use `state` directly for anything the tool or callback computes itself.

## Validation failures and edge cases

Structured output dramatically reduces parse errors, but doesn't eliminate bad values:

- **The model may satisfy the letter of the schema with nonsense** — `confidence: 1.0` on a guess, `evidence` quoting text that isn't there. Schemas guarantee shape, not truth; your evals guarantee quality.
- **Post-parse business validation still matters.** A `category` that's valid per schema but outside your routing table should be caught by your code.
- **For open models or connectors with weaker support** ([LiteLLM, Ollama](/blog/adk-litellm-third-party-models-claude-openai-mistral)), structured enforcement may be prompt-level rather than API-level — wrap parsing defensively and treat failures as [retriable tool-style errors](/blog/adk-agent-exceptions-graceful-fallback).
- **`output_schema` in `generate_content_config` raises `ValueError`** on `LlmAgent` — schema is structure, not a sampling knob. Set it via the agent's `output_schema` field as shown above.

```python
def validate_triage(raw: dict) -> TicketTriage:
    triage = TicketTriage.model_validate(raw)
    if triage.category == "other" and triage.urgency == "critical":
        # business rule the schema can't express
        logger.warning("critical ticket categorized as other")
    return triage
```

## Structured output vs. plain text

Not everything should be a schema. Choose deliberately:

**Use `output_schema` when:**
- another component consumes the answer programmatically,
- it's a stage handoff in a pipeline or swarm,
- you need stable fields for analytics or evaluation,
- the model must pick from a controlled vocabulary.

**Prefer plain text when:**
- the audience is a human (schemas make prose stilted),
- the task is open-ended writing,
- you'd invent dozens of thin fields to model something a paragraph says better.

A common hybrid: structured for the *decision* (`action`, `confidence`), plain text for the *content* (`reply_text` field inside the schema) — both worlds in one object.

## Testing structured agents

```python
def test_triage_agent_parses():
    result = parse_agent_output(SentimentResult, {
        "label": "negative", "confidence": 0.8, "evidence": ["waited 3 days"]
    })
    assert result.label == "negative"

def test_triage_schema_rejects_bad_confidence():
    with pytest.raises(ValidationError):
        SentimentResult(label="negative", confidence=1.7, evidence=[])
```

Schema tests are pure unit tests — no model, no network — and they catch the regression where someone widens a field and silently breaks a downstream consumer.

## Where to go next

Structured outputs are the handoff layer for everything else: typed decisions feed [dynamic routing](/blog/adk-dynamic-model-routing-task-complexity), pair with [bounded generation](/blog/adk-max-output-tokens-truncation-strategies) so a large schema has room to be filled, and slot into the [pipeline and swarm patterns](/blog/adk-design-patterns-single-pipeline-swarm) as typed stage contracts.

## References

- [Simple agents with `LlmAgent`](https://adk.dev/agents/llm-agents/)
- [Multi-agent workflow patterns](https://adk.dev/workflows/patterns/)
- [google/adk-python](https://github.com/google/adk-python)
- [googleapis/python-genai](https://github.com/googleapis/python-genai)
