jasman.ai ←back to portfolio

Multi-Document RAGanswers grounded in cited chunks

An API where you upload PDFs, ask questions across all of them, and get an answer that points back to the exact source chunks it came from. Retrieval is a small LangGraph state machine that checks its own results and retries, and the model provider is a runtime setting, not a code dependency.

I built it to treat RAG as a system with failure modes — thin retrieval, cross-language questions, provider lock-in, leaked keys — rather than a single vector-search call.

2Retrievers fused
(vector + BM25)
7Nodes in the
LangGraph pipeline
1Adapter per port,
any OpenAI-compatible provider
0Provider keys
in .env
164Test functions
(unit + integration)
01
Context

The brief I set myself

Most RAG demos stop at "embed, search, stuff into a prompt". I wanted one that holds up when the documents are in a different language from the question, when the first retrieval misses, and when the person deploying it wants to switch from OpenAI to Gemini or a local model without a code change.

The stack is FastAPI, ChromaDB, BM25, LangGraph, Postgres and a plain HTML/JS frontend with no build step. It is deployed through a Railway config and a Dockerfile.

Scope. This is a personal project, built and tested by me end to end. The only test document is a synthetic, fictitious company profile. There is no client data and no production traffic behind it, so I make no usage or accuracy claims here.

02
Architecture

Retrieval as a state machine

The query path is a LangGraph graph rather than a linear function. Each step reads and writes a shared state, so the retry loop and the "no results" exit are explicit edges, not nested if statements.

precheck → analyze_query → retrieve → grade_documents → generate
                              ↑               │
                              └─ rewrite_query ┘   (if graded "insufficient",
                                                    bounded by RAG_MAX_RETRIES)
empty corpus → no_results
precheckIs the corpus empty? If so, exit early with a clear message.
analyze_queryAsk the LLM for up to 3 query variants, including a translation into a target language.
retrieveVector and BM25 search per variant, fused with reciprocal rank fusion.
grade_documentsJudge whether the candidates answer the question: sufficient, partial or insufficient.
rewrite_queryOn "insufficient", generate new variants using what was missing, then retrieve again.
generateAnswer only from numbered chunks, with inline citations.
03
Retrieval

Vector and keyword, fused

Embedding search finds paraphrases; BM25 finds the exact term, name or number that embeddings blur. Both run for every query variant and the ranked lists are merged with reciprocal rank fusion (k = 60), which needs no score normalisation between two very different scoring systems.

BM25 is indexed over the whole collection, or over the selected documents only, not over whatever the vector search happened to return. Otherwise a keyword match that the embedder ranked low could never surface. Chunking defaults to 1000 characters with 150 overlap; candidate counts (10 vector, 10 BM25, 8 final) are settings.

04
Failure handling

Grade, rewrite, retry

Skip the grader when it's obvious

If the top candidate's similarity is at or above a threshold (default 0.55), the grading LLM call is skipped. That saves a round trip on the easy majority of queries.

Fail open, not shut

If grading returns malformed JSON or errors, the verdict defaults to "sufficient". A flaky grader should never block an answer.

Bounded retries

A rewrite uses the "what was missing" note from the grader. Retries are capped by RAG_MAX_RETRIES (default 1), then it answers with what it has or falls back to "no results".

Cross-language by design

Question variants include a translation, and the generation prompt treats translations and synonyms as matches, so an English question can find an Indonesian passage.

05
Generation

Answers you can check

The model is told to answer using only the numbered context chunks and to cite them inline as [1], [2]. It chooses between two structured formats: steps for procedures and paragraph for everything else, and replies in the language of the question. The response carries the source chunks, and an admin setting can turn source display off.

The prompt also covers a quieter failure: a broad question like "summarise the key findings" shouldn't be refused just because the document has no section with that title. It should describe what the document does contain, and only say it can't find something when the context is truly unrelated.

06
Design

Ports and adapters, so providers are config

The core (services, retriever) depends only on two abstract ports, EmbedderPort and LLMPort. Concrete code lives in adapters: one LLM adapter and one embedder adapter, both built on openai.AsyncOpenAI(api_key, base_url).

OpenAI, Gemini (through its OpenAI-compatible endpoint), and local runtimes like Ollama, vLLM and LM Studio all speak that protocol. Switching provider is therefore a change of base URL, model and key, not a new class.

Those settings live in Postgres, one active row per role, and an admin edits them at runtime on /admin.html. Query and ingest return 503 until both the LLM and the embedder are configured, instead of failing obscurely halfway through.

07
Security

Auth and where the secrets live

JWT auth

Register, login, refresh and /me, with access and refresh tokens and bcrypt-hashed passwords. Admin routes are role-gated.

Keys encrypted at rest

Provider API keys are stored with Fernet encryption. The only secret that has to stay in .env is the root ENCRYPTION_KEY that protects the rest.

Write-only key field

The UI shows only whether a key is configured. No endpoint returns it in plaintext, and the form has explicit "keep", "replace" and "clear" states.

08
Verification

Tests and shipping

The suite has 164 test functions split into unit tests (adapters, hybrid retrieval and RRF, chunker, crypto, security, answer format, RAG service, repositories) and integration tests for the admin, auth, documents, ingest and query routes, plus a test that the API refuses to run when no provider is configured. Run it with make test from backend/. Migrations are Alembic, and the Railway config runs them once per deploy before the container starts.

FastAPI + Pydantic v2 LangGraph state machine ChromaDB vector store rank-bm25 + RRF PostgreSQL + Alembic SQLAlchemy async PyMuPDF pytest Docker · Railway
09
Honesty

What's weakest

BM25 is rebuilt on every query

The keyword index is built from the full corpus per request. That's fine for a handful of documents and will not scale to a large library. A persistent index is the fix.

No retrieval benchmark yet

I have not measured recall or answer quality on a labelled question set. The behaviour above is designed and unit-tested, not benchmarked, which is why this page quotes no accuracy number.

PDF only, text only

Ingestion handles text PDFs. Scanned PDFs, Office formats and streaming answers are written up as draft specs in my roadmap, not shipped.

Single shared collection

There is one document collection for the deployment. Per-team workspaces and conversation history are planned, not built.

The code, README and migrations are on GitHub.

View the repository