Skip to content
Shehryar Ahmed
All projects

Case study 01 · Independent build

IlmoraEnterprise RAG Knowledge Assistant

A company knowledge assistant that answers only from uploaded documents and cites the section behind every statement.

Role
Sole engineer: architecture, retrieval pipeline, backend, frontend, Docker and CI
Status
Core product implemented · answer-level evaluation planned
Core stack
  • Python
  • FastAPI
  • PostgreSQL
  • pgvector
  • OpenAI
  • React

The source code is in a private repository, so this page documents the design instead of linking to it.

01

Overview

Ilmora is an internal knowledge assistant. Admins upload company documents (policies, workflows and feature guides as PDF, Word or Excel) and employees ask questions in a chat. The assistant answers only from those documents and cites the document and section behind each statement.

I built it end to end, in phases. Each phase added one capability and was documented with the reasoning and measurements behind it: parsing and chunking, embeddings and vector search, grounded generation, conversation history, hybrid retrieval with reranking, and finally feedback and analytics.

02

Business problem

  • Policies and process guides live in long documents. Employees ask the same questions repeatedly, or answer from memory.
  • A general-purpose chatbot is the wrong tool for this: it answers confidently from general knowledge, cannot show where an answer came from, and cannot tell when the documents simply don't cover a question.
  • Internal documents are full of short forms (SDR, MQL, PTO, T&E) and numeric rules ("up to 20% over the city limit"). Plain vector search handles the first poorly, and single-pass generation handles the second poorly.

03

Solution

  • Structure-aware ingestion that keeps headings, numbered steps and tables intact, so every chunk is a coherent section that carries its heading path.
  • Hybrid retrieval: pgvector semantic search next to PostgreSQL full-text search, merged with reciprocal rank fusion, plus glossary expansion for short forms and a local cross-encoder reranker that also decides when nothing relevant exists.
  • A grounded prompt that permits only the retrieved sources, requires [n] citations, and makes the model work out rules and calculations before concluding. Answers stream over server-sent events, and citations are validated server-side.
  • The product around it: JWT auth with rotating refresh tokens, conversation history with follow-up rewriting, an admin knowledge base, glossary management, a search playground, feedback review, an unanswered-questions log and analytics.

04

My contribution

  • Designed the architecture and built the whole system: FastAPI backend, ingestion and retrieval pipeline, prompts, React and TypeScript frontend, Docker images and GitHub Actions CI.
  • Wrote a retrieval evaluation script and labelled question set, and used it to measure every retrieval step before keeping it.
  • Documented each design decision and its measurements alongside the code.

05

Technical architecture

Ingestion and question answering

9 stages

  1. 01

    Document upload

    PDF, DOCX, XLSX or CSV via the admin API

  2. 02

    Parsing

    Headings, lists, tables and pages; repeated headers and footers removed

  3. 03

    Structure-aware chunking

    300–700 tokens, semantic boundaries first, heading breadcrumbs

  4. 04

    Embeddings

    OpenAI text-embedding-3-small at 768 dimensions

  5. 05

    PostgreSQL + pgvector

    HNSW vector index and a weighted tsvector (GIN) per chunk

  6. 06

    Hybrid retrieval

    Vector + keyword search, glossary expansion, RRF

  7. 07

    Reranking

    Cross-encoder on CPU with a relevance floor

  8. 08

    LLM

    Grounded prompt, streamed over SSE

  9. 09

    Cited response

    Validated [n] citations and a highlighted source viewer

Ingestion runs as a background task after upload. Retrieval and generation run per question; sources are sent to the client before the answer starts streaming.

Ingestion

  • Parsers for Word, PDF, Excel and CSV produce typed blocks
  • Section builder assigns every block a heading path
  • Chunker keeps lists, tables and rows whole
  • Document overview chunk written by the model
  • Embeddings and keyword vectors stored in one transaction

Retrieval

  • Two-way glossary expansion (SDR ↔ Sales Development Representative)
  • Unexplained short forms spelled out by the model as an extra query
  • Vector and keyword search, 20 candidates each, fused with RRF
  • Top 12 reranked; low-scoring questions get no sources
  • Split sections completed within a 3-source / 2,000-token budget

