← Back to Portfolio
Case Study — Production AI System

Multi-Tenant
RAG Document Chatbot

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.

Python / FastAPI ChromaDB / RAG Multi-Provider LLM OAuth 2.0 Docker / CI-CD ▶ Personal Project · 2024–2025
6 LLM Providers
$0 Embedding API Cost
100% Offline Test Suite
MT Multi-Tenant Isolated
01 — The Problem

Why Another Chatbot?

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.

🔒

Vendor Lock-in

When OpenAI raises prices or hits an outage, apps built on a single provider go dark. A failover chain was mandatory from day one.

💵

Embedding Cost at Scale

Cloud embedding APIs charge per token. With high document volume, costs compound fast. Local ONNX MiniLM delivers comparable quality at zero marginal cost.

🔓

Data Isolation

Shared vector stores create cross-tenant data bleed risk. Each user needs a separate ChromaDB collection to enforce strict ownership boundaries.

02 — Architecture

How It All Connects

A clean separation between ingestion, retrieval, generation, and authentication. Each layer is independently swappable.

Client
React / cURL / REST Client JWT Bearer Token
↓ OAuth 2.0 (Google / GitHub)
Auth
FastAPI OAuth Router JWT Session Middleware SQLite Users DB
↓ Authenticated Request
Ingest
PDF / TXT / DOCX Parser Token-Aware Chunker (tiktoken) ONNX MiniLM Embedder
↓ Embeddings stored per-user
Vector DB
ChromaDB (per-user collection) Cosine Similarity Top-K Retrieval Fernet-Encrypted API Keys
↓ Retrieved chunks + history
LLM Layer
OpenAI Gemini Claude Grok Groq Ollama (local)
↓ Grounded answer + source citations
Response
{ answer, sources[] } Rolling Summary (6-turn window)
03 — Features

What It Actually Does

Eight production capabilities, each solving a real deployment problem.

💾

Local Embeddings

ONNX MiniLM runs entirely in-process. No embedding API, no latency, no per-token billing.

⚡

Auto-Failover LLM

Provider chain tries the next model automatically on rate-limit or error. Zero manual intervention.

🔒

Multi-Tenant Isolation

Each user gets their own ChromaDB collection. No cross-user data bleed, by design.

🔐

Encrypted Keys at Rest

Fernet symmetric encryption protects stored API keys. Rotate the master key, re-encrypt all.

📄

Smart Chunking

tiktoken-aware splitting with 800-token chunks and 150-token overlap. No semantic truncation.

💬

Rolling Summaries

Conversation compresses to summaries after 6 turns. Context window stays clean across sessions.

📋

Source Citations

Every answer includes doc name, page number, and a 200-character snippet. No black-box outputs.

🆕

Offline Test Suite

Fake embeddings, mock LLM, isolated temp DB. CI runs with zero external API calls.

04 — Stack

Technology Choices

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
05 — Design Decisions

Five Calls That Mattered

These are the tradeoffs that shaped the final architecture.

01

ONNX over cloud embeddings

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.

02

Provider chain over a single LLM

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.

03

Per-user ChromaDB collections, not row-level filtering

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.

04

Rolling summaries over full history

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.

05

Explicit NO_CONTEXT_MESSAGE over hallucination

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.

06 — Implementation

Core RAG Orchestrator

The function that ties retrieval, grounding enforcement, and source citation together.

app/core/rag.py Python
# 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}
07 — Challenges

What Was Actually Hard

The problems that required real thinking, not just wiring libraries together.

🔥 LLM API surface inconsistency

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 implementation

🔀 Context window management

Multi-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 window

🔎 Testing without live APIs

CI 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 providers

🔐 Secure credential storage

Users 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 rest
08 — Outcomes

What This Demonstrates

What a hiring manager or client should take away from this project.

6+1 LLM Providers Cloud failover chain plus local Ollama for air-gapped deployments.
$0 Embedding Cost Local ONNX MiniLM: no token billing, no network round-trip, no dependency.
100% CI Coverage Test suite runs fully offline. No live API keys required in CI.
MT Multi-Tenant Safe Structural isolation via per-user collections, not query-time filtering.
0 Hallucination Path When retrieval is empty, the LLM is never called. No parametric gap-filling.
∞ Session Length Rolling summaries keep context window bounded regardless of conversation length.
09 — Learnings

What This Project Taught Me

The durable lessons from building a production AI system end-to-end.

🎯

Abstractions should follow, not precede, the specifics

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.

🔒

Security is structural, not a checklist

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.

🏭

Test design is a design problem

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.

📈

RAG quality is a retrieval problem first

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.

🌎

Free-tier hosting has real constraints

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.

Available for work

Want to build something
like this together?

I'm open to full-time roles and freelance projects in AI engineering, full-stack development, and backend systems.