Module 22: State and Memory - Building a Personal Tutor Agent
Lab 22: Building a Personal Learning Tutorβ
Goalβ
In this lab, you will put ADK's session architecture into practice by building a Personal Learning Tutor that leverages all four state scopes (user:, app:, unprefixed session state, and temp:), inspecting live state_delta events in adk web, and programmatically persisting multi-session state to a local SQLite database with DatabaseSessionService alongside InMemoryMemoryService.
The Use Caseβ
You will build and verify a tutor system that:
- Stores a student's preferences (
language,difficulty_level) and completed study history inuser:state so they survive across every new session. - Tracks the active lesson topic in unprefixed session state so each conversation thread stays independent.
- Uses
temp:state for single-turn quiz grading math that is discarded immediately after the turn. - Dynamically injects global catalog metadata from
app:state into the system prompt via{app:course_version?}. - Persists multiple sessions onto disk using
DatabaseSessionService(sqlite+aiosqlite) and archives completed sessions intoInMemoryMemoryService.
Step 1: Create the Project Structureβ
Environment setup:
- 1-Click Launch (Browser): Open in GitHub CodespacesOpen in Google Cloud Shell
- Local machine: If you're continuing the course in sequence,
cdinto theadk-trainingproject you created in Module 2 and skip the block below -- your environment and dependencies already carry forward. If you're starting fresh at this module, create that project first:uv init adk-training --python 3.10 && cd adk-training
uv add "google-adk>=2.1.0" python-dotenv- DevContainer / Codespaces (Alternative): If you opened this repository in a DevContainer or GitHub Codespaces, Python 3.11,
uv,gcloud, and all core ADK dependencies are pre-installed in your container environment.
From your adk-training workspace directory, scaffold the personal_tutor agent package (stay inside adk-training for all subsequent commands!):
uv run adk create personal_tutor
Select any default model/backend prompt during creationβyou will configure gemini-3.8-flash explicitly in personal_tutor/agent.py next.
Step 2: Implement the State-Management Tools (personal_tutor/agent.py)β
Exercise: Open personal_tutor/agent.py, replace its contents with the starter skeleton below, and complete every # TODO: using tool_context.state and the appropriate scoping prefixes (user:, temp:, or unprefixed session keys) from the Theory tab.
# personal_tutor/agent.py (Starter Code)
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict
from dotenv import load_dotenv
from google.adk.agents import Agent
from google.adk.tools.tool_context import ToolContext
load_dotenv(Path(__file__).with_name(".env"), override=True)
ALLOWED_DIFFICULTIES = {"beginner", "intermediate", "advanced"}
# ============================================================================
# TOOLS: State Management & Memory Operations
# ============================================================================
def set_user_preferences(
language: str,
difficulty_level: str,
tool_context: ToolContext,
) -> Dict[str, Any]:
"""
Set user learning preferences (stored persistently across all sessions).
Args:
language: Preferred language code or name (en, es, fr, it, etc.)
difficulty_level: beginner, intermediate, or advanced
"""
# TODO: Normalize/validate inputs (e.g., fallback to 'beginner' if difficulty_level
# is not in ALLOWED_DIFFICULTIES) and save 'user:language' and 'user:difficulty_level'
# in tool_context.state so they persist across all sessions for this user.
pass
return {
"status": "success",
"message": f"Preferences saved: {language}, {difficulty_level} level",
}
def record_topic_completion(
topic: str,
quiz_score: int,
tool_context: ToolContext,
) -> Dict[str, Any]:
"""
Record that the user completed a topic (stored persistently across sessions).
Args:
topic: Topic name (e.g., "Python Basics", "Data Structures")
quiz_score: Score out of 100
"""
# TODO: Read 'user:topics_covered' (list) and 'user:quiz_scores' (dict) from state,
# append/update them with the new topic and quiz_score, and write them back to state.
# Tip: Wrap retrieved values in list(...) and dict(...) before mutating!
topics = [] # Placeholder
return {
"status": "success",
"topics_count": len(topics),
"message": f"Recorded: {topic} with score {quiz_score}/100",
}
def get_user_progress(tool_context: ToolContext) -> Dict[str, Any]:
"""
Get the user's learning progress summary across all sessions.
"""
# TODO: Read 'user:language', 'user:difficulty_level', 'user:topics_covered',
# and 'user:quiz_scores' from tool_context.state and compute the average score.
language = "en"
difficulty = "beginner"
topics = []
scores = {}
avg_score = 0.0
return {
"status": "success",
"language": language,
"difficulty_level": difficulty,
"topics_completed": len(topics),
"topics": topics,
"average_quiz_score": round(avg_score, 1),
"all_scores": scores,
}
def start_learning_session(
topic: str,
tool_context: ToolContext,
) -> Dict[str, Any]:
"""
Start a new learning session for a topic.
Uses unprefixed session state to track the active topic in this session only.
"""
# TODO: Store 'current_topic' and an ISO-8601 'session_start_time'
# (datetime.now(timezone.utc).isoformat()) in session-scoped state (no prefix).
# TODO: Read the user's persistent difficulty level (defaulting to 'beginner').
difficulty = "beginner"
return {
"status": "success",
"topic": topic,
"difficulty_level": difficulty,
"message": f"Started learning session: {topic} at {difficulty} level",
}
def calculate_quiz_grade(
correct_answers: int,
total_questions: int,
tool_context: ToolContext,
) -> Dict[str, Any]:
"""
Calculate a quiz grade using temporary invocation-scoped state (temp:).
"""
# TODO: Guard against total_questions <= 0, compute percentage, store 'temp:raw_score'
# and 'temp:quiz_percentage' in temporary state, and assign a letter grade
# ('A' >= 90, 'B' >= 80, 'C' >= 70, 'D' >= 60, else 'F').
percentage = 0.0
grade = "F"
return {
"status": "success",
"score": f"{correct_answers}/{total_questions}",
"percentage": round(percentage, 1),
"grade": grade,
"message": f"Quiz grade: {grade} ({percentage:.1f}%)",
}
def search_past_lessons(
query: str,
tool_context: ToolContext,
) -> Dict[str, Any]:
"""
Search past learning history for relevant completed topics.
"""
# TODO: Read 'user:topics_covered' from state and filter topics matching query.lower().
return {
"status": "success",
"found": False,
"message": f'No past sessions found for "{query}"',
}
# ============================================================================
# AGENT DEFINITION
# ============================================================================
# TODO: Instantiate root_agent with model="gemini-3.8-flash", all 6 tools,
# output_key="last_tutor_response", and an instruction that includes {app:course_version?}
# so global app state is dynamically interpolated when present!
root_agent = None
Step 3: Inspect Live Sessions & Scoped State in adk webβ
-
Verify your credentials in
personal_tutor/.env. -
From your
adk-trainingworkspace directory, launch the Dev UI:uv run adk web -
Select
personal_tutorfrom the agent dropdown and walk through this 5-step copy-paste sequence to test all 6 tools and all 4 state scopes (app:,user:, unprefixed session state, andtemp:):-
3.1 Seed Global
app:State (Before Sending Your First Message): In the bottom chat input bar, click More options (+) β Update state and paste:{"app:course_version": "2.1"} -
3.2 Test
user:State + Session State (current_topic) +{app:course_version?}: Send:Set my preferred language to Italian at intermediate level, and start a session on Python Decorators.(Open the State tab in the left panel: you will see
app:course_version,user:language,user:difficulty_level,current_topic,session_start_time, andlast_tutor_response, plusEventActions(state_delta=...)inside Events / Trace.) -
3.3 Test
temp:Scratchpad State + Persistent Completion inuser:: Send:I finished the quiz on Python Decorators with 9 correct answers out of 10. Grade my quiz and record the completion.(Notice how
calculate_quiz_gradeusestemp:raw_scoreandtemp:quiz_percentagein memory during the turn to compute90.0% (A), whileSessionServiceautomatically strips everytemp:*key before committingβso neither State nor persisted Events are polluted bytemp:*, whereasuser:topics_coveredanduser:quiz_scoresremain durably saved!) -
3.4 Test Past Lesson Search (
user:topics_covered): Send:Search my past lessons for Decorators. -
3.5 Test Cross-Session Persistence (
+ New Session): Click+ New Sessionin the top bar and send:What is my progress and what topic are we studying right now?(Observe that
user:language,user:difficulty_level,user:topics_covered,user:quiz_scores, andapp:course_versionall carried over into the brand-newsession_id, whilecurrent_topicstarted clean!) -
Local Storage Under the Hood: Stop (
Ctrl+C) and restartuv run adk web. Because ADK 2.0+ enables--use_local_storageby default (personal_tutor/.adk/session.db), your sessions anduser:/app:state survive server restarts! Tryuv run adk web --no_use_local_storagewhenever you want volatile RAM-only testing instead.
-
Step 4: Programmatic SQLite Persistence (DatabaseSessionService) & MemoryServiceβ
Now let's build a standalone Python script that wires Runner to both DatabaseSessionService (sqlite+aiosqlite) and InMemoryMemoryService, proving multi-session scoping on disk plus cross-session recall.
- From your
adk-trainingworkspace directory, install the ADK SQLAlchemy database extra (oruv pip install "google-adk[db]"if running inside a non-pyproject.tomlcontainer):uv add "google-adk[db]" - Create
personal_tutor/test_session_persistence.pyusing the starter skeleton below and complete the# TODO:steps:
# personal_tutor/test_session_persistence.py (Starter Code)
import asyncio
from pathlib import Path
from dotenv import load_dotenv
from google.adk.memory import InMemoryMemoryService
from google.adk.runners import Runner
from google.adk.sessions import DatabaseSessionService
from google.genai import types
from agent import root_agent
load_dotenv(Path(__file__).with_name(".env"), override=True)
async def test_sqlite_sessions():
db_file = Path(__file__).resolve().with_name("tutor_sessions.db")
if db_file.exists():
db_file.unlink()
db_url = f"sqlite+aiosqlite:///{db_file.as_posix()}"
app_name = "personal_tutor_app"
user_id = "student_42"
memory_service = InMemoryMemoryService()
# TODO 1: Open DatabaseSessionService(db_url=db_url) using `async with ... as session_service:`
# and instantiate a `Runner` bound to app_name, root_agent, session_service, and memory_service.
# TODO 2: Create "session_1" via `await session_service.create_session(...)`
# seeded with state={"app:course_version": "2.1", "current_topic": "Onboarding"}.
# TODO 3: Run one user turn on "session_1" via `runner.run_async(...)` asking the tutor
# to set language="Spanish", difficulty="intermediate", and start a session on "Python Asyncio".
# Then reload "session_1" via `get_session(...)`, archive it with
# `await memory_service.add_session_to_memory(s1_loaded)`, and query `memory_service.search_memory(...)`!
# TODO 4: Create a brand-new "session_2" for the SAME user_id ("student_42")
# and print `session_2.state` to verify that `app:*` and `user:*` persisted across sessions
# while unprefixed session keys (`current_topic`, `last_tutor_response`) started clean!
# TODO 5: Call `await session_service.list_sessions(app_name=app_name, user_id=user_id)`
# and print the list of stored session IDs from SQLite.
pass
if __name__ == "__main__":
asyncio.run(test_sqlite_sessions())
- Run your persistence verification script from
adk-training:Confirm in the terminal output thatuv run python personal_tutor/test_session_persistence.pyMemoryServicerecallsAsyncio,session_2.stateinheritsapp:course_versionand youruser:*preferences fromtutor_sessions.db, andlist_sessions()reports['session_1', 'session_2']!
Step 5 (Bonus Challenge): Context Compaction & Session Rewindβ
For fast finishers: in long-running tutoring threads, you can configure automatic sliding-window summarization (EventsCompactionConfig) and roll back an accidental turn (runner.rewind_async).
Exercise: Create personal_tutor/test_memory_advanced.py and complete the # TODO: markers:
# personal_tutor/test_memory_advanced.py (Bonus Starter Code)
import asyncio
from pathlib import Path
from dotenv import load_dotenv
from google.adk.apps.app import App
from google.adk.runners import InMemoryRunner
from google.genai import types
from agent import root_agent
# TODO 1: Import EventsCompactionConfig (from google.adk.apps.app),
# LlmEventSummarizer (from google.adk.apps.llm_event_summarizer),
# and LLMRegistry (from google.adk.models).
load_dotenv(Path(__file__).with_name(".env"), override=True)
async def test_advanced_memory():
# TODO 2: Instantiate EventsCompactionConfig with compaction_interval=2,
# overlap_size=1, and summarizer=LlmEventSummarizer(llm=LLMRegistry.new_llm("gemini-3.8-flash")).
compaction_config = None
app = App(
name="advanced_tutor_app",
root_agent=root_agent,
events_compaction_config=compaction_config,
)
async with InMemoryRunner(app=app) as runner:
user_id = "student_42"
session_id = "session_math_1"
await runner.session_service.create_session(
app_name=app.name,
user_id=user_id,
session_id=session_id,
)
# TODO 3: Run Turn 1 (setting preferences), Turn 2 (starting Python Lists),
# and Turn 3 (starting an accidental topic like Quantum Tensor Calculus).
# Capture `event.invocation_id` from Turn 3, then call:
# await runner.rewind_async(user_id=user_id, session_id=session_id, rewind_before_invocation_id=...)
# Print rewound.state afterward to verify session state rolled back while user: state stayed intact!
if __name__ == "__main__":
asyncio.run(test_advanced_memory())
Run it from adk-training with:
uv run python personal_tutor/test_memory_advanced.py
Lab Summaryβ
You have built and verified a stateful Personal Learning Tutor backed by real ADK session management:
- Scoped state cleanly across
user:,app:, unprefixed session keys, and ephemeraltemp:keys. - Interpolated optional state into instructions with
{app:course_version?}. - Inspected
EventActions(state_delta=...)and.adk/local SQLite storage inadk web. - Persisted multi-session state onto disk with
DatabaseSessionService(sqlite+aiosqlite), archived sessions intoInMemoryMemoryService, and queried sessions viacreate_session,get_session, andlist_sessions. - (Bonus) Configured
EventsCompactionConfigand rolled back session-scoped state withrunner.rewind_async.
Self-Reflection & Interactive Knowledge Checksβ
Why is the 'temp:' state prefix automatically stripped before SessionService commits an event to storage?
In Step 4, when you created 'session_2' in DatabaseSessionService for the same user_id ('student_42'), which keys were automatically present in session_2.state?
How does EventsCompactionConfig with LlmEventSummarizer keep long-running sessions healthy?
Classroom Debrief Questionsβ
- How does
uv run adk webpersist sessions locally compared toInMemorySessionServiceandDatabaseSessionService(SQLite vs. PostgreSQL)? - Why is
temp:state discarded after each turn, and why must secrets/API keys still never be placed intemp:? - How does
MemoryService(InMemoryMemoryService/VertexAiMemoryBankService) complementsession.state? - When
runner.rewind_async(...)rolls back a turn, why doesuser:state remain untouched?
π Reference Solution Vaultβ
Official Solution Vault β Module 22
Locked Challenge β Active Pedagogical Socratic Gate