Urgent.News

What's breaking now, across thousands of outlets.

AI

How to Add Long-Term Memory to a Python AI Agent (Store, Recall, Forget, Per User)

Most agents forget everything when the process exits. Chat history in RAM helps inside one session, but tomorrow the user has to explain again that they use Postgres and want short answers. This tutorial adds long-term memory to a plain Python agent: it stores durable facts, recalls the relevant ones before each model call, keeps each user's memory separate , and forgets a fact when the user…

This tutorial demonstrates how to add long-term memory to a Python AI agent using the MemorySync SDK. The agent will store durable facts, recall relevant ones before each model call, separate each user's memory, and forget facts upon user request. The MemorySync Python SDK is used throughout the tutorial, which is compatible with LangChain, CrewAI, the OpenAI Agents SDK, or other agent frameworks.

To implement this, you'll create an AgentMemory class with one instance per end-user. The end-user ID serves as the memory scope, passed to the MemorySyncClient. This ensures separate memory for each user during a session.

When storing facts, the remember() method extracts lasting facts from the input text. It returns an AddSkippedResponse if no facts are worth saving or a record with the stored data otherwise. The Agent Memory guide suggests storing user-approved preferences, confirmed outcomes, and stable constraints.

To recall relevant facts before each model call, the context_block() method searches for relevant facts using the recall() method. The relevant facts are then formatted as data for the prompt, keeping the prompt concise by keeping only the first line of each fact up to a specified character limit.

To forget a fact, the forget_matching() method is used. It deletes a fact only after confirming it is the correct one. This method is called when the user requests forgetting a specific fact.

Finally, the agent_turn() method incorporates the memory into the prompt before calling your LLM, allowing the AI agent to utilize its long-term memory effectively.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in AI

More from Tuesday 20 October →