Answering

  • Follow-ups rewritten into standalone search queries
  • Recent turns included within a token budget
  • Streamed generation with cancellation
  • Citations validated against the provided sources
  • Every answer saved with an outcome (answered, not found, no sources)

Product and admin

  • JWT auth with refresh-token rotation and reuse detection
  • Knowledge base with versioning and chunk preview
  • Search playground that shows every retrieval step
  • Feedback review, unanswered questions and analytics
  • User management and system status

06

Technology stack

Backend
  • Python 3.12
  • FastAPI
  • SQLAlchemy (async)
  • asyncpg
  • Alembic
Retrieval
  • PostgreSQL 16
  • pgvector (HNSW)
  • Postgres full-text search
  • fastembed cross-encoder (ONNX)
AI
  • OpenAI API
  • text-embedding-3-small
  • gpt-4.1-mini
  • gpt-4o-transcribe
Frontend
  • React 19
  • TypeScript
  • Vite
Infrastructure
  • Docker
  • Docker Compose
  • Caddy (HTTPS)
  • GitHub Actions

07

Key engineering challenges

Acronyms and short forms

Vector search scored "What is an MQL?" at 0.49 against the chunk that defines it, lower than some unrelated questions. The fix combined keyword search, a glossary extracted from the documents (validated with the Schwartz–Hearst algorithm), two-way expansion of questions, and a model call to spell out short forms only when nothing in the knowledge base explains them.

Knowing when not to answer

Embedding similarity could not separate off-topic questions from answerable ones: an off-topic question still reached 0.46. The reranker's score gives a usable floor. Below it, the assistant returns a fixed "couldn't find this" reply without calling the model, and the question is logged as unanswered for admins.

Procedures split across chunks

Long sections are split by size, so a how-to could reach the model with half its steps. Retrieval adds adjacent parts with the same heading path (up to three each way), then fits the groups into the source and token budget, shrinking a group around its matched chunk if needed.

Rules that need arithmetic

A "direct answer first" prompt made models commit to "Yes" for a $265 hotel before computing the $264 limit. The prompt now requires listing each applicable rule and writing out the calculation before a bold conclusion.

Streaming without holding connections

Database sessions close as soon as the question is stored and streaming starts. The answer is saved in a new short-lived session when the stream ends, whether it completed, was stopped by the user or failed.

08

Technical decisions and trade-offs

Why hybrid search instead of vector search alone?

Vector search captures meaning but is weak on exact tokens: acronyms, product names, codes and numbers. Keyword search over a weighted tsvector (heading path weighted above content) catches exactly those.

The two return scores on different scales (cosine similarity versus ts_rank_cd), so they are merged by rank with reciprocal rank fusion: each chunk scores the sum of 1 / (60 + rank) across the rankings it appears in. Nothing needs calibrating, and chunks found by both searches rise to the top.

Trade-off: More candidates also means a noisier first place. On the evaluation set, hybrid search alone slightly lowered hit@1. That is the reranker's job to fix.

Why reranking?

Embedding search compares two vectors that were computed independently. A cross-encoder reads the question and the passage together, so it judges relevance much more precisely. The top 12 fused candidates are rescored by ms-marco-MiniLM-L-12-v2 running in-process on ONNX Runtime.

Its score also provides a relevance floor that recognises off-topic questions, which embedding similarity could not do.

Trade-off: Latency: roughly 65 ms per passage on a laptop CPU, so retrieval went from about 0.1 s to about 2 s in development measurements. If the model is still loading or failed to load, questions are answered without reranking instead of waiting.

How do citations and grounding work?

Each selected section is passed to the model as a numbered <source> block with its document title, heading path and location (page, or sheet and rows). The system prompt permits only those sources, requires [n] citations for every statement, and prescribes the exact phrase to use when the sources don't cover the question.

Sources are treated as reference material, not instructions, and a closing source tag inside document text is neutralised to guard against prompt injection. After streaming, only citation numbers that map to a provided source are kept. In the UI, a citation opens the original PDF page or Word paragraph with the passage highlighted.

Trade-off: Strict grounding means the assistant declines questions a general model could answer. For internal policy, that is the intended behaviour.

How are retrieval quality and answer faithfulness evaluated?

