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
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
- Lab 6 done, or at least read: RAG from scratch. This lab rebuilds it, so every idea (chunks, embeddings, cosine similarity, numbered sources, the minimum score) is explained there first.
- Lab 1's settings pattern (
.envandconfig.py): Your first LLM call. Streaming basics help for step 7: Streaming chat. - Python generators (
yield) and dicts: Iterators and generators, Lists, dicts, sets and tuples. - About 3 GB of free disk space for the two models, plus about 450 MB if you do the optional Chroma step.
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.
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" 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.
uv --version 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.
ollama --version 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.
ollama pull llama3.2:3b
ollama pull nomic-embed-text
ollama list NAME ID SIZE MODIFIED nomic-embed-text:latest 0a109f422b47 274 MB 2 seconds ago llama3.2:3b a80c4f17acd5 2.0 GB 3 days ago
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.
# 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 - Ollama's OpenAI-compatible API.
ChatOpenAIandOpenAIEmbeddingsboth get this URL asbase_url.line 2 - Ollama ignores the key, but the OpenAI client refuses to start without one, so any text works.line 3
- Documents and questions must be embedded by the **same** model, or their vectors cannot be compared.line 5
- The same threshold as lab 6, measured there on real questions. With the same embedding model, the scores here are the same.line 8
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")),
) load_dotenv()copies.envintoos.environ. Variables already set in your shell or on the server take priority.line 6frozen=Truemakes the settings read-only, like a Javarecord.line 9- Environment variables are always strings.
float(...)turns"0.65"into a number, likeDouble.parseDouble.line 24
.venv/
__pycache__/
.env
index.json
chroma/ - Never commit
.env: one day it holds a real key.line 3 - The saved in-memory store (step 4). It is rebuilt from the handbook, so it does not belong in git.line 4
- Chroma's database folder (step 8). Also rebuilt by
ingest.py.line 5
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 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 dependenciesmentioningrequires-python- These LangChain versions need Python 3.11 or newer. Run
uv python pin 3.12in the project folder, then theuv addline again.
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.
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) - The same prefixes as lab 6. Other embedding models use other prefixes, or none: read the model card.line 7
class NomicEmbeddings(Embeddings)extends LangChain's abstract base class, likeimplements Embeddingsin Java. It has two abstract methods; Python refuses to create the object if one is missing.line 11- The **decorator pattern**: it wraps another
Embeddings(hereOpenAIEmbeddings) and adds the prefix before passing the call on.line 14 - 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 ChatOpenAIaccepts the same names you used with the SDK:model,base_url,api_key. Change.envand the same code talks to a hosted API.line 26- Temperature 0: the most likely words. For answering from documents you want faithful, repeatable answers.line 30
- 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
- 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
- The rest of the code only ever sees
NomicEmbeddings, so the prefixes cannot be forgotten.line 44
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]]}") invokeis the one method every LangChain building block has: give it an input, get the output. A plain string becomes one user message.line 4type(reply).__name__prints the class name, likereply.getClass().getSimpleName().line 5usage_metadatais LangChain's provider-neutral version ofusage:input_tokensandoutput_tokensinstead ofprompt_tokensandcompletion_tokens.line 6embed_queryaddssearch_query:(our wrapper) and returns a plain Python list of 768 floats.line 8
uv run hello.py 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] 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: 400from the embeddings callcheck_embedding_ctx_length=Falseis missing, so token ids were sent instead of text. Add it as in line 42.
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.
# 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. - The longest section (three paragraphs, about 460 characters), so it becomes two chunks.line 8
- The answer to the question you ask in step 6: 250 euros a night in London.line 9
# 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. # 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. # 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. # 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. # 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. # 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. # 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. 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}) Iterator[Document]is the type of what a generator function returns: something you can loop over once, like Java'sIterator<Document>.line 1- Extending
BaseLoadergives youload()for free; you only writelazy_load.line 8 - A **generator**:
yieldhands 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 sorted(...)so the order, and so the chunk ids, is the same on every machine.glob("*.md")lists the Markdown files.line 15- Only the file name goes into the metadata. It comes back later in every citation.line 17
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()) - Which headings to cut at, and the metadata key for each:
#goes toh1,##toh2.###headings would stay inside the text.line 6 - 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
- The default separators are
["\n\n", "\n", " ", ""]: paragraph, line, word, character.line 12 split_texttakes 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- Undo the header splitter's Markdown line breaks (
" \n", two spaces and a newline), so the chunk text is clean.line 18 split_documentskeeps each section's metadata on every piece.enumeratenumbers the pieces 0, 1, 2 ... within one file.line 19- The heading path,
Travel and expenses > Hotels. A generator expression insidejoin: for every(marker, key)pair inHEADERS, take that key from the metadata if it is there._is the name Python uses for a value you ignore.line 20 - A readable, stable id:
expenses.md#1. Vector stores useDocument.idas their key, so ingesting twice replaces chunks instead of duplicating them.line 22 - The heading goes **into the text**. A vector store embeds
page_contentand nothing else: metadata is never embedded. Lab 6 did the same infor_embedding(); here the model sees the heading in its sources too.line 23
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}") !rprints thereprof the string: with quotes and\nvisible, so you can see exactly what the loader read.line 7- Format specs:
:<16pads to 16 characters, left-aligned;:>3right-aligns. LikeString.format("%-16s")in Java.line 12 {c.metadata['source'] for c in chunks}is a set comprehension: the distinct file names.line 13
uv run show_chunks.py 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. Stuck on this step?
Loaded 0 files- The
handbookfolder is not next toshow_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.
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.
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) Pathis the file path type from the standard library, likejava.nio.file.Path.line 7- A subclass that changes one thing. Everything else (add, search, dump, load) is inherited.line 11
- 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: scoreis a function that returns its input, likes -> s.line 15 loadis 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 22add_documentsembeds all 30 texts (in batches, by default up to 1000 per request) and stores them under theirid.line 31- Writes every Document and its vector to
index.json(about 650 KB here). The next run loads it instead of embedding again.line 32 - 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
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") choices=STORESmakes argparse reject unknown names with a clear message, anddefault="memory"is used when you leave the option out.line 9time.perf_counter()is a precise clock for measuring durations, likeSystem.nanoTime().line 13- The whole ingest in one line: a new store, every chunk embedded (with
search_document:added byNomicEmbeddings) and saved.line 14
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']}") - The words after the script name, joined into one question. With none, a default question.line 6
- Returns
(Document, score)pairs, best first. Thefor doc, score in ...loop unpacks each pair, like destructuring in JavaScript.line 8
uv run ingest.py
uv run search.py "How much can I spend on a hotel in London?" 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
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. NotImplementedErrorfromsimilarity_search_with_relevance_scores- The store is a plain
InMemoryVectorStore, notScoredInMemoryVectorStore. Checkopen_storeandrebuildboth 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.jsonwas built by a different embedding model than the one embedding the question (or a different server answered on port 11434). CheckEMBED_MODELandLLM_BASE_URL, then runuv run ingest.pyagain. - 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.
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.
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) - One fixed sentence for "not in the handbook". Your code and your tests can recognise it.line 4
- 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 from_messagestakes(role, template)pairs."human"is LangChain's name for the user role; it is sent as"user".line 13- 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
[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
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) - A prompt template is a Runnable too:
invokewith a dict of the placeholder values.line 11 to_messages()returns the list of message objects the model will get.message.typeissystem,humanorai.line 12
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()
) - The retriever and the model come in as parameters. Tests pass fakes here (step 10).line 7
- Brackets around the whole chain only let it continue over several lines, like
(...)in any expression.line 9 - A dict step: both values get the question.
retriever | format_sourcesturns it into the numbered sources text;RunnablePassthrough()keeps the question as it is.line 10 - Fills the template with the dict from line 10.line 11
- The chat model: prompt value in,
AIMessageout. Anything with the Runnable methods works here.line 12 AIMessagein, plainstrout.line 13
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)) as_retrieverwraps the store in a retriever.search_kwargsare passed tosimilarity_search: here, the 4 closest chunks.line 9- The whole pipeline runs in this one call: embed the question, search, format, fill the prompt, call the model, take the text.line 11
uv run peek_prompt.py
uv run ask.py "How much can I spend on a hotel in London?" --- 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].
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
PROMPTmust have exactly the placeholder names:sourcesandquestion. 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.
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.
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)
) - 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 - A chained comparison:
1 <= n <= n_sourcesmeans1 <= n and n <= n_sources. It drops made-up numbers like[7]when there were four sources.line 18 - 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 - A function inside a function. It can use
storeandkfrom the outer function, like a Java lambda capturing effectively final variables.line 26 - 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 RunnableLambdaturns the function into a Runnable, so it hasinvoke,streamandbatchand can be piped with|.line 33- 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 - The minimum score check from lab 6, as a list comprehension: like
.stream().filter(...).toList().line 46 - The refusal: a plain string is the result, and the model is never called. Cheaper, faster and safe.line 50
- Returning a Runnable means "run this with the same input". The answer chain gets the whole dict.line 51
- The first step: retrieve the chunks and keep the question, both from the same input.line 54
- Adds
sources: the retrieved chunks that pass the minimum score.line 55 - Adds
answer: the fixed sentence, or the model's answer.line 56
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)") - A positional argument: the question, in quotes on the command line.line 12
action="store_true": a flag with no value.--debugpresent meansargs.debugis True.line 14- Asking an empty store gives empty answers that look like a broken model. Fail early with the fix instead.line 19
resultis the dict the chain built:retrieved,question,sourcesandanswer.line 24- Timeout before connection error, on purpose:
APITimeoutErroris a subclass ofAPIConnectionError, and Python uses the firstexceptthat matches. LangChain lets the OpenAI SDK's exceptions through unchanged.line 25 - Ollama answers 404 for a model it does not have, chat or embedding.line 29
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{status:<7}pads to 7 characters, so the columns line up.line 36- Citation
[n]issources[n - 1]: the list starts at 0, the numbers at 1.line 47 - No citation is a warning sign: the model may have answered from its own memory.line 50
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?" --- 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)
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 lowerMIN_SCOREin.env, or re-runuv run ingest.pyif you changed the embeddings. KeyError: 'score'- The retriever is still
store.as_retriever()from step 5, which puts no score in the metadata. Usemake_retriever(store).
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.
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)") - The debug table moved into a function, because it is now printed from inside the loop.line 23
- The answer starts empty and grows piece by piece. Everything else is stored as it arrives.line 32
- Each
partis a dict with one key:{"retrieved": [...]},{"sources": [...]}or{"answer": "250 "}.line 34 end=""prints no newline after the piece;flush=Truesends it to the terminal now.line 36dict.updatecopies the part's key intoresult, likeMap.putAll.line 39sourcesarrives afterretrievedand before the first answer piece: the right moment for the debug table.line 40- 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 - The streamed text did not end with a newline; this adds it.line 48
uv run ask.py --debug "How many weeks of parental leave do I get?" --- 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
Stuck on this step?
- The whole answer appears at once
- Check
flush=Trueon line 36. Some terminals and IDE consoles also buffer output; try a normal terminal. - The debug table never appears
- Pass
--debugbefore or after the question in quotes, for exampleuv run ask.py --debug "...".
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.
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"]) - Now
--store chromais accepted by argparse iningest.pyandask.py, without touching them.line 8 - 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
- A collection is Chroma's table. One collection per kind of document is typical.line 28
- The same
NomicEmbeddings: Chroma callsembed_documentsandembed_queryexactly like the in-memory store.line 29 - Where Chroma keeps its files. Without it, everything is lost when the program ends.line 30
- 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
- Deletes the collection and creates it again, empty, with the same settings.line 44
- Chroma also stores the Documents under their
id, so citations show the sameexpenses.md#1.line 45 get(include=[])returns only the ids. Chroma has nostoredict, socountasks it.line 52
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?" 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
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 chromaneeds it. - Chroma scores are much lower than the in-memory ones
- The collection was created earlier without
collection_configuration(so with L2 distance). Delete thechromafolder and ingest again.
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.
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.
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 - A tiny Markdown document inside the test: you see the input and the expected output on one screen.line 6
- The loader sorts by file name, so the order (and the chunk ids) never depends on the machine.line 23
- The heading path goes into the text and the metadata. Citations depend on both.line 31
- Three 30-character lines, at most 70 characters per chunk:
aandbfit together,cdoes not. The second chunk starts withb: the overlap.line 37 - One test on the real handbook: 30 chunks, unique ids, and the long Hotels section really split in two.line 43
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) == [] GenericFakeChatModellives in langchain-core, so tests need no extra package.line 4w.startswith(v)so "hotels" counts as "hotel".sum(...)over booleans counts the Trues.line 21- Every prompt the chain sends is stored in
calls: the system and the user message.line 36 - Returns two values (a tuple): the fake model and the list of calls, unpacked by the caller in one line.line 39
- A **parametrized fixture**: pytest runs each test that asks for
storeonce per param.tmp_pathis a fresh temporary folder per test.line 52 - A new store object that reads the file the first one wrote.line 59
pytest.raisespasses only if the code inside raises that exception. This test documents the trap from step 4.line 74- Unpacks the two messages of the first (and only) call.line 83
- The most important refusal check: the fake model recorded **no** call.line 95
messagestakes an iterator: the fake replies with the next message on each call.iter([...])makes one from a list.line 99- More than one answer piece proves it really streamed; joined, they are the whole reply.line 102
uv run pytest -q .............. [100%] 14 passed in 0.35s
Stuck on this step?
14 passed, 17 warningswithDeprecationWarning: 'asyncio.iscoroutinefunction' is deprecatedfromlangsmith- Harmless: uv picked a newer Python than 3.12 (look for
Using CPython 3.15in theuv syncoutput), and a LangChain dependency still calls a function that Python 3.15 deprecates. Your code is fine. To match this lab exactly, runuv python pin 3.12in the project folder, thenuv sync. ModuleNotFoundError: No module named 'chunking'- Run pytest from the project folder (where
chunking.pyis) withuv 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]inKeywordEmbeddings.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.
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?" 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, keepuv.lockin 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.
rm -rf index.json chromarm -rf index.json chromaRemove-Item -Recurse -Force 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.
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.
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.