Structured Outputs in ADK: Pydantic Output Schemas and output_key
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.
Published on • November 25, 2026
AI Assistant

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
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_keypersists the result. The validated object is written into session state undersentiment, so later stages — or the next turn — can readstate["sentiment"]directly.
# 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: 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:
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:
- Narrow types over wide ones.
Literalenums beat freestr— the model can’t drift into"urgent"vs"high"mismatches, and downstream code can switch exhaustively. - Bound numbers explicitly.
ge/leon confidences and scores; unbounded floats are where validation errors breed. - Describe the content, not the type.
floatsays nothing; “0.0–1.0, one decimal” is a usable instruction. - Optional fields need a stated condition. Tell the model when to leave it null, or it will invent filler.
- Keep it shallow. Deeply nested schemas with many required fields increase the chance of a near-miss; flatten where you can.
- 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.0on a guess,evidencequoting text that isn’t there. Schemas guarantee shape, not truth; your evals guarantee quality. - Post-parse business validation still matters. A
categorythat’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), structured enforcement may be prompt-level rather than API-level — wrap parsing defensively and treat failures as retriable tool-style errors.
output_schemaingenerate_content_configraisesValueErroronLlmAgent— schema is structure, not a sampling knob. Set it via the agent’soutput_schemafield as shown above.
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
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, pair with bounded generation so a large schema has room to be filled, and slot into the pipeline and swarm patterns as typed stage contracts.