ADK Sessions & State

adk web handles sessions, state, and runners for us. Below is what’s happening under the hood.

Original Notion page had a screenshot of the session/runner flow. See the migrated_from URL if needed.

Each session is a stateful chat history

  • State — all information in a dictionary.
  • Events — message history (tool calls, messages, etc.).
  • Metadata — additional information:
    • id
    • app_name
    • user_id
    • last_update_time

Types of sessions

  • InMemorySessionService — once you close the application, it’s gone.
  • DatabaseSessionService — conversation stored in a database. See ADK-Database-Sessions.
  • VertexAISessionService — store on the cloud.
from google.adk.sessions import InMemorySessionService, Session
 
temp_service = InMemorySessionService()
example_session: Session = temp_service.create_session(
    app_name="my_app",
    user_id="example_user",
    state={"initial_key": "initial_value"},
)

Runners

A collection of agents and a session service.

  1. User message
  2. Session — look through all sessions
  3. Agents — pass to the right agent
  4. The agent runs
  5. Tools and LLM
  6. Update Session (adding new events)
  7. Agent response
from google.adk.runners import Runner
 
runner = Runner(
    agent=question_answering_agent,
    app_name=APP_NAME,
    session_service=session_service_stateful,
)

Example folder layout (sessions + state lesson)

5-sessions-and-state/
├── .venv/
├── question_answering_agent/
├── .env
└── basic_stateful_session.py

Referencing state in instructions (string interpolation)

# In the instruction, use { key } to access state
"""
Name:
{user_name}
"""

Building a user message

from google.genai import types
 
new_message = types.Content(
    role="user",
    parts=[types.Part(text="What is Brandon's favorite TV show?")],
)

See next