Skip to content
Blog

Defining Input, Output, and State Schemas with Pydantic for Workflows

Use Pydantic BaseModel input_schema and output_schema on ADK agents and workflow nodes to enforce typed data contracts between steps, and learn when a schema beats session state.

Published on • December 2, 2026

AI Assistant

“Return JSON” is a request. A schema is a contract. When you ask an LLM to produce structured data with nothing but a sentence in the prompt, you are hoping the model complies — and hoping gets worse as outputs grow: a missing field, a string where a number belongs, a price rendered as "$1,299.00" instead of a float. Downstream code then spends its life re-parsing and re-validating text that should have been typed from the start.

ADK 2.0 workflows give you a better lever. Because nodes pass data to each other as real Python values — not as prompt text — you can attach Pydantic BaseModel classes to agents and validate the boundary where data crosses from one step to the next. In this tutorial you will learn how input_schema and output_schema constrain node data, how structured payloads travel between function nodes, how agents read schema fields inside their instructions, and when a schema is the right tool versus plain session state.

Prerequisites

  • ADK 2.0 (pip install google-adk), Python 3.10+
  • Basic familiarity with graph workflows: Workflow, edges, and Event (see the graph routes docs)
  • pydantic v2 installed (it ships with ADK)

1. Know the three channels first

Before schemas make sense, know where data can travel. According to the data handling docs, a node’s Event carries three distinct kinds of data:

  • output — data passed to the next node. This is the channel schemas govern.
  • message — a response intended for the user. The runtime renders it; the graph does not forward it.
  • state — data persisted across nodes and turns via session state.

Schemas constrain output (and the input a node accepts). Everything else — user messages, state — lives outside the contract. Keeping these three channels separate is half of writing clean workflows.

2. Schemas on agents: input_schema and output_schema

The simplest declaration is a pair of Pydantic models passed to an Agent. The output schema forces the model’s reply into a given shape; the input schema validates what the agent receives:

from datetime import date

from google.adk import Agent
from pydantic import BaseModel, Field


class FlightSearchInput(BaseModel):
    origin: str           # Airport code "SFO"
    destination: str      # Airport code "CDG"
    departure_date: date  # date(2026, 3, 15)
    passengers: int = Field(default=1, ge=1, le=9)


class Flight(BaseModel):
    carrier: str
    price: float


class FlightSearchOutput(BaseModel):
    flights: list[Flight]
    cheapest_price: float


flight_searcher = Agent(
    name="flight_searcher",
    model="gemini-flash-latest",
    instruction="Search for available flights.",
    input_schema=FlightSearchInput,
    output_schema=FlightSearchOutput,
    tools=[search_flights_api],
    mode="single_turn",
)

Two properties make this more than validation sugar:

  1. The output schema shapes the model’s answer. The agent is required to respond in that structure, so the next node receives a FlightSearchOutput-shaped payload instead of free text it has to guess its way through.
  2. Pydantic constraints travel with the type. Field(ge=1, le=9) is not documentation — it is enforced. A schema turns “between 1 and 9 passengers” from a prompt sentence into a validation error.

Agents used as graph nodes must run in single_turn mode (the default) or task mode, so the schema applies cleanly to a single node execution.

3. Structured data passing between nodes

Function nodes are not limited to strings. Any serializable value can ride the output channel, and a Pydantic model is the natural choice because it serializes cleanly and validates on both ends:

from google.adk import Event
from pydantic import BaseModel


class CityTime(BaseModel):
    time_info: str  # time information
    city: str       # city name


def lookup_time_function(node_input: str):
    """Simulate returning the current time in the specified city."""
    return Event(output=CityTime(time_info="10:10 AM", city=node_input))


city_report_agent = Agent(
    name="city_report_agent",
    model="gemini-flash-latest",
    input_schema=CityTime,
    instruction="""
        You receive a CityTime with time_info and city fields. Reply with a
        single sentence stating that it is that time in that city right now.
    """,
    mode="single_turn",
)

