AI Engineering · Build lab 8 of 14

RAG with LangChain in Python: loaders, splitters, vector stores, LCEL chains and streaming

Rebuild the lab 6 handbook RAG with LangChain 1.x: ChatOpenAI and OpenAIEmbeddings on Ollama, a loader, two splitters, InMemoryVectorStore then Chroma, and an LCEL chain that cites its sources, refuses weak retrieval and streams. Then compare it with the from-scratch version, job by job.

⏱ 70 minIntermediate💸 Free (local models)10 steps

Python 3.12uvOllamallama3.2:3bnomic-embed-textlangchain-core 1.8langchain-openai 1.8langchain-text-splitters 1.2Chroma (optional)

Overview video

1 / 7

0 of 10 steps done

What you will build

The same question answering tool for the Larkspur handbook as lab 6: ask "How much can I spend on a hotel in London?" and get an answer from the handbook with a citation like [1] that points to the file and section. When nothing relevant is found, it refuses without calling the model.

This time LangChain does the plumbing: ChatOpenAI and OpenAIEmbeddings talk to Ollama, a loader turns files into Document objects, two splitters cut them by heading and by size, a vector store keeps the vectors (in memory, then Chroma on disk), a prompt template builds the messages and an LCEL chain (prompt | llm | parser) wires it together, returns the sources and streams the answer word by word.

Because you built every part by hand in lab 6, you can see exactly what each LangChain piece does for you, and what it hides. The last step puts both versions side by side. The tests use LangChain's own fake chat model and a fake embedding model, so they need no Ollama.

Before you start

Setup

S1Install uv (the Python project tool)

Skip this if you did lab 1. uv installs Python for you, creates the virtual environment and manages packages. One tool instead of pyenv + venv + pip.

Run
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
You should see
everything's installed!

S2Check uv works

The export PATH=... line makes uv work in this terminal right away. New terminal windows find it on their own (the installer added it to your shell settings). On Windows, open a new terminal after installing.

Run
uv --version
You should see
uv 0.x.y

S3Install Ollama (runs models on your machine)

Skip this if you did lab 1. Download it from ollama.com/download and open it once. It runs a small server on port 11434 with an OpenAI-compatible API under /v1, for chat and for embeddings. That is why LangChain's OpenAI classes work with it.

Run
ollama --version
You should see
ollama version is 0.x.y

S4Pull the chat model and the embedding model

The same two models as lab 6: llama3.2:3b (about 2 GB) writes the answers, nomic-embed-text (about 270 MB) turns text into 768 numbers. ollama list should show both afterwards.

Run
ollama pull llama3.2:3b
ollama pull nomic-embed-text
ollama list
You should seeyour text will differ: the model writes it
NAME                       ID              SIZE      MODIFIED
nomic-embed-text:latest    0a109f422b47    274 MB    2 seconds ago
llama3.2:3b                a80c4f17acd5    2.0 GB    3 days ago
1

Create the project

A fresh project with the three LangChain packages this lab needs, pinned, plus the settings from lab 6.

uv init creates the project folder and pyproject.toml (the project file, like package.json or pom.xml). uv add installs packages into the project's own virtual environment and records them, so anyone can recreate it with uv sync.

LangChain is not one package but a family. This lab uses three of them, all from the LangChain 1.x line: langchain-core (the building blocks: Document, prompts, vector store and retriever interfaces, the | chains), langchain-openai (ChatOpenAI and OpenAIEmbeddings, which work with any OpenAI-compatible server, Ollama included) and langchain-text-splitters (the chunkers). The package called just langchain (1.5 at the time of writing) is now mostly about agents and pulls in LangGraph; the next lab uses it, this one does not need it.

We pin exact versions (==) because LangChain moves fast and renames things between releases; every line in this lab was run against these versions. The quotes keep zsh and bash from reading anything in them as shell syntax. numpy is needed too: LangChain's in-memory vector store computes cosine similarity with it but does not install it for you.

The settings are lab 6's without the database URL. Copy .env, config.py and .gitignore from below.

.env
# Local models through Ollama (free). Ollama ignores the key, but the SDK needs a value.
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
LLM_MODEL=llama3.2:3b
EMBED_MODEL=nomic-embed-text

# Retrieval: below this cosine similarity a chunk does not count as relevant.
MIN_SCORE=0.65
  1. Ollama's OpenAI-compatible API. ChatOpenAI and OpenAIEmbeddings both get this URL as base_url.line 2
  2. Ollama ignores the key, but the OpenAI client refuses to start without one, so any text works.line 3
  3. Documents and questions must be embedded by the **same** model, or their vectors cannot be compared.line 5
  4. The same threshold as lab 6, measured there on real questions. With the same embedding model, the scores here are the same.line 8
config.py
import os
from dataclasses import dataclass

from dotenv import load_dotenv

load_dotenv()  # read .env into environment variables (real env vars win)


@dataclass(frozen=True)
class Settings:
    base_url: str
    api_key: str
    model: str
    embed_model: str
    min_score: float


def settings() -> Settings:
    return Settings(
        base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
        api_key=os.environ.get("LLM_API_KEY", "ollama"),
        model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
        embed_model=os.environ.get("EMBED_MODEL", "nomic-embed-text"),
        min_score=float(os.environ.get("MIN_SCORE", "0.65")),
    )
  1. load_dotenv() copies .env into os.environ. Variables already set in your shell or on the server take priority.line 6
  2. frozen=True makes the settings read-only, like a Java record.line 9
  3. Environment variables are always strings. float(...) turns "0.65" into a number, like Double.parseDouble.line 24
.gitignore
.venv/
__pycache__/
.env
index.json
chroma/
  1. Never commit .env: one day it holds a real key.line 3
  2. The saved in-memory store (step 4). It is rebuilt from the handbook, so it does not belong in git.line 4
  3. Chroma's database folder (step 8). Also rebuilt by ingest.py.line 5
Run
uv init rag-langchain
cd rag-langchain
uv add "langchain-core==1.8.5" "langchain-openai==1.8.5" "langchain-text-splitters==1.2.0" numpy python-dotenv
uv add --dev pytest
You should seeyour text will differ: the model writes it
Initialized project `rag-langchain` at `.../rag-langchain`
Resolved 43 packages in 600ms
Installed 41 packages in 60ms
 + langchain-core==1.8.5
 + langchain-openai==1.8.5
 + langchain-text-splitters==1.2.0
 + langsmith==0.16.2
 + numpy==2.5.5
 + openai==3.60.0
 + python-dotenv==1.2.4
 + tiktoken==0.14.0
 ...
Stuck on this step?
uv: command not found
Run export PATH="$HOME/.local/bin:$PATH" (macOS and Linux), or open a new terminal so the installer's PATH change applies.
uv also created main.py
Newer uv versions write a hello-world main.py. This lab does not use it: delete it or leave it.
No solution found when resolving dependencies mentioning requires-python
These LangChain versions need Python 3.11 or newer. Run uv python pin 3.12 in the project folder, then the uv add line again.
2

Talk to Ollama through LangChain

A chat model and an embedding model as LangChain objects, pointed at Ollama, with nomic's task prefixes added for you.

ChatOpenAI is LangChain's wrapper around the same OpenAI SDK you used in lab 1. You give it the model, base_url and api_key, and it sends the same POST /v1/chat/completions. What you get back is an AIMessage object instead of raw JSON: the text is in .content, the token counts in .usage_metadata.

OpenAIEmbeddings needs one setting you would never guess: check_embedding_ctx_length=False. By default it first cuts every text into tokens with OpenAI's tokenizer (the tiktoken package) and sends lists of token numbers instead of text, so it can split texts that are too long for OpenAI's models. Ollama and most other servers only accept text, and their models use different tokenizers anyway. False sends plain strings, exactly what lab 6 sent.

LangChain does not know that nomic-embed-text expects search_document: before every chunk and search_query: before every question (lab 6, step 4). So you add them yourself, with a small class that implements LangChain's Embeddings interface: two methods, embed_documents and embed_query. Every vector store calls exactly these two, so wrapping them changes what every store sends.

models.py
from langchain_core.embeddings import Embeddings
from langchain_openai import ChatOpenAI, OpenAIEmbeddings

from config import settings

# nomic-embed-text was trained with a task prefix on every text: one for documents, one for questions.
DOC_PREFIX = "search_document: "
QUERY_PREFIX = "search_query: "


class NomicEmbeddings(Embeddings):
    """Adds nomic's task prefixes, then lets another Embeddings object do the real work."""

    def __init__(self, inner: Embeddings):
        self.inner = inner

    def embed_documents(self, texts: list[str]) -> list[list[float]]:
        return self.inner.embed_documents([DOC_PREFIX + t for t in texts])

    def embed_query(self, text: str) -> list[float]:
        return self.inner.embed_query(QUERY_PREFIX + text)


def make_chat() -> ChatOpenAI:
    s = settings()
    return ChatOpenAI(
        model=s.model,
        base_url=s.base_url,
        api_key=s.api_key,
        temperature=0,
        timeout=120,
        max_retries=2,
    )