Retrieval is measured with a script over a labelled question set, where each question lists the sections that answer it. Metrics: hit@1, hit@5, mean reciprocal rank, whether an answering section reaches the final sources, and whether off-topic questions correctly get none. Each retrieval step was added and measured on its own.

Answer faithfulness is not evaluated automatically yet. The plan is a golden Q&A set that checks whether every cited statement is supported by its source, used together with the signals the app already records: answer outcomes, thumbs up/down with reasons, and the unanswered-questions log.

Trade-off: The current set is small (32 questions over two documents), so it guides decisions rather than serving as a benchmark.

Reciprocal rank fusion

python
def fuse(
    rankings: Sequence[tuple[Literal["vector", "keyword"], list[ChunkHit]]], k: int
) -> list[Candidate]:
    """Reciprocal rank fusion of the rankings, best first."""
    candidates: dict[uuid.UUID, Candidate] = {}
    for kind, hits in rankings:
        for rank, hit in enumerate(hits, start=1):
            candidate = candidates.get(hit.chunk.id)
            if candidate is None:
                candidate = candidates[hit.chunk.id] = Candidate(
                    hit.chunk, hit.document, hit.similarity
                )
            candidate.fused_score += 1 / (k + rank)
            if kind == "vector":
                candidate.vector_rank = min(candidate.vector_rank or rank, rank)
            else:
                candidate.keyword_rank = min(candidate.keyword_rank or rank, rank)
    return sorted(
        candidates.values(), key=lambda c: (-c.fused_score, -c.similarity)
    )
Excerpt from the retrieval service. Vector and keyword rankings are merged by rank, so their incompatible scores never need to be compared.

09

Implemented functionality

ImplementedPlanned
  • Document ingestion for PDF, Word (.docx), Excel (.xlsx) and CSV

    Implemented
  • Structure-aware parsing and chunking with heading breadcrumbs

    Implemented
  • OpenAI embeddings stored in pgvector with an HNSW index

    Implemented
  • Hybrid retrieval: vector + full-text search merged with RRF

    Implemented
  • Glossary expansion from extracted and admin-managed terms

    Implemented
  • Cross-encoder reranking with a relevance floor

    Implemented
  • Grounded answers streamed over SSE with validated citations

    Implemented
  • Source viewer that highlights the cited PDF page or Word paragraph

    Implemented
  • Conversation history with follow-up question rewriting

    Implemented
  • JWT authentication, refresh-token rotation, admin and user roles

    Implemented
  • Admin tools: knowledge base, glossary, search playground, users, status

    Implemented
  • Feedback, unanswered-question log and analytics dashboard

    Implemented
  • Voice questions via OpenAI transcription

    Implemented
  • Docker images, production Compose config and GitHub Actions CI

    Implemented
  • Retrieval evaluation script (hit@k, MRR, off-topic handling)

    Implemented
  • Answer correctness and faithfulness evaluation

    Planned
  • OCR for scanned PDFs and a dedicated ingestion job queue

    Planned
  • Multilingual retrieval (full-text search and reranker are English-only)

    Planned

10

Outcomes and future improvements

Outcomes

  • A complete RAG product: ingestion, hybrid retrieval, grounded streaming answers, and the admin tooling needed to run and improve it.
  • On the development evaluation set, the full pipeline ranked an answering section first for 93% of questions and rejected every off-topic question, compared with 83% and none for vector search alone.
  • All model calls go through one OpenAI client that can point at any OpenAI-compatible endpoint.

Retrieval evaluation, step by step

Retrieval modehit@1hit@5MRROff-topic rejected
Vector search only83%100%0.890 of 3
+ keyword search (hybrid, RRF)79%100%0.890 of 3
+ glossary expansion76%100%0.870 of 3
+ short forms spelled out72%100%0.850 of 3
+ cross-encoder reranker (default)93%100%0.963 of 3
Development measurements on 32 questions over two sample documents (15 use short forms, 3 are off-topic). Measured with an earlier local embedding model before the switch to OpenAI embeddings, and not yet re-measured, so treat them as directional.

Next steps

  • Automated answer evaluation for correctness and faithfulness, with a larger question set run in CI.
  • OCR for scanned PDFs and a dedicated job queue for ingestion.
  • Multilingual retrieval and semantic caching.