Introduction
In the previous module, we engineered the backbone of a resilient agent: a system that can checkpoint its state and recover from failures, ensuring that long-running tasks can proceed reliably. We built an agent that can pause and resume, a critical capability for production-grade systems. Now, with this reliable execution framework in place, we can turn our attention from how the agent works to what the agent knows.
This lesson marks the beginning of Module 5, where we will explore Retrieval-Augmented Generation (RAG). RAG is a powerful technique that allows an agent to access and reason over external knowledge sources, dramatically improving the factual accuracy and relevance of its responses. Instead of relying solely on the pre-trained knowledge baked into the LLM, our agent will learn to "look things up."
Our first step in building a RAG system is to convert our knowledge source—a corpus of documents—into a format that a machine can understand and search based on semantic meaning. Today, you will learn how to generate text embeddings, which are numerical representations of text, using a specialized embedding model. This is the foundational process for unlocking knowledge retrieval.
From Words to Vectors: The Concept of Embeddings
At its core, an agent that needs to find relevant information faces a search problem. However, traditional keyword-based search is often too brittle. A user might ask, "What part of a cell produces energy?" but the source document might state, "The mitochondria is the powerhouse of the cell." A simple keyword search would fail to see the connection.
This is the problem that embeddings solve. An embedding is a dense vector of floating-point numbers that represents the semantic meaning of a piece of text. Instead of representing text as a string of characters, we represent it as a point in a high-dimensional "meaning space." In this space, texts with similar meanings are located close to one another, regardless of the specific words they use.
To get a first-principles understanding of this transformation, please read the following sections from "The Complete Guide to Embeddings and RAG".
The Complete Guide to Embeddings and RAG
This guide provides an excellent, comprehensive overview of embeddings.
Start by reading the introduction and the section What Are Embeddings? for a concise definition. Then, jump to the section What Embeddings Solve, focusing on the contrast between keyword search and semantic search.
The key idea is that by converting both our query and our documents into these vector representations, we can find relevant information by searching for vectors that are "closest" in this semantic space, a task computers are exceptionally good at.
The Architecture of an Embedding Model
How is a text string transformed into a dense vector? This process is handled by a neural network called an embedding model. While early models like Word2Vec existed, modern RAG systems almost exclusively use Transformer-based architectures. Understanding the components of this architecture is key to grasping how meaning is captured.

