A production-grade document Q&A system with per-user isolation, six LLM providers with auto-failover, local ONNX embeddings at zero API cost, and end-to-end encrypted credential storage.
Off-the-shelf RAG libraries lock you into one LLM provider, charge per embedding, and mix every user's documents in a shared vector index. Any one of these is a production liability. This project was built to eliminate all three simultaneously.
When OpenAI raises prices or hits an outage, apps built on a single provider go dark. A failover chain was mandatory from day one.
Cloud embedding APIs charge per token. With high document volume, costs compound fast. Local ONNX MiniLM delivers comparable quality at zero marginal cost.
Shared vector stores create cross-tenant data bleed risk. Each user needs a separate ChromaDB collection to enforce strict ownership boundaries.
A clean separation between ingestion, retrieval, generation, and authentication. Each layer is independently swappable.
Eight production capabilities, each solving a real deployment problem.
ONNX MiniLM runs entirely in-process. No embedding API, no latency, no per-token billing.
Provider chain tries the next model automatically on rate-limit or error. Zero manual intervention.
Each user gets their own ChromaDB collection. No cross-user data bleed, by design.
Fernet symmetric encryption protects stored API keys. Rotate the master key, re-encrypt all.
tiktoken-aware splitting with 800-token chunks and 150-token overlap. No semantic truncation.
Conversation compresses to summaries after 6 turns. Context window stays clean across sessions.
Every answer includes doc name, page number, and a 200-character snippet. No black-box outputs.
Fake embeddings, mock LLM, isolated temp DB. CI runs with zero external API calls.
Every choice has a reason. No cargo-culting.
| Layer | Technology | Why |
|---|---|---|
| API Framework | FastAPI | Automatic OpenAPI docs, async support, Pydantic validation out of the box |
| Vector Store | ChromaDB | Embeddable, file-based, supports per-collection namespacing without infrastructure |
| Embeddings | ONNX MiniLM | Local inference, 384-dim vectors, runs CPU-only without GPU or cloud dependency |
| Auth | OAuth 2.0 (Google / GitHub) | No password management, delegates identity to trusted providers |
| Encryption | Fernet (cryptography) | Symmetric authenticated encryption; rotate master key to re-encrypt all stored credentials |
| Chunking | tiktoken | Exact token counting matches the target LLM's tokenizer, prevents silent truncation |
| Persistence | SQLite | Zero-config relational DB for users and sessions; replaces with Postgres via one env var |
| Infra | Docker GitHub Actions | Reproducible environments, automated lint and test on every push |
These are the tradeoffs that shaped the final architecture.
Cloud embedding APIs introduce per-request latency and metered cost that compound with volume. ONNX MiniLM runs synchronously in-process with no network hop. The quality tradeoff for retrieval tasks is negligible at this chunk size.
A six-provider failover chain means the system degrades gracefully under rate limits or outages. The LLMProvider base class enforces a single interface so adding a new provider is a 50-line drop-in with no changes to the RAG core.
Row-level filtering on a shared index requires every query to include a user filter predicate. Miss it once and you have a data leak. Separate collections make tenant isolation a structural guarantee, not a query discipline.
Passing full conversation history grows the prompt indefinitely. After six turns the system compresses older turns into a running summary. The LLM sees a bounded context window regardless of how long the session runs.
When retrieval returns zero chunks, the system returns a fixed "no relevant context" message instead of letting the LLM fill the gap from parametric memory. Grounding must be structural, not a system-prompt request.
The function that ties retrieval, grounding enforcement, and source citation together.
# NO_CONTEXT_MESSAGE prevents hallucination when retrieval returns nothing # The LLM never fills gaps from parametric memory def answer_question( vectorstore, llm, question, top_k=4, history=None, max_history_turns=6 ): # 1. Retrieve top-k chunks from user's isolated ChromaDB collection chunks = vectorstore.query(question, top_k=top_k) # 2. Hard stop if nothing was retrieved -- no LLM call, no hallucination if not chunks: return {"answer": NO_CONTEXT_MESSAGE, "sources": []} # 3. Generate grounded answer with conversation history answer = llm.complete( question, chunks, history=history, max_history_turns=max_history_turns ) # 4. Build source citations from retrieved chunk metadata sources = [ { "doc_id": c.metadata.get("doc_id"), "filename": c.metadata.get("filename"), "page": c.metadata.get("page"), "snippet": c.text[:200] } for c in chunks ] return {"answer": answer, "sources": sources}
The problems that required real thinking, not just wiring libraries together.
Each provider has different auth, error codes, and streaming protocols. The LLMProvider base class was designed last, after learning all six APIs -- not before. Designing the abstraction too early would have been wrong.
✓ Unified base class with per-provider implementationMulti-turn conversations grow the prompt unboundedly. Naive history truncation loses mid-conversation context that answers depend on. Rolling summaries preserve meaning while keeping token usage flat.
✓ Progressive summarization after 6-turn windowCI that calls real LLM APIs is slow, expensive, and flaky. Fake embeddings that return deterministic vectors and a mock LLM that echoes the prompt made the test suite fully offline and fast.
✓ Offline pytest suite with mock providersUsers supply their own LLM API keys. Storing them in plaintext is a non-starter. Fernet encryption with a server-side master key encrypts at write time and decrypts at use time, with no plaintext ever persisted.
✓ Fernet symmetric encryption at restWhat a hiring manager or client should take away from this project.
The durable lessons from building a production AI system end-to-end.
I built the OpenAI provider first, then Gemini, then the base class. Each concrete implementation revealed what the interface actually needed. Abstracting first would have locked in wrong assumptions.
Encryption at rest, tenant isolation, and hallucination prevention are enforced by architecture, not by runtime checks that can be bypassed. The system cannot accidentally expose data because the right exposure path doesn't exist.
Offline testing required the same design decisions as the production system: clean interfaces, injectable dependencies, no global state. Tests that require live APIs aren't testing the application logic -- they're integration tests dressed up as unit tests.
Better prompts don't fix bad retrieval. If the wrong chunks come back, no instruction to the LLM recovers the answer. Chunk size, overlap, and similarity threshold matter more than the system prompt in most failure cases.
Persistent file storage, long-lived processes, and in-memory model loading are incompatible with serverless platforms. Understanding platform execution models is now part of architecture planning, not an afterthought.
I'm open to full-time roles and freelance projects in AI engineering, full-stack development, and backend systems.