Skip to content

About

Retrieval-augmented generation over your own documents: Voyage AI embeddings and reranking, MongoDB Atlas Vector Search and Claude, with a CLI, a Streamlit chat app and a LangSmith-judged eval.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

RAG Pipeline

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.

The Streamlit chat app answering a question from the sample documents, citing its source, with the active models in the sidebar
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

What leaves your machine

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).

Prerequisites

  • 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-local image, not your cluster.
  • LangSmith. An API key, only for rag eval or tracing.

Setup

  1. Install dependencies:

    uv sync
  2. Get an Anthropic key in the Claude Console.

  3. 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.

  4. Create a MongoDB Atlas cluster in Atlas (labels approximate):

    1. Create a project, then a Free (M0) cluster.
    2. Under Security → Database Access, add a user with an autogenerated password and the Read and write to any database role.
    3. Under Security → Network Access, add your current IP address (not 0.0.0.0/0).
    4. On the cluster, Connect → Drivers → Python shows the connection string.
  5. Fill in .env: copy the template, then set MONGODB_URI (with the password), VOYAGE_API_KEY and ANTHROPIC_API_KEY.

    cp .env.example .env

    .env is git-ignored, and the app never displays the keys. Everything else in it is an optional override (see Configuration).

Usage

1. Build the index

uv run rag ingest

Loads 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_SIZE or CHUNK_OVERLAP re-embeds everything. Changing EMBEDDING_DIMENSIONS also needs a new COLLECTION_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.

2. Ask questions from the terminal

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.

3. Use the chat app

uv run streamlit run streamlit_app.py

A 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.

An answer with its retrieved passages open: the first passage holds the sentence the answer paraphrases
  • 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.toml binds it to 127.0.0.1. Pass --server.address 0.0.0.0 to open it to your network on purpose.
  • External IP lookup. Streamlit sometimes asks checkip.amazonaws.com for this machine's external IP address: at headless startup when bound to 0.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.toml also turns off the file watcher, which would walk every loaded module on every run. When editing streamlit_app.py, add --server.fileWatcherType auto.

What to expect

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.

Add your own documents

Use either route:

  • From the app. Drag .md/.txt/.pdf files onto Add documents in the sidebar and click Add to index. They are saved to data/ 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 run uv 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.

Keeping documents private

  • .gitignore ignores everything in data/ except the 3 samples. Saving your own file under a sample's name overwrites a tracked file, so use your own names. A DATA_DIR elsewhere inside the checkout is not ignored; add it to .git/info/exclude.
  • .env, .env.* and .streamlit/secrets.toml are ignored too. Only .env.example is 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.

Evaluation

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 sample data/ 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 baseline

A 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.json creates 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-baseline refuses 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 correct barely does; grounded can 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_TRACING is set to. Nothing outside the eval is traced.

Tracing with LangSmith

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_TRACING is the only switch, so a leftover LANGCHAIN_TRACING_V2=true sends nothing. Values other than true/false are 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 query waits at most about 10 seconds to send what is still queued.
  • Ingest is not traced. Only questions are.

Configuration

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.

Development

Linting and type checking

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 check

Tests

uv run pytest

Needs 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_URI are 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.

Live tests

These check what the fakes can't: that the real APIs behave as assumed.

uv run pytest -m live

They 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

Coverage is on demand, with no threshold:

uv run pytest --cov=rag_pipeline --cov=streamlit_app --cov-report=term-missing

The uncovered lines should only be ones a real terminal or API reaches, which the live tests cover.

Continuous integration

.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 pytest

Releases

A 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 push

When 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 main is 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-pipeline is taken there).

Project structure

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

How it works

  • Embedding. Voyage AI's voyage-4-large (1024 dimensions) embeds documents at ingest and questions at query time, each with the matching input_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() in ingest.py is the one way to open the store, and the process shares one MongoDB client.
  • Reranking. Vector search fetches FETCH_K candidates; Voyage rerank-3 scores each against the question directly and keeps the top RETRIEVAL_K. Its factory, build_reranker(), lives in pipeline.py because 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 why claude_model.py has its own adapter.

Swapping components

  • Another Voyage embedding model or reranker: change EMBEDDING_MODEL or RERANK_MODEL in .env.
  • Another Claude model: change CHAT_MODEL, and adjust the request in claude_model.py.
  • Another provider's embedder or reranker: edit build_embeddings() or build_reranker().
  • Another vector store: start with open_store() in ingest.py. The bookkeeping in ingest(), the index management and the writer lock also use MongoDB queries directly.

Invariants

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.

License

MIT. See LICENSE.

About

Retrieval-augmented generation over your own documents: Voyage AI embeddings and reranking, MongoDB Atlas Vector Search and Claude, with a CLI, a Streamlit chat app and a LangSmith-judged eval.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages