Persist AI Agent Memory with ADK Sessions & Profiles
Replace ADK's InMemorySessionService with DatabaseSessionService to save chats across restarts; add recall/save tools for user preferences in new sessions.
Durable Chats via Pluggable Session Services
ADK agents lose in-memory session data on app restarts, wiping conversation history and state. Fix this by swapping InMemorySessionService (fast but ephemeral) for DatabaseSessionService, which persists user messages, agent replies, and state changes to a database file or Postgres. Agent logic stays unchanged—use the helper get_or_create_session: it fetches existing sessions by ID to resume or creates new ones. Same session ID post-restart loads full history and latest state, enabling seamless continuation. ADK also supports managed Vertex AI Session Service for cloud persistence, covered in future episodes on memory banks.
Long-Term Personalization with User Profile Tools
Persistent sessions resume ongoing chats but fail for new sessions (different IDs). Store key user facts in a simple database table: one row per user ID and preference key like dietary, favorite_thing, or transport_mode—keep it structured and small for easy curation. Equip the agent with two tools tied to user ID context:
- recall_user_preference: Reads all saved preferences for the user.
- save_user_preference: Inserts or updates a key-value pair, returning success confirmation.
Embed instructions in agent prompts:
- Recall first: Call recall at conversation start.
- Personalize and plan: Use retrieved data to tailor responses.
- Present and learn: After planning, ask about new facts to save.
- Save last: Call save before ending if new info provided.
This setup personalizes even brand-new chats weeks later without relying on transcripts.
Demo Validates Cross-Session Recall
In practice, first-time user asks for trip planning: agent recalls nothing, proposes plan, asks for preferences. User specifies "vegetarian"; agent saves it successfully. App restart clears RAM but loads session from disk and profile from table. Existing chat resumes mid-flow. New chat (fresh ID) triggers recall, finds dietary=vegetarian, and instantly personalizes the trip plan. Source code via provided links (e.g., goo.gle/agentmemorylab) shows full integration. Next steps extend to memory banks archiving full conversations with semantic search across text, images, audio, video.