We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Chunked Semantic Embeddings

Now that we can chunk documents, let's create embeddings for those chunks. This is the foundation for a more useful search system: it can find relevant sections inside longer documents.

In this lesson, we'll focus on:

  1. Chunking documents using our semantic chunking approach
  2. Creating embeddings for each individual chunk
  3. Storing metadata to map chunks back to their original documents

Creating embeddings for chunks instead of full documents lets us find specific relevant sections within longer texts. That's crucial for RAG systems when documents are too large, too broad, or too noisy to embed as one unit.

This is very similar to the embeddings we created for full documents, but it's a little trickier because we need to map chunks back to their original documents.

Assignment

Implement a system that creates embeddings for document chunks.

  1.  class ChunkedSemanticSearch(SemanticSearch):
         def __init__(self, model_name: str = "all-MiniLM-L6-v2") -> None:
             super().__init__(model_name)
             self.chunk_embeddings = None
             self.chunk_metadata = None
    
        • movie_idx: The index of the document in self.documents
        • chunk_idx: The index of the chunk within the document
        • total_chunks: The total number of chunks in the document
    1. json.dump({"chunks": chunk_metadata, "total_chunks": len(all_chunks)}, f, indent=2)
      
    1. print(f"Generated {len(embeddings)} chunked embeddings")
      

Run and submit the CLI tests.

Building the embeddings for the first time might take quite a while. Go make yourself a nice soy latte.

We're storing metadata about each chunk so we can later map chunks back to their original documents.

Tip

If you want to type the chunk metadata shape explicitly, a TypedDict works well here:

from typing import TypedDict


class ChunkMetadata(TypedDict):
    movie_idx: int
    chunk_idx: int
    total_chunks: int