Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 65

Vector Stores for Agent Memory & Retrieval

This lesson is built with resources from youtube.com, mbrenndoerfer.com and 1 more site.

Hello! Welcome back to our series on building advanced AI agents.

In our last lesson, you built an impressive agent that can dynamically re-plan when it encounters errors. It's resilient and can adapt its strategy mid-task. However, it has one major limitation: it's forgetful. Once a conversation ends, everything it learned—about the task, about you, about the world—is gone. Its memory is purely short-term.

Today, we will fix that. This lesson is all about giving your agent a persistent, long-term memory. You will learn to integrate a vector store to provide an agent with long-term memory and retrieval capabilities. This will transform your agent from a stateless tool into a personalized companion that can recall past interactions and learn over time.

The Agent's Brain: From Short-Term to Long-Term Memory

To build a truly intelligent agent, it's helpful to think about how human memory works. We have different memory systems for different purposes. We'll explore a framework that models AI agent memory in a similar way, distinguishing between the immediate context (working memory) and more persistent knowledge stores.

Let's start by watching a video that introduces this powerful concept.

Building Brain-Like Memory for AI | LLM Agent Memory Systems

The video 'Building Brain-Like Memory for AI' by Adam Lucek provides an excellent conceptual framework. It breaks down an agent's memory into four types. We'll focus on implementing the long-term aspects today.

Watch the introduction from 00:00 to 02:53. Pay close attention to the distinction between a 'stateless' LLM call and the four types of memory that can give it persistence: working, episodic, semantic, and procedural.

As the video explains, our agents so far have primarily used working memory—the history of the current conversation. To make them more capable, we need to add:

  • Episodic Memory: Memory of specific past events or conversations. For an agent, this could be "Last week, the user and I discussed their travel plans to Japan."
  • Semantic Memory: Structured knowledge and facts about the world, like a personal knowledge base. This could be "The user's birthday is July 20th" or technical documentation for a library.

Both of these long-term memory types can be implemented using a powerful tool you may have heard of in the context of RAG: the vector store.


The Engine of Long-Term Memory: Vector Stores

A vector store is a specialized database designed to store and search for information based on semantic meaning, not just keywords. Your background as a software engineer will make the core idea intuitive: it's a persistent storage layer, but instead of querying with SQL, you query with meaning.

The process works in three steps:

  1. Store (Embed & Index): Text is converted into numerical representations called embeddings using an embedding model. These vectors, which capture the text's semantic meaning, are stored in the vector store.
  2. Query (Embed): Your search query is also converted into an embedding using the same model.
  3. Retrieve (Similarity Search): The vector store finds the stored vectors that are most similar to your query vector (e.g., closest in the vector space). It then returns the original text associated with those vectors.

This diagram perfectly illustrates the workflow:

Vector Store Workflow Diagram
This diagram shows the core process: 1. Source data is loaded, embedded, and stored. 2. A user query is embedded. 3. The vector store retrieves the most semantically similar data from storage. This is the foundation of an agent's long-term memory.

To solidify this concept, let's look at a practical article that builds a memory system from scratch.

Long-Term Knowledge Storage and Retrieval

The article 'Long-Term Knowledge Storage and Retrieval' by Michael Brenndoerfer provides a clear, code-driven explanation of why vector stores are superior to simple key-value storage for agent memory.

Read the sections from the beginning up to and including 'Understanding Meaning, Not Just Keywords'. Focus on how the example evolves from a simple dictionary to a VectorMemory class. The code in this last section demonstrates exactly how semantic search works.

The key takeaway is that by using embeddings, an agent can retrieve "User is allergic to peanuts" when asked "What should I avoid eating?", even though the words don't match. This is the magic that makes long-term memory truly useful.


Implementing Long-Term Memory in a LangChain Agent

Now, let's integrate this into an agent. We don't need to build the vector memory class from scratch; LangChain provides abstractions that connect directly to various vector stores. A particularly useful one is VectorStoreRetrieverMemory. This component automatically handles the process of:

  1. Storing the history of a conversation in a vector store.
  2. When a new input comes in, retrieving the most relevant parts of the history from that vector store.
  3. Injecting this retrieved history into the prompt.

The following article provides a concise, end-to-end example of using this pattern with LangChain and the Milvus vector store. The principles apply to any vector store you choose.

Conversational AI with Long-Term Memory Using ...

This blog post from Zilliz, 'Conversational AI with Long-Term Memory Using ...', demonstrates the exact pattern we'll use to give our agent memory.

Read the section 'Build a Conversational Agent with Long-Term Memory using LangChain and Milvus'. Pay attention to the roles of OpenAIEmbeddings, Milvus (the vector store), and especially VectorStoreRetrieverMemory.

Putting it into Practice

Let's build a simple agent that remembers facts. We'll use ChromaDB, a popular vector store that can run locally and save to disk, making it easy to get started without any extra services.

First, make sure you have the necessary libraries installed:
pip install langchain langchain_openai chromadb

Here is the code for an agent that can remember your name:

import os
from langchain_openai import OpenAI, OpenAIEmbeddings
from langchain.memory import VectorStoreRetrieverMemory
from langchain.chains import ConversationChain
from langchain.prompts import PromptTemplate
from langchain_community.vectorstores import Chroma

# --- Environment Setup ---
# Make sure your OPENAI_API_KEY is set in your environment
# os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"

# --- 1. Set up Vector Store for Long-Term Memory ---
# We'll use ChromaDB, which will store data in a local directory.
# This directory will persist between runs.
persist_directory = "agent_memory_db"
embedding_model = OpenAIEmbeddings()

