Velamuvi AIAcademy
LangChain

Lesson 6 of 9 · Composition

Retrievers

Find relevant text with LangChain: Documents, text splitters with overlap, embeddings, InMemoryVectorStore, retrievers with k and MMR, and a citing RAG chain.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Represent text as Document objects with metadata
  • Split documents into overlapping chunks
  • Embed chunks into a vector store and turn it into a retriever
  • Control how many results come back and how relevant they must be
  • Build a RAG chain that answers from retrieved context with citations

Finding the right text

Models don't know your company's policies, documents or data. Retrieval-augmented generation (RAG) fixes that by retrieving relevant text and putting it in the prompt (see the Retrieval-Augmented Generation course for the full theory). LangChain gives each step a standard component.

Split, embed, store, retrieve

from langchain.embeddings import init_embeddings
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_text_splitters import RecursiveCharacterTextSplitter

docs = [
    Document(page_content="Returns: you can return a bike within 30 days of delivery for a full refund. "
                          "Bikes must be unused and in the original box. Refunds take 5 working days.",
             metadata={"source": "returns-policy.md"}),
    Document(page_content="Warranty: frames are covered for 5 years and batteries for 2 years. "
                          "Warranty repairs are free at any partner workshop.",
             metadata={"source": "warranty.md"}),
    Document(page_content="Delivery: orders ship within 2 working days. Delivery to Portugal and Spain is free.",
             metadata={"source": "delivery.md"}),
]

splitter = RecursiveCharacterTextSplitter(chunk_size=120, chunk_overlap=20)
chunks = splitter.split_documents(docs)              # metadata is copied onto every chunk
print(len(docs), "documents ->", len(chunks), "chunks")

embeddings = init_embeddings("openai:text-embedding-3-small")
store = InMemoryVectorStore.from_documents(chunks, embeddings)
retriever = store.as_retriever(search_kwargs={"k": 2})

for doc in retriever.invoke("How many days do I have to return a bike?"):
    print(f"[{doc.metadata['source']}] {doc.page_content}")
Output
3 documents -> 4 chunks
[returns-policy.md] Returns: you can return a bike within 30 days of delivery for a full refund. Bikes must be unused and in the original
[returns-policy.md] and in the original box. Refunds take 5 working days.

Step by step:

  1. Documents carry their source in metadata, which is copied onto every chunk, so answers can cite where they came from.
  2. RecursiveCharacterTextSplitter cuts text into chunks of up to chunk_size characters, preferring to break between paragraphs, then lines, then words, so chunks rarely end mid-word. chunk_overlap repeats a little text between neighbouring chunks, so a sentence cut at a boundary still appears whole somewhere (notice “and in the original” in both chunks).
  3. init_embeddings creates an embedding model from a "provider:model" string, just like init_chat_model. This one needs the langchain-openai package and an OpenAI key.
  4. InMemoryVectorStore stores the chunk vectors. It's ideal for learning and tests; for real data, use a vector database integration such as Chroma, pgvector or Qdrant (see the Vector Databases course). They share the same interface.
  5. as_retriever(search_kwargs={"k": 2}) returns the 2 most similar chunks for a query.

The same steps in plain Python

Here's a simple splitter with overlap and a similarity search over its chunks:

Try it yourselfPython
import math, re

# What a splitter and a retriever do, in plain Python
def split(text, size, overlap):
    """Cut text into chunks of about `size` characters, breaking at spaces, with `overlap` repeated."""
    chunks, start = [], 0
    while start < len(text):
        end = min(start + size, len(text))
        if end < len(text):
            end = text.rfind(" ", start, end) or end          # don't cut a word in half
        chunks.append(text[start:end].strip())
        if end >= len(text):
            break
        start = max(text.rfind(" ", start, end - overlap) + 1, start + 1)   # step back for overlap
    return chunks

TOPICS = {"returns": {"return", "refund", "days", "box"}, "warranty": {"warranty", "battery", "frame"},
          "delivery": {"delivery", "ship", "free"}}
def embed(text):
    words = set(re.findall(r"[a-z]+", text.lower()))
    v = [len(words & t) for t in TOPICS.values()]
    n = math.sqrt(sum(x * x for x in v)) or 1
    return [x / n for x in v]

policy = ("You can return a bike within 30 days for a full refund if it is unused and in the box. "
          "The battery has a 2 year warranty and the frame 5 years. Delivery is free and we ship in 2 days.")
chunks = split(policy, size=90, overlap=20)
for i, c in enumerate(chunks):
    print(f"chunk {i}: {c}")

query = "how many days to return it?"
q = embed(query)
scored = sorted(((sum(a * b for a, b in zip(q, embed(c))), c) for c in chunks), reverse=True)
print(f"\nTop 2 for {query!r}:")
for score, c in scored[:2]:
    print(f"  {score:.2f}  {c}")

The overlap repeated “unused and in the box” at the start of the second chunk. That's the trade-off: overlap protects sentences that span a boundary, but repeated text can also make a chunk look a little relevant to a query it isn't really about (score 0.30 here).

How many results, and how relevant?

  • k sets how many chunks come back. Too few and the answer may be missing; too many and the prompt fills with noise.
  • Relevance scores: store.similarity_search_with_score(query, k=4) returns each document with its score, so you can drop weak matches yourself, for example keeping only scores above 0.5. Many vector store integrations also support search_type="similarity_score_threshold" in as_retriever.
  • search_type="mmr" (maximal marginal relevance) picks results that are relevant but different from each other, avoiding five near-identical chunks.

A RAG chain

Now connect the retriever to a prompt and a model. The dictionary at the start runs the retriever on the question and formats the documents, while passing the question through unchanged:

from langchain.chat_models import init_chat_model
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough

def format_docs(docs):
    return "\n\n".join(f"[{d.metadata['source']}] {d.page_content}" for d in docs)

prompt = ChatPromptTemplate.from_messages([
    ("system", "Answer using only the context below, and cite sources in square brackets. "
               "If the answer isn't in the context, say you don't know.\n\nContext:\n{context}"),
    ("human", "{question}"),
])
model = init_chat_model("anthropic:MODEL_NAME")

rag = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | model
    | StrOutputParser()
)
print(rag.invoke("How many days do I have to return a bike?"))
Output
You can return a bike within 30 days of delivery for a full refund, as long as it's unused and in its original box [returns-policy.md].

The prompt does three important jobs: it tells the model to answer only from the context, to cite sources, and to say it doesn't know when the context has no answer. Without that last instruction, models fill gaps from their general knowledge, which for company policies means confident, wrong answers.

Common mistakes

Practice exercise

Split text into overlapping chunks, the job a text splitter does before documents are embedded.

Your solutionPython
words = "one two three four five six seven eight nine ten".split()
size, overlap = 4, 1

# Make chunks of `size` words. Each chunk starts `size - overlap` words after the previous one,
# so neighbouring chunks share `overlap` words. Stop once a chunk reaches the last word.
# Print each chunk as a string, one per line.
Knowledge check

Why do text splitters use chunk_overlap?

Summary

  • A Document holds page_content and metadata (keep the source).
  • Split with overlap, embed with init_embeddings, store in a vector store, and retrieve with as_retriever.
  • Tune k, filter by score, and use MMR for variety.
  • A RAG chain formats retrieved documents into a prompt that answers only from context, cites sources and admits when it doesn't know.

Next: tools in LangChain.

Finished reading? Tick it off to track your progress.