Google ADK — Sessions & State
Core Concepts
- Session: A conversation between user and agent (contains events/messages)
- State: Key-value store attached to a session (persists across turns)
- SessionService: Backend that stores/retrieves sessions
Session Services
| Service |
Persistence |
Use Case |
InMemorySessionService |
None (RAM only) |
Development, testing |
SqliteSessionService |
Local SQLite file |
Local persistence |
DatabaseSessionService |
PostgreSQL/MySQL |
Production, multi-instance |
VertexAiSessionService |
Vertex AI |
Google Cloud managed |
Basic Usage with Runner
from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
agent = Agent(
name="my_agent",
model="gemini-2.5-flash",
instruction="You are a helpful assistant.",
)
session_service = InMemorySessionService()
runner = Runner(agent=agent, session_service=session_service, app_name="my_app")
# Create a session
session = await session_service.create_session(
app_name="my_app",
user_id="user_123",
)
# Run agent
message = types.Content(
role="user",
parts=[types.Part(text="Hello!")],
)
async for event in runner.run_async(
session_id=session.id,
user_id="user_123",
new_message=message,
):
if event.content and event.content.parts:
print(event.content.parts[0].text)
SQLite Session Service
from google.adk.sessions.sqlite_session_service import SqliteSessionService
session_service = SqliteSessionService(db_url="sqlite:///./sessions.db")
Database Session Service (PostgreSQL)
from google.adk.sessions import DatabaseSessionService
session_service = DatabaseSessionService(
db_url="postgresql+asyncpg://user:pass@localhost/mydb",
)
Vertex AI Session Service
from google.adk.sessions import VertexAiSessionService
session_service = VertexAiSessionService(
project="my-gcp-project",
location="us-central1",
)
Working with State
State is a dict attached to the session, accessible in tools and instruction providers.
Reading State (in instruction provider)
from google.adk.agents.readonly_context import ReadonlyContext
def dynamic_instruction(ctx: ReadonlyContext) -> str:
user_name = ctx.state.get("user_name", "friend")
history_count = ctx.state.get("interaction_count", 0)
return f"You are helping {user_name} (interaction #{history_count + 1})."
Writing State (in tools)
from google.adk.tools.tool_context import ToolContext
def set_user_preference(key: str, value: str, tool_context: ToolContext) -> str:
"""Sets a user preference.
Args:
key: The preference key.
value: The preference value.
"""
prefs = tool_context.state.get("preferences", {})
prefs[key] = value
tool_context.state["preferences"] = prefs
return f"Set {key} = {value}"
State Prefixes
| Prefix |
Scope |
Visible To |
| (none) |
Session-level |
All agents in session |
app: |
Application-level |
Persists across sessions for same app |
user: |
User-level |
Persists across sessions for same user |
temp: |
Temporary |
Current invocation only |
def save_data(tool_context: ToolContext) -> str:
"""Example of different state scopes."""
# Session state (default)
tool_context.state["current_task"] = "researching"
# App-level (persists across sessions)
tool_context.state["app:total_queries"] = tool_context.state.get("app:total_queries", 0) + 1
# User-level (persists for this user across sessions)
tool_context.state["user:preferred_language"] = "python"
# Temp (gone after this invocation)
tool_context.state["temp:intermediate_result"] = "..."
return "Data saved."
Session Lifecycle
# Create
session = await session_service.create_session(
app_name="my_app",
user_id="user_123",
state={"initial_key": "initial_value"}, # Optional initial state
)
# Get
session = await session_service.get_session(
app_name="my_app",
user_id="user_123",
session_id=session.id,
)
# List sessions for user
sessions = await session_service.list_sessions(
app_name="my_app",
user_id="user_123",
)
# Delete
await session_service.delete_session(
app_name="my_app",
user_id="user_123",
session_id=session.id,
)
Key Rules
- State persists across invocations within the same session
- Use
output_key on agents to automatically store their output in state
- State values must be JSON-serializable (strings, numbers, lists, dicts)
- Use state prefixes (
app:, user:, temp:) for different persistence scopes
InMemorySessionService loses all data on restart — use SQLite+ for persistence
- The CLI (
adk web, adk run) uses InMemorySessionService by default
Related Skills
google-adk-memory — Long-term memory across sessions
google-adk-app — App pattern (wraps session + memory services)
google-adk-deploy — Production deployment (persistent session services)