Agent memories with ADK
Copy as MarkdownADK Agents will automatically have session persistence when deployed on Agent Platform. You can test this by asking follow up questions in the running sessions like “What trades did you execute?”. The full conversation history is preserved, even while the agent is suspended (you’re not paying for it to run continuously), and is visibile in the console.
When you start a new session however, that context is gone. It’s common to want some level of memory and personalization for an agent. For example, if the user says “I never want to buy ___ stock”, ideally we would remember this and factor that in to trading decisions.
Memory Bank is a product in the products in the Agent Platform product suite designed to solve this problem. It provides an embedding model which is capable of analyzing session logs to determine data it thinks is worth storing, and a vector database to serve that data directly into the agent’s LLM context. You can also directly store data as a memory bypassing the embedding model.
Let’s configure Memory Bank, and have it ingest our session log to see if there’s
anything worth remembering. To do this, we need to add an after_agent_callback to save the memory, and crutially, due to the
way Agent Platform suspends agents after the response, we need to ensure the memory is flushed before
returning to the user.
This is the key code to add to our agent:
async def save_to_memory(callback_context: CallbackContext):
await callback_context.add_events_to_memory(
events=callback_context.session.events,
custom_metadata={"force_flush": True},
)
and to the agent call
tools=[get_financial_news, get_portfolio_status, get_latest_price, place_trade_order, PreloadMemoryTool(), LoadMemoryTool()],
after_agent_callback=save_to_memory,
And here’s what it looks like now, as a diff against the previous version:
The simplest way to test is during a session say “Remember that I don’t want to trade ____”, and it should not trade that ticker. You don’t have to save remember—the embedding model is smart enough to determine what to remember—but it’s a sure-fire way to get a memory. After doing this, view your memories in the UI and you should see it listed.
How ADK’s add_session_to_memory memories work is that a special LLM embedding model analyzes the session looking for pertinent data to save. If you specifically say something like “remember that …” it will almost certainly remember it. However, it may or may not specifically remember the trading actions.
In the next post, to add a bit more determinisim, we’ll look at how to save a memory.