Code by

Carter

Phan

RAG Document Analysis Backend

RAG Document Analysis Backend

Year2026
PythonFastAPILangChainLangGraphPostgreSQLpgvectorOpenAIGoogle Drive APISupabase AuthPrometheusOpenTelemetryDocker

Project Description

Verbiage — a production RAG backend for storm damage inspection reports. Hybrid retrieval (pgvector + Postgres FTS fused with RRF), a pre-LLM relevance gate that refuses off-corpus questions, optional cross-encoder reranking, and one-shot corrective rewrite. Ships a LangGraph report writer with vision analysis and PDF/DOCX export, Google Drive ingestion via a durable Postgres job queue, Supabase auth, Prometheus/OTel observability, and an NLI-based faithfulness eval gate.

Every inspection team has the same invisible tax: the report you need to write has already been written a hundred times before, sitting in a PDF somewhere nobody can search. A field engineer describes a hail-damaged roof, then spends forty minutes hunting for the wording another engineer used on a nearly identical claim three years ago.

I built Verbiage to kill that tax. You describe the case, it retrieves the closest matching language from your own past reports, and it hands back grounded verbiage with citations — or it refuses, out loud, when your corpus genuinely doesn't cover the question.

Flow diagram: field notes enter as a query, get normalized, split between lexical and hybrid retrieval, fused with Reciprocal Rank Fusion, gated by cosine similarity, then either refused before any LLM call or reranked and sent to generation with citations.

The gate is the whole point

The easy version of this project is twenty lines: embed the question, grab top-k chunks, stuff them in a prompt, ship it. It demos beautifully and lies constantly, because a vector index always returns something. Cosine similarity will happily hand you the least-irrelevant chunk in a corpus that has nothing to do with the question, and the LLM will dutifully write confident prose around it.

So the first thing I built wasn't retrieval. It was the refusal path.

Before any text ever reaches a model, the best chunk's cosine similarity has to clear RAG_MIN_RELEVANCE_SCORE. Below that line, the request is answered with "I don't have relevant context" and the LLM is never called. Off-corpus questions cost zero tokens and produce zero hallucinations, deterministically, because the decision is a comparison rather than a judgement call.

That single constraint changed how every other component had to be designed — including how queries get cleaned, which is a detail most RAG systems skip.

Query normalization: protecting the gate from fluffy questions

Real users don't type search queries. They type "hey can you tell me what kind of damage was documented on the roof at 100 Harbor Example Road." Embed that sentence verbatim and the instructional padding — "can you tell me", "kind of" — drags the vector away from the actual topic and pushes cosine similarity down toward the gate. The system refuses a question it could have answered.

So retrieval runs against a normalized query instead. Quoted phrases are preserved as-is, since a user quoting exact wording is telling you what matters. Otherwise the instructional prefixes and corpus fillers get stripped, leaving the topic. The LLM prompt still receives the original question — the model should hear the user, not the query-optimized husk. Normalization exists purely to keep embeddings and the lexical index honest.

Hybrid retrieval, fused by rank

Semantic search is bad at the thing users do most: exact lookups. Ask for a claim number, a street name, a specific identifier, and embeddings smear it into a blur of similar-looking tokens. Postgres full-text search nails it, but has no idea that "roof damage" and "hail-damaged shingles" are the same concept.

So retrieval runs both and fuses them. Vector results from pgvector and lexical results from Postgres ts_rank are combined with Reciprocal Rank Fusion — each result's score is its rank position rather than its raw distance, which sidesteps the fact that cosine similarity and ts_rank live on incomparable scales. A FusedHit carries both provenance and the fused rank.

Which path runs depends on the query's shape. Short identifier-style and quoted queries route straight to lexical. Everything else goes hybrid. Callers can force vector, lexical, or hybrid explicitly, but the auto router handles it correctly most of the time — and because the routing rule is a classifier rather than a loop, it's cheap enough to run on every request.

Diagram of the retrieval layers: pgvector cosine candidates and Postgres ts_rank candidates merging through reciprocal rank fusion into a single ranked candidate pool before the cross-encoder reranks the survivors.

Optional reranking, for when recall isn't precision

RRF gives you a strong candidate pool. It doesn't guarantee the best chunk sits at position one. When RERANK_ENABLED=1, the pipeline pulls a wider net and runs the candidates through a cross-encoder — ms-marco-MiniLM-L-6-v2 — which scores each chunk against the query jointly rather than comparing two independently-produced vectors. Joint scoring catches relevance that cosine similarity structurally cannot express.

The model is warmed at startup, kept off in tests and CI to avoid the load cost, and behaves as a no-op when the flag is false. Retrieval quality becomes a deployment dial instead of a rewrite.

Corrective rewrite-once

There's a failure mode that survives all of the above: retrieval clears the gate, so the model runs, but the model decides the context doesn't actually answer the question and soft-refuses with "no source documents contain that information."

Sometimes that's correct. Sometimes the user asked about intact roof tiles and the corpus says "no storm-created opening" — same concept, zero lexical overlap, so the query never had a chance. Verbiage handles that with exactly one corrective step. If the soft refuse maps to a known domain phrase, the query gets rewritten, re-embedded, re-retrieved, and generated against once more. If the map produces nothing, the soft refuse stands.

One retry, hard stop. That's the entire loop — and deliberately so.