root_agent = Workflow(
    name="root_agent",
    edges=[
        ("START", city_generator_agent, lookup_time_function, city_report_agent)
    ],
)

The producer emits a typed object; the consumer’s input_schema validates it and delivers it as its input. No JSON parsing, no reading session state, no string slicing — the successor “receives it as a typed object, with no JSON parsing or state reads required.”

One output per execution

A detail that bites early: a node may emit only one Event.output payload per execution. You can yield several events to stream progress messages, but two yields that both carry output raise a runtime error. Progress belongs in Event(message=...); the single result belongs in output.

4. Referencing schema fields in instructions

Once an agent has a typed input, its instruction can talk about the fields by name. The docs define three placeholder forms — and the differences matter:

  • {Class.field} — reads a field from this node’s input. {CityTime.time_info} resolves against the incoming payload.
  • <Class.field from source_node> — reads a field from a named predecessor’s output. Use it when several upstream nodes share a field name.
  • {state_key} — reads session state, not the node input.

The Class. prefix is documentation only; resolution uses the field name after the dot. The classic trap: curly-brace placeholders in an instruction are substituted from session state, so {CityTime.time_info} written without the field-access form is left in the prompt verbatim. If you want a value templated from state, write it to state first (with output_key or Event(state=...)) and reference it as {time_info}.

5. Schemas versus state: choose by lifetime

Both schemas and session state move data through a workflow, but they answer different questions:

QuestionUse a schema on outputUse session state
Who reads it?The next node onlyAny later node, plus tools and callbacks
How long does it live?One edge traversalSession (or longer, with prefixes)
Is it typed?Validated against BaseModelLoose key-value store
Is it large?Fine — it flows along the edgeNo — keep it small

The rule of thumb from the docs: when only the next node needs a value, pass it along the edge as node output. Use state when a value must outlive the run, or when a tool, a callback, or {key} instruction templating needs to read it back. And when the data is genuinely large — file contents, binaries, query results — neither is appropriate: reach for artifacts or a database tool instead.

6. Schemas travel to dynamic workflows too

If you later move a step from a static graph into a dynamic workflow — an orchestrator calling ctx.run_node() — the contract does not change. The dynamic workflows docs confirm that you “can also pass specific data schemas using a defined class and configure input and output schemas, similar to graph-based workflow nodes”:

from google.adk import Context
from google.adk.workflow import node


@node
def city_time_function(node_input: str):
    """Simulate returning the current time in a specified city."""
    return CityTime(time_info="10:10 AM", city=node_input)


@node(rerun_on_resume=True)
async def city_workflow(ctx: Context):
    city_time = await ctx.run_node(city_time_function, "Paris")
    report_text = await ctx.run_node(city_report_agent, city_time)
    return report_text

Here ctx.run_node() returns the child’s result directly, so the typed value flows from node to node with no session-state reads in between — the same output-channel discipline you learned in section 3, now expressed as function calls instead of graph edges. Define the BaseModel once, attach it at both ends, and it guards the boundary whichever orchestration style the workflow uses.

7. Checklist

Before shipping a schema-bearing workflow:

  • Every cross-node payload has a BaseModel — not a loose dict you index into with .get().
  • Constraints that matter (ge, le, regex, required fields) live in the model, not only in the prompt.
  • Exactly one output is emitted per node execution; progress uses message.
  • Instructions use the correct placeholder form: {Class.field} for input, <Class.field from source> for a predecessor, {key} for state.
  • State is used only for values that outlive the edge; large payloads go to artifacts or a database.
  • Agents inside the graph run in single_turn mode.

Schemas do not replace good prompts — the model still has to do its job. What they replace is the fragile handoff: the moment where typed data degrades into a string, gets parsed by guesswork, and fails three nodes later with an error that names the wrong cause. Declare the contract once, and let Pydantic argue with the data instead of your production logs.

References