Skip to content
Blog

Cross-Session Long-Term Memory: Storing Facts and Preferences Across User Turns

Give your ADK agent a memory that outlives the chat: the MemoryService write and read paths, the three implementations compared, and the after_agent_callback pattern that remembers conversations automatically.

Published on • December 3, 2026

AI Assistant

A user tells your support agent in session one that they always want rush shipping. In session two, the agent asks for their preference again. State could not help: user: prefixed state is scoped to a session’s storage, and the new session started with an empty scratchpad. What was needed is a different mechanism entirely — memory, the searchable archive that spans conversations.

ADK draws a hard line: sessions and state are short-term, MemoryService is long-term. Nothing is remembered automatically — memory ingestion is a decision you wire up, and retrieval is a decision your agent makes (or you make for it). This tutorial covers both halves: writing facts to memory at the end of a conversation, and reading them back at the start of the next one.

Prerequisites

  • ADK installed (pip install google-adk) and a Runner you have run at least once.
  • Read of the session/state model: memory assumes you already know why state is not enough.
  • For the Vertex AI options: a GCP project with the Agent Platform API (pip install google-adk[gcp]).

1. The MemoryService contract

The base service defines four operations — two required, two optional:

OperationWhat it ingestsRequired?
add_session_to_memory(session)A full completed session — the “remember this conversation” callCore
add_events_to_memory(...)A delta of events (e.g. the latest turn) without re-ingesting the sessionOptional — confirm your implementation supports it
add_memory(memories=[...])Explicit MemoryEntry objects — fine-grained facts from other sourcesOptional
search_memory(query)Retrieval: returns relevant snippets for a queryCore

Reading happens on the same service, always scoped by app_name and user_id — memory belongs to a user across all of their sessions.

2. Pick an implementation

InMemoryMemoryServiceVertexAiMemoryBankServiceVertexAiRagMemoryService
PersistenceNone — lost on restartManaged by Agent PlatformStored in Knowledge Engine
ExtractionStores the full conversationLLM extracts and consolidates meaningful memoriesStores the full conversation
SearchBasic keyword matchingAdvanced semantic searchVector similarity
SetupNone — it’s the defaultLow — needs an Agent RuntimeMedium — needs a RAG corpus
Best forPrototyping, local testsAgents that learn from past interactionsRaw transcript retrieval, existing RAG stacks

InMemoryMemoryService is where every project starts:

from google.adk.memory import InMemoryMemoryService
from google.adk.sessions import InMemorySessionService

session_service = InMemorySessionService()
memory_service = InMemoryMemoryService()   # shared across Runners

Services must be shared across Runner instances — a memory service per runner is a memory that cannot see its own past.

3. Writing: the after_agent_callback pattern

Memory is written explicitly. The common production pattern hooks the end of each agent run:

from google.adk.agents import LlmAgent
from google.adk.tools import preload_memory


async def remember_conversation(callback_context):
    """Ingest the finished session into long-term memory."""
    await callback_context.add_session_to_memory()


agent = LlmAgent(
    model="gemini-flash-latest",
    name="Generic_QA_Agent",
    instruction="Answer the user's questions",
    tools=[preload_memory],
    after_agent_callback=remember_conversation,
)

Or call the service directly when a session concludes, which makes the timing explicit:

completed = await session_service.get_session(
    app_name="support_app", user_id="u_123", session_id=session_id
)
await memory_service.add_session_to_memory(completed)

For facts that did not come from a conversation — a CRM record, a profile import — skip the session and push an explicit entry:

from google.adk.memory.memory_entry import MemoryEntry
from google.genai.types import Content, Part

await memory_service.add_memory(
    app_name="support_app",
    user_id="u_123",
    memories=[
        MemoryEntry(
            content=Content(parts=[Part(text="Customer prefers rush shipping.")])
        )
    ],
)

(add_memory and add_events_to_memory are optional operations — VertexAiMemoryBankService supports both, with consolidation available via custom_metadata={"enable_consolidation": True}; check your implementation before relying on them.)

4. Reading: three routes into the agent