The distinction matters because "agentic RAG" gets thrown around loosely. Adaptive retrieval decides which path. Corrective retrieval decides whether to loop. An agent owns the loop with a stop condition. This system has a bounded corrective step, not an agent — and being honest about which one you built is worth more in an interview than claiming the buzzword.

Chunking that respects how reports are written

Paragraph-first chunking, not fixed token windows. Line endings normalize, text splits on blank paragraphs, and section headers get detected from numbered lines, short all-caps lines, and title-case headings. Paragraphs merge up to roughly 1,200 characters with 150 characters of overlap, and oversized paragraphs split at sentence boundaries so a thought never gets guillotined mid-clause.

Then each chunk gets a breadcrumb prefix applied at index time — the document title, optionally the source and filename, plus the detected section label. Embedding [Document: Roof Inspection — Harbor Rd] [Section: Findings] alongside the body text means a chunk about tile damage is retrievable as tile damage in a roof inspection, not as free-floating vocabulary. This is a quiet, unglamorous change that moved retrieval quality more than any prompt engineering I did.

Crucially, the full extracted text lives in documents.full_text. Chunking strategy becomes reversible — change the parameters, hit the reindex endpoint, and rebuild embeddings from stored text without asking anyone to re-upload a single PDF.

Ingestion as a durability problem

Uploads are the least interesting part of a RAG system and the one that breaks most often. A 200-document Google Drive folder sync isn't a request; it's a job.

Ingest goes through a Postgres-backed queue with an in-process worker, batch status tracking, stale job reclamation, and cancellation. Drive batches return immediately with a batch ID the frontend polls. A crashed worker doesn't lose work — the job is still in the table, still claimable. Documents report their index state as indexed, not indexed, or stale, so a re-run only touches what actually drifted, and repeated Drive syncs collapse to the newest version of each file instead of piling up duplicates.

Text extraction handles PDFs and DOCX and deliberately skips Apple Pages, because every report already ships as PDF or DOCX and parsing Apple's XML buys nothing but fragility.

Screenshot-style diagram of the document library showing index status badges, source filenames, chunk counts, and the embedding model used for each record.

Report Writer: from retrieval to a finished draft

Ask is reactive — you ask, it answers. The Report Writer is the generative half: a LangGraph state machine that drafts structured report sections from field notes, claim metadata, and photos of the actual damage.

It runs through the same relevance gate as Ask. If similar past reports don't support a section, it refuses rather than inventing boilerplate — the gate isn't a feature of one endpoint, it's a property of the system. Photo analysis uses vision models with a cache so re-running a draft doesn't re-pay for the same image, Drive photo sync keeps claim photos current, and a retry path exists for jobs that get stuck mid-analysis.

Sections regenerate individually, so fixing one paragraph doesn't re-trigger photo analysis across the whole report. Graph state checkpoints to Postgres, which makes long generations resumable, and an optional human-in-the-loop pause lets a reviewer sanity-check context before spending tokens on generation. Progress streams to the SPA over SSE. Finished reports export to PDF and DOCX with configurable photo limits.

A node-and-edge diagram of the LangGraph report workflow: field notes and photos enter, retrieval gates on relevance, vision analysis caches per image, sections generate in parallel, validation checks each draft, then export renders PDF or DOCX.

Measuring faithfulness instead of hoping for it

Grounding claims are cheap to make and expensive to verify, so I built the verification. The eval harness freezes a small corpus and a set of gold questions, runs the full pipeline in Docker, and scores faithfulness — breaking each answer into claims and asking, per claim, whether the retrieved context actually supports it.

The scoring uses a local NLI model rather than calling OpenAI on every tweak, which makes the gate fast enough to run as a regression check. The gold set requires faithfulness of 1.0, meaning every generated claim is supported. That's a regression gate, not a quality trophy — the gold set is small and hand-built, so it catches the moment a prompt or retrieval change starts letting unsupported claims through, and it says nothing about absolute real-world quality.

Alongside it, live metrics track the drift a test suite can't see. A low-quality-retrieval counter fires whenever top-1 similarity lands under threshold, which is the earliest signal that a corpus, an embedding model, or a chunking change is quietly degrading answers. Prometheus exposes /metrics behind an optional bearer token, OpenTelemetry traces export to Grafana Tempo, and /health/ready gates deploys on database reachability and reranker warm-up rather than just process liveness.

What I took from building it

The relevance gate is the design decision everything else orbits. Once the system is allowed to say "I don't know," two things happen: users trust the answers it does give, and you stop needing to bolt guardrails onto the prompt. Refusal as a first-class output is cheaper, faster, and more honest than any amount of "please only answer from the context provided."

Second, the boring infrastructure is the product. Query normalization, breadcrumb prefixes, canonical full-text storage, a durable job queue, index status badges — none of it is demo material, and all of it is the difference between a notebook and something a team uses on a Tuesday when a batch import fails halfway through.

Third, bounded agency beats unbounded cleverness. One rewrite, one stop condition, one gate. I could bolt on a multi-tool planner and let it loop until it's satisfied; every extra degree of freedom is another way to burn tokens on a question the corpus can't answer anyway.

The roadmap is where the architecture naturally points: multi-turn follow-ups that carry conversation state without re-retrieving everything, a confidence score surfaced to the user so "this is close" reads differently from "this is exact," and expanding the corpus beyond reports into inspection standards so the writer can cite the code requirement alongside the precedent.