A modern embedding model typically consists of several stages working in sequence. For a clear, step-by-step breakdown of this architecture, let's turn to a talk by Anshul Bhamri on building large-scale embedding models.
Building Embedding Models for Large-Scale Real-World Applications
This resource provides a clear, architectural view of an embedding model's internal components.
Please read the section titled Architecture of Embedding Models. Pay close attention to the roles of the tokenizer, the transformer, and the pooler. This explains the journey from a raw text string to a single, final embedding vector.
As you've read, the process involves:
- Tokenization: The input text is broken down into smaller pieces called tokens.
- Embedding Projection: Each token ID is mapped to an initial, non-contextual vector.
- Transformer (Encoder): This is the core of the model. It processes the sequence of token vectors, using self-attention mechanisms to create new vectors for each token that are enriched with the context of the entire sentence.
- Pooling: The model aggregates the contextualized token vectors from the final layer into a single vector that represents the entire input text. Mean pooling (averaging the token vectors) is a common and effective strategy.
From BERT to Sentence Transformers
The architecture described above is characteristic of models like BERT (Bidirectional Encoder Representations from Transformers). BERT and its variants are powerful because they produce contextual word embeddings—the vector for the word "bank" is different in "river bank" versus "investment bank."
However, a standard BERT model is not optimized for generating sentence embeddings for similarity search. It outputs a vector for each token, and simply averaging them (mean pooling) often yields poor-quality sentence representations. This is because BERT was pre-trained on tasks like predicting masked words, not on understanding sentence-level similarity.
To see why this is a problem and how it's solved, the following video gives a fantastic explanation.
Sentence Transformers - EXPLAINED!
The video "Sentence Transformers - EXPLAINED!" by CodeEmporium clearly explains the limitations of using a base BERT model for sentence similarity and introduces the solution.
Please watch the first three parts. Start with the problem setup from the Quora example to understand why running BERT for every pair of sentences is computationally infeasible. Then, watch the segment on the naive mean-pooling approach and why it fails. Finally, the crucial explanation is in the section on further training, which introduces the idea of fine-tuning BERT on sentence-level tasks to create a true Sentence Transformer.
As the video highlights, to get high-quality sentence embeddings, the base Transformer model must be fine-tuned on a task that teaches it sentence-level semantics. This is done using specialized datasets and network structures (like Siamese networks) to train the model to produce embeddings where similar sentences are close and dissimilar ones are far apart. The resulting models are called Sentence Transformers.
Practical Implementation: Generating Embeddings in Python
For practical purposes, we don't need to implement the fine-tuning process ourselves. The sentence-transformers library provides access to hundreds of pre-trained models and a simple, high-performance interface for generating embeddings.
Let's walk through the process of generating embeddings for a small corpus of documents.
First, you'll need to install the necessary library.
pip install sentence-transformers
Now, let's write the Python code. We'll use the all-MiniLM-L6-v2 model, which is a popular choice for getting started because it offers a good balance of speed, size, and performance.
from sentence_transformers import SentenceTransformer
import numpy as np
# 1. Load a pre-trained Sentence Transformer model
# The model will be downloaded from the Hugging Face Hub automatically
model = SentenceTransformer('all-MiniLM-L6-v2')
# 2. Define our corpus of documents
# In a real application, these would be loaded from files, a database, etc.
# These could be sentences, paragraphs, or other chunks of text.
documents = [
"The agent operates in a loop of observe, think, act.",
"State management is crucial for resilient systems.",
"Embeddings are numerical representations of text.",
"A vector database is used to store and query embeddings.",
"The mitochondria is the powerhouse of the cell."
]
print(f"Corpus contains {len(documents)} documents.")
# 3. Generate embeddings for the documents
# The encode() method processes the documents in batches for efficiency.
# It can take a single string or a list of strings.
embeddings = model.encode(documents, show_progress_bar=True)
# 4. Inspect the output
print(f"\nShape of the embeddings matrix: {embeddings.shape}")
print(f"Each document is represented by a vector of size {embeddings.shape[1]}.")
# The output `embeddings` is a NumPy array.
# Each row `i` corresponds to the embedding for `documents[i]`.
print("\nFirst 5 dimensions of the first document's embedding:")
print(embeddings[0][:5])
# Example: Check the type and shape of a single embedding
single_embedding = embeddings[0]
print(f"\nA single embedding is a NumPy array of shape {single_embedding.shape} and type {single_embedding.dtype}.")
# The embeddings are already normalized to unit length (length of 1), which is
# optimal for cosine similarity search later. We can verify this.
first_vector_norm = np.linalg.norm(single_embedding)
print(f"\nNorm of the first embedding vector: {first_vector_norm:.4f}")
Running this code will download the model, process your list of documents, and produce a (5, 384) NumPy matrix. This matrix contains your vectorized knowledge base: five documents, each represented by a 384-dimensional vector.
Production Engineering Considerations
Generating embeddings for a few documents is straightforward. Scaling this to thousands or millions of documents, as required in a production system, introduces engineering challenges that leverage your background in distributed systems.
Document Chunking
Embedding models have a maximum token limit (e.g., 512 tokens for many BERT-based models). Documents longer than this limit must be split into smaller chunks. This isn't just a technical necessity; it's also beneficial for retrieval quality. Smaller, focused chunks often lead to better search results. The chunking strategy itself is a topic we'll revisit, but for now, the key is to split large documents while trying to preserve semantic boundaries (e.g., splitting by paragraphs or sentences rather than a fixed number of characters).
The article "The Complete Guide to Embeddings and RAG" has a code snippet showing a simple token-based chunking strategy.
The Complete Guide to Embeddings and RAG
This snippet demonstrates how to handle documents that exceed the model's token limit.
Find the section Ignoring Token Limits. The chunk_document function provides a basic but effective pattern for splitting a long text into manageable pieces before embedding.
Batching, Caching, and Parallelization
Generating embeddings is computationally intensive, especially on a CPU.
- Batching: The
model.encodemethod is highly optimized to process texts in batches, making it much faster than encoding one by one in a loop. When you pass a list of strings, it handles this automatically. For very large datasets, you might manually create batches to manage memory. - Caching: If your corpus contains duplicate content, you are wasting compute cycles (and money, if using a paid API) by re-embedding the same text. A robust pipeline should use a content-aware cache. You can compute a hash (e.g., SHA256) of each text chunk and use it as a key in a cache like Redis. Before embedding a chunk, you check the cache; if the hash exists, you retrieve the pre-computed embedding.
- Parallelization: To process a massive corpus quickly, you need to parallelize the workload across multiple cores or even multiple machines. This is where tools for distributed computing come into play.
The following diagram illustrates a production-grade, distributed pipeline for generating embeddings at scale.

This architecture directly applies principles from distributed systems. The task is sharded, processed in parallel, and the results are aggregated into a final data store. Designing and building such a pipeline is a core task for an AI Systems Architect.
Conclusion
In this lesson, we have taken the first and most critical step in building a RAG system. We've demystified the process of converting unstructured text into structured, meaningful numerical data.
Here are your key takeaways:
- Embeddings are semantic coordinates: They represent the meaning of text as vectors in a high-dimensional space, allowing for similarity search that goes beyond simple keywords.
- Sentence Transformers are the right tool for the job: While based on general Transformer architectures like BERT, these models are specifically fine-tuned to produce high-quality embeddings for entire sentences or text chunks.
- The process is
chunk -> encode: You must first split large documents into semantically meaningful chunks that fit within the model's context window, and then use a Sentence Transformer model to encode these chunks into vectors. - Productionizing requires systems thinking: Scaling the embedding process involves engineering patterns you're familiar with, such as batch processing, caching to avoid redundant work, and distributed computing for handling massive datasets.
We now have the raw material for our agent's knowledge base: a matrix of embedding vectors. However, these vectors are not yet useful. We need a way to store them and, more importantly, to efficiently search through millions or billions of them to find the most relevant ones for a given query. In our next lesson, we will tackle this by implementing a vector store.