Experiencing Persistent Storage
Build a memory_agent that uses DatabaseSessionService and SQLite so reminders and user data survive application restarts, not just conversation turns.
What Changed from Module 5?
Module 5’s question_answering_agent used InMemorySessionService — a session service that stores conversation state directly in the application’s RAM. That works, but it has one hard limitation: the moment the Python process exits, the session is gone. Restart the script, and the agent has no memory of who you are or what you told it.
This module fixes that with DatabaseSessionService, backed by a SQLite file on disk. The agent you build here — memory_agent — keeps working across restarts, because its session state is no longer tied to the lifetime of the process. You’ll run the same script twice in this lesson and watch the agent remember you the second time, with zero code changes to make that happen.
InMemorySessionService (Module 5) | DatabaseSessionService (this module) | |
|---|---|---|
| Storage location | Application RAM | SQL database file (SQLite here) |
| Survives restart? | No — state is lost | Yes — state is read back from disk |
| Best for | Local development, quick demos | Production-style persistence |
| Multi-instance support | No | Yes — multiple processes can share one database |
DatabaseSessionService and SQLite
ADK’s DatabaseSessionService stores session data in a SQL database instead of memory. That buys you four things:
- Long-term memory — information persists across application restarts
- Consistent user experiences — users pick up conversations where they left off
- Multi-user support — different users’ data stays separate
- Scalability — the same interface works with production databases (PostgreSQL, MySQL), not just SQLite
SQLite is what makes this practical for local development. It’s a C library — bundled with Python’s standard library as the sqlite3 module since Python 2.5 — that implements a full relational database in a single file on disk. No server process, no configuration:
- Serverless and file-based — the entire database is one portable file you can copy, move, or delete
- Zero configuration —
sqlite3.connect("file.db")creates the file if it doesn’t exist - DB-API 2.0 compliant — the same interface pattern (connect → cursor → execute → commit → close) works if you later swap in PostgreSQL or MySQL
You won’t touch sqlite3 directly in this lesson — DatabaseSessionService handles the connect/cursor/execute/commit cycle internally. But it’s worth knowing what’s happening underneath: every reminder your agent stores is a row being written to a .db file on your local filesystem.
System Architecture
Here’s the full path a request takes through memory_agent:
- The user types a message in the interactive CLI (
main.py). - At startup,
main.pyreadGOOGLE_API_KEYfrom.envand initializedDatabaseSessionServicepointed atmy_agent_data.db(SQLite). main.pychecks for an existing session for this user. If one exists, it’s reused; otherwise a new session is created withinitial_state(user_name,reminders=[]).- The
Runnerpasses the user’s query tomemory_agent, which sends the prompt and its five tool definitions to Gemini over HTTPS. - Gemini decides which tool to invoke —
add_reminder,view_reminders,update_reminder,delete_reminder, orupdate_user_name— and returns a tool call request. - The tool function executes locally, reading and writing the
reminderslist anduser_namethroughToolContext.state. DatabaseSessionServicepersists the updated state tomy_agent_data.dbafter the interaction.- The
Runnerdelivers the agent’s final response back to the CLI.
The key difference from every prior module: step 7. Nothing before Module 6 wrote anything to disk that outlived the process. Now every tool call is a write to a SQLite file that will still be there tomorrow.
What You’ll Build
A memory_agent — a reminder assistant that:
- Remembers the user’s name across sessions
- Adds, views, updates, and deletes reminders
- Persists all of this to a SQLite database, so a second run of
main.pypicks up exactly where the first one left off
Step 1: Install Dependencies
Add to requirements.txt:
google-adk[database]==1.6.1
google-genai==1.30.0
python-dotenv==1.1.1
pip install -r requirements.txt
Every prior module in this course pinned google-adk[database]==1.6.1 even when the agent only used InMemorySessionService and never touched a database. This module is where that extra actually gets exercised: the [database] extra pulls in the SQL driver dependencies that DatabaseSessionService needs to talk to SQLite (and, if you swapped the connection string, PostgreSQL or MySQL). Without it, DatabaseSessionService would fail at runtime the moment it tried to open a connection.
google-genai is Google’s Python SDK for Gemini — sending prompts, receiving responses, and handling function calling. python-dotenv reads GOOGLE_API_KEY out of .env so it never has to live in your source code.
Step 2: Project Structure
touch .env
touch main.py
touch utils.py
mkdir memory_agent
touch memory_agent/agent.py
.env:
GOOGLE_GENAI_USE_VERTEXAI=FALSE
GOOGLE_API_KEY=your_actual_api_key_here
Add both .env and *.db to .gitignore. The API key is an obvious secret — but my_agent_data.db is one too, once real users start storing reminders in it. A SQLite file with someone’s name and to-do list is personal data, and it shouldn’t end up in a public GitHub repo any more than a credential would.
Step 3: Build memory_agent/agent.py
from google.adk.agents import Agent
from google.adk.tools.tool_context import ToolContext
def add_reminder(reminder: str, tool_context: ToolContext) -> dict:
"""Add a new reminder to the user's reminder list.
Args:
reminder: The reminder text to add
tool_context: Context for accessing and updating session state
Returns:
A confirmation message
"""
print(f"--- Tool: add_reminder called for '{reminder}' ---")
reminders = tool_context.state.get("reminders", [])
reminders.append(reminder)
tool_context.state["reminders"] = reminders
return {
"action": "add_reminder",
"reminder": reminder,
"message": f"Added reminder: {reminder}",
}
def view_reminders(tool_context: ToolContext) -> dict:
"""View all current reminders.
Args:
tool_context: Context for accessing session state
Returns:
The list of reminders
"""
print("--- Tool: view_reminders called ---")
reminders = tool_context.state.get("reminders", [])
return {"action": "view_reminders", "reminders": reminders, "count": len(reminders)}
def update_reminder(index: int, updated_text: str, tool_context: ToolContext) -> dict:
"""Update an existing reminder.
Args:
index: The 1-based index of the reminder to update
updated_text: The new text for the reminder
tool_context: Context for accessing and updating session state
Returns:
A confirmation message
"""
print(f"--- Tool: update_reminder called for index {index} with '{updated_text}' ---")
reminders = tool_context.state.get("reminders", [])
if not reminders or index < 1 or index > len(reminders):
return {
"action": "update_reminder",
"status": "error",
"message": f"Could not find reminder at position {index}. Currently there are {len(reminders)} reminders.",
}
old_reminder = reminders[index - 1]
reminders[index - 1] = updated_text
tool_context.state["reminders"] = reminders
return {
"action": "update_reminder",
"index": index,
"old_text": old_reminder,
"updated_text": updated_text,
"message": f"Updated reminder {index} from '{old_reminder}' to '{updated_text}'",
}
def delete_reminder(index: int, tool_context: ToolContext) -> dict:
"""Delete a reminder.
Args:
index: The 1-based index of the reminder to delete
tool_context: Context for accessing and updating session state
Returns:
A confirmation message
"""
print(f"--- Tool: delete_reminder called for index {index} ---")
reminders = tool_context.state.get("reminders", [])
if not reminders or index < 1 or index > len(reminders):
return {
"action": "delete_reminder",
"status": "error",
"message": f"Could not find reminder at position {index}. Currently there are {len(reminders)} reminders.",
}
deleted_reminder = reminders.pop(index - 1)
tool_context.state["reminders"] = reminders
return {
"action": "delete_reminder",
"index": index,
"deleted_reminder": deleted_reminder,
"message": f"Deleted reminder {index}: '{deleted_reminder}'",
}
def update_user_name(name: str, tool_context: ToolContext) -> dict:
"""Update the user's name.
Args:
name: The new name for the user
tool_context: Context for accessing and updating session state
Returns:
A confirmation message
"""
print(f"--- Tool: update_user_name called with '{name}' ---")
old_name = tool_context.state.get("user_name", "")
tool_context.state["user_name"] = name
return {
"action": "update_user_name",
"old_name": old_name,
"new_name": name,
"message": f"Updated your name to: {name}",
}
# Create a simple persistent agent
memory_agent = Agent(
name="memory_agent",
model="gemini-2.0-flash",
description="A smart reminder agent with persistent memory",
instruction="""
You are a friendly reminder assistant that remembers users across conversations.
The user's information is stored in state:
- User's name: {user_name}
- Reminders: {reminders}
You can help users manage their reminders with the following capabilities:
1. Add new reminders
2. View existing reminders
3. Update reminders
4. Delete reminders
5. Update the user's name
Always be friendly and address the user by name. If you don't know their name yet,
use the update_user_name tool to store it when they introduce themselves.
**REMINDER MANAGEMENT GUIDELINES:**
When dealing with reminders, you need to be smart about finding the right reminder:
1. When the user asks to update or delete a reminder but doesn't provide an index:
- If they mention the content of the reminder (e.g., "delete my meeting reminder"), look through the reminders to find a match.
- If you find an exact or close match, use that index.
- Never clarify which reminder the user is referring to, just use the first match.
- If no match is found, list all reminders and ask the user to specify.
2. When the user mentions a number or position:
- Use that as the index (e.g., "delete reminder 2" means index=2).
- Remember that indexing starts at 1 for the user.
3. For relative positions:
- Handle "first", "last", "second", etc. appropriately.
4. For viewing:
- Always use the view_reminders tool when the user asks to see their reminders.
- Format the response in a numbered list for clarity.
5. For addition:
- Extract the actual reminder text from the user's request.
- Remove phrases like "add a reminder to" or "remind me to".
6. For updates:
- Identify both which reminder to update and what the new text should be.
7. For deletions:
- Confirm deletion when complete and mention which reminder was removed.
Remember to explain that you can remember their information across conversations.
IMPORTANT:
- Use your best judgement to determine which reminder the user is referring to.
- You don't have to be 100% correct but try to be as close as possible.
- Never ask the user to clarify which reminder they are referring to.
""",
tools=[
add_reminder,
view_reminders,
update_reminder,
delete_reminder,
update_user_name,
],
)
Every tool follows the same three-step pattern:
- Read from state:
tool_context.state.get("reminders", [])— the.get()with a default prevents an error on the very first call, before any reminders exist. - Mutate the local value: append, replace, or pop an item from the Python list.
- Write back to state:
tool_context.state["reminders"] = reminders— this is the line that actually persists the change.DatabaseSessionServicepicks up this write and flushes it tomy_agent_data.db.
update_reminder and delete_reminder both validate index before touching the list (not reminders or index < 1 or index > len(reminders)), and both convert the user-facing 1-based index to Python’s 0-based indexing with index - 1. Notice that none of the five tools log who called them, when, or what changed beyond a print() statement to the console — you’ll come back to that gap in Lesson 2.
Step 4: Build utils.py
utils.py handles two jobs: printing session state for debugging, and running a single turn of conversation through the agent.
from google.genai import types
# ANSI color codes for terminal output
class Colors:
RESET = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
# Foreground colors
BLACK = "\033[30m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
# Background colors
BG_BLACK = "\033[40m"
BG_RED = "\033[41m"
BG_GREEN = "\033[42m"
BG_YELLOW = "\033[43m"
BG_BLUE = "\033[44m"
BG_MAGENTA = "\033[45m"
BG_CYAN = "\033[46m"
BG_WHITE = "\033[47m"
def display_state(session_service, app_name, user_id, session_id, label="Current State"):
"""Display the current session state in a formatted way."""
try:
session = session_service.get_session(
app_name=app_name, user_id=user_id, session_id=session_id
)
print(f"\n{'-' * 10} {label} {'-' * 10}")
user_name = session.state.get("user_name", "Unknown")
print(f"👤 User: {user_name}")
reminders = session.state.get("reminders", [])
if reminders:
print("📝 Reminders:")
for idx, reminder in enumerate(reminders, 1):
print(f" {idx}. {reminder}")
else:
print("📝 Reminders: None")
print("-" * (22 + len(label)))
except Exception as e:
print(f"Error displaying state: {e}")
async def process_agent_response(event):
"""Process and display agent response events."""
print(f"Event ID: {event.id}, Author: {event.author}")
has_specific_part = False
if event.content and event.content.parts:
for part in event.content.parts:
if hasattr(part, "executable_code") and part.executable_code:
print(f" Debug: Agent generated code:\n```python\n{part.executable_code.code}\n```")
has_specific_part = True
elif hasattr(part, "code_execution_result") and part.code_execution_result:
print(f" Debug: Code Execution Result: {part.code_execution_result.outcome} - Output:\n{part.code_execution_result.output}")
has_specific_part = True
elif hasattr(part, "tool_response") and part.tool_response:
print(f" Tool Response: {part.tool_response.output}")
has_specific_part = True
elif hasattr(part, "text") and part.text and not part.text.isspace():
print(f" Text: '{part.text.strip()}'")
final_response = None
if event.is_final_response():
if (
event.content
and event.content.parts
and hasattr(event.content.parts[0], "text")
and event.content.parts[0].text
):
final_response = event.content.parts[0].text.strip()
print(f"\n{Colors.BG_BLUE}{Colors.WHITE}{Colors.BOLD}╔══ AGENT RESPONSE ═════════════════════════════════════════{Colors.RESET}")
print(f"{Colors.CYAN}{Colors.BOLD}{final_response}{Colors.RESET}")
print(f"{Colors.BG_BLUE}{Colors.WHITE}{Colors.BOLD}╚═════════════════════════════════════════════════════════════{Colors.RESET}\n")
else:
print(f"\n{Colors.BG_RED}{Colors.WHITE}{Colors.BOLD}==> Final Agent Response: [No text content in final event]{Colors.RESET}\n")
return final_response
async def call_agent_async(runner, user_id, session_id, query):
"""Call the agent asynchronously with the user's query."""
content = types.Content(role="user", parts=[types.Part(text=query)])
print(f"\n{Colors.BG_GREEN}{Colors.BLACK}{Colors.BOLD}--- Running Query: {query} ---{Colors.RESET}")
final_response_text = None
display_state(runner.session_service, runner.app_name, user_id, session_id, "State BEFORE processing")
try:
async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=content):
response = await process_agent_response(event)
if response:
final_response_text = response
except Exception as e:
print(f"Error during agent call: {e}")
display_state(runner.session_service, runner.app_name, user_id, session_id, "State AFTER processing")
return final_response_text
call_agent_async calls display_state(...) once before the agent processes the query and once after. This before/after pair is the single most useful debugging habit this lesson teaches: it lets you visually confirm that a tool call actually changed persisted state, rather than just trusting that it did. When you run the agent below, watch the reminders list in the “AFTER” block — that’s DatabaseSessionService reflecting a write that just landed in my_agent_data.db.
Step 5: Build main.py
import asyncio
from dotenv import load_dotenv
from google.adk.runners import Runner
from google.adk.sessions import DatabaseSessionService
from memory_agent.agent import memory_agent
from utils import call_agent_async
load_dotenv()
# ===== PART 1: Initialize Persistent Session Service =====
# Using SQLite database for persistent storage
db_url = "sqlite:///./my_agent_data.db"
session_service = DatabaseSessionService(db_url=db_url)
# ===== PART 2: Define Initial State =====
# This will only be used when creating a new session
initial_state = {
"user_name": "Brandon Hancock",
"reminders": [],
}
async def main_async():
# Setup constants
APP_NAME = "Memory Agent"
USER_ID = "aiwithbrandon"
# ===== PART 3: Session Management - Find or Create =====
# Check for existing sessions for this user
existing_sessions = await session_service.list_sessions(
app_name=APP_NAME,
user_id=USER_ID,
)
# If there's an existing session, use it, otherwise create a new one
if existing_sessions and len(existing_sessions.sessions) > 0:
# Use the most recent session
SESSION_ID = existing_sessions.sessions[0].id
print(f"Continuing existing session: {SESSION_ID}")
else:
# Create a new session with initial state
new_session = await session_service.create_session(
app_name=APP_NAME,
user_id=USER_ID,
state=initial_state,
)
SESSION_ID = new_session.id
print(f"Created new session: {SESSION_ID}")
# ===== PART 4: Agent Runner Setup =====
# Create a runner with the memory agent
runner = Runner(
agent=memory_agent,
app_name=APP_NAME,
session_service=session_service,
)
# ===== PART 5: Interactive Conversation Loop =====
print("\nWelcome to Memory Agent Chat!")
print("Your reminders will be remembered across conversations.")
print("Type 'exit' or 'quit' to end the conversation.\n")
while True:
user_input = input("You: ")
if user_input.lower() in ["exit", "quit"]:
print("Ending conversation. Your data has been saved to the database.")
break
await call_agent_async(runner, USER_ID, SESSION_ID, user_input)
if __name__ == "__main__":
asyncio.run(main_async())
main_async is where persistence actually becomes visible in the code. Compare it to what Module 5 would have needed: with InMemorySessionService, every run of the script starts from a blank slate — there’s nothing to “find,” because nothing survives between runs. Here, session_service.list_sessions(app_name=APP_NAME, user_id=USER_ID) queries the SQLite database on startup and checks whether this user already has a session.
- If a session exists — the code reuses its ID and continues where the conversation left off,
remindersand all. - If none exists — a new session is created and seeded with
initial_state, exactly as Module 5’sInMemorySessionService.create_session()did.
This is also why USER_ID matters more here than it did in earlier modules. It’s the key DatabaseSessionService uses to look up “does this person already have data in my_agent_data.db?” Get that wrong — a typo, or a value that changes between runs — and the agent will silently start a fresh session instead of resuming the old one.
Step 6: Run It Twice
Navigate to the project root and run:
python main.py
This will connect to my_agent_data.db (creating it if it doesn’t exist), check for a previous session, and start the conversation loop.
First run — try these:
"What's my name?""My name is John.""Add a reminder to buy groceries.""Add another reminder to finish the report.""What are my reminders?"- Exit with
"exit"
After exiting, note that my_agent_data.db now exists in your project directory — that’s the SQLite file holding everything you just told the agent.
Second run — start python main.py again:
"What's my name?"— the agent should answer “John,” with no re-introduction needed."What reminders do I have?"— both reminders from the first run should still be there."Update my second reminder to submit the report by Friday.""Delete the first reminder."
Everything in the second run builds on state the first run wrote to disk. No code changed between runs — only the database file persisted.
In main_async, why does the code call session_service.list_sessions() before deciding whether to call create_session()?
Reveal Answer & Explanation
Because with DatabaseSessionService, a session from a previous run of the script might already exist in my_agent_data.db. Calling create_session() unconditionally would either raise an error (if ADK prevents duplicate sessions for the same ID) or, worse, silently overwrite the user’s existing reminders and user_name with a fresh initial_state, discarding everything that was persisted.
list_sessions(app_name=APP_NAME, user_id=USER_ID) checks the database first. If a session for this user already exists, its ID is reused and the conversation continues from where it left off. Only if no session exists does the code fall through to create_session() with initial_state.
This find-or-create pattern is specific to persistent session services. With InMemorySessionService from Module 5, this check would always come back empty on every run — there was nothing to find, because nothing outlived the process. Here, that same code path is what makes “the agent remembers me” actually true across restarts.
What’s Next
You now have an agent whose memory survives a full process restart — the same conversation loop, but backed by a SQLite file instead of RAM. That’s a real capability gain, and it comes with a real cost: session data that used to vanish when the process exited now sits on disk indefinitely, in plaintext, readable by anything with filesystem access.
In Lesson 2, we threat model that trade-off — mapping the new DatabaseSessionService ↔ SQLite trust boundary and the direct line from LLM-generated tool arguments to persistent state that ToolContext creates.