vectorstore = Chroma(
    collection_name="agent_long_term_memory",
    embedding_function=embedding_model,
    persist_directory=persist_directory
)

# The retriever is the component that searches the vector store.
# search_kwargs={"k": 1} tells it to retrieve the single most relevant document.
retriever = vectorstore.as_retriever(search_kwargs=dict(k=1))

# --- 2. Create the Memory Component ---
# VectorStoreRetrieverMemory links the vector store to the conversation chain.
memory = VectorStoreRetrieverMemory(retriever=retriever)

# --- 3. Save some initial facts to memory ---
# This is how you can "seed" the agent's memory.
# In a real application, you might do this when a user says "Remember that..."
initial_facts = [
    "My name is Alex.",
    "I'm a software engineer.",
    "My favorite food is pizza."
]
# The add_documents method handles embedding and storing the text.
vectorstore.add_texts(initial_facts)
print("Initial facts stored in long-term memory.")


# --- 4. Define the Agent's Prompt ---
# The prompt template includes a {history} placeholder where the
# retrieved memories will be injected.
llm = OpenAI(temperature=0)
PROMPT_TEMPLATE = """The following is a friendly conversation between a human and an AI.
The AI is talkative and provides lots of specific details from its context.
If the AI does not know the answer to a question, it truthfully says it does not know.

Relevant pieces of previous conversation (retrieved from long-term memory):
{history}

Current conversation:
Human: {input}
AI:"""
prompt = PromptTemplate(
    input_variables=["history", "input"], template=PROMPT_TEMPLATE
)

# --- 5. Create the Conversation Chain with Memory ---
conversation_with_memory = ConversationChain(
    llm=llm,
    prompt=prompt,
    memory=memory, # Here we plug in our long-term memory component
    verbose=True
)

# --- 6. Interact with the Agent ---
print("\n--- Starting conversation ---")

# First, ask a question the agent can answer from its seeded memory.
response = conversation_with_memory.predict(input="What is my name and what do I do for a living?")
print(f"AI Response: {response.strip()}")

# Now, have a conversation and see if it remembers.
response = conversation_with_memory.predict(input="That's correct! By the way, I'm learning to play the guitar.")
print(f"AI Response: {response.strip()}")
print("\n--- Conversation ended. Run the script again to test persistence. ---")

How to test persistence:

  1. Run the script once. It will create a directory named agent_memory_db and store the facts.
  2. Comment out the vectorstore.add_texts(initial_facts) lines.
  3. Run the script again. Ask a new question: "What hobby am I learning?".

The agent will correctly answer "guitar"! It works because the second conversation ("I'm learning to play the guitar.") was automatically saved to the ChromaDB vector store by the VectorStoreRetrieverMemory. When you run the script again, the agent retrieves this fact from its persistent memory.

Test your understanding!

In the VectorStoreRetrieverMemory setup, we defined a retriever with search_kwargs=dict(k=1). What does k=1 mean, and what would be the effect of changing it to k=3?

Show answer

k represents the number of most relevant documents to retrieve from the vector store for any given query.

By setting k=1, we are telling the agent to retrieve only the single most similar piece of information from its memory to use as context.

If you changed it to k=3, the agent would retrieve the top three most relevant memories. This would provide the LLM with a richer context, which could be helpful for more complex questions, but it would also use more tokens in the prompt. It's a trade-off between context richness and computational cost.


Advanced Memory Architectures

The VectorStoreRetrieverMemory is a powerful pattern, but we can make it even more sophisticated. The video we watched earlier demonstrated an agent that combines multiple memory systems. Let's see how that's implemented.

Building Brain-Like Memory for AI | LLM Agent Memory Systems

Let's return to the 'Building Brain-Like Memory for AI' video to see how episodic and semantic memory are combined in a full agentic loop.

Watch the following segments to see the full implementation: Episodic Memory (08:32 - 17:18): See how conversation summaries are created and stored in a vector database (Weaviate, in this case), and then retrieved to dynamically modify the system prompt. Semantic Memory (21:30 - 29:44): See how a RAG pipeline is integrated to provide factual knowledge, which is added as another layer of context for the agent.

This video showcases a sophisticated architecture where:

  1. The user's input is used to query both an episodic memory store (past conversations) and a semantic memory store (factual documents).
  2. The retrieved episodic memories are used to update the system prompt, providing ongoing guidance and learned behaviors.
  3. The retrieved semantic facts are formatted into a special message that is inserted into the conversation history, providing just-in-time factual context.
LangChain Agent Ecosystem Overview
This diagram shows where our new component fits. 'Memory' is a core part of the agent ecosystem, and it is divided into short-term buffers and the long-term vector stores we've implemented today.

Conclusion

You've now equipped your agent with one of the most critical components for advanced intelligence: long-term memory. It can now learn, recall, and personalize its interactions across different sessions.

Key Takeaways:

  • AI agents need both short-term (working) memory for current context and long-term memory for persistent knowledge.
  • Vector stores are the key technology for implementing long-term memory, enabling semantic search based on meaning.
  • The workflow involves embedding text into vectors for storage and then performing similarity searches to retrieve relevant information.
  • In LangChain, components like VectorStoreRetrieverMemory provide a high-level abstraction for integrating this capability into a conversational agent.

What's Next?
So far, we have focused on building a single, powerful agent. But what if a problem is too complex for one agent to solve alone? In the next lesson, you will learn about multi-agent collaboration. We'll explore patterns where multiple specialized agents can delegate tasks, debate solutions, and work together as a team to tackle even more challenging problems.