RouteWhen it firesUse it when
load_memory toolThe agent decides to call itRetrieval should be a model judgment call
preload_memory toolAutomatically at the start of each turnYou always want relevant memories in context
tool_context.search_memory(query)Inside your own custom toolYou need to shape, filter, or combine results
from google.adk.tools import ToolContext


async def search_past_conversations(
    query: str, tool_context: ToolContext
) -> dict:
    response = await tool_context.search_memory(query)
    return {
        "results": [
            part.text
            for entry in response.memories
            for part in (entry.content.parts or [])
            if part.text
        ]
    }

5. The round trip

Capture in one session, recall in the next — the full loop:

from google.adk.agents import LlmAgent
from google.adk.memory import InMemoryMemoryService
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.tools import load_memory
from google.genai.types import Content, Part

APP_NAME, USER_ID, MODEL = "memory_example_app", "mem_user", "gemini-flash-latest"
session_service = InMemorySessionService()
memory_service = InMemoryMemoryService()

capture_agent = LlmAgent(model=MODEL, name="InfoCaptureAgent", instruction="Acknowledge the user's statement.")
recall_agent = LlmAgent(model=MODEL, name="MemoryRecallAgent", tools=[load_memory],
                        instruction="Answer the user's question. Use the 'load_memory' "
                                    "tool if the answer might be in past conversations.")

# --- Turn 1: capture ---
runner1 = Runner(agent=capture_agent, app_name=APP_NAME, session_service=session_service, memory_service=memory_service)
s1 = await session_service.create_session(app_name=APP_NAME, user_id=USER_ID)
msg1 = Content(role="user", parts=[Part(text="My favorite project is Project Alpha.")])
async for _ in runner1.run_async(user_id=USER_ID, session_id=s1.id, new_message=msg1):
    pass
completed = await session_service.get_session(app_name=APP_NAME, user_id=USER_ID, session_id=s1.id)
await memory_service.add_session_to_memory(completed)   # <-- the decision to remember

# --- Turn 2: recall, in a brand-new session ---
runner2 = Runner(agent=recall_agent, app_name=APP_NAME, session_service=session_service, memory_service=memory_service)
s2 = await session_service.create_session(app_name=APP_NAME, user_id=USER_ID)
msg2 = Content(role="user", parts=[Part(text="What is my favorite project?")])
async for event in runner2.run_async(user_id=USER_ID, session_id=s2.id, new_message=msg2):
    if event.is_final_response() and event.content and event.content.parts:
        print(event.content.parts[0].text)   # -> "Project Alpha"

The gap between the two sessions is bridged by exactly two lines of intent: add_session_to_memory on the way out, load_memory (or preload_memory) on the way in.

6. Choosing what to remember

Not every session deserves ingestion, and not every turn deserves a search call. Practical guidance: ingest at natural boundaries (conversation end, task completion) rather than per message; prefer preload_memory for always-on personalization and load_memory for on-demand lookup; and for production on Google Cloud, move to VertexAiMemoryBankService so extraction and consolidation are handled by the platform instead of by keyword matching.

Checklist

  • One MemoryService instance is created and shared across all Runners for the app.
  • Ingestion is wired explicitly (after_agent_callback or a direct add_session_to_memory call) — never assumed.
  • The agent has exactly one read route it needs: load_memory, preload_memory, or a custom tool using tool_context.search_memory.
  • add_events_to_memory / add_memory are verified as supported by the chosen implementation before use.
  • Production memory uses a persistent implementation — InMemoryMemoryService forgets on restart.
  • Memory reads are scoped per user_id, and no code shares one user’s memory with another.
  • The recall path is tested: capture in session A, ask in session B, assert the answer.
  • VertexAiMemoryBankService prerequisites (Agent Runtime, google-adk[gcp]) are confirmed before switching.

Conclusion

State remembers this conversation; memory remembers this user. ADK’s MemoryService makes the distinction enforceable: ingestion is an explicit write (add_session_to_memory at the end of a turn), retrieval is an explicit read (load_memory, preload_memory, or search_memory in a tool), and the implementation you choose decides whether that knowledge keyword-matches, semantically searches, or gets consolidated by an LLM on a managed platform. Wire the two ends up and your agent stops asking for what it was already told.

References