A small, readable retrieval-augmented generation pipeline built with
LangChain. Documents are embedded with
Voyage AI (voyage-4-large), stored and searched in MongoDB Atlas
Vector Search, reranked with Voyage (rerank-3), and answered by
Claude Sonnet 5.5. A core library, a CLI and a Streamlit chat app share the
same code.
Ingest (once): data/ ──load──▶ split ──embed──▶ store (MongoDB Atlas + vector index)
Query (per Q): question ──embed──▶ search ──rerank──▶ [top-k chunks + question] ──▶ Claude ──▶ answer + sources
Contents: What leaves your machine · Prerequisites · Setup · Usage · Add your own documents · Evaluation · Tracing with LangSmith · Configuration · Development · Project structure · How it works · Invariants · License
Every model is a hosted API, so your documents do too:
- MongoDB Atlas. Stores their text and vectors.
- Voyage AI. Embeds every document and question, and reranks each question's candidate passages.
- Anthropic. Receives each question with the passages kept for it.
- LangSmith. Receives traces only if you turn tracing on,
and the eval corpus only when you run
rag eval.
The chat app sends nothing else: .streamlit/config.toml turns off Streamlit's
usage statistics and its first-run email prompt, and binds the app to this
machine (with one caveat, below).
- Tools. uv and Python 3.11+, on macOS or Linux. No GPU and no model downloads.
- MongoDB Atlas. A cluster. The free tier (M0) holds an index of a few thousand pages. Atlas pauses a free cluster that sits unused for a long time; resume it there if the app cannot connect.
- Voyage AI. An API key, for embedding and reranking. The first 200 million tokens per model are free.
- Anthropic. An API key, for the answers. A question costs about half a US cent at the default settings.
- Docker. To run the tests, which use MongoDB's
atlas-localimage, not your cluster. - LangSmith. An API key, only for
rag evalor tracing.
-
Install dependencies:
uv sync
-
Get an Anthropic key in the Claude Console.
-
Get a Voyage AI key in the Voyage AI dashboard and add a payment method. Without one the account is limited to 3 requests and 10,000 tokens a minute, which is less than one ingest batch. The free tokens are still used first.
-
Create a MongoDB Atlas cluster in Atlas (labels approximate):
- Create a project, then a Free (M0) cluster.
- Under Security → Database Access, add a user with an autogenerated password and the Read and write to any database role.
- Under Security → Network Access, add your current IP address (not
0.0.0.0/0). - On the cluster, Connect → Drivers → Python shows the connection string.
-
Fill in
.env: copy the template, then setMONGODB_URI(with the password),VOYAGE_API_KEYandANTHROPIC_API_KEY.cp .env.example .env
.envis git-ignored, and the app never displays the keys. Everything else in it is an optional override (see Configuration).
uv run rag ingestLoads the .md/.txt/.pdf files under data/ (recursively, any extension
case), splits them into overlapping chunks, embeds them, and stores them in
rag_db.rag_docs. The first run creates the collection and its vector index.
Every run waits until its writes are searchable, so you can ask about them
straight away.
- Incremental. Only new, edited or removed files are re-embedded. Afterwards
the collection holds exactly what is in
data/: no duplicates, and nothing left over from deleted files. A re-run with no changes makes no embedding calls. - Scoped. Unrelated documents that share the collection are never read or deleted.
- Resilient. An unreadable file (bad encoding, corrupt PDF, permissions) is skipped with a warning. So is a PDF with no extractable text, such as a scan, which needs OCR first. A blank text file is skipped silently.
- Settings-aware. Changing
EMBEDDING_MODEL,EMBEDDING_DIMENSIONS,CHUNK_SIZEorCHUNK_OVERLAPre-embeds everything. ChangingEMBEDDING_DIMENSIONSalso needs a newCOLLECTION_NAME, because a vector index serves one width. Ingest checks this before deleting anything. - One writer at a time. A second ingest on the same collection (from the terminal, the app or another machine) waits for the first. The lock is a lease stored in MongoDB Atlas, so an ingest that crashes releases it within 5 minutes.
uv run rag query "What is chunking and why do we overlap chunks?"Streams the answer, then lists the source files it drew on. Ctrl-C stops the answer (exit status 130) and closes the request to Claude, so the rest is neither generated nor billed.
uv run streamlit run streamlit_app.pyA browser chat over the same pipeline. Answers stream in, each with a panel of the passages it was generated from, so you can check a claim against its source text. The sidebar shows the active configuration and accepts uploads.
- Stop. Ends an answer immediately, closing the request to Claude. The turn stays in the history, marked as interrupted.
- Connections. Those to the index and the models are made once, on first load, and kept for the life of the server, including across re-indexing.
- Local only. The app has no login, so
.streamlit/config.tomlbinds it to127.0.0.1. Pass--server.address 0.0.0.0to open it to your network on purpose. - External IP lookup. Streamlit sometimes asks
checkip.amazonaws.comfor this machine's external IP address: at headless startup when bound to0.0.0.0, and whenever a page from another origin connects (Streamlit refuses that connection). The request carries nothing about the app. - No auto-reload.
.streamlit/config.tomlalso turns off the file watcher, which would walk every loaded module on every run. When editingstreamlit_app.py, add--server.fileWatcherType auto.
Typical timings with the default settings and an M0 (free) Atlas cluster:
| Step | Time |
|---|---|
Connecting (rag query, or the app's first load) |
~1.3 s |
| Embedding documents (ingest) | ~435 chunks/s, in batches of 256 |
| Embedding a question | ~0.18 s |
| Vector search in Atlas | ~0.4 s (median) |
| Reranking 20 candidates | ~0.18 s |
| First word of the answer | ~1.4 s after the question (median of 5) |
| Whole answer | ~2 s for a few sentences |
Most of the wait is 3 network round trips before Claude starts (embed, search, rerank), so an Atlas region near you matters more than any setting.
Use either route:
- From the app. Drag
.md/.txt/.pdffiles onto Add documents in the sidebar and click Add to index. They are saved todata/and indexed immediately, so your next question can use them. This works before any index exists. A file with the same name as an existing one replaces it. - From the filesystem. Put files in
data/and runuv run rag ingest. The 3 sample files are just a starter corpus, and you can delete them.
Either way, the CLI and the app both see the new content right away. The app reloads its pipeline when the index changes.
.gitignoreignores everything indata/except the 3 samples. Saving your own file under a sample's name overwrites a tracked file, so use your own names. ADATA_DIRelsewhere inside the checkout is not ignored; add it to.git/info/exclude..env,.env.*and.streamlit/secrets.tomlare ignored too. Only.env.exampleis tracked.- Upload filenames are untrusted:
save_upload()keeps only the final path component and rejects unsupported types, so an upload cannot pick its own directory.
rag eval scores the pipeline on 106 fixed questions, so the effect of a change
(model, setting, prompt) shows up across all of them at once.
The questions are about evals/corpus/, the engineering handbook of
Tallowmere, a fictional freight-tracking company (66 documents, 108 chunks).
rag eval indexes it into its own rag_eval collection and never touches your
documents.
- Fictional. The model cannot answer from its own knowledge.
- Confusable. Services are documented alike with different values (7 of them written to one template), out-of-date documents sit beside the ones that replaced them, and a customer SLA sits next to internal SLOs.
- Large enough. Vector search, which fetches
FETCH_K= 20 chunks, has to choose. (The 9 chunks of the sampledata/scored 100% on everything.)
Each question gets 6 scores:
| Score | Measures | Scored by |
|---|---|---|
retrieval_hit |
Whether a correct source file is among the chunks in the prompt (not scored for the 13 unanswerable questions) | Computed from the pipeline's output |
retrieval_rank |
1 ÷ the rank of the first chunk from a correct file (0 if none), averaged as mean reciprocal rank. Catches a right file slipping down before it drops out | Computed from the pipeline's output |
retrieval_recall |
The fraction of the correct files among the chunks in the prompt. Equal to retrieval_hit for a one-file question; for a two-file one, sees half the evidence missing |
Computed from the pipeline's output |
candidate_rank |
retrieval_rank over the FETCH_K vector-search candidates, before the reranker. A diagnostic: high here but low in the prompt means the reranker dropped the chunk; low here means the embedder never fetched it |
Computed from the pipeline's output |
correct |
Whether the answer matches the reference, or, for an unanswerable question, says it cannot answer | Claude Opus 5.5 |
grounded |
Whether every claim is supported by the retrieved chunks | Claude Opus 5.5 |
Each question also has a category (CATEGORIES in evaluation.py), and
every score is reported per category as well as overall, so a hard category's
failures are not diluted by the easy questions' passes. easy is the original
set; each other category stresses one part of the pipeline (chunking, the
reranker, the embedder, RETRIEVAL_K, or declining to answer). LangSmith's
compare view can filter an experiment's rows by category.
It needs the pipeline's 3 keys plus LANGSMITH_API_KEY, which uploads the
questions as a LangSmith dataset and records each
run as an experiment, with answers, passages and the judge's reasoning.
ANTHROPIC_API_KEY also pays for the judge, Claude Opus 5.5.
uv run rag eval # score, and compare with evals/baseline.json
uv run rag eval --save-baseline # score, and save as the new baselineA run takes about 15 minutes and costs about $2–4, mostly for the judge. It prints each score overall and per category, the change from the baseline, and a link to the experiment. It checks the keys, the judge and LangSmith before loading any model.
- Comparable only within one question set and one judge. The dataset name is
a hash of the questions, so editing
evals/questions.jsoncreates a new dataset and the report won't compare it with an old baseline. The judge is fixed in code (JUDGE_MODEL) with no fallback model; a grade it declines is recorded as unscored. - A baseline needs every question scored.
--save-baselinerefuses a run with a failed question or a declined grade. - Retrieval scores are exact. They do not change between runs on the same
index and models, and
correctbarely does;groundedcan move by about one question. One run is enough to read a retrieval change. - Full traces. Every experiment row includes the question's full trace,
whatever
LANGSMITH_TRACINGis set to. Nothing outside the eval is traced.
Off by default. When it's on, each question, from the terminal or the app, is recorded as one trace in LangSmith:
RAGPipeline chain the question, and the answer
├─ VectorStoreRetriever retriever the FETCH_K candidates from vector search
├─ _VoyageRerank retriever candidates in; the RETRIEVAL_K kept, with scores, out
└─ generate chain
├─ ChatPromptTemplate prompt the prompt, with the passages filled in
└─ ClaudeChatModel llm messages, answer, token counts, stop reason
To turn it on, add this to .env:
LANGSMITH_TRACING=true
LANGSMITH_API_KEY=lsv2_...Traces go to the rag-pipeline project (LANGSMITH_PROJECT), which is created
on first use. The sidebar shows when tracing is on. For an EU account, also set
LANGSMITH_ENDPOINT=https://eu.api.smith.langchain.com. The free plan's 5,000
traces a month cover about 165 questions a day, one trace each, but rag eval
spends about 740 of them per run (each question, plus each of its 6 scores as a
trace of its own), so about 6 eval runs exhaust it. Past the limit LangSmith
bills pay-as-you-go if billing is set up, and otherwise refuses new traces until
the month resets: questions and evals still work, and an eval's scores and saved
baseline are complete, but its experiment in LangSmith is missing rows.
- A trace contains everything. It holds the question, every retrieved passage, the prompt and the answer.
- Off means off.
LANGSMITH_TRACINGis the only switch, so a leftoverLANGCHAIN_TRACING_V2=truesends nothing. Values other thantrue/falseare rejected. - A stopped answer is not an error. Its trace is tagged
stopped, with the partial answer. LangChain's own model run still shows an error, because LangChain reports a closed stream that way. - An unreachable LangSmith doesn't affect answers. Traces are sent in the
background and failures are logged to stderr, which can interrupt a streaming
answer in the terminal. On exit,
rag querywaits at most about 10 seconds to send what is still queued. - Ingest is not traced. Only questions are.
MONGODB_URI, VOYAGE_API_KEY and ANTHROPIC_API_KEY are required (see
Setup). Keys are not settings: they have no default and never appear
in the app or in error messages. Every setting below has a default, which you
can override in .env (see .env.example) or the environment:
| Variable | Default | Purpose |
|---|---|---|
CHAT_MODEL |
claude-sonnet-5-5 |
Claude model that writes the answers. The request uses Claude Sonnet 5.5's between_tools thinking setting, which other models reject, so another model also needs claude_model.py changed |
MAX_TOKENS |
1024 |
Maximum answer length in tokens. An answer cut off here ends with a note |
EMBEDDING_MODEL |
voyage-4-large |
Voyage AI embedding model for ingest and query. Must accept an output dimension. Changing it re-embeds everything |
EMBEDDING_DIMENSIONS |
1024 |
Vector width: 256, 512, 1024 or 2048. Changing it needs a new COLLECTION_NAME |
RETRIEVAL_K |
4 |
Chunks kept after reranking and put in the prompt |
FETCH_K |
20 |
Candidates fetched by vector search before reranking |
RERANK_MODEL |
rerank-3 |
Voyage reranker |
CHUNK_SIZE |
1000 |
Characters per chunk |
CHUNK_OVERLAP |
200 |
Characters shared by adjacent chunks |
DATA_DIR |
./data |
Folder of source documents |
MONGODB_DB |
rag_db |
MongoDB Atlas database |
COLLECTION_NAME |
rag_docs |
Atlas collection for chunks and vectors. Must match between ingest and query |
VECTOR_INDEX_NAME |
vector_index |
Atlas Vector Search index, created by rag ingest. Must match between ingest and query |
MONGODB_TIMEOUT_MS |
10000 |
How long to wait for the cluster. Generous, because a paused free cluster resumes slowly |
LANGSMITH_TRACING |
false |
true sends each question to LangSmith (see Tracing) |
LANGSMITH_PROJECT |
rag-pipeline |
LangSmith project for traces |
Streamlit's own settings are in .streamlit/config.toml, each with a comment
explaining it.
Ruff and ty are
pinned in the dev dependencies and configured in pyproject.toml:
uv run ruff check --fix . # lint (run before formatting: fixes can reorder code)
uv run ruff format . # format
uv run ty check # type checkuv run pytestNeeds Docker, but no API keys, network or MongoDB Atlas cluster. The suite uses fake
embedding, rerank and chat models, and a real Atlas Vector Search in MongoDB's
mongodb-atlas-local image (about 1 GB, pulled on first run). The store is real
because its behavior (asynchronous indexing, writes that become searchable a
moment later, filter fields) is exactly what a fake would get wrong. It takes
about 4 minutes on an M2 Max.
Guards keep the suite offline:
- Your API keys and
MONGODB_URIare removed for every test, so a test that forgets to inject a fake fails instead of calling a paid API. - Sockets to any host but this machine are blocked.
- Tracing is forced off, and a test that leaves a tracing context set fails.
The suite covers configuration, loading and splitting, ingest idempotency and
scoping, uploads, a full ingest → retrieve → generate round trip, the CLI, and
the Streamlit app driven headlessly. claude_model.py is tested through the
real Anthropic SDK against a stand-in server, including that stopping an answer
closes its HTTP request. See CLAUDE.md for the design.
These check what the fakes can't: that the real APIs behave as assumed.
uv run pytest -m liveThey call Anthropic's and Voyage AI's APIs (about 1 minute, a few cents) and
skip when a key is missing. A plain uv run pytest and CI never run them, so run
them by hand after changing claude_model.py or a model factory, or after a
uv.lock change that moves anthropic, voyageai or langchain-voyageai. A
skipped test has not been checked.
Coverage is on demand, with no threshold:
uv run pytest --cov=rag_pipeline --cov=streamlit_app --cov-report=term-missingThe uncovered lines should only be ones a real terminal or API reaches, which the live tests cover.
.github/workflows/ci.yml runs on every push and pull request:
| Job | Status check name | Runs |
|---|---|---|
lint |
ruff + ty |
ruff check, ruff format --check, ty check |
test |
pytest (py3.11), pytest (py3.13), pytest (py3.15) |
The test suite on the oldest supported, the pinned and the newest Python; a test whose vector index never became queryable is rerun once, since atlas-local occasionally stalls one on a hosted runner |
release |
release |
On a push to main, after both pass: a GitHub release for a new version |
Jobs install with uv sync --locked, which fails if uv.lock is out of date
with pyproject.toml. They run on Linux with no secrets. Each action is pinned
to a commit SHA, and Dependabot proposes updates to them monthly
(.github/dependabot.yml). Nothing gates main; to require checks before
merging, add a repository ruleset for the status check names above.
To run the same checks locally:
uv sync --locked && uv run ruff check . && uv run ruff format --check . && uv run ty check && uv run pytestA release is a version bump pushed to main:
uv version --bump minor # or patch / major; updates pyproject.toml and uv.lock
git commit -am "Release 1.3.0" && git pushWhen lint and tests pass, the release job tags the commit (v1.3.0) and
publishes a GitHub release listing the commits since the last tag.
- Only the head of
mainis released. If a newer push lands first, the release waits for it. - A version that already has a release is skipped. A failed release is retried
on the next push to
main. - An existing tag of the same name on a different commit fails the job until you delete the tag or bump the version.
- A pre-release version (
1.3.0rc1) is published as a pre-release. - Nothing is built or uploaded to PyPI (the name
rag-pipelineis taken there).
rag_pipeline/
config.py Settings, loaded from environment variables
ingest.py load → split → embed → store; build_embeddings() and open_store()
pipeline.py RAGPipeline: retrieve, rerank, stream_answer() / answer()
claude_model.py Claude behind LangChain's chat-model interface
tracing.py the LangSmith client, when tracing is on
evaluation.py rag eval: questions as a LangSmith dataset, judged by Claude
cli.py rag ingest | rag query "..." | rag eval
streamlit_app.py Streamlit chat UI
.github/ ci.yml (checks and releases) and dependabot.yml
.streamlit/ config.toml: no telemetry or email prompt, no file watcher, localhost only
data/ sample documents; add your own (git-ignored)
docs/ README screenshots
evals/ corpus/, questions.json and baseline.json for rag eval
tests/ the suite, with conftest.py (fixtures, offline guards), fakes and invariants.py
.env.example every variable, with its default
CLAUDE.md the design, and the rules for changing it
- Embedding. Voyage AI's
voyage-4-large(1024 dimensions) embeds documents at ingest and questions at query time, each with the matchinginput_type. Both sides must use the same model, so they share one factory,build_embeddings(). Calls are retried with backoff (5 attempts) and time out after 60 seconds. - Storage and search. MongoDB Atlas stores chunks with their vectors, and a
Vector Search index finds the nearest ones. Every chunk carries an ownership
marker that every read, delete and search filters on, so other data in the
collection is never touched or cited.
open_store()iningest.pyis the one way to open the store, and the process shares one MongoDB client. - Reranking. Vector search fetches
FETCH_Kcandidates; Voyagererank-3scores each against the question directly and keeps the topRETRIEVAL_K. Its factory,build_reranker(), lives inpipeline.pybecause reranking has no ingest side. - Answering. Claude Sonnet 5.5 answers only from the retrieved passages and cites them. Thinking is at its lowest setting and effort is low, which keeps the first word quick. Claude takes no sampling parameters, so wording can vary between runs; the cited passages are what keep answers checkable. A question Claude declines is reported as declined, never as an empty answer.
- Streaming.
stream_answer(question)returns the retrieved sources and a lazy stream of the answer.answer()joins that stream for callers who want a string. Stopping a stream closes the request to Claude, so generation and billing stop too. LangChain's own Anthropic integration leaves the request open, which is whyclaude_model.pyhas its own adapter.
- Another Voyage embedding model or reranker: change
EMBEDDING_MODELorRERANK_MODELin.env. - Another Claude model: change
CHAT_MODEL, and adjust the request inclaude_model.py. - Another provider's embedder or reranker: edit
build_embeddings()orbuild_reranker(). - Another vector store: start with
open_store()iningest.py. The bookkeeping iningest(), the index management and the writer lock also use MongoDB queries directly.
Some rules say that a certain call never happens, so no test can observe them
at runtime. They are kept as data in tests/invariants.py and checked by
tests/test_invariants.py against every .py file that git does not ignore:
| Rule | Forbids | Why |
|---|---|---|
store-factory |
Constructing MongoDBAtlasVectorSearch(...), MongoDBAtlasVectorSearch.from_*(...) or MongoClient(...) outside ingest.py, including in tests (except tests/conftest.py, which manages the test container) |
Ingest and query must open the store the same way, through the one shared client |
embeddings-factory |
Constructing VoyageAIEmbeddings(...) or HuggingFaceEmbeddings(...) outside ingest.py, including in tests (a class definition of that name is allowed) |
Documents and questions must use the same model; tests inject a fake |
no-suppressions |
Any suppression ruff or ty honours: noqa (any case, including file-level forms), ruff's ignore[…], file-ignore[…] and disable[…], isort's skip, skip_file, off and split, ty: ignore, type: ignore, and @no_type_check. # fmt: directives are allowed |
Fix the finding instead |
The documentation is checked too: every Settings field needs a row in
.env.example and in the configuration table
(test_every_setting_is_documented), and every rule needs a row in the table
above (test_every_rule_is_documented).
Everything else is tested through behavior, which catches cases a text rule
would miss. See Enforcing the invariants in CLAUDE.md.
MIT. See LICENSE.