Skip to main content
In this lesson we cover how to use state in Google ADK to build smarter multi-turn conversational agents. Previously we built an agent that can answer questions and call tools; now we go one level deeper to show how agents maintain context across turns so they can perform structured troubleshooting and other multi-step tasks. State management makes agents intelligent: ADK gives agents a way to remember curated values, track progress through workflows, and keep essential details across turns. This enables structured troubleshooting flows rather than single-shot responses.

Session, state, history — how they fit

  • Session: the top-level container that tracks the conversation, user identity, and event history.
  • State: a curated key/value store used to remember values the agent needs to continue a flow (progress markers, flags, decisions, preferences).
  • History: the full transcript of messages and tool calls.
History is the complete log of the conversation (every message and tool call). State is selective — a small set of intentionally remembered values that help the agent move a workflow forward (for example, issue type or current troubleshooting step). Think of state as the agent’s working memory: small, curated, and purposeful. Here’s a simple example showing how you might use session.state to track a VPN troubleshooting flow:
# Example: conceptual use of session.state for an ongoing VPN troubleshooting conversation
session.state["issue_type"] = "vpn_connectivity"
session.state["progress"] = {"current_step": "verify_credentials", "attempts": 1}
session.state["user_email"] = "alice@example.com"
An infographic titled "What Should Live in State?" showing four colored boxes: Task Progress, Flags & Decisions, User Preferences, and Temporary Scratch Data, each with a short explanation of what to store. A footer notes that state stores only what matters for decision-making and continuity across turns.

What belongs in state

Store only the small set of values that help the agent make decisions and continue a flow — not a verbatim copy of the transcript.
CategoryPurposeExamples
Task progressWhere you are in a multi-step processonboarding:step_2, asking_email
Flags & decisionsBranching or escalation markersrequires_escalation: True
User preferencesSettings that affect behaviorlocale: "en-US", theme: "dark"
Temporary scratch dataShort-lived parsed values used within a stepvalidation results, extracted entity IDs
Use state for decision-making and continuity; keep it minimal and purposeful.

State key prefixes: scoping your data

ADK supports key prefixes to control the lifecycle and scope of state values. Prefixes make it easy to reason about how long values should live and who they apply to.
A presentation slide titled "State Key Prefixes: Scoping Your Data" showing four colored panels (user:, app:, No prefix, temp:) with bullet points explaining each prefix’s data scope and lifecycle. It summarizes how prefix-based state keys control data across calls, sessions, users, and the app.
PrefixScopeTypical lifecycle / use
user:Per-user, persisted across sessionsLong-lived user preferences and user profile metadata
app:App-wide, shared across usersGlobal configuration or app-wide flags
(no prefix)Session-scopedValues that live for the current session only
temp:Invocation-scopedEphemeral scratch data used only for a single model call
Prefixing keys keeps state predictable: use temp: for per-invocation scratch, session keys for conversation continuity, user: for persistent preferences, and app: for global settings.
Keep state minimal and purposeful. Start with the smallest set of values that let the agent complete the flow, then expand only when necessary.

State strategy for our help desk assistant

For a help desk assistant, keep state intentionally small. Track only what you need to run the troubleshooting flow: the current issue type, troubleshooting progress, and any contextual user information that influences decisions. Avoid over-engineering state early; you can expand the schema as needs arise.
A presentation slide titled "State Strategy for Our Helpdesk Assistant" that outlines what to track: current issue, troubleshooting progress, and user context. It emphasizes minimal/purposeful storage and future user preferences.

Injecting state into agent instructions (dynamic prompts)

A powerful ADK feature is automatic injection of state values into agent instruction templates. Write instruction templates with placeholders (for example, {topic} or {issue_type}), set session.state values, and ADK will replace those placeholders before sending the prompt to the LLM. This keeps templates simple and behavior context-aware without manual prompt assembly.
A three-step diagram titled "Dynamic Instructions: Injecting State Into LLM Prompts." It shows 01 Define Template (create instructions with key placeholders), 02 Set State (update session.state with actual values), and 03 Automatic Injection (ADK replaces placeholders before sending to the LLM).
Example: defining an LLM agent with a placeholder
from google.adk.agents import LlmAgent

story_generator = LlmAgent(
    name="StoryGenerator",
    model="gemini-2.0-flash",
    instruction="Write a short story about a cat, focusing on the theme: {topic}."
)
If you set session.state["topic"] = "friendship", ADK will automatically replace {topic} with "friendship" before calling the model.

Automatic state updates: output_key and state deltas

ADK provides two primary ways to update state from agent runs:
  • output_key — a simple option where the agent’s final response is saved into session.state under the provided key.
  • state delta / events — an advanced mechanism that emits precise state-change events for fine-grained control over updates (recommended for production workflows that require deterministic state changes).
MethodWhen to useBehavior
output_keyQuick and simple persistenceSaves the agent’s final text to session.state["key"] automatically
State deltas / eventsProduction control and validationEmit explicit state-change events describing exactly what to write/remove
Example: using output_key to capture the last greeting
from google.adk.agents import LlmAgent

greeting_agent = LlmAgent(
    name="Greeter",
    model="gemini-2.0-flash",
    instruction="Generate a short, friendly greeting.",
    output_key="last_greeting"  # ADK will save the agent's response into session.state["last_greeting"]
)
When this agent runs, ADK automatically stores the final greeting into session.state["last_greeting"]. For production systems where you need exact control over what changes and when, use state-delta events instead.

Putting it together: a multi-step troubleshooting flow

A typical smart IT help desk assistant models a structured flow:
  1. Problem clarification — ask focused questions to identify the exact issue.
  2. Information gathering — collect required details (email, system ID).
  3. Tool execution — call tools to look up user data or check service status.
  4. Solution and next steps — present resolution or escalate.
Use session.state to track progress across these steps so the agent can pick up where it left off and follow deterministic workflows.
A slide titled "Applying State to Our Helpdesk Assistant" showing a state-management flow with three steps: Problem Clarification, Information Gathering, and Tool Execution. Each step is connected to a central timeline with numbered nodes and brief descriptions of the agent actions (ask focused questions, collect user/system details, invoke tools).

What’s next

Next, we’ll design a complete troubleshooting flow and address key design choices:
  • How many clarifying questions to ask and when to stop
  • When and how to invoke tools
  • How to author instructions for predictable LLM behavior
  • Guardrails and validation to ensure reliable enterprise workflows
You’ll learn how to balance conversational flexibility with structured reliability so the agent maps natural language into structured data requests and returns structured results.
A presentation slide titled "Next: Designing the Troubleshooting Flow" that lists five upcoming agenda items about building an end-to-end troubleshooting flow (clarifying questions, invoking tools, structuring LLM instructions, and applying guardrails). The slide has a dark teal background with numbered circular icons down the left and brief descriptions to the right.
Avoid storing sensitive personal data in long-lived state fields. Favor session- or temp-scoped keys for transient data and ensure you comply with your organization’s privacy and retention policies.
Use these resources to deepen your understanding of stateful agents and to guide production-ready designs.