The Need for Memory and Context Management
local graph
Chapter 4 — The Need for Memory and Context Management
Section titled “Chapter 4 — The Need for Memory and Context Management”Large language models (LLMs) are fundamentally stateless, despite how coherent and conversational they seem. They only know what you tell them in the current prompt. There’s no persistent context or history unless you explicitly build it in. Done well, memory allows agents to be consistent, context-aware, and even personalized over time.
Throughout this chapter, we’re going to cover the following topics:
- Different types of memory
- Managing context windows
- Storing, retrieving, and refreshing memory
- Popular tools to manage memory
By the end of this chapter, you’ll have a solid understanding of how memory functions in AI agents and the tools and patterns needed to make your agents smarter, more reliable, and context-aware.
Different types of memory
Section titled “Different types of memory”Just like humans rely on memory to make sense of the world, AI agents need memory to operate intelligently over time. Memory enables agents to retain information across interactions, remember past events, store useful knowledge, and build consistent behavior. Without memory, even the most powerful language models are stateless—reacting only to the current input with no awareness of what came before.
As AI agents become more sophisticated, so do the demands placed on their memory systems. It’s no longer enough for an agent to simply generate responses—it must remember, adapt, and improve over time. Interestingly, the way researchers design memory architectures for agents draws heavily from how psychologists understand human memory. This parallel has led to a growing taxonomy of memory types in AI, each serving a distinct purpose, from handling recent interactions to building long-term knowledge and skills.
In this section, we’ll break down the different types of memory systems that power modern AI agents, following the same framework proposed by Theodore R. Sumers et al. in their Cognitive Architectures for Language Agents paper (https://arxiv.org/pdf/2309.02427).
Short-term memory
Section titled “Short-term memory”Short-term memory (STM) is the agent’s immediate workspace—the scratchpad where recent inputs are temporarily held for quick reference. That’s why STM is often referred to as working memory (according to the terminology used in the aforementioned paper).
In conversational systems, this is essential for maintaining coherence across multi-turn interactions. If a user says, “Book me a table at 7 for 4 people,” and follows up with, “Add one more seat,” STM helps the agent connect those dots.

Figure 4.1: Example of short-term memory context window
Figure 4.1: Example of short-term memory context window
Technically, STM is often implemented using a rolling context window or buffer, which holds the most recent chunks of dialogue or data.
Definition
Context window refers to the maximum amount of information (tokens) a model can process at once—typically including the prompt, conversation history, and any retrieved or injected knowledge. It’s a key constraint in memory management, as exceeding the window forces the agent to forget or summarize past data to stay within the limit.
As new input arrives, older data is pushed out. This keeps interactions responsive and lightweight but also means STM is inherently transient. Once the buffer fills up or the session ends, that information is gone.
So, while STM is ideal for quick Q&A-style interactions, it falls short when it comes to remembering preferences or learning from past sessions. This raises a key question: how can AI agents retain long-term context and continuity across interactions?
Long-term memory
Section titled “Long-term memory”While STM handles the present, long-term memory (LTM) is about continuity over time. It allows agents to recall information across different sessions, enabling personalization, persistent knowledge, and better decision-making.
LTM is typically backed by persistent storage systems—vector databases, knowledge graphs, or structured repositories. One of the most effective techniques here is retrieval-augmented generation (RAG), where an agent pulls in relevant knowledge from a stored base to inform its responses. This makes LTM essential for agents such as customer support assistants, recommendation engines, or personalized tutors.
Note that STM and LTM are related, as STM can eventually be flushed into LTM the moment it is no longer relevant for the user’s session (we will explore similar techniques in the upcoming section).

Figure 4.2: Example of short-term memory pushed out into long-term memory
Figure 4.2: Example of short-term memory pushed out into long-term memory
Within long-term memory, we can further break down three distinct subtypes that mirror human cognition.
Semantic memory
Section titled “Semantic memory”Semantic memory stores general knowledge—facts, concepts, rules, and definitions. It’s the part of the system that “knows things,” enabling agents to reason, explain, and provide informed answers.
Note that, by design, LLMs come with parametric knowledge that already provides extensive knowledge of the world: they know physics, maths, general culture, and everything that has been encoded in any form of document publicly available on the internet. However, this knowledge might not be enough or relevant for our specific use case: what if we want our AI agent to have memory of all past diagnoses that we did in our healthcare center? Of course, this is something that could not be part of the training set and, henceforth, it’s not part of the parametric knowledge of the LLM powering our agent.
That’s why semantic memory is especially useful for agents operating in complex domains such as law, medicine, or finance, where factual correctness and domain understanding are critical.
In practice, semantic memory may be implemented via vector-encoded embeddings stored in a vector store, and the retrieval principle is similar to the concept of RAG explored in Chapter 1.
Note
Semantic memory can also be the final destination of a certain extent of the STM. In fact, some components or conversations in STM context windows may be worth preserving and, if this is the case, they can be vectorized and stored in the semantic memory’s vector database.
Episodic memory
Section titled “Episodic memory”Episodic memory, in the context of the human brain, refers to the capability of recalling specific past events in which one personally participated. When it comes to AI, episodic memory would allow AI agents to store and retrieve memories of particular experiences or episodes from their interactions with the environment, rather than just general factual knowledge.
For instance, an AI tutor might recall how a student answered a math problem last week and use that to adapt today’s lesson. This memory is often stored as structured logs or event histories that the agent can reference to make case-based decisions or adapt its behavior.
In practice, episodic memory can be seen as an extension of the few-shot prompting technique.
Definition
Few-shot prompting is a technique used in large language models where the model is provided with a small number (typically 2-5) of illustrative examples within the prompt itself. These examples help guide the model’s responses to better align with the desired task, without requiring extensive fine-tuning or training data.
Here’s an example:
Task: Sentiment Analysis
Example 1:
Text: "I loved this movie!"
Sentiment: Positive
Example 2:
Text: "This movie was terrible."
Sentiment: Negative
Now classify the following text:
Text: "The movie was enjoyable overall, despite some flaws."
Sentiment:
In this way, few-shot prompting leverages the model’s ability to quickly learn patterns from just a handful of examples, improving its performance on specific tasks without explicit retraining.
In fact, by storing a set of pairs of (“user’s question,” “given answer”) or (“user’s question,” “performed task”), the AI agent can be guided through the correct way to perform specific actions.
According to the paper Episodic memory in AI agents poses risks that should be studied and mitigated by Chad DeChant, implementing episodic memory in AI agents would allow significant enhancements, such as the following:
- Planning and decision making: Memories provide building blocks to form new strategies or plans by recalling similar previous experiences and outcomes
- Improved learning: AI agents can better adapt to new scenarios by reflecting on past events and their outcomes, identifying patterns and learning from mistakes
- Problem solving: Episodic memory provides examples from past scenarios to help solve current problems by analogy or recombination of past solutions
- Prediction and imagination: Just as humans mentally simulate future scenarios based on past events, AI agents could use episodic memory to predict possible outcomes
However, the author also highlights some potential risks associated with episodic memory:
- Deception: Agents could leverage episodic memories to carry out complex deception, by recalling past interactions and strategically manipulating future ones
- Unwanted knowledge retention: Agents could retain and recall information that users wish to keep private, posing significant privacy risks
- Unpredictable behaviors: As agents reuse past experiences to form future actions, it may be difficult to predict how certain stored memories could influence future behaviors, potentially leading to unintended consequences
- Enhanced situational awareness: Improved memory capabilities could enable AI to better understand and adapt to its operational environment, possibly escaping controls or audits intended to ensure safety
Despite the potential risks associated with integrating episodic memory into AI agents, the overall capability remains highly promising. The paper emphasizes that these risks can be significantly mitigated through carefully designed containment strategies and safety principles, such as ensuring human interpretability of memories, providing user control to add or delete memories, isolating memory storage, and restricting AI agents from editing their own memories.
Note
In both human cognition and AI systems, episodic and semantic memory serve different purposes:
Episodic memory is like a personal diary. It stores “what happened”—specific events, interactions, and experiences tied to a time and place. For AI, this could mean remembering a particular user’s complaint or the steps taken during a failed process.
Semantic memory is more like an encyclopedia. It stores “what is known”—general facts, concepts, and rules independent of context. For an AI agent, this might include product specifications, policy rules, or domain knowledge.
Keeping these two types of memory distinct allows agents to reason more effectively: they can draw on past events when needed while relying on established knowledge for consistency and accuracy.
Typically, AI agents capture episodic memories by logging interactions, which typically include the following:
- User inputs: The queries or commands provided by the user
- Agent responses: The actions or replies generated by the AI
- Contextual metadata: Additional information such as timestamps, user identifiers, and environmental context
These interactions are stored in structured formats within databases. Common storage solutions include the following:
- Relational databases: Systems such as SQLite and PostgreSQL are used to store structured logs of interactions
- Vector databases: Tools such as Pinecone, Weaviate, and Chroma store embeddings (numerical representations) of interactions, facilitating efficient similarity-based retrieval
When an AI agent needs to recall past experiences to inform current decisions, it performs the following steps:
- Query embedding: The current user input is converted into an embedding
- Similarity search: This embedding is compared against stored embeddings in the vector database to find the most relevant past interactions
- Contextual injection: Retrieved memories are incorporated into the agent’s current context, often through prompt engineering, to influence response generation
This process enables the agent to adapt its behavior based on prior experiences, enhancing personalization and continuity in interactions.
Procedural memory
Section titled “Procedural memory”The final memory we need to mention is procedural memory. For us, this type of long-term memory is responsible for storing how to do things, such as remembering how to ride a bike or tie our shoes—skills that, once learned, can be performed without conscious thought. In the context of AI agents, procedural memory serves a similar function: it encodes the foundational “know-how” that governs an agent’s behavior. For example, in self-driving cars, procedural memory enables the execution of navigation routines and obstacle avoidance without reevaluating each decision from scratch.
According to the CoALA framework proposed in the Cognitive Architectures for Language Agents paper, procedural memory in agents consists of two main components:
- The LLM weights, which encode vast amounts of procedural knowledge implicitly—such as language usage, reasoning patterns, and world models
- The agent code, which explicitly defines procedures such as prompt construction, retrieval mechanisms, grounding routines, and decision-making logic
In essence, procedural memory is encoded in the architecture of the model. As such, most current AI agents treat this memory as static (different from human procedural memory, which can adapt over time through experience). The LLM’s weights remain unchanged during deployment, and the agent code is rarely rewritten by the agent itself.
Note
It is theoretically possible to create agents that can automatically update their own source code—especially to its set of skills (by coding new skills, for example) or decision-making logic. On the other hand, in-the-wild LLM fine-tuning (i.e., modifying weights) remains uncommon due to high costs, complexity, and safety concerns.
A more practical and observed behavior is agents modifying their system messages —essentially updating the instructions they give themselves to guide behavior. This approach offers a lightweight form of procedural adaptation, though it’s still limited in scope and underutilized in most current systems.
Each type of memory we have covered plays a unique role in shaping the agent’s intelligence, from enabling action to informing decisions and learning from the past (refer to Table 4.1 below):
| Memory Type | Purpose | Content | Storage Mechanism | Usage Example | Update Mechanism |
|---|---|---|---|---|---|
| Semantic | Stores general world knowledge and facts | Abstract concepts, definitions, and relationships (e.g., “Paris is the capital of France”) | Knowledge bases, vector databases, or embedded within model parameters | Retrieving factual information or domain-specific knowledge | Updated through training on structured data or manual input |
| Episodic | Records specific events and experiences | Contextual details of past interactions (e.g., a user’s previous queries) | Logs, databases, or structured memory stores | Personalizing responses based on user history | Captured during interactions; may involve user feedback |
| Procedural | Encodes how-to knowledge and skills | Sequences of actions or routines (e.g., steps to process a user request) | Embedded in code, model weights, or defined workflows | Executing tasks such as authentication or data processing | Refined through training, reinforcement learning, or manual updates |
Table 4.1: Types of memory with usage and examples
Together, they form the backbone of an agent’s persistent capabilities and accumulated knowledge.
We’ve covered long- and short-term memory; however, there is a third category that is worth mentioning: semantic in-memory cache.
In between short-term memory and long-term memory – the role of semantic caches
Section titled “In between short-term memory and long-term memory – the role of semantic caches”Between the immediacy of STM and the durability of LTM, semantic caches offer a nimble, high-speed layer for retrieving recent information based on meaning. These caches operate by storing recent interactions as vector embeddings, enabling semantic similarity search within the current session—without needing to query or persist data in long-term stores.
Note
In traditional application development, an in-memory cache is a temporary storage layer that holds frequently accessed data in memory (typically RAM) to reduce latency and improve performance. Instead of repeatedly querying a database or external API for the same data, the application retrieves it from the cache—enabling much faster access. Tools such as Redis, Memcached, and in-memory layers in app frameworks are commonly used for this purpose.
These caches typically operate on key-value pairs—you store a result using a unique key and retrieve it by referencing that key later. This is extremely efficient for scenarios such as storing user sessions, API responses, or computed values that don’t change frequently.
In the context of AI agents and, more broadly, LLM-powered apps, the concept is similar, but the key-value pairs are based on embeddings so that the retrieval can happen through a vector search rather than a keyword match.
In Figure 4.3, you can see an example of the difference between a keyword and a semantic in-memory cache:

Figure 4.3: Difference between keyword and semantic in-memory cache
Figure 4.3: Difference between keyword and semantic in-memory cache
Unlike STM, which relies on the model’s token context window, and unlike LTM, which is designed for durable memory across sessions, a semantic cache is session-scoped, transient, and fast. It’s not designed to retain knowledge or events over time but rather to help the agent surface relevant context dynamically during an ongoing interaction—even if phrased differently from how it was originally expressed.
This real-time recall is made possible by vector-enabled databases designed specifically for semantic retrieval. Tools such as Cosmos DB with integrated vector indexing, Pinecone, Weaviate, and Qdrant allow developers to store and query embeddings with low latency. These systems support features such as in-memory search, filtering by metadata, and scoring based on relevance and recency—making them ideal for implementing semantic caches.
For example, during a patient scheduling flow, if the user previously said “Afternoons work best,” and later asks “Do you have anything post 3 pm?”, a semantic cache can retrieve and match the prior statement—even if it’s no longer in the context window. This enables agents to maintain coherence and context-awareness without incurring additional token costs.
In practice, semantic caches serve as an intelligent short-term recall layer, empowering agents to remain responsive, semantically fluent, and efficient—all without a long-term commitment. They don’t replace STM or LTM, but they complement them by enabling low-latency, relevance-driven memory within the flow of conversation.
In the next section, we’ll turn our attention to STM—how agents hold and manipulate active information during decision-making. This is where perception, reasoning, and context come together in real time.
Managing context windows
Section titled “Managing context windows”When it comes to STM (or working memory), the concept of a context window is pivotal. It defines the maximum span of text—measured in tokens—that a model can process simultaneously. This window allows the model to “remember” and utilize a specific segment of information when generating responses so that the user doesn’t have to repeat contextual information.
Despite the increase in the maximum number of tokens that the latest LLMs can handle (up to 128K tokens for models such as GPT-4o), managing context windows presents challenges. When the input exceeds the model’s context window, the model may struggle to maintain coherence and relevance, as it cannot access earlier parts of the text. This limitation can lead to outputs that lack context or continuity, especially in tasks requiring the processing of extensive documents or prolonged dialogues.
Consequently, we need to properly design the handling of context windows. There are numerous techniques in this landscape, and in this section, we are going to examine some of the most popular ones:
- Sliding window: The sliding window technique manages short-term memory by maintaining a fixed-size window of recent messages and updating it dynamically. First, it is essential to determine the window size, either by fixing the number of recent messages or setting a token limit based on system constraints and the desired response quality. The window is then updated dynamically by discarding the oldest messages as new ones arrive to maintain its size. For example, if we set our sliding window to keep 4 messages at a time (which are typically set in terms of the number of tokens we want to retain), we will have something similar to the following:

Figure 4.4: Example of short-term memory sliding window
Figure 4.4: Example of short-term memory sliding window
This process shifts the window forward, retaining only the current relevant information.
- Editing message lists:Editing message lists is an extension of the sliding window approach, with the possibility of being more granular in deciding which messages to preserve. It involves selectively trimming or filtering messages before they’re processed by the LLM powering your agent. For example, imagine an AI customer support agent helping a user troubleshoot a software issue. Over a 20-message back-and-forth, only the last few messages are directly relevant to the user’s latest request. Instead of feeding all 20 messages to the LLM (which may exceed the token limit), the system selectively keeps the following:
- The user’s most recent question
- The assistant’s last 1–2 responses
- An earlier message with critical context (e.g., the user’s OS version)
- The user’s most recent question
All other small talk or redundant questions are trimmed out. This ensures the model focuses only on the most pertinent details within the context window.
In practice, you will need to establish explicit rules or guidelines to determine which messages should be retained or discarded. Common criteria include the following:
- Recency (which is a form of sliding window): Prioritize recent messages to maintain relevant context
- Relevance: Retain messages directly related to the current query or task (this “assessment” might be performed by another LLM assessing the relevancy, thanks to a specific system prompt)
- Sender: Retain only messages coming from a specific sender (either the user or one agent)
The level of detail of your filter will depend on the metadata associated to each and every message in your chat window.
For example, we could decide only to keep messages coming from the user sent in the last 5 minutes:

Figure 4.5: Example of editing short-term memory message list
Figure 4.5: Example of editing short-term memory message list
As we will see in the hands-on chapters, frameworks such as LangGraph provide an out-of-the-box, very detailed metadata structure associated with your message, so that you can apply filters on it very granularly.
For example, in the preceding example, a potential set of metadata could be the following:
{"sender": "user", "timestamp": dd-mm-hh-mm, "content": "I like option 2", …}- Summarization: Summarization is the process of condensing extensive conversation histories or lengthy documents into concise, focused overviews. This technique captures essential points and key information, significantly reducing the number of tokens required while preserving the critical context.

Figure 4.6: Example of summarizing short-term memory messages
Figure 4.6: Example of summarizing short-term memory messages
In practice, the summary is generated by the LLM itself and passed as a parameter in that portion of the system message that tells the agent how to handle the short-term memory.
Note
Besides the specific technique we are going to employ, it is important to know when we want to apply this technique—for example, when the number of tokens of the STM reaches a given amount (which we can set close to the maximum number of tokens handled by the LLM we are using). By performing token checking, we make sure that, when the token count approaches the limit, the selected strategy (such as summarization or message editing) is enforced.
The preceding techniques are key to handling STM context windows; however, they might not be enough. In fact, depending on the kind of AI agent you are developing, you might need to keep and store working memories for a longer period of time, beyond the user’s session.
In the next section, we are going to see how to handle similar scenarios.
Storing, retrieving, and refreshing memory
Section titled “Storing, retrieving, and refreshing memory”Moving information from STM to LTM in AI agents is essential for retaining context across sessions and enabling learning over time. This process typically involves identifying relevant facts, user preferences, or insights from recent interactions and storing them in a structured, retrievable format.
Long-term memory can be implemented in various ways, depending on the use case. One common approach is to use vector databases for semantic storage—where chunks of information are embedded into vectors and stored for similarity-based retrieval, often in conjunction with RAG. This allows the system to recall contextually relevant data even if it’s not part of the immediate prompt.
The stored information can also be organized as structured metadata (such as user profiles or preferences) or appended as factual entries to a broader knowledge base.
Note that this approach can be coupled with the vector store one. This hybrid approach allows the system to first filter relevant information using explicit, structured fields—such as user ID, topic tags, or timestamps—and then apply semantic vector search within that filtered subset. For example, in a multi-user application, the agent can first retrieve only the documents associated with a specific user, ensuring that the context is scoped correctly.

Figure 4.7: Example of hybrid memory retrieval, combining filters with vector search
Figure 4.7: Example of hybrid memory retrieval, combining filters with vector search
Once the relevant slice of memory is isolated, a vector similarity search can surface the most contextually appropriate pieces of information based on the current query. This layered method increases both precision and relevance, enabling more accurate and personalized responses. It also improves performance by narrowing the search space before invoking the more computationally expensive vector similarity operations.
Ultimately, we need to consider how to manage our memory in the long run. Refreshing and updating memory in AI agents involves periodically reviewing and modifying stored knowledge to ensure it remains relevant, accurate, and useful. This process can be both reactive, triggered by specific interactions or changes, or proactive, scheduled as a background task.
Memory updates can be implemented either at the working memory layer in real time, or asynchronously in the background for the long-term memory. For example, if a user changes a preference or corrects the agent, that data can immediately overwrite or amend the corresponding entry in memory.

Figure 4.8: Example of editing memory in the context of a user session
Figure 4.8: Example of editing memory in the context of a user session
On the other hand, agents can also periodically review accumulated interactions to refine summaries, restructure profiles, or remove outdated facts.
A common technique for refreshing semantic memory is to regenerate embeddings of updated documents and replace the old vectors in the database. For structured metadata, updates might involve overwriting fields in a user profile or adjusting scores and counters that reflect user behavior over time. By combining both real-time and background refresh strategies, and allowing for both semantic and structured updates, AI agents can maintain a memory system that evolves in tandem with user needs and application dynamics—ensuring that the information they rely on stays both current and contextually accurate.
Temporal and spatial reasoning in AI agents
Section titled “Temporal and spatial reasoning in AI agents”For AI agents to operate effectively in dynamic environments, they must possess the ability to understand and reason about temporal sequences and spatial contexts. This involves not only recalling past events but also anticipating future occurrences based on learned patterns. Let’s see some examples:
- Utilizing time-sequenced events: Temporal reasoning enables agents to process events in chronological order, allowing them to understand cause-and-effect relationships and predict subsequent actions. For instance, in a customer service chatbot, recognizing that a user previously inquired about a product’s availability can inform the agent to proactively provide updates or related information in future interactions.
In reinforcement learning scenarios, agents benefit from temporal reasoning by recalling sequences of actions that led to successful outcomes, thereby refining their strategies over time.
- Referencing past interactions: By maintaining a history of interactions, agents can personalize responses and maintain continuity in conversations. This episodic memory allows for more natural and context-aware engagements, as the agent can reference specific details from prior exchanges, enhancing user experience and trust.
- Managing temporal decay: Just as humans tend to forget information that is not reinforced, AI agents must also manage the relevance of stored information over time. Implementing temporal decay mechanisms ensures that outdated or less pertinent data does not clutter the agent’s memory, allowing for more efficient processing and retrieval of relevant information.
Here are the strategies for managing temporal decay:
- Time-aware retrieval: Prioritizing recent and frequently accessed information during decision-making processes. For example, the agent can attach timestamps to each memory and use recency scoring during retrieval. Vector stores may decay embeddings over time or apply filters to retrieve only recent entries.
- Reinforcement mechanisms: Strengthening the retention of information that is repeatedly accessed or deemed important, while allowing less critical data to fade. For example, you can enforce a mechanism to track access frequency and apply a reinforcement signal (e.g., boosting vector similarity scores or tagging them as “pinned”). These can be managed through custom retrieval logic or hybrid RAG pipelines.
- Memory pruning: Regularly evaluating and removing obsolete information to optimize memory usage and maintain system performance. For example, you can have LLMs or memory managers periodically evaluate memory entries using criteria such as age, access frequency, and relevance. Low-value items are either archived or deleted to optimize memory usage and latency.
By effectively managing temporal decay, AI agents can maintain a balance between retaining useful information and discarding irrelevant data, leading to more accurate and contextually appropriate responses.
Popular tools to manage memory
Section titled “Popular tools to manage memory”As we saw in this chapter, equipping AI agents with sophisticated memory systems is vital for delivering personalized and coherent user experiences, especially over long or recurring interactions.
Popular AI orchestrators such as LangChain, LangGraph, Semantic Kernel, and so on, provide pre-built libraries to make it easier to manage both STM and LTM. However, some applications might require complex memory management, which might become cumbersome by solely relying on the above-mentioned frameworks.
Henceforth, many memory-specific, lightweight frameworks have been recently released to provide developers with a robust toolkit for complex applications.
Let’s explore three of the most popular: LangMem, Mem0, and MemGPT—each offering distinct approaches to enhancing agent memory.
LangMem
Section titled “LangMem”LangMem is a purpose-built memory management tool developed within the LangChain ecosystem to give developers granular, intentional control over how AI agents remember and recall information. LangMem allows memory to be treated as an active, programmable part of an agent’s workflow—especially when used with LangGraph. This integration enables developers to specify exactly when an agent should write to or read from memory, such as after a decision point, an external API call, or user input.
LangMem introduces a memory architecture that distinguishes between two complementary modes of memory processing: the hot path and background memory. These modes define when and how information is stored and processed by an AI agent, giving developers precise control over memory behavior.

Figure 4.9: Hot path and background memory in Langmem. Source: https://langchain-ai.github.io/langmem/hot\_path\_quickstart/
Figure 4.9: Hot path and background memory in Langmem. Source: https://langchain-ai.github.io/langmem/hot\_path\_quickstart/
The hot path refers to memory that is written during the agent’s active reasoning process. In other words, as the agent interacts with a user—answering questions, solving tasks, or guiding workflows—it can consciously decide what information to remember. This is done through a tool called manage_memory, which the agent can call, using natural language input, to store meaningful facts, decisions, or preferences. For example, if a user says, “I prefer morning appointments,” the agent can choose to save that preference immediately into memory. These memories are organized into namespaces —a sort of folder system—so that they can be scoped to specific users, topics, or threads. This gives developers precise control over what gets stored, where, and why.
On the other hand, background memory works passively and asynchronously. Rather than being triggered by the agent during the conversation, this mode runs in the background—typically after the interaction ends. It can process the entire conversation history to extract summaries, recurring themes, or useful metadata without interfering with the user’s experience. This is especially useful for building long-term user profiles or condensing long interactions into a few digestible insights. Think of it as a post-conversation reflection, where the system learns from the dialogue without needing to be explicitly told what to remember.
LangMem is tightly integrated with the LangGraph framework, which allows developers to build AI agents with structured workflows and state management. Because memory in LangMem is thread-aware, it tracks along with the conversation flow, so agents don’t just recall isolated facts but also understand when and why those facts were stored.
LangMem also supports different storage backends. Developers can begin with an in-memory setup—useful for testing and rapid development—and later switch to a more persistent store such as a database when building for production. This flexibility ensures that memory strategies can scale alongside the complexity and lifespan of the agent.
By combining hot path and background memory, LangMem enables agents that are both reactive and reflective: capable of making smart decisions in real time, while also learning and adapting over time. It bridges short-term awareness with long-term learning, making it a powerful foundation for intelligent, memory-aware agents.
Mem0 is a specialized memory layer engineered to equip AI agents with the capability to retain, adapt, and personalize their behavior across different users and sessions.
According to the Mem0 official documentation, this framework has the following features:
- Memory processing: Mem0 leverages LLMs to automatically extract and distill meaningful insights from conversations. It captures entities, events, and relationships while preserving full context, enabling agents to remember relevant facts without manual tagging or input formatting.
- Dual storage architecture: Mem0 combines two complementary storage systems:
- A vector database for storing semantic representations of memories, optimized for similarity-based retrieval.
- A graph database for capturing and querying relationships between entities, providing structure and traceability to the memory network.
- A vector database for storing semantic representations of memories, optimized for similarity-based retrieval.
Definition
A graph database is a type of database that stores data in a graph structure—composed of nodes (entities) and edges (relationships between entities). Unlike traditional relational databases that use tables, graph databases are optimized for navigating and querying relationships, making them ideal for representing complex, interconnected data such as social networks, recommendation engines, or knowledge graphs.
- Smart retrieval system: Mem0’s hybrid retrieval engine uses both vector search and graph-based queries to retrieve the most relevant memories. It prioritizes information based on importance, recency, and context, ensuring the agent responds with precise and meaningful references from its memory.
- Simple API integration: Developers can integrate Mem0 effortlessly through a lightweight API. It offers intuitive endpoints for adding new memories (add) and retrieving contextually relevant ones (search), making it easy to build memory-enabled agents without deep infrastructure work.
- Memory management: As new information becomes available, Mem0 updates stored memory while resolving inconsistencies and contradictions. This ensures the agent’s memory stays coherent and trustworthy, even as user preferences or facts evolve over time.
Note that this latter feature—memory management—is an example of adaptive learning. As agents interact with users, Mem0 empowers them to dynamically refine and expand their memory—effectively allowing them to “learn” without requiring formal retraining. This capability is especially beneficial in long-term deployments where agents need to deliver a personalized experience that evolves with the user.
In summary, Mem0 functions as a cognitive backbone for AI agents, bridging short-term interaction with long-term memory. Its emphasis on personalization, adaptability, and flexible deployment positions it as an ideal choice for developers aiming to build agents that do more than just react—they remember, evolve, and engage with depth.
LeTTA (formerly MemGPT)
Section titled “LeTTA (formerly MemGPT)”Letta—formerly known as MemGPT—is an open source framework for building stateful, memory-aware AI agents. Its core innovation lies in how it transforms traditional stateless LLM interactions into dynamic, ongoing relationships by equipping agents with long-term memory, multi-step reasoning, and adaptive context management. This means Letta-based agents can remember key facts, user preferences, and prior decisions across sessions—enabling truly coherent and personalized conversations over time.
Letta is designed to be model-agnostic, which allows developers to choose the best model for their use case without being tied to a specific provider. One of Letta’s most unique components is the Agent Development Environment (ADE), a graphical interface that gives developers deep visibility into an agent’s state.
Through ADE, you can observe how the agent is reasoning, what memory it’s accessing, which tools it’s using, and how it’s responding—offering a transparent and interactive debugging experience rarely found in other frameworks.
From an engineering perspective, Letta is built for robustness and integration. It includes full API and SDK support (via REST, Python, and TypeScript), making it easy to plug into both new and existing applications. Its auto-persistence layer ensures that every interaction, memory update, and internal state transition is stored securely in a PostgreSQL database. This not only guarantees continuity between sessions but also supports auditability and analytics.
Letta also supports the Model Context Protocol (MCP), which allows agents to access and orchestrate external tools dynamically—such as web search, calendars, or custom APIs.
Definition
The MCP is a standardized interface that allows AI agents to dynamically access, invoke, and coordinate external tools, APIs, or data sources during their reasoning process. It acts as a communication layer between the language model and a library of available capabilities, enabling the agent to extend its core functionality beyond text generation.
The MCP is especially powerful in multi-agent or tool-rich environments, where flexibility, modularity, and coordination are essential for building intelligent, autonomous systems.
By combining deep memory integration, flexible tooling, persistent state tracking, and transparent observability, Letta stands out as a comprehensive platform for developing truly autonomous, context-aware AI agents—ones that grow smarter and more capable with every interaction.
Summary
Section titled “Summary”Memory is a foundational component of intelligent AI agents, enabling them to maintain context, personalize interactions, and adapt over time. This chapter explored the spectrum of memory types—short-term and long-term—and their subcategories, including semantic, episodic, and procedural memory.
We examined strategies for managing the limited context window of LLMs, as well as techniques for storing, retrieving, and refreshing memory using both structured and semantic approaches. A hybrid model, combining metadata filtering with vector search, emerged as a powerful method for scalable and relevant memory access.
Finally, we introduced key tools— LangMem, Mem0, and MemGPT —that operationalize memory in different ways, from workflow-aware storage to operating system-inspired context management.
In the next chapter, we will see how to integrate memory with the actual capability of AI agents of “doing things,” by properly defining tools and integration layers with the surrounding ecosystem.
References
Section titled “References”- Cognitive Architectures for Language Agents: https://arxiv.org/pdf/2309.02427
- What is AI agent memory? https://www.ibm.com/think/topics/ai-agent-memory#:~:text=AI%20agent%20memory%20refers%20to%20an%20artificial%20intelligence,experiences%20to%20improve%20decision-making%2C%20perception%20and%20overall%20performance
- Types of memory: https://www.psychologytoday.com/us/basics/memory/types-of-memory?ref=blog.langchain.dev
- Episodic memory in AI agents poses risks that should be studied and mitigated: https://arxiv.org/pdf/2501.11739
- Mastering long-term agentic memory with LangGraph: https://saptak.in/writing/2025/03/23/mastering-long-term-agentic-memory-with-langgraph#:~:text=This%20is%20precisely%20the%20challenge%20that%20long-term%20memory,primary%20types%20of%20memory%3A%20semantic%2C%20episodic%2C%20and%20procedural
- Memory persistence: from fundamental mechanisms to translational opportunities: https://pmc.ncbi.nlm.nih.gov/articles/PMC10867010/
- Can AI Forget Like Humans? Exploring Memory Dynamics in LLMs: https://ai.gopubby.com/can-ai-forget-like-humans-exploring-memory-dynamics-in-llms-c7a49678c469
- Back to the Future: Towards Explainable Temporal Reasoning with Large Language Models: https://arxiv.org/abs/2310.01074
- LangMem: https://github.com/langchain-ai/langmem
- Mem0: https://github.com/mem0ai/mem0
- Letta: https://github.com/letta-ai/letta