def make_embeddings() -> Embeddings:
    s = settings()
    openai_embeddings = OpenAIEmbeddings(
        model=s.embed_model,
        base_url=s.base_url,
        api_key=s.api_key,
        check_embedding_ctx_length=False,
    )
    return NomicEmbeddings(openai_embeddings)
  1. The same prefixes as lab 6. Other embedding models use other prefixes, or none: read the model card.line 7
  2. class NomicEmbeddings(Embeddings) extends LangChain's abstract base class, like implements Embeddings in Java. It has two abstract methods; Python refuses to create the object if one is missing.line 11
  3. The **decorator pattern**: it wraps another Embeddings (here OpenAIEmbeddings) and adds the prefix before passing the call on.line 14
  4. A list comprehension: a new list with the prefix in front of every text, like texts.stream().map(t -> DOC_PREFIX + t).toList().line 18
  5. ChatOpenAI accepts the same names you used with the SDK: model, base_url, api_key. Change .env and the same code talks to a hosted API.line 26
  6. Temperature 0: the most likely words. For answering from documents you want faithful, repeatable answers.line 30
  7. Seconds before a call gives up, and how often the SDK retries timeouts, 429 and 5xx errors. Both are passed straight to the OpenAI client underneath.line 31
  8. Send plain text, not tiktoken token ids. Without this line the request carries lists of numbers instead of strings, which Ollama does not accept, and the call fails. Needed for most non-OpenAI embedding servers.line 42
  9. The rest of the code only ever sees NomicEmbeddings, so the prefixes cannot be forgotten.line 44
hello.py
from models import make_chat, make_embeddings

chat = make_chat()
reply = chat.invoke("In one sentence: what is a vector database?")
print(type(reply).__name__, "->", reply.content)
print("tokens:", reply.usage_metadata)

vector = make_embeddings().embed_query("How much can I spend on a hotel?")
print(f"embedding: {len(vector)} numbers, starting {[round(x, 3) for x in vector[:3]]}")
  1. invoke is the one method every LangChain building block has: give it an input, get the output. A plain string becomes one user message.line 4
  2. type(reply).__name__ prints the class name, like reply.getClass().getSimpleName().line 5
  3. usage_metadata is LangChain's provider-neutral version of usage: input_tokens and output_tokens instead of prompt_tokens and completion_tokens.line 6
  4. embed_query adds search_query: (our wrapper) and returns a plain Python list of 768 floats.line 8
Run
uv run hello.py
You should seeyour text will differ: the model writes it
AIMessage -> A vector database is a database that stores data as numeric vectors and finds the most similar ones quickly.
tokens: {'input_tokens': 37, 'output_tokens': 23, 'total_tokens': 60, 'input_token_details': {}, 'output_token_details': {}}
embedding: 768 numbers, starting [-0.043, 0.118, -0.19]
Why this way? LangChain's value is one interface per job. ChatOpenAI, ChatAnthropic and ChatOllama (from the langchain-ollama package) all have invoke and stream and return an AIMessage, so the rest of your code does not care which one it gets. We use ChatOpenAI because Ollama, vLLM and most hosted APIs speak the OpenAI protocol: three lines in .env move the same code from your laptop to production.
Stuck on this step?
openai.APIConnectionError: Connection error.
Ollama is not running. Open the Ollama app or run ollama serve. LangChain passes the OpenAI SDK's own exceptions through, so the error names are the ones from lab 1.
openai.NotFoundError: ... model "nomic-embed-text" not found
You have not pulled the embedding model: run ollama pull nomic-embed-text.
openai.BadRequestError: Error code: 400 from the embeddings call
check_embedding_ctx_length=False is missing, so token ids were sent instead of text. Add it as in line 42.
3

Load the handbook and split it

Turn eight Markdown files into 30 chunks with LangChain's Document, a loader and two splitters, and get the same chunks as lab 6.

The handbook. Make a folder called handbook with the eight files below: the same made-up company handbook as lab 6, so the model cannot know the answers from training. If you did lab 6, copy the folder instead: cp -r ../rag-handbook/handbook . (Windows: Copy-Item -Recurse ..\rag-handbook\handbook .).

Document. Everything in LangChain RAG passes around Document objects: page_content (the text), metadata (a dict: file name, heading, anything you like) and an optional id. It is lab 6's Chunk class, with the extra fields moved into one dict.

A loader turns some source into Documents. LangChain has hundreds (PDF, web pages, Notion, S3), but they all implement one tiny interface from langchain-core: BaseLoader, with one method, lazy_load, that yields Documents one at a time; load() collects them into a list. Writing our own takes eight lines and has no extra dependencies. The ready-made DirectoryLoader and TextLoader live in the separate langchain-community package, which is being wound down (version 0.4.2 prints a deprecation warning when you import it), and DirectoryLoader returns files in whatever order the file system lists them; ours sorts them, so chunk ids are the same on every machine.

Two splitters. MarkdownHeaderTextSplitter does what lab 6's split_sections did: it cuts at # and ## headings and puts the heading titles into the metadata ({"h1": "Travel and expenses", "h2": "Hotels"}). RecursiveCharacterTextSplitter then cuts any section longer than chunk_size characters. It tries the separators in order, blank line, then newline, then space, then between characters, and uses the first one that makes the pieces small enough. chunk_overlap is a maximum: the next piece starts with as many whole trailing pieces of the previous one as fit into 200 characters. Here that is exactly one line, like lab 6's one-paragraph overlap.

One thing the header splitter does quietly: it joins the lines of a section with two spaces and a newline (" \n", a Markdown line break), so the blank lines between paragraphs are gone. Line 18 turns them back into plain newlines.

handbook/expenses.md
# Travel and expenses

## Booking travel
Book all work travel in TravelDesk, at least 14 days ahead when you can. Fly economy class. For trips under four hours, take the train instead of flying.

Your manager approves each trip in TravelDesk before you book. Trips to a customer also need the account owner's approval.

## Hotels
Hotels are covered up to 180 euros a night. In London, Paris and New York the limit is 250 euros a night.

Book a hotel within walking distance or a short public transport ride of where you work. Breakfast is included in the limit when the hotel sells it with the room.

If a conference hotel costs more than the limit, ask your manager before booking. Approved exceptions are noted on the trip in TravelDesk, so finance can see them when you submit the bill.

## Meals
On a work trip, meals are covered up to 60 euros a day. Alcohol is not covered.

## Submitting expenses
Submit expenses in Peoplebase within 30 days, with a photo of every receipt. They are paid with your next salary.
  1. The longest section (three paragraphs, about 460 characters), so it becomes two chunks.line 8
  2. The answer to the question you ask in step 6: 250 euros a night in London.line 9
handbook/time-off.md
# Time off

## Vacation
Everyone gets 25 vacation days a year, plus the public holidays of the country you work from. The year runs from January to December.

You can carry up to 5 unused days into the next year. Carried days expire on 31 March.

## Sick leave
There is no fixed number of sick days. Tell your manager before 10:00 on the first day. From the fourth day in a row, send a doctor's note to the People team.

## Parental leave
Every parent gets 16 weeks of fully paid leave, to take within the first year after a birth or adoption. You can split it into up to three blocks.

## How to request time off
Request time off in Peoplebase. For more than three days in a row, ask at least two weeks ahead.
handbook/remote-work.md
# Remote work

## Where you can work
You can work from any country where Larkspur has a company: Portugal, Spain, Germany or the United Kingdom.

Working from another country is allowed for up to 30 days a year. Tell the People team before you go, because of tax and insurance rules.

## Core hours
Be available from 11:00 to 15:00 Lisbon time. Outside core hours, plan your day as you like.

## Home office budget
New joiners get a one-time budget of 1,000 euros for a desk, a chair and a screen. Internet at home is paid with 40 euros a month on top of your salary.
handbook/security.md
# Security

## Your laptop
Laptops use full-disk encryption and lock after 5 minutes. Never leave your laptop in a car, not even in the trunk.

## Passwords and two-factor login
Use the company password manager for every work account. Turn on two-factor login with the hardware key you get on your first day.

## Lost or stolen devices
If a laptop, phone or hardware key is lost or stolen, report it in the #security-help channel within one hour, or email security@larkspur.example. The security team locks the device remotely.

## Phishing
Forward suspicious emails to phishing@larkspur.example and delete them. The finance team never asks for payments by email or chat.
handbook/onboarding.md
# Your first week

## Before day one
Your laptop and hardware key arrive at your home address a few days before you start. Do not set them up yet.

## Day one
The welcome call starts at 10:00 Lisbon time. You meet your onboarding buddy, who sets up the laptop with you and answers questions for your first month.

## First week checklist
Read this handbook, set up the password manager, book a coffee chat with each person on your team, and ship one small change to production.
handbook/on-call.md
# On-call

## The rotation
Engineers join the on-call rotation after three months at Larkspur. A shift lasts one week, from Monday 10:00 to the next Monday 10:00.

## On-call pay
You get 300 euros for each week on call, plus 50 euros for each incident you handle outside working hours.

## Responding to a page
Acknowledge a page within 15 minutes. If you cannot fix it within 30 minutes, escalate to the secondary on-call engineer.

## After an incident
Write a blameless postmortem within five working days and share it in the #incidents channel.
handbook/benefits.md
# Benefits

## Health insurance
Private health insurance covers you, your partner and your children from your first day.

## Learning budget
Each person has 1,500 euros a year for books, courses and conferences. Spending over 500 euros at once needs your manager's approval.

## Equipment
You get a new laptop every three years. A broken laptop is replaced straight away.

## Wellbeing
Larkspur pays up to 50 euros a month towards a gym, a sports club or a meditation app.
handbook/offices.md
# Offices

## The Lisbon office
The Lisbon office is open from 08:00 to 20:00 on working days. Guests sign in at reception and wear a visitor badge.

## Meeting rooms
Book meeting rooms in the office calendar. Free a room you no longer need, so others can use it.

## Team weeks
Each team meets in Lisbon for one week, twice a year. Larkspur pays the travel and the hotel for team weeks.
loader.py
from collections.abc import Iterator
from pathlib import Path

from langchain_core.document_loaders import BaseLoader
from langchain_core.documents import Document


