Why this matters: Build and inspect a minimal Python ADK 2.8.0 agent turn rather than treating execution as a single model call. You will explicitly create sessions, invoke `Runner.run_async`, classify intermediate versus final events, inspect persisted state, and document state ownership boundaries.

Diagram of a user request entering an application boundary, passing through an ADK runner and workflow to an LLM agent, with events written to a session service and deterministic controls surrounding external actions.

What you will be able to do

  • Invoke an ADK Python 2.8.0 runner with explicit application, user, and session identifiers.
  • Capture and interpret intermediate and final events instead of reducing a turn to one text value.
  • Demonstrate session-, user-, app-, and invocation-scoped state behavior.
  • Explain the persistence and concurrency trade-offs of an in-memory versus persistent session service, and define data that remains authoritative outside ADK.

1. Establish the bounded build

Decision first: prevent a support-session bug

Failure mode: “The agent remembered that the customer was eligible, so issue the credit.” That statement combines three different things: conversational context, ADK-managed state, and the subscription system’s source of truth. Only the last should determine eligibility or record a credit. This practicum deliberately has no tools and no side effects; the agent may explain a policy, but deterministic application code must validate identity, plan, entitlement, policy version, and prior credit records before a future mutation is even proposed.

Version pin (fact): use Python with google-adk==2.8.0. The currently published 2.8.0 package requires Python 3.10+ and ADK 2.x includes breaking changes from 1.x in agent APIs, the event model, and session schema. Pinning prevents a lesson written for a different runtime surface from silently becoming your implementation contract. ([pypi.org](https://pypi.org/project/google-adk/))

python -m venv .venv
source .venv/bin/activate
pip install "google-adk==2.8.0"
python -m pip show google-adk

Design choice: use an LLM agent only for bounded explanation and clarification. Keep routing rules such as “is the request read-only?” and all entitlement/credit decisions as explicit application or workflow logic. A later production mutation path needs authenticated principal propagation, least-privilege credentials, server-side validation, idempotency keys, retry classification, durable audit logging, and—where policy requires it—human approval.

2. Draw the runner-to-session boundary

Map the execution contract before writing prompts

In ADK Python, the Runner is the public execution interface. For a turn, it obtains (or, if configured, creates) a session identified by its runner app_name plus the supplied user_id and session_id; it then drives agent/workflow execution and yields events. The synchronous run exists for local convenience, while the source explicitly recommends run_async for production usage. ([github.com](https://github.com/google/adk-python/blob/main/src/google/adk/runners.py))

Terminology for this module: an application is your deployable agent system and namespace, identified here by app_name. Its root can be a single Agent or a graph-based Workflow; ADK 2.x presents those as distinct building blocks. A workflow is appropriate when routing, ordering, retries, ownership, and termination must be deterministic—not merely suggested in a prompt. ([pypi.org](https://pypi.org/project/google-adk/)) An event is the observable unit emitted during a turn. Its content may be partial streamed output, a final response, a tool/action-related result in more advanced builds, or an event whose importance is its actions rather than user-visible text.

Do not generalize this Python surface to every SDK. ADK documents language-specific differences in state primitives; Python and TypeScript unify callback/tool context around Context, while Java, Go, and Kotlin have their own APIs. This lesson uses Python 2.8.0 only. ([github.com](https://github.com/google/adk-docs/blob/main/docs/sessions/state.md))

3. Run, trace, and classify events

Implement: two conversations, explicit identifiers, observable events

Create runner_trace.py. Substitute a valid model identifier and configure credentials according to your chosen model provider before running it. The code intentionally prints metadata rather than assuming the last event is the only meaningful output.

import asyncio
from google.adk import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types

APP = "support-readonly-v1"
USER = "user-42"

agent = Agent(
    name="support_explainer",
    model="gemini-2.5-flash",
    instruction=(
        "You explain subscription policy. You are read-only: never claim that "
        "a credit was issued, an entitlement changed, or an account was verified."
    ),
)
sessions = InMemorySessionService()
runner = Runner(app_name=APP, agent=agent, session_service=sessions)

def message(text: str) -> types.Content:
    return types.Content(role="user", parts=[types.Part(text=text)])

async def run_turn(session_id: str, text: str, state_delta=None):
    print(f"n--- user={USER} session={session_id} ---")
    async for event in runner.run_async(
        user_id=USER,
        session_id=session_id,
        new_message=message(text),
        state_delta=state_delta,
    ):
        parts = event.content.parts if event.content else []
        rendered = "".join(part.text or "" for part in parts)
        delta = getattr(event.actions, "state_delta", None) if event.actions else None
        print({
            "author": event.author,
            "invocation_id": event.invocation_id,
            "partial": event.partial,
            "final": event.is_final_response(),
            "text": rendered,
            "state_delta": delta,
        })

async def main():
    await run_turn(
        "case-1001", "What information would determine credit eligibility?",
        state_delta={
            "case_stage": "triage",             # session scope
            "user:preferred_style": "concise",  # user scope
            "app:policy_version": "2026-09",    # app scope
            "temp:trace_label": "first-turn",   # invocation scope
        },
    )
    await run_turn("case-1001", "Summarize the safe next step.")
    await run_turn("case-1002", "What is my preferred response style?")

    for sid in ("case-1001", "case-1002"):
        session = await sessions.get_session(
            app_name=APP, user_id=USER, session_id=sid
        )
        print(f"nPersisted view for {sid}: {session.state}")
        print(f"Stored event count: {len(session.events)}")

asyncio.run(main())

Run and inspect: python runner_trace.py. The exact natural-language output and count of intermediate events can vary by model and configuration. Your evidence is instead: the first run records an input event/action carrying the supplied delta; the same session retains case_stage; the second session for the same user can see user:preferred_style; and both sessions under the same app namespace can see app:policy_version. The runner’s current interface accepts state_delta on both async and synchronous turn entrypoints, and it obtains sessions using all three identifiers. ([github.com](https://github.com/google/adk-python/blob/main/src/google/adk/runners.py))

4. Prove scope, then name authoritative data

State scope is a design decision, not free memory

ADK combines state behind one state collection, but prefixes express scope. Unprefixed keys belong to one session; user: keys span sessions for the same user within an app; app: keys span all users and sessions in that app; temp: keys last only for the current invocation. Persistent behavior for the first three scopes comes from a persistent session service—not from an in-memory demo. ([github.com](https://github.com/google/adk-docs/blob/main/docs/sessions/state.md))

State changes must travel with an appended event. The runner processes the event and its action delta, then the session service applies it. For code inside a callback or tool, update the supplied context’s state rather than mutating a Session object fetched independently from the service. Direct mutation bypasses event history and may not be persisted. Critically, a change is only guaranteed committed after the carrying event is yielded and processed; do not make a critical business decision based only on an uncommitted in-invocation mutation. ([github.com](https://github.com/google/adk-docs/blob/main/docs/runtime/event-loop.md))

Replace the service thoughtfully: InMemorySessionService is ideal for this local lab but loses state when the process restarts. ADK documentation identifies DatabaseSessionService and VertexAiSessionService as persistent alternatives, and notes that database sessions serialize concurrent updates to the same session with a per-session lock, unlike the in-memory service. That changes durability and concurrency behavior; it does not make chat history a ledger or automatically make cross-system writes atomic. Also note a Python-specific caveat: get_user_state is unavailable for VertexAiSessionService; its documented behavior is to raise NotImplementedError. ([github.com](https://github.com/google/adk-docs/blob/main/docs/sessions/state.md))

5. Evaluate the smallest useful agent

Test and debug the boundary

Write four representative checks. Case A—same session: after two turns in case-1001, case_stage remains present. Case B—same user, new session: case-1002 can access the user preference but must not inherit case_stage. Case C—different user: create user-99; it must not receive user-42’s preference. Case D—restart simulation: construct a fresh InMemorySessionService; prior state is gone. Success means each observation matches its intended ownership—not a particular model sentence.

Debug checklist: if context seems missing, first print the exact app, user, and session IDs at the request boundary; mismatched identifiers form a different namespace. Next fetch the session after fully consuming the event generator. Stopping iteration early can cancel outstanding execution, and a state change not attached to a yielded/processed event is not a reliable commit. Finally, inspect event action deltas, not just final text. The runner is responsible for forwarding events and coordinating session-service commitment of state and artifact actions. ([github.com](https://github.com/google/adk-docs/blob/main/docs/runtime/event-loop.md))

Authoritative outside ADK: customer identity and authentication session; subscription and entitlement facts; policy version and effective dates; credit/refund decision and idempotency key; payment/provider transaction; approval decision and operator identity; retention/deletion obligations; security audit trail. Store stable references in ADK state only when useful—for example, case_id or a policy snapshot ID—and fetch/validate the record from the owning service at action time.

Practicum: Trace a Read-Only Support Turn Across Sessions

Scenario: You are building the first internal support agent for a subscription product. A developer has used one `InMemorySessionService`, a hard-coded session ID, and the chat history to infer whether a customer is eligible for a credit. It appears to work locally, then loses context after a restart and risks applying a credit twice after a retry. Your constrained task is to implement a traceable, read-only support turn: run two conversations for one user under distinct session IDs, inspect every emitted event, prove state scope behavior, and identify what must remain authoritative in the subscription service.

Complete the implementation in one pair-programming cycle. One learner runs and records the trace; the other reviews identifiers, event deltas, and the authority table. Swap roles after the restart simulation. Submit: (1) the version evidence, (2) redacted event trace for the three turns, (3) before/after session-state snapshots, and (4) a one-page ownership table separating ADK state from subscription-system records.

Self-review checklist

  • Create a clean virtual environment and install exactly `google-adk==2.8.0`; record `python –version` and `pip show google-adk` in the practicum notes.
  • Set valid model credentials/configuration for your environment before executing the agent.
  • Run two turns for `user-42` in `case-1001`, then one turn for the same user in `case-1002`.
  • For every emitted event, record author, invocation ID, partial/final classification, text presence, and any `actions.state_delta`.
  • Fetch both sessions after the runs and compare unprefixed, `user:`, and `app:` keys. Confirm that `temp:` is absent after the invocation completes; exact event count and wording are model-dependent, so do not snapshot them as fixed values in this exercise alone.([github.com](https://github.com/google/adk-docs/blob/main/docs/sessions/state.md)) ([github.com](https://github.com/google/adk-docs/blob/main/docs/sessions/state.md))

Module capstone: apply the module in the AI Agentic School Decision Lab below. Mastery unlocks the LearnDash completion control for this topic.

AI Agentic School Decision Lab

Please sign in to submit your module decision and receive feedback.

Key takeaways

  • Pin the workshop to `google-adk==2.8.0` and Python 3.10+; do not teach from a moving `main` branch.
  • Treat the Runner as the turn executor: it retrieves the session using `(app_name, user_id, session_id)`, appends/processes events, applies event actions, and streams events to the caller.
  • A chat transcript is not an authoritative business database. Keep orders, permissions, balances, idempotency records, and audit records in application-owned systems.
  • State scope is encoded in key prefixes: unprefixed session state, `user:`, `app:`, and invocation-only `temp:`. Persistence depends on the configured session service, not the key name alone.
  • In production, consume the complete asynchronous event stream and persist/reconcile critical business effects outside ADK.

Useful terms

Runner
The ADK component that executes a turn, manages the event loop, coordinates services, and streams yielded events to the caller.
Event
The observable record emitted during execution. It can carry content, metadata, and actions such as a state delta; it is not necessarily final customer-facing text.
Session service
The component that creates, retrieves, and updates sessions and their event/state records. Its implementation determines whether state survives restarts.
State delta
A set of state changes carried in an event’s actions and applied when the session service appends/processes that event.

Research & review note

This lesson is built from source-traceable research and reviewed before publication. AI Agentic School uses AI as a research and practice tool, not as a substitute for evidence or editorial judgment.

Sources & further reading