RAG Docs (opens in a new tab) answers questions about documents you upload, and shows the passages it used. This post explains how it works, from the moment a file is uploaded to the moment an answer comes back, and the problems I fixed along the way. Everything here is taken from the app's code.
What RAG means here
RAG stands for retrieval-augmented generation. A language model doesn't know what is in your files, so before asking it anything, the app finds the parts of your files that are most likely to hold the answer and sends only those, with the question. The model writes the answer from that text.
Finding "the most likely parts" uses embeddings: a model turns a piece of text into a list of numbers, and texts with similar meaning get similar numbers. Store one embedding per chunk of a document, embed the question the same way, and the closest chunks are the best candidates.
The stack
- Next.js 16 and React 19 for the app and its API routes.
- Supabase for sign-in and a Postgres database with the pgvector extension, which stores embeddings and measures the distance between them.
- Transformers.js (
@huggingface/transformers) running all-MiniLM-L6-v2 on the server to make embeddings. - The Anthropic and OpenAI SDKs to write answers, with the user's own key.
- Vitest for tests.
Uploading a document
An upload goes through one API route, in this order:
- Check the file. PDF, TXT or Markdown, up to 10MB. Windows browsers often send an empty type for
.mdfiles, so the route also accepts the.mdand.txtextensions. - Check the user's limits. Up to 50 documents, and one upload at a time.
- Extract the text. PDFs go through
pdf-parse; everything else is read as UTF-8 text. - Split it into chunks. Whitespace is collapsed, then the text is cut into 1,000-character chunks, each starting 150 characters before the previous one ended. The overlap means a sentence that falls on a boundary still appears whole in one chunk.
- Embed and store. Chunks are embedded and inserted 64 at a time, each row carrying its document, its owner and its position.
- Mark the document ready.
The chunker is deliberately simple:
const CHUNK_SIZE = 1000;
const CHUNK_OVERLAP = 150;
export function chunkText(text, chunkSize = CHUNK_SIZE, overlap = CHUNK_OVERLAP) {
const normalized = text.replace(/\s+/g, " ").trim();
if (!normalized) return [];
const chunks = [];
let start = 0;
while (start < normalized.length) {
const end = Math.min(start + chunkSize, normalized.length);
chunks.push(normalized.slice(start, end));
if (end === normalized.length) break;
start = end - overlap;
}
return chunks;
}
Embeddings run on my server
I chose to run the embedding model myself instead of calling an embeddings API. all-MiniLM-L6-v2 is small (about 90MB, downloaded once into a cache on first use) and returns 384 numbers per text. The model is loaded once per server process and reused.
One function is the only place the model is called. Stored chunks and incoming questions both go through it, so they are always embedded the same way. Mixing two embedding methods would make every distance meaningless.
Running the model on the server's CPU has a cost, and I measured it. On an M4 machine each chunk took about 15 milliseconds whatever the batch size, but peak memory grew with the batch: about 640MB for 16 chunks at a time, and about 1.5GB for 64. So the model runs on slices of 16, and the route inserts rows 64 at a time. A large file no longer takes the server's memory with it.
That CPU cost is also why the limits exist. A file over 2,000 chunks, about 1.5 million characters, is rejected before anything is embedded, because the request would outlive typical host timeouts. The user is asked to split it instead.
Searching only your own chunks
Search is a Postgres function, match_chunks, called from the question route. It takes the question's embedding
and the user's id, and optionally one document to search in. It returns the six chunks with the smallest cosine
distance, along with a similarity score.
Two rules are built into that function:
- Only the caller's chunks. The user id comes from the signed-in session on the server, never from the request body.
- Only finished documents. Chunks are inserted in batches while a document is still processing, so the function joins each chunk to its document and skips any document that isn't marked ready. A half-uploaded file never shows up in an answer.
Why there is no vector index
The first version had an IVFFlat index on the embeddings, the usual way to speed up vector search in pgvector. An IVFFlat index groups vectors into lists and, by default, only probes one list per search. The user filter was applied after that probe, so if the list it picked held none of your chunks, your search came back empty.
I removed the index. Search is now exact: Postgres uses the index on user_id to find one user's chunks and
compares the question with each of them. At the size of one person's documents that is fast, and it is always
correct. The schema notes when to revisit it: past about 100,000 chunks for one user, add an HNSW index with
iterative scan.
Writing the answer
The six chunks are numbered and sent with the question to Claude or OpenAI. The system prompt is short:
You answer questions using only the provided document excerpts. If the excerpts don't contain the answer, say so clearly instead of guessing. Cite which excerpt(s) you used by their number, like [1] or [2].
The chat shows the answer with a collapsed "sources" list underneath, numbered to match the citations, so you can check what the answer was based on.
Two edge cases are handled in code rather than left to the model:
- A refusal. If the model declines and returns no text, the app says the model declined, instead of showing an empty bubble.
- A cut-off answer. If Claude hits its output limit, the answer is shown with "(answer truncated)" at the end.
If nothing relevant is found at all, the model isn't called; the app asks you to upload a document or rephrase.
Bring your own key
RAG Docs doesn't pay for anyone's answers. Each user enters an Anthropic or OpenAI key in the app:
- The key stays in the browser. It is saved in local storage and sent with each question. The server uses it for that one request and never stores it.
- Keys are checked before you rely on them. A check calls the provider's list-models endpoint, which costs no tokens. A rejected key is reported as invalid; a network error or rate limit is reported as "could not verify", so a good key is never called wrong.
- Keys belong to one account. Browser storage is shared by everyone using that browser, so when a different account signs in, the previous account's keys are deleted.
The database only trusts the server
Supabase gives the browser a public key that can talk to the database directly, so row-level security decides what it may do. In RAG Docs the browser may only read its own documents and chunks. There are no insert, update or delete policies at all.
Every write goes through an API route that checks the session and then uses the server's own key. That matters because the limits live in those routes: if the browser could insert rows itself, it could skip the 50-document cap and the one-upload-at-a-time rule. Deletes are matched on both the document id and the signed-in user, so nobody can delete another person's file by guessing an id.
When an upload fails
A failure partway through could leave some chunks stored and the document stuck. The route handles both:
- Partial chunks are deleted and the document is marked failed, so a failed upload leaves nothing searchable.
- Errors meant for the user (no text in the file, too much text) are shown as written. Anything else shows a generic "Could not process this file", with the details in the server log rather than the browser.
- A stuck upload doesn't block you forever. If a crash leaves a document "processing", it stops counting as your active upload after 10 minutes.
One shortcut is written down in the code: two uploads sent at the exact same moment can both pass the one-at-a-time check. At this scale that is acceptable.
Tests
The Vitest suite covers the parts most likely to break quietly: chunking, the upload route (batching, cleanup on failure, every limit, and that an upload is always owned by the signed-in user), the question route (length limits and searching only the caller's chunks), deleting only your own documents, key storage across accounts, and answer generation.
You can try it at rag.iamsaumya.com (opens in a new tab) with your own Claude or OpenAI key.
Want AI that answers from your own data?
I build retrieval features that cite their sources and fail safely: document search, support answers, internal knowledge tools. Tell me what your data looks like.