class MarkdownFolderLoader(BaseLoader):
    """One Document per Markdown file in a folder, in file name order."""

    def __init__(self, folder: str):
        self.folder = Path(folder)

    def lazy_load(self) -> Iterator[Document]:
        for path in sorted(self.folder.glob("*.md")):
            text = path.read_text(encoding="utf-8")
            yield Document(page_content=text, metadata={"source": path.name})
  1. Iterator[Document] is the type of what a generator function returns: something you can loop over once, like Java's Iterator<Document>.line 1
  2. Extending BaseLoader gives you load() for free; you only write lazy_load.line 8
  3. A **generator**: yield hands out one Document and pauses until the caller asks for the next. A loader over a million files never holds them all in memory.line 14
  4. sorted(...) so the order, and so the chunk ids, is the same on every machine. glob("*.md") lists the Markdown files.line 15
  5. Only the file name goes into the metadata. It comes back later in every citation.line 17
chunking.py
from langchain_core.documents import Document
from langchain_text_splitters import MarkdownHeaderTextSplitter, RecursiveCharacterTextSplitter

from loader import MarkdownFolderLoader

HEADERS = [("#", "h1"), ("##", "h2")]


def split_documents(docs: list[Document], chunk_size: int = 400, chunk_overlap: int = 200) -> list[Document]:
    """Cut every file at its headings, then cut long sections to at most chunk_size characters."""
    by_heading = MarkdownHeaderTextSplitter(headers_to_split_on=HEADERS)
    by_size = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
    chunks = []
    for doc in docs:
        source = doc.metadata["source"]
        sections = by_heading.split_text(doc.page_content)
        for section in sections:
            section.page_content = section.page_content.replace("  \n", "\n")
        for n, piece in enumerate(by_size.split_documents(sections)):
            heading = " > ".join(piece.metadata[key] for _, key in HEADERS if key in piece.metadata)
            chunks.append(Document(
                id=f"{source}#{n}",
                page_content=f"{heading}\n{piece.page_content}",
                metadata={"source": source, "heading": heading},
            ))
    return chunks


def load_handbook(folder: str = "handbook") -> list[Document]:
    return split_documents(MarkdownFolderLoader(folder).load())
  1. Which headings to cut at, and the metadata key for each: # goes to h1, ## to h2. ### headings would stay inside the text.line 6
  2. 400 characters and a maximum of 200 characters of overlap: the same sizes as lab 6, so you get the same 30 chunks.line 9
  3. The default separators are ["\n\n", "\n", " ", ""]: paragraph, line, word, character.line 12
  4. split_text takes a string and returns one Document per section, with the heading titles in its metadata. The file name is not there: we add it below.line 16
  5. Undo the header splitter's Markdown line breaks (" \n", two spaces and a newline), so the chunk text is clean.line 18
  6. split_documents keeps each section's metadata on every piece. enumerate numbers the pieces 0, 1, 2 ... within one file.line 19
  7. The heading path, Travel and expenses > Hotels. A generator expression inside join: for every (marker, key) pair in HEADERS, take that key from the metadata if it is there. _ is the name Python uses for a value you ignore.line 20
  8. A readable, stable id: expenses.md#1. Vector stores use Document.id as their key, so ingesting twice replaces chunks instead of duplicating them.line 22
  9. The heading goes **into the text**. A vector store embeds page_content and nothing else: metadata is never embedded. Lab 6 did the same in for_embedding(); here the model sees the heading in its sources too.line 23
show_chunks.py
from chunking import load_handbook
from loader import MarkdownFolderLoader

files = MarkdownFolderLoader("handbook").load()
print(f"Loaded {len(files)} files. The first one:")
print(f"  metadata: {files[0].metadata}")
print(f"  page_content: {files[0].page_content[:40]!r}...")

chunks = load_handbook("handbook")
print()
for c in chunks:
    print(f"{c.id:<16} {c.metadata['heading']:<42} {len(c.page_content):>3} chars")
print(f"\n{len(chunks)} chunks from {len({c.metadata['source'] for c in chunks})} files")

print("\nThe Hotels section is too long for one chunk. The overlap repeats a line:")
for c in chunks:
    if c.metadata["heading"].endswith("Hotels"):
        print(f"\n[{c.id}]\n{c.page_content}")
  1. !r prints the repr of the string: with quotes and \n visible, so you can see exactly what the loader read.line 7
  2. Format specs: :<16 pads to 16 characters, left-aligned; :>3 right-aligns. Like String.format("%-16s") in Java.line 12
  3. {c.metadata['source'] for c in chunks} is a set comprehension: the distinct file names.line 13
Run
uv run show_chunks.py
You should see
warning: The `UV_NATIVE_TLS` environment variable is deprecated and will be removed in a future release. Use `UV_SYSTEM_CERTS` instead.
Loaded 8 files. The first one:
  metadata: {'source': 'benefits.md'}
  page_content: '# Benefits\n\n## Health insurance\nPrivate '...

benefits.md#0    Benefits > Health insurance                116 chars
benefits.md#1    Benefits > Learning budget                 160 chars
benefits.md#2    Benefits > Equipment                       103 chars
benefits.md#3    Benefits > Wellbeing                       107 chars
expenses.md#0    Travel and expenses > Booking travel       313 chars
expenses.md#1    Travel and expenses > Hotels               297 chars
expenses.md#2    Travel and expenses > Hotels               380 chars
expenses.md#3    Travel and expenses > Meals                107 chars
expenses.md#4    Travel and expenses > Submitting expenses  155 chars
offices.md#0     Offices > The Lisbon office                144 chars
offices.md#1     Offices > Meeting rooms                    120 chars
offices.md#2     Offices > Team weeks                       129 chars
on-call.md#0     On-call > The rotation                     158 chars
on-call.md#1     On-call > On-call pay                      128 chars
on-call.md#2     On-call > Responding to a page             152 chars
on-call.md#3     On-call > After an incident                121 chars
onboarding.md#0  Your first week > Before day one           142 chars
onboarding.md#1  Your first week > Day one                  179 chars
onboarding.md#2  Your first week > First week checklist     178 chars
remote-work.md#0 Remote work > Where you can work           278 chars
remote-work.md#1 Remote work > Core hours                   117 chars
remote-work.md#2 Remote work > Home office budget           185 chars
security.md#0    Security > Your laptop                     138 chars
security.md#1    Security > Passwords and two-factor login  172 chars
security.md#2    Security > Lost or stolen devices          225 chars
security.md#3    Security > Phishing                        150 chars
time-off.md#0    Time off > Vacation                        240 chars
time-off.md#1    Time off > Sick leave                      180 chars
time-off.md#2    Time off > Parental leave                  172 chars
time-off.md#3    Time off > How to request time off         131 chars

30 chunks from 8 files

The Hotels section is too long for one chunk. The overlap repeats a line:

[expenses.md#1]
Travel and expenses > Hotels
Hotels are covered up to 180 euros a night. In London, Paris and New York the limit is 250 euros a night.
Book a hotel within walking distance or a short public transport ride of where you work. Breakfast is included in the limit when the hotel sells it with the room.

[expenses.md#2]
Travel and expenses > Hotels
Book a hotel within walking distance or a short public transport ride of where you work. Breakfast is included in the limit when the hotel sells it with the room.
If a conference hotel costs more than the limit, ask your manager before booking. Approved exceptions are noted on the trip in TravelDesk, so finance can see them when you submit the bill.
Why this way? The chunk borders are identical to lab 6, but you wrote 20 lines instead of 80. That is the honest trade: LangChain's splitters are well tested and cover cases you did not think of (code, very long lines, other languages), but their behaviour lives in their source code, not yours. When retrieval is bad, print the chunks, as here, before you blame the model.
Stuck on this step?
Loaded 0 files
The handbook folder is not next to show_chunks.py, or the files do not end in .md. Run the command from the project folder.
You get more or fewer than 30 chunks
A handbook file differs from the ones above (often a missing blank line before a ## heading, or a changed Hotels section). Compare with the files above, or copy them again.
4

Embed, store and search

Put the chunks into LangChain's InMemoryVectorStore, save it to a file, and see the scores for a question.

A LangChain vector store takes Documents and an Embeddings object. add_documents calls embed_documents on all the texts, and stores each vector with its Document. similarity_search(question, k=4) calls embed_query and returns the 4 closest Documents. InMemoryVectorStore (in langchain-core) keeps everything in a Python dict and computes cosine similarity with NumPy, like lab 6's InMemoryStore. dump() and load() save it to a JSON file and read it back.

What does a score mean? That depends on the store, and it is the classic LangChain trap. similarity_search_with_score returns whatever the store computes: a similarity for InMemoryVectorStore (higher is closer) but a distance for Chroma and many others (lower is closer). similarity_search_with_relevance_scores is the method that converts every store's number into a 0-to-1 relevance where higher is closer, so a threshold like 0.65 means the same thing everywhere. Each store has to say how to convert, and InMemoryVectorStore does not: calling it raises NotImplementedError. Our subclass says "the score already is the relevance" in three lines.

store.py hides which store you use behind two functions: open_store (for asking) and rebuild (for ingesting). Step 8 adds Chroma there and nothing else changes.

store.py
from pathlib import Path

from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.vectorstores import InMemoryVectorStore, VectorStore

INDEX = Path("index.json")
STORES = ("memory",)


class ScoredInMemoryVectorStore(InMemoryVectorStore):
    """InMemoryVectorStore already scores by cosine similarity (1.0 = same direction).
    Saying so here is what makes similarity_search_with_relevance_scores work."""

    def _select_relevance_score_fn(self):
        return lambda score: score


def open_store(kind: str, embeddings: Embeddings) -> VectorStore:
    if kind == "memory":
        if INDEX.exists():
            return ScoredInMemoryVectorStore.load(str(INDEX), embeddings)
        return ScoredInMemoryVectorStore(embeddings)
    raise ValueError(f"unknown store {kind!r}, choose one of {STORES}")


def rebuild(kind: str, embeddings: Embeddings, chunks: list[Document]) -> VectorStore:
    """Throw away what the store held and add every chunk again."""
    if kind == "memory":
        store = ScoredInMemoryVectorStore(embeddings)
        store.add_documents(chunks)
        store.dump(str(INDEX))
        return store
    raise ValueError(f"unknown store {kind!r}, choose one of {STORES}")


def count(store: InMemoryVectorStore) -> int:
    return len(store.store)
  1. Path is the file path type from the standard library, like java.nio.file.Path.line 7
  2. A subclass that changes one thing. Everything else (add, search, dump, load) is inherited.line 11
  3. The method the base class calls to turn a raw score into a relevance score. The leading _ means "internal", but it is the documented way to adapt a store. lambda score: score is a function that returns its input, like s -> s.line 15
  4. load is a class method: it creates a new store of **our** class and fills it from the JSON file. The embeddings object is needed again, to embed questions.line 22
  5. add_documents embeds all 30 texts (in batches, by default up to 1000 per request) and stores them under their id.line 31
  6. Writes every Document and its vector to index.json (about 650 KB here). The next run loads it instead of embedding again.line 32
  7. The in-memory store keeps its data in a plain dict called store, keyed by id. Step 8 makes this work for Chroma too.line 37
ingest.py
import argparse
import time

from chunking import load_handbook
from models import make_embeddings
from store import STORES, count, rebuild

parser = argparse.ArgumentParser(description="Load, split, embed and store the handbook.")
parser.add_argument("--store", choices=STORES, default="memory")
args = parser.parse_args()

chunks = load_handbook("handbook")
start = time.perf_counter()
store = rebuild(args.store, make_embeddings(), chunks)
seconds = time.perf_counter() - start
print(f"Embedded and stored {len(chunks)} chunks in {seconds:.1f}s")
print(f"The {args.store} store now holds {count(store)} chunks")
  1. choices=STORES makes argparse reject unknown names with a clear message, and default="memory" is used when you leave the option out.line 9
  2. time.perf_counter() is a precise clock for measuring durations, like System.nanoTime().line 13
  3. The whole ingest in one line: a new store, every chunk embedded (with search_document: added by NomicEmbeddings) and saved.line 14
search.py
import sys

from models import make_embeddings
from store import open_store

question = " ".join(sys.argv[1:]) or "How much can I spend on a hotel?"
store = open_store("memory", make_embeddings())
for doc, score in store.similarity_search_with_relevance_scores(question, k=4):
    print(f"{score:.3f}  {doc.id:<16} {doc.metadata['heading']}")
  1. The words after the script name, joined into one question. With none, a default question.line 6
  2. Returns (Document, score) pairs, best first. The for doc, score in ... loop unpacks each pair, like destructuring in JavaScript.line 8
Run
uv run ingest.py
uv run search.py "How much can I spend on a hotel in London?"
You should seeyour text will differ: the model writes it
Embedded and stored 30 chunks in 2.1s
The memory store now holds 30 chunks
0.785  expenses.md#1    Travel and expenses > Hotels
0.679  expenses.md#2    Travel and expenses > Hotels
0.594  expenses.md#3    Travel and expenses > Meals
0.582  benefits.md#1    Benefits > Learning budget
Why this way? These are the same four chunks with the same scores as lab 6's search.py (0.785 for the first Hotels chunk), because the chunks, the prefixes and the model are the same. That is the best test that the LangChain version is right: compare it with a version you understand.
Stuck on this step?
ImportError: cosine_similarity requires numpy to be installed
Run uv add numpy. LangChain needs it for the in-memory store but does not install it.
NotImplementedError from similarity_search_with_relevance_scores
The store is a plain InMemoryVectorStore, not ScoredInMemoryVectorStore. Check open_store and rebuild both use the subclass.
ValueError: Number of columns in X and Y must be the same. X has shape (1, 8) and Y has shape (30, 768)
The saved index.json was built by a different embedding model than the one embedding the question (or a different server answered on port 11434). Check EMBED_MODEL and LLM_BASE_URL, then run uv run ingest.py again.
Your scores differ a little from the ones shown
Normal: they depend on the exact model build and your hardware. The order should be the same, with the two Hotels chunks on top.
5

A prompt template and your first LCEL chain

Build the prompt with ChatPromptTemplate, then wire retriever, prompt, model and parser into one chain with the | operator.

ChatPromptTemplate is lab 6's build_messages() as an object: a list of (role, template) pairs with {name} placeholders. PROMPT.invoke({"sources": ..., "question": ...}) fills them in and returns a prompt value that the chat model accepts. The rules are the same as lab 6: only the numbered sources, cite them, a fixed sentence when they do not answer. peek_prompt.py shows what the model will receive, with no model call.

LCEL (LangChain Expression Language) is the | operator. Every building block is a Runnable: an object with invoke (one input, one output), stream (output in pieces) and batch (many inputs). a | b makes a new Runnable that calls a, then gives its output to b, like a Unix pipe or Function.andThen in Java. Python lets a class decide what | means (the __or__ method), and LangChain uses that.

Two more rules make chains short. A plain function in a chain is wrapped in a RunnableLambda automatically. A dict in a chain runs every value with the same input and returns a dict of the results (a RunnableParallel). So {"sources": retriever | format_sources, "question": RunnablePassthrough()} turns the question into {"sources": "[1] expenses.md ...", "question": "How much ..."}: exactly the two names the prompt needs. RunnablePassthrough() passes its input through unchanged.

store.as_retriever() turns the store into a retriever: a Runnable that takes a question and returns a list of Documents. StrOutputParser takes the AIMessage and returns its text.

prompt.py
from langchain_core.documents import Document
from langchain_core.prompts import ChatPromptTemplate

NOT_FOUND = "I don't know. The handbook does not say."

SYSTEM = f"""You answer questions about the Larkspur employee handbook.
Rules:
- Use only the numbered sources in the user message. Do not use outside knowledge.
- After each fact, cite the number of its source in square brackets, like [1] or [2].
- If the sources do not answer the question, reply exactly: {NOT_FOUND}
- Keep the answer short: one to three sentences."""

PROMPT = ChatPromptTemplate.from_messages([
    ("system", SYSTEM),
    ("human", "Sources:\n\n{sources}\n\nQuestion: {question}"),
])


def format_sources(docs: list[Document]) -> str:
    """[1] file name, then the chunk (heading path and text). Numbered from 1, in ranking order."""
    blocks = [f"[{n}] {doc.metadata['source']}\n{doc.page_content}" for n, doc in enumerate(docs, start=1)]
    return "\n\n".join(blocks)
  1. One fixed sentence for "not in the handbook". Your code and your tests can recognise it.line 4
  2. An f-string, so {NOT_FOUND} is filled in **now**, by Python. The result becomes a template, so a { or } in this text would be read as a placeholder. To write a literal brace in a template, double it: {{.line 6
  3. from_messages takes (role, template) pairs. "human" is LangChain's name for the user role; it is sent as "user".line 13
  4. The sources and the question go in the user message, not the system message: documents are **data** and may contain text aimed at the model ([prompt injection](/ai/prompting/prompt-injection)).line 15
  5. [1] expenses.md, then the chunk, which starts with its heading path. enumerate(docs, start=1) numbers from 1, like a person counts.line 21
peek_prompt.py
from langchain_core.documents import Document

from prompt import PROMPT, format_sources

docs = [
    Document(page_content="Travel and expenses > Hotels\nIn London the limit is 250 euros a night.",
             metadata={"source": "expenses.md"}),
    Document(page_content="Travel and expenses > Meals\nMeals are covered up to 60 euros a day.",
             metadata={"source": "expenses.md"}),
]
prompt_value = PROMPT.invoke({"sources": format_sources(docs), "question": "Hotel limit in London?"})
for message in prompt_value.to_messages():
    print(f"--- {message.type} ---")
    print(message.content)
  1. A prompt template is a Runnable too: invoke with a dict of the placeholder values.line 11
  2. to_messages() returns the list of message objects the model will get. message.type is system, human or ai.line 12
rag.py
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import Runnable, RunnablePassthrough

from prompt import PROMPT, format_sources


def build_chain(retriever: Runnable, llm: Runnable) -> Runnable:
    """question (str) -> answer (str)"""
    return (
        {"sources": retriever | format_sources, "question": RunnablePassthrough()}
        | PROMPT
        | llm
        | StrOutputParser()
    )
  1. The retriever and the model come in as parameters. Tests pass fakes here (step 10).line 7
  2. Brackets around the whole chain only let it continue over several lines, like ( ... ) in any expression.line 9
  3. A dict step: both values get the question. retriever | format_sources turns it into the numbered sources text; RunnablePassthrough() keeps the question as it is.line 10
  4. Fills the template with the dict from line 10.line 11
  5. The chat model: prompt value in, AIMessage out. Anything with the Runnable methods works here.line 12
  6. AIMessage in, plain str out.line 13
ask.py
import sys

from models import make_chat, make_embeddings
from rag import build_chain
from store import open_store

question = " ".join(sys.argv[1:]) or "How much can I spend on a hotel in London?"
store = open_store("memory", make_embeddings())
retriever = store.as_retriever(search_kwargs={"k": 4})
chain = build_chain(retriever, make_chat())
print(chain.invoke(question))
  1. as_retriever wraps the store in a retriever. search_kwargs are passed to similarity_search: here, the 4 closest chunks.line 9
  2. The whole pipeline runs in this one call: embed the question, search, format, fill the prompt, call the model, take the text.line 11
Run
uv run peek_prompt.py
uv run ask.py "How much can I spend on a hotel in London?"
You should seeyour text will differ: the model writes it
--- system ---
You answer questions about the Larkspur employee handbook.
Rules:
- Use only the numbered sources in the user message. Do not use outside knowledge.
- After each fact, cite the number of its source in square brackets, like [1] or [2].
- If the sources do not answer the question, reply exactly: I don't know. The handbook does not say.
- Keep the answer short: one to three sentences.
--- human ---
Sources:

[1] expenses.md
Travel and expenses > Hotels
In London the limit is 250 euros a night.

[2] expenses.md
Travel and expenses > Meals
Meals are covered up to 60 euros a day.

Question: Hotel limit in London?
In London, hotels are covered up to 250 euros a night [1]. Breakfast is included in the limit when the hotel sells it with the room [1].
Why this way? A chain is data, not just code that runs: LangChain can stream it, batch it, run it async (ainvoke) and trace every step (with LangSmith or OpenTelemetry) without you writing any of that. The price is indirection: when something breaks, the stack trace goes through LangChain's Runnable classes (and the dict step runs its values in threads), so it is longer than your own function calls. Keep chains short, and keep the logic (refusal, citations) in plain functions you can test.
Stuck on this step?
KeyError: Input to ChatPromptTemplate is missing variables {'question'}
The dict before PROMPT must have exactly the placeholder names: sources and question. A typo in either name causes this.
TypeError: Expected mapping type as input to ChatPromptTemplate. Received <class 'str'>
A string reached the prompt directly. The dict step in line 10 must come before PROMPT.
6

Return the sources, cite them, and refuse when retrieval is weak

A chain that returns the question, the retrieved chunks with scores, the sources it used and the answer, and never calls the model when nothing is relevant.

The chain from step 5 returns only text, so you cannot print which files it used, and it always calls the model, even for "What is the capital of Australia?". Lab 6 solved both: keep the hits, drop those below the minimum score, refuse without a model call when nothing is left, and check the [n] citations. Here is the same logic as a chain.

A retriever with scores. as_retriever() returns Documents without their scores. (Its similarity_score_threshold mode filters by score, but throws the scores away and logs a warning to the terminal whenever nothing passes.) A retriever is just a Runnable from question to Documents, so make_retriever writes one with RunnableLambda and puts each relevance score into the Document's metadata.

RunnablePassthrough.assign(name=f) keeps the input dict and adds one key, computed from it. The chain grows a dict step by step: {retrieved, question}, then + sources (the relevant ones), then + answer. The final result has everything ask.py needs.

Refusing. answer_or_refuse returns either a plain string or the answer chain. When a function in a chain returns a Runnable, LangChain runs that Runnable with the same input; when it returns anything else, that is the result. So with no relevant sources the answer is the fixed sentence and the model is never called. This is LangChain's routing pattern.

cited_numbers is lab 6's function, unchanged: LangChain has no citation checker. ask.py gets --store and --debug options like lab 6.

rag.py 38 new or changed lines
import re

from langchain_core.documents import Document
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import Runnable, RunnableLambda, RunnablePassthrough
from langchain_core.vectorstores import VectorStore

from prompt import NOT_FOUND, PROMPT, format_sources

CITATION = re.compile(r"\[(\d+)\]")


def cited_numbers(text: str, n_sources: int) -> list[int]:
    """The source numbers cited in the text, in order, without repeats or made-up numbers."""
    found = []
    for match in CITATION.finditer(text):
        n = int(match.group(1))
        if 1 <= n <= n_sources and n not in found:
            found.append(n)
    return found


def make_retriever(store: VectorStore, k: int = 4) -> Runnable:
    """question -> the k closest chunks, each with its relevance score in metadata["score"]."""

    def retrieve(question: str) -> list[Document]:
        hits = store.similarity_search_with_relevance_scores(question, k=k)
        return [
            Document(id=doc.id, page_content=doc.page_content, metadata={**doc.metadata, "score": score})
            for doc, score in hits
        ]

    return RunnableLambda(retrieve)


def build_chain(retriever: Runnable, llm: Runnable, min_score: float = 0.65) -> Runnable:
    """question (str) -> {"retrieved": [...], "question": str, "sources": [...], "answer": str}"""
    answer_chain = (
        {"sources": lambda x: format_sources(x["sources"]), "question": lambda x: x["question"]}
        | PROMPT
        | llm
        | StrOutputParser()
    )

    def keep_relevant(x: dict) -> list[Document]:
        return [doc for doc in x["retrieved"] if doc.metadata["score"] >= min_score]

    def answer_or_refuse(x: dict):
        if not x["sources"]:
            return NOT_FOUND  # nothing relevant: the model is never called
        return answer_chain

    return (
        {"retrieved": retriever, "question": RunnablePassthrough()}
        | RunnablePassthrough.assign(sources=keep_relevant)
        | RunnablePassthrough.assign(answer=answer_or_refuse)
    )
  1. Matches [1], [12]: a literal [, one or more digits (captured), a literal ]. r"..." is a raw string, so \[ reaches the regex engine unchanged.line 10
  2. A chained comparison: 1 <= n <= n_sources means 1 <= n and n <= n_sources. It drops made-up numbers like [7] when there were four sources.line 18
  3. Works with any LangChain vector store: it only calls similarity_search_with_relevance_scores, which every store maps to 0 to 1, higher is closer.line 23
  4. A function inside a function. It can use store and k from the outer function, like a Java lambda capturing effectively final variables.line 26
  5. A new Document with the score added. {**doc.metadata, "score": score} copies the dict and adds a key, like {...meta, score} in JavaScript. Copying keeps the stored Document unchanged.line 29
  6. RunnableLambda turns the function into a Runnable, so it has invoke, stream and batch and can be piped with |.line 33
  7. The step 5 chain, now reading its input from a dict: x["sources"] is a list of Documents, x["question"] the question. The lambdas are wrapped as Runnables automatically.line 39
  8. The minimum score check from lab 6, as a list comprehension: like .stream().filter(...).toList().line 46
  9. The refusal: a plain string is the result, and the model is never called. Cheaper, faster and safe.line 50
  10. Returning a Runnable means "run this with the same input". The answer chain gets the whole dict.line 51
  11. The first step: retrieve the chunks and keep the question, both from the same input.line 54
  12. Adds sources: the retrieved chunks that pass the minimum score.line 55
  13. Adds answer: the fixed sentence, or the model's answer.line 56
ask.py
import argparse
import sys

import openai

from config import settings
from models import make_chat, make_embeddings
from rag import build_chain, cited_numbers, make_retriever
from store import STORES, count, open_store

parser = argparse.ArgumentParser(description="Ask the Larkspur handbook a question.")
parser.add_argument("question")
parser.add_argument("--store", choices=STORES, default="memory")
parser.add_argument("--debug", action="store_true", help="show the retrieved chunks and their scores")
args = parser.parse_args()

s = settings()
store = open_store(args.store, make_embeddings())
if count(store) == 0:
    sys.exit(f"The {args.store} store is empty. Run: uv run ingest.py --store {args.store}")

chain = build_chain(make_retriever(store), make_chat(), min_score=s.min_score)
try:
    result = chain.invoke(args.question)
except openai.APITimeoutError:
    sys.exit("The model took too long. Try again, or use a smaller model.")
except openai.APIConnectionError:
    sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
except openai.NotFoundError:
    sys.exit(f"A model is missing. Run: ollama pull {s.model} and ollama pull {s.embed_model}")

if args.debug:
    print(f"--- retrieved {len(result['retrieved'])} chunks, min score {s.min_score} ---")
    for doc in result["retrieved"]:
        status = "used" if doc in result["sources"] else "dropped"
        print(f"{doc.metadata['score']:.3f} {status:<7} {doc.id:<16} {doc.metadata['heading']}")
    print("---")

print(result["answer"])
sources = result["sources"]
cited = cited_numbers(result["answer"], len(sources))
if not sources:
    print("(no chunk reached the minimum score, so the model was not asked)")
elif cited:
    print("\nSources:")
    for n in cited:
        doc = sources[n - 1]
        print(f"  [{n}] {doc.metadata['source']} > {doc.metadata['heading']}")
else:
    print("\n(the answer cites no sources: check it before trusting it)")
  1. A positional argument: the question, in quotes on the command line.line 12
  2. action="store_true": a flag with no value. --debug present means args.debug is True.line 14
  3. Asking an empty store gives empty answers that look like a broken model. Fail early with the fix instead.line 19
  4. result is the dict the chain built: retrieved, question, sources and answer.line 24
  5. Timeout before connection error, on purpose: APITimeoutError is a subclass of APIConnectionError, and Python uses the first except that matches. LangChain lets the OpenAI SDK's exceptions through unchanged.line 25
  6. Ollama answers 404 for a model it does not have, chat or embedding.line 29
  7. doc in result["sources"] compares Documents by value (they are Pydantic models, which compare their fields), so it finds the same chunk in the other list.line 35
  8. {status:<7} pads to 7 characters, so the columns line up.line 36
  9. Citation [n] is sources[n - 1]: the list starts at 0, the numbers at 1.line 47
  10. No citation is a warning sign: the model may have answered from its own memory.line 50
Run
uv run ask.py --debug "How much can I spend on a hotel in London?"
uv run ask.py --debug "What is the capital of Australia?"
You should seeyour text will differ: the model writes it
--- retrieved 4 chunks, min score 0.65 ---
0.785 used    expenses.md#1    Travel and expenses > Hotels
0.679 used    expenses.md#2    Travel and expenses > Hotels
0.594 dropped expenses.md#3    Travel and expenses > Meals
0.582 dropped benefits.md#1    Benefits > Learning budget
---
In London, hotels are covered up to 250 euros a night [1]. Breakfast is included in that limit when the hotel sells it with the room [1].

Sources:
  [1] expenses.md > Travel and expenses > Hotels
--- retrieved 4 chunks, min score 0.65 ---
0.534 dropped remote-work.md#0 Remote work > Where you can work
0.521 dropped remote-work.md#1 Remote work > Core hours
0.508 dropped offices.md#2     Offices > Team weeks
0.506 dropped onboarding.md#1  Your first week > Day one
---
I don't know. The handbook does not say.
(no chunk reached the minimum score, so the model was not asked)
Why this way? The retrieval numbers match lab 6 exactly: the Hotels chunks pass 0.65, and for Australia nothing does, so the model is not asked. Lab 6 also showed why a threshold alone is not enough ("Who is the CEO of Larkspur?" just passes with 0.662), and the prompt rule handles that. The safety logic did not get shorter with LangChain; it moved into small functions inside the chain.
Stuck on this step?
Everything is refused, even good questions
Your scores are lower (another embedding model, or the prefixes are missing). Look at --debug, then lower MIN_SCORE in .env, or re-run uv run ingest.py if you changed the embeddings.
KeyError: 'score'
The retriever is still store.as_retriever() from step 5, which puts no score in the metadata. Use make_retriever(store).
7

Stream the answer

Print the answer word by word as the model writes it, with the sources first and the citations at the end.

Every Runnable has stream() as well as invoke(). For a chain, LangChain streams as far through it as it can: ChatOpenAI asks Ollama for a streamed reply ("stream": true, the server-sent events from lab 2), StrOutputParser passes each piece on, and the assign steps hand out the dict one key at a time: first question and retrieved, then sources, then many small answer pieces.

So chain.stream(question) is a generator of small dicts. ask.py prints each answer piece the moment it arrives (flush=True pushes it to the terminal right away instead of waiting for a full line), keeps everything else, and shows the --debug table as soon as sources is known, before the model has written a word. The refusal still works: the fixed sentence arrives as a single answer piece.

Citations can only be checked once the whole answer is there, so the Sources list comes at the end.

ask.py 23 new or changed lines
import argparse
import sys

import openai

from config import settings
from models import make_chat, make_embeddings
from rag import build_chain, cited_numbers, make_retriever
from store import STORES, count, open_store

parser = argparse.ArgumentParser(description="Ask the Larkspur handbook a question.")
parser.add_argument("question")
parser.add_argument("--store", choices=STORES, default="memory")
parser.add_argument("--debug", action="store_true", help="show the retrieved chunks and their scores")
args = parser.parse_args()

s = settings()
store = open_store(args.store, make_embeddings())
if count(store) == 0:
    sys.exit(f"The {args.store} store is empty. Run: uv run ingest.py --store {args.store}")


def show_retrieved(result: dict) -> None:
    print(f"--- retrieved {len(result['retrieved'])} chunks, min score {s.min_score} ---")
    for doc in result["retrieved"]:
        status = "used" if doc in result["sources"] else "dropped"
        print(f"{doc.metadata['score']:.3f} {status:<7} {doc.id:<16} {doc.metadata['heading']}")
    print("---")


chain = build_chain(make_retriever(store), make_chat(), min_score=s.min_score)
result = {"answer": ""}
try:
    for part in chain.stream(args.question):
        if "answer" in part:
            print(part["answer"], end="", flush=True)
            result["answer"] += part["answer"]
        else:
            result.update(part)
            if "sources" in part and args.debug:
                show_retrieved(result)
except openai.APITimeoutError:
    sys.exit("\nThe model took too long. Try again, or use a smaller model.")
except openai.APIConnectionError:
    sys.exit("\nCannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
except openai.NotFoundError:
    sys.exit(f"\nA model is missing. Run: ollama pull {s.model} and ollama pull {s.embed_model}")
print()

sources = result["sources"]
cited = cited_numbers(result["answer"], len(sources))
if not sources:
    print("(no chunk reached the minimum score, so the model was not asked)")
elif cited:
    print("\nSources:")
    for n in cited:
        doc = sources[n - 1]
        print(f"  [{n}] {doc.metadata['source']} > {doc.metadata['heading']}")
else:
    print("\n(the answer cites no sources: check it before trusting it)")
  1. The debug table moved into a function, because it is now printed from inside the loop.line 23
  2. The answer starts empty and grows piece by piece. Everything else is stored as it arrives.line 32
  3. Each part is a dict with one key: {"retrieved": [...]}, {"sources": [...]} or {"answer": "250 "}.line 34
  4. end="" prints no newline after the piece; flush=True sends it to the terminal now.line 36
  5. dict.update copies the part's key into result, like Map.putAll.line 39
  6. sources arrives after retrieved and before the first answer piece: the right moment for the debug table.line 40
  7. Errors can happen in the middle of the stream, after some text was printed, so each message starts on a new line (\n).line 43
  8. The streamed text did not end with a newline; this adds it.line 48
Run
uv run ask.py --debug "How many weeks of parental leave do I get?"
You should seeyour text will differ: the model writes it
--- retrieved 4 chunks, min score 0.65 ---
0.872 used    time-off.md#2    Time off > Parental leave
0.671 used    time-off.md#0    Time off > Vacation
0.631 dropped time-off.md#3    Time off > How to request time off
0.629 dropped time-off.md#1    Time off > Sick leave
---
You get 16 weeks of fully paid leave, to take within the first year after a birth or adoption [1].

Sources:
  [1] time-off.md > Time off > Parental leave
Why this way? Streaming does not make the answer faster, it makes it feel faster: the first words appear after a fraction of a second instead of after the whole answer. In a web app you would send the same pieces to the browser as server-sent events, exactly like lab 2, with the sources in the first event.
Stuck on this step?
The whole answer appears at once
Check flush=True on line 36. Some terminals and IDE consoles also buffer output; try a normal terminal.
The debug table never appears
Pass --debug before or after the question in quotes, for example uv run ask.py --debug "...".
8

Optional: swap in Chroma, a vector database on disk

Add Chroma behind the same two functions, ingest into it and ask the same question, with no change to the chain.

Chroma is an open-source vector database that runs inside your Python process and keeps its data in a folder (SQLite plus an HNSW index, like the one pgvector built in lab 6). langchain-chroma wraps it as a LangChain vector store. It is a big install (about 450 MB, mostly chromadb and its dependencies), so we add it as an optional extra named chroma: uv add --optional chroma ... records it under [project.optional-dependencies], plain uv sync skips it, and uv run --extra chroma ... installs it and runs with it. Like a Maven profile.

Chroma's default distance is Euclidean (L2). We ask for cosine with collection_configuration, so its relevance score is 1 - cosine distance: the same cosine similarity the in-memory store computes, and the same 0.65 threshold works. Without it the scores come out on a different scale and the threshold means something else.

rebuild empties the collection with reset_collection() before adding, so ingesting twice gives 30 chunks, not 60. count asks Chroma for the ids only (include=[]), not the texts or vectors.

store.py 17 new or changed lines
from pathlib import Path

from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.vectorstores import InMemoryVectorStore, VectorStore

INDEX = Path("index.json")
STORES = ("memory", "chroma")


class ScoredInMemoryVectorStore(InMemoryVectorStore):
    """InMemoryVectorStore already scores by cosine similarity (1.0 = same direction).
    Saying so here is what makes similarity_search_with_relevance_scores work."""

    def _select_relevance_score_fn(self):
        return lambda score: score


def open_store(kind: str, embeddings: Embeddings) -> VectorStore:
    if kind == "memory":
        if INDEX.exists():
            return ScoredInMemoryVectorStore.load(str(INDEX), embeddings)
        return ScoredInMemoryVectorStore(embeddings)
    if kind == "chroma":
        from langchain_chroma import Chroma  # imported only when needed

        return Chroma(
            collection_name="handbook",
            embedding_function=embeddings,
            persist_directory="chroma",
            collection_configuration={"hnsw": {"space": "cosine"}},
        )
    raise ValueError(f"unknown store {kind!r}, choose one of {STORES}")


def rebuild(kind: str, embeddings: Embeddings, chunks: list[Document]) -> VectorStore:
    """Throw away what the store held and add every chunk again."""
    if kind == "memory":
        store = ScoredInMemoryVectorStore(embeddings)
        store.add_documents(chunks)
        store.dump(str(INDEX))
        return store
    store = open_store(kind, embeddings)
    store.reset_collection()
    store.add_documents(chunks)
    return store


def count(store: VectorStore) -> int:
    if isinstance(store, InMemoryVectorStore):
        return len(store.store)
    return len(store.get(include=[])["ids"])
  1. Now --store chroma is accepted by argparse in ingest.py and ask.py, without touching them.line 8
  2. An import inside the function: chromadb is only loaded when you ask for Chroma, so the memory store and the tests never need it.line 25
  3. A collection is Chroma's table. One collection per kind of document is typical.line 28
  4. The same NomicEmbeddings: Chroma calls embed_documents and embed_query exactly like the in-memory store.line 29
  5. Where Chroma keeps its files. Without it, everything is lost when the program ends.line 30
  6. Cosine distance for the HNSW index. Set it when the collection is created: an existing collection keeps the distance it was created with.line 31
  7. Deletes the collection and creates it again, empty, with the same settings.line 44
  8. Chroma also stores the Documents under their id, so citations show the same expenses.md#1.line 45
  9. get(include=[]) returns only the ids. Chroma has no store dict, so count asks it.line 52
Run
uv add --optional chroma "langchain-chroma==1.2.0"
uv run --extra chroma ingest.py --store chroma
uv run --extra chroma ask.py --store chroma --debug "How much can I spend on a hotel in London?"
You should seeyour text will differ: the model writes it
Resolved 108 packages in 720ms
Installed 60 packages in 220ms
 + chromadb==1.5.9
 + langchain-chroma==1.2.0
 + onnxruntime==1.32.0
 ...
Embedded and stored 30 chunks in 2.4s
The chroma store now holds 30 chunks
--- retrieved 4 chunks, min score 0.65 ---
0.785 used    expenses.md#1    Travel and expenses > Hotels
0.679 used    expenses.md#2    Travel and expenses > Hotels
0.594 dropped expenses.md#3    Travel and expenses > Meals
0.582 dropped benefits.md#1    Benefits > Learning budget
---
In London, hotels are covered up to 250 euros a night [1]. Breakfast is included in that limit when the hotel sells it with the room [1].

Sources:
  [1] expenses.md > Travel and expenses > Hotels
Why this way? Same chunks, same scores, same answer, and the chain did not change: the vector store interface did its job. In production you would pick the store for operational reasons (Postgres with pgvector if you already run Postgres, a managed vector database for very large collections); with LangChain, switching is a new branch in open_store, provided you check what its scores mean.
Stuck on this step?
The install takes minutes or fails building a package
chromadb pulls large binary wheels (onnxruntime, tokenizers). They exist for Python 3.12 on macOS, Linux and Windows; if uv tries to build one from source, you are probably on a very new Python. Run uv python pin 3.12, then the command again.
ModuleNotFoundError: No module named 'langchain_chroma'
You ran without --extra chroma. Every command that uses --store chroma needs it.
Chroma scores are much lower than the in-memory ones
The collection was created earlier without collection_configuration (so with L2 distance). Delete the chroma folder and ingest again.
9

From scratch vs LangChain, side by side

See what LangChain did for you, what it hid, and when each version is the better choice.

Both versions answer the same questions with the same chunks and the same scores. Here is where each job lives.

Job Lab 6, from scratch Lab 8, LangChain
Call the chat model client.chat.completions.create(...), read choices[0].message.content ChatOpenAI(...), then invoke or stream; AIMessage.content
Embed Embedder: batching, sort by index, normalize, prefixes OpenAIEmbeddings(check_embedding_ctx_length=False) + our NomicEmbeddings for the prefixes
Load files Path.glob inside load_handbook BaseLoader.lazy_load yielding Document objects
Chunk split_sections + pack, about 60 lines MarkdownHeaderTextSplitter + RecursiveCharacterTextSplitter, about 15 lines
Store and search InMemoryStore (NumPy matrix, @, argsort), PgVectorStore InMemoryVectorStore (+ 3-line subclass), Chroma
What a score means You decide: always cosine similarity Depends on the store; use similarity_search_with_relevance_scores
Prompt build_messages() with f-strings ChatPromptTemplate with {placeholders}
Pipeline Plain function calls in answer() LCEL: {...} | PROMPT | llm | StrOutputParser(), RunnablePassthrough.assign
Refuse when weak if not relevant: return Answer(NOT_FOUND, ...) A routing function that returns a string or a Runnable
Citations cited_numbers The same cited_numbers: LangChain has none
Streaming Parse server-sent events yourself (lab 2) chain.stream()
Test fakes SimpleNamespace fake client GenericFakeChatModel, or any RunnableLambda

What LangChain hid, and you had to find out: OpenAIEmbeddings sends token ids unless told not to; the nomic prefixes are your job; InMemoryVectorStore cannot compute relevance scores until you say how; Chroma and the in-memory store mean different things by "score"; the Markdown splitter removes blank lines; the threshold retriever drops scores and logs warnings; numpy is needed but not installed. None of these is a bug: they are defaults chosen for other cases, and you only find them because you knew what the from-scratch version sends.

When to use which. LangChain pays off when you want to swap models and stores, use its many loaders and splitters, stream and trace without extra code, or grow into agents (next lab). Plain code pays off for a small, fixed pipeline where every line is yours to debug, and for teams that do not want a fast-moving dependency (pin it, as here, and read the changelog before you upgrade). Many teams mix both: LangChain's loaders, splitters and model wrappers, with their own retrieval and safety logic in plain functions, like rag.py here.

Why this way? Interviewers often ask "would you use LangChain?". The strong answer is neither "always" nor "never": it is knowing what the framework does underneath, which pieces you would keep, and which defaults you would check first.
10

Test it without a model

Tests for loading, splitting, retrieval, the prompt, refusals, streaming and citations that run in well under a second.

LangChain ships fakes for testing. GenericFakeChatModel is a real chat model class that replies with the messages you give it, and streams them word by word, so chain.stream can be tested too. You can also pass any Runnable as the model: recording_llm is a RunnableLambda that records every prompt it receives and returns a fixed AIMessage, so a test can check the exact prompt, or that there was no call at all.

For embeddings, KeywordEmbeddings implements the two methods of the Embeddings interface by counting a few known words: texts that share words get similar vectors. It adds a constant 0.1 so no vector is all zeros, because the cosine of a zero vector is undefined and LangChain raises an error for it.

The store fixture runs every store test twice: with a fresh store, and with a store that was dumped to a file and loaded again, so saving and loading are tested too.

test_chunking.py
from langchain_core.documents import Document

from chunking import load_handbook, split_documents
from loader import MarkdownFolderLoader

DOC = Document(
    page_content="""# Expenses

## Hotels
Up to 180 euros a night.

## Meals
Up to 60 euros a day.
""",
    metadata={"source": "expenses.md"},
)


def test_loader_reads_every_file_in_name_order():
    files = MarkdownFolderLoader("handbook").load()
    names = [f.metadata["source"] for f in files]
    assert len(names) == 8
    assert names == sorted(names)
    assert files[0].page_content.startswith("# Benefits")


def test_one_chunk_per_section_with_heading_and_id():
    chunks = split_documents([DOC])
    assert [c.id for c in chunks] == ["expenses.md#0", "expenses.md#1"]
    assert chunks[0].metadata == {"source": "expenses.md", "heading": "Expenses > Hotels"}
    assert chunks[0].page_content == "Expenses > Hotels\nUp to 180 euros a night."


def test_long_section_is_split_and_the_pieces_overlap():
    lines = ["a" * 30, "b" * 30, "c" * 30]
    doc = Document(page_content="## Long\n" + "\n\n".join(lines), metadata={"source": "long.md"})
    chunks = split_documents([doc], chunk_size=70, chunk_overlap=35)
    assert [c.page_content for c in chunks] == [f"Long\n{'a' * 30}\n{'b' * 30}", f"Long\n{'b' * 30}\n{'c' * 30}"]


def test_the_handbook():
    chunks = load_handbook("handbook")
    assert len(chunks) == 30
    assert len({c.id for c in chunks}) == len(chunks)  # ids are unique
    hotels = [c for c in chunks if c.metadata["heading"] == "Travel and expenses > Hotels"]
    assert len(hotels) == 2
  1. A tiny Markdown document inside the test: you see the input and the expected output on one screen.line 6
  2. The loader sorts by file name, so the order (and the chunk ids) never depends on the machine.line 23
  3. The heading path goes into the text and the metadata. Citations depend on both.line 31
  4. Three 30-character lines, at most 70 characters per chunk: a and b fit together, c does not. The second chunk starts with b: the overlap.line 37
  5. One test on the real handbook: 30 chunks, unique ids, and the long Hotels section really split in two.line 43
test_rag.py
import pytest
from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from langchain_core.runnables import RunnableLambda
from langchain_core.vectorstores import InMemoryVectorStore

from prompt import NOT_FOUND
from rag import build_chain, cited_numbers, make_retriever
from store import ScoredInMemoryVectorStore

VOCAB = ["hotel", "night", "laptop", "stolen", "vacation", "days"]


class KeywordEmbeddings(Embeddings):
    """A fake embedding model: counts a few known words, so texts that share words get similar vectors."""

    def vector(self, text: str) -> list[float]:
        words = text.lower().replace("?", " ").replace(".", " ").split()
        counts = [float(sum(w.startswith(v) for w in words)) for v in VOCAB]
        return counts + [0.1]  # never all zeros: cosine similarity is undefined for a zero vector

    def embed_documents(self, texts: list[str]) -> list[list[float]]:
        return [self.vector(t) for t in texts]

    def embed_query(self, text: str) -> list[float]:
        return self.vector(text)


def recording_llm(reply: str):
    """A stand-in for ChatOpenAI: any Runnable that turns a prompt into a message will do."""
    calls = []

    def respond(prompt_value):
        calls.append(prompt_value.to_messages())
        return AIMessage(reply)

    return RunnableLambda(respond), calls


CHUNKS = [
    Document(id="expenses.md#1", page_content="Travel and expenses > Hotels\nHotels are covered up to 180 euros a night.",
             metadata={"source": "expenses.md", "heading": "Travel and expenses > Hotels"}),
    Document(id="security.md#2", page_content="Security > Lost or stolen devices\nReport a stolen laptop within one hour.",
             metadata={"source": "security.md", "heading": "Security > Lost or stolen devices"}),
    Document(id="time-off.md#0", page_content="Time off > Vacation\nEveryone gets 25 vacation days a year.",
             metadata={"source": "time-off.md", "heading": "Time off > Vacation"}),
]


@pytest.fixture(params=["memory", "saved-and-loaded"])
def store(request, tmp_path):
    """Every test that asks for a store runs twice: fresh, and after a save to disk and a load."""
    s = ScoredInMemoryVectorStore(KeywordEmbeddings())
    s.add_documents(CHUNKS)
    if request.param == "saved-and-loaded":
        s.dump(str(tmp_path / "index.json"))
        s = ScoredInMemoryVectorStore.load(str(tmp_path / "index.json"), KeywordEmbeddings())
    return s


def test_retriever_ranks_the_closest_chunk_first_with_its_score(store):
    docs = make_retriever(store, k=2).invoke("my laptop was stolen")
    assert len(docs) == 2
    assert docs[0].id == "security.md#2"
    assert docs[0].metadata["score"] > 0.9
    assert docs[1].metadata["score"] < 0.5


def test_the_plain_in_memory_store_has_no_relevance_scores():
    plain = InMemoryVectorStore(KeywordEmbeddings())
    plain.add_documents(CHUNKS)
    with pytest.raises(NotImplementedError):
        plain.similarity_search_with_relevance_scores("hotel", k=1)


def test_answer_sends_numbered_sources_and_returns_them(store):
    llm, calls = recording_llm("Hotels are covered up to 180 euros a night [1].")
    result = build_chain(make_retriever(store), llm, min_score=0.5).invoke("hotel price per night?")
    assert [d.id for d in result["sources"]] == ["expenses.md#1"]
    assert result["answer"] == "Hotels are covered up to 180 euros a night [1]."
    system, user = calls[0]
    assert "Use only the numbered sources" in system.content
    assert "[1] expenses.md\nTravel and expenses > Hotels\nHotels are covered" in user.content
    assert user.content.endswith("Question: hotel price per night?")


def test_low_scores_refuse_without_calling_the_model(store):
    llm, calls = recording_llm("this reply must never be used")
    result = build_chain(make_retriever(store), llm).invoke("What is the capital of Australia?")
    assert result["answer"] == NOT_FOUND
    assert result["sources"] == []
    assert len(result["retrieved"]) == 3  # still there for --debug
    assert calls == []


def test_the_answer_streams_in_pieces(store):
    llm = GenericFakeChatModel(messages=iter([AIMessage("Up to 180 euros a night [1].")]))
    parts = list(build_chain(make_retriever(store), llm, min_score=0.5).stream("hotel per night?"))
    pieces = [p["answer"] for p in parts if "answer" in p]
    assert len(pieces) > 1
    assert "".join(pieces) == "Up to 180 euros a night [1]."
    assert any("sources" in p for p in parts)


def test_cited_numbers_ignores_repeats_and_made_up_sources():
    assert cited_numbers("A [2]. B [1][2]. C [7].", n_sources=3) == [2, 1]
    assert cited_numbers("No citations here.", n_sources=3) == []
  1. GenericFakeChatModel lives in langchain-core, so tests need no extra package.line 4
  2. w.startswith(v) so "hotels" counts as "hotel". sum(...) over booleans counts the Trues.line 21
  3. Every prompt the chain sends is stored in calls: the system and the user message.line 36
  4. Returns two values (a tuple): the fake model and the list of calls, unpacked by the caller in one line.line 39
  5. A **parametrized fixture**: pytest runs each test that asks for store once per param. tmp_path is a fresh temporary folder per test.line 52
  6. A new store object that reads the file the first one wrote.line 59
  7. pytest.raises passes only if the code inside raises that exception. This test documents the trap from step 4.line 74
  8. Unpacks the two messages of the first (and only) call.line 83
  9. The most important refusal check: the fake model recorded **no** call.line 95
  10. messages takes an iterator: the fake replies with the next message on each call. iter([...]) makes one from a list.line 99
  11. More than one answer piece proves it really streamed; joined, they are the whole reply.line 102
Run
uv run pytest -q
You should see
..............                                                           [100%]
14 passed in 0.35s
Why this way? Unit tests check your code and your wiring: the chunk borders, the prompt, the refusal, the stream, the citations. Whether real questions get the right chunks and faithful answers is a different test, an evaluation set run against the real models (see Evaluating RAG and the evals lab). Keep the fakes in tests, never in the app.
Stuck on this step?
14 passed, 17 warnings with DeprecationWarning: 'asyncio.iscoroutinefunction' is deprecated from langsmith
Harmless: uv picked a newer Python than 3.12 (look for Using CPython 3.15 in the uv sync output), and a LangChain dependency still calls a function that Python 3.15 deprecates. Your code is fine. To match this lab exactly, run uv python pin 3.12 in the project folder, then uv sync.
ModuleNotFoundError: No module named 'chunking'
Run pytest from the project folder (where chunking.py is) with uv run pytest -q.
ValueError: NaN values found, please remove the NaN values and try again
A fake embedding returned all zeros. Keep the + [0.1] in KeywordEmbeddings.vector.

Check it works

Three checks: the tests pass with no model, a covered question streams an answer with a citation, and an off-topic question is refused without calling the model.

If you did step 8, run the last two commands again with --extra chroma after uv run and --store chroma after ask.py: the sources and the refusal should be the same.

Test
uv run pytest -q
uv run ingest.py
uv run ask.py "What should I do if my laptop is stolen?"
uv run ask.py "What is the dress code?"
You should see
14 passed in 0.35s
Embedded and stored 30 chunks in 0.4s
The memory store now holds 30 chunks
If your laptop is stolen, report it in the #security-help channel within one hour [1]. The security team will lock the device remotely.

Sources:
  [1] security.md > Security > Lost or stolen devices
I don't know. The handbook does not say.
(no chunk reached the minimum score, so the model was not asked)

Troubleshooting

An ImportError or AttributeError after upgrading a LangChain package

LangChain renames and moves things between versions, and its packages must match each other (langchain-openai 1.8.5 needs langchain-core 1.8.4 or newer, for example). Go back to the pinned versions with uv sync, then upgrade one package at a time and read its release notes.

The right chunk is retrieved, but the answer is wrong or mixes facts

Run with --debug and read the sources the model got. If the answer is there, it is a generation problem: keep the temperature at 0, make the rules stricter, or use a larger model (llama3.1:8b).

The right chunk is not in the top 4

A retrieval problem: no prompt fixes it. Check that NomicEmbeddings is used everywhere (the prefixes), re-run uv run ingest.py after any change to chunking or embeddings, try k=6 in make_retriever, or add keyword search (Hybrid search and reranking).

Answers ignore a change you made to the handbook

The store still holds the old chunks. Run uv run ingest.py (and with --store chroma) again after every change to the documents.

A stack trace that is 40 lines of langchain_core/runnables/base.py

Read it from the bottom: the last lines are the real error (often a wrong key name or a server error). To find the step, call the pieces one by one: retriever.invoke(q), then PROMPT.invoke({...}), then llm.invoke(...).

Everything is slow on the first question

Ollama loads each model into memory on first use (the embedding model, then the chat model). Later questions are faster.

What changes in production

  • Pin LangChain and upgrade on purpose. The packages release every few weeks and must stay compatible with each other. Pin exact versions in pyproject.toml, keep uv.lock in git, and run the tests and an evaluation set before every upgrade.
  • Keep the safety logic in your own functions. The minimum score, the refusal and the citation check are small plain functions inside the chain, with their own tests. Framework defaults change; your rules should not change with them.
  • Trace every step. A chain makes tracing easy: LangSmith or OpenTelemetry callbacks record the retrieved ids and scores, the prompt and the tokens of every run without changing the chain. Log refusals: they show what the documents are missing.
  • Treat retrieved text as untrusted. Documents can contain instructions aimed at the model. Keep them in the user message labelled as sources, never give a RAG chain tools that act on their own, and show citations so people can check.
  • Version the embedding model with the index. Vectors from different models (or with and without prefixes) cannot be compared. Changing the model means re-embedding everything into a new collection and switching when it is complete.

Interview angle

“Would you use LangChain for a RAG feature? What does it give you, and what do you watch out for?”

I would use it for the plumbing and keep the rules in my own code. It gives me one interface per job: chat models and embeddings I can swap through configuration, loaders and splitters for many formats, vector stores behind one API, and LCEL chains that stream, batch and trace without extra code. What I watch: defaults made for OpenAI (the embeddings class sends token ids, which other servers reject), what a score means in each vector store (similarity in one, distance in another), embedding-model details like task prefixes, and version churn, so I pin versions and test before upgrading. The minimum-score refusal and the citation check stay plain functions with unit tests, run inside the chain, and I compare retrieval against a simple from-scratch baseline or an evaluation set to make sure the framework is doing what I think.

Clean up

The index.json file and the chroma folder can be deleted any time: uv run ingest.py recreates them. Keep the project: the next lab builds an agent with LangGraph on the same building blocks. To free disk space later, remove the models with ollama rm.

Run
rm -rf index.json chroma

Practice

No model needed: these run in your browser and check your answer.

Build your own | pipe

LCEL's | is ordinary Python. Complete the class Step so that a | b returns a new Step that calls a, then b with its result. The right side may be a Step, a plain function, or a dict; a dict means "call every value with the same input and return a dict of the results", like LangChain's dict step. A dict or function on the left of a Step must work too: Python then calls the right side's __ror__ method. invoke(value) runs the step.

Exercise
class Step:
    def __init__(self, fn):
        self.fn = fn

    def invoke(self, value):
        return self.fn(value)

    # add __or__ (self | other) and __ror__ (other | self)


print(Step(str.strip).invoke("  hello  "))
Hint

Write a helper `as_step(x)` that returns `x` if it is a `Step`, wraps a dict as `Step(lambda v: {k: as_step(f).invoke(v) for k, f in x.items()})`, and wraps anything else as `Step(x)`. Then `__or__` is `Step(lambda v: as_step(other).invoke(self.invoke(v)))`, and `__ror__` is `as_step(other) | self`.

Put a streamed result back together

A streamed chain hands out small dicts, as in step 7. Write merge_stream(parts) that combines them into one dict: when a key already holds a string and the new value is a string too, append it (the answer pieces); otherwise the new value replaces the old one (lists, numbers, the first string for a key). Return the merged dict.

Exercise
def merge_stream(parts):
    result = {}
    for part in parts:
        result.update(part)
    return result


print(merge_stream([{"question": "q"}, {"answer": "Up to "}, {"answer": "250 euros [1]."}]))
Hint

Loop over every `key, value` in `part.items()`. If `isinstance(value, str)` and `isinstance(result.get(key), str)`, use `+=`; otherwise assign.

The full project

Every file from this lab, as it is after the last step.

Download Python project (.zip)