Module 2 · Lesson 4 · 16 min read
Vector memory and retrieval
Vector Memory and Retrieval
Introduction
How does an agent find information in its memory when the user asks with words different from the ones saved? The answer is searching by meaning through vector representations. In this lesson we build a simplified vector memory step by step and discuss the important design decisions.
Learning objectives
- Explain the idea of vector embeddings and cosine similarity
- List the steps of building a vector memory, from chunking to retrieval
- Build a similarity search that returns the top k results with a minimum score
- Evaluate the decisions about k, hybrid search and metadata
The problem: searching by meaning, not by words
Suppose the agent's memory contains the sentence "A student may withdraw from a course until the end of the tenth week", and the student asks: "What is the last date to drop a subject?" Keyword search will fail, because "drop a subject" does not literally match "withdraw from a course", even though the meaning is the same. This is where vector memory comes in.
Embeddings
An embedding is a list of numbers (a vector) into which a specialized model, called an embedding model, turns a text. The basic idea: texts that are close in meaning get vectors that are close in space. So we can measure "similarity of meaning" by measuring the distance or the angle between two vectors.
The best-known measure is cosine similarity:
cos(a, b) = (a · b) / (|a| × |b|)A value close to 1 means a similar direction (close meaning), and a value close to 0 means no relationship.
Steps for building a vector memory
- Chunking: splitting long documents into short, coherent chunks; a chunk that is too long mixes topics, and one that is too short loses context.
- Embedding: turning each chunk into a vector and saving it with the original text and metadata such as the source and date.
- Indexing: saving the vectors in a store that supports fast search, called a vector database.
- Querying: when a question is asked, the question is turned into a vector with the same model.
- Retrieval: finding the k nearest chunks (top-k) and returning them with their similarity scores.
A practical example that runs without libraries
We will not use a real embedding model here; instead we build simple vectors from word counts with a small synonym dictionary that simulates the idea of "closeness of meaning". The aim is to understand the mechanism, not accuracy.
import math
from collections import Counter
SYNONYMS = {"drop": "withdraw", "dropping": "withdraw", "withdrawal": "withdraw", "subject": "course",
"courses": "course", "date": "end", "last": "end"}
def normalize(text):
words = text.replace("?", "").split()
return [SYNONYMS.get(w, w) for w in words]
def embed(text):
return Counter(normalize(text)) # a sparse vector: word -> count
def cosine(a, b):
dot = sum(a[k] * b[k] for k in a if k in b)
na = math.sqrt(sum(v * v for v in a.values()))
nb = math.sqrt(sum(v * v for v in b.values()))
return dot / (na * nb) if na and nb else 0.0
class VectorMemory:
def __init__(self):
self.items = []
def add(self, text, source):
self.items.append({"text": text, "vec": embed(text), "source": source})
def search(self, query, k=2, min_score=0.1):
qv = embed(query)
scored = [(cosine(qv, it["vec"]), it) for it in self.items]
scored.sort(key=lambda p: p[0], reverse=True)
return [(round(s, 2), it["text"], it["source"]) for s, it in scored[:k] if s >= min_score]
mem = VectorMemory()
mem.add("A student may withdraw from a course until the end of the tenth week", "regulation-4.2")
mem.add("The maximum course load is 18 credit hours", "regulation-3.1")
mem.add("The library is open from eight in the morning until ten in the evening", "library-guide")
for hit in mem.search("What is the last date to drop a subject?"):
print(hit)With a real embedding model you will not need the synonym dictionary; the model has learned these relationships from huge amounts of data. But the steps remain: embed, then compute similarity, then rank, then take the top k with a minimum score.
Important design decisions
- The value of k: too small and you miss information, too large and you fill the context with noise.
- The minimum similarity: prevents returning weakly related results when there is no answer in memory.
- Hybrid search: combining vector search with keyword search; useful for names, numbers and exact codes such as a course number.
- Metadata: allows filtering (for example: only this year's regulations) and citing the source.
Summary
Vector memory makes it possible to search by meaning instead of literal words, by turning texts into vectors with an embedding model and measuring the similarity between them, usually with cosine similarity. The build steps are: chunking, embedding, indexing, embedding the question and retrieving the top k results. The same embedding model must be used for the documents and the questions. The value of k, the minimum similarity, hybrid search and saving sources are decisions that directly affect the quality of the agent.
Terms
| Term | English | Definition |
|---|---|---|
| Embedding | Embedding | A vector of numbers that represents the meaning of a text |
| Cosine similarity | Cosine Similarity | A measure of how close the directions of two vectors are, used to measure closeness of meaning |
| Chunking | Chunking | Splitting long documents into short, coherent chunks |
| Vector database | Vector Database | A store that supports fast search for the nearest vectors |
| Top k results | Top-k | Returning the k chunks closest to the user's question |
| Hybrid search | Hybrid Search | Combining vector search with keyword search |
Review questions
- Why does keyword search fail in the "drop a subject" example?
- What happens if you use two different embedding models for the documents and the questions?
- Discuss the effect of choosing a value of k that is too small or too large.
- When is hybrid search better than vector search alone?
References
- Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks arxiv.org Reviewed on 2026-11-18
- MemGPT: Towards LLMs as Operating Systems arxiv.org Reviewed on 2026-11-18
