AI work/Document chat

Document chat

FastAPI, pgvector on Neon, a Gemini free tier, and an answer that names the chunk it came from or refuses to answer at all.

  • 53 of 53 eval questions
  • 100% citation and refusal
  • 4.1 s mean answer

Running live: document-chat-rag-vnid.onrender.com · Docker on Render, Neon pgvector, 295 chunks from 8 documents

01

A question in, a cited answer or a refusal out

Ask about a set of Markdown documents and get an answer built only from them, with the chunks it used and the file each came from. Ask something the documents do not cover and it says so, without calling the model at all.

  • Python 3.12
  • FastAPI
  • pgvector
  • Neon Postgres
  • Gemini API
  • Flutter client
  • pytest

8 documents, 53 eval questions · 1,099 backend tests, 155 client tests · Ghon4/document-chat-rag

02

What you get, before the architecture

Every chat app with a model behind it answers confidently about things it was never given. That is fine for a toy and useless for a document: a person who cannot check the answer has to take it on faith, and the app has no way to tell them when the faith is misplaced.

This one is built the other way round. An answer carries the chunks it was built from, so the claim can be checked in one tap. When nothing close enough is found, the answer is a refusal and the model is never called, so a refusal is cheap, fast and the same every time.

An answer you can check, or an honest no. The interesting part is everything that decides which one you get.

03

The problem

Three things go wrong in a retrieval system, and they pull against each other.

  1. Retrieval that is too eager invents. Something is always the closest chunk in the store, so a system with no floor answers every question, including the ones the corpus cannot support.
  2. Retrieval that is too strict hides the answer. A compound question ("how do I X, and how do I Y") is two searches pretending to be one, and a single search tends to find only one half.
  3. An answer nobody can check is not an answer. Without the chunk and the file, the reader has to trust the model's summary of text they cannot see.

So there are three separate jobs: decide whether to answer at all, get the evidence for every part of the question, and show it.

04

The design

The first decision is made in code, before the model is involved. Everything else follows from it.

What retrieval findsWhat the person gets
Chunks closer than 0.6An answer built only from them, with those chunks returned as sources
Nothing closer than 0.6The refusal text, grounded: false, no sources, and no model call
A question asking two thingsEach part searched on its own, then the closest chunks of every part together
Another user's chunksNever retrieved: the owner is a filter on the query itself

The refusal is decided before the model is called

MAX_DISTANCE is 0.6, one number in ask.py. If every chunk of this owner is farther away than that, the answer is the fixed refusal string and the chat model is never asked. A refusal therefore costs one embedding call, takes about half a second, and cannot vary between runs. The model is never in a position to decide that a question is out of scope, which is exactly the decision it is worst at.

Citations are the chunks, not a bibliography

POST /ask returns the chunks it sent to the model: the file, the chunk index, the cosine distance and the text. The client makes each one tappable, so the reader lands on the paragraph the answer was built from rather than on a list of documents. A citation that cannot be opened is decoration.

A compound question is split, because one search returns one thing

split_question cuts on punctuation and conjunctions and searches each part separately, then adds the closest chunks of each part to the set. Without it, the half of the question with weaker word overlap disappears from the evidence, and the model refuses a question the corpus does answer.

The owner is a filter on every query, not a check in the app

Every chunk row carries an owner, and every read filters on it, including the search inside the agent's tool. There is no code path that lists chunks across owners. It is isolation between names, not authentication: a user is a string the client sends.

The model sits behind an interface

src/python_ai/llm.py defines the provider, and providers/gemini.py is one implementation of it. Every test runs on a fake, so the suite never needs a key, never opens a socket and never spends quota. Swapping the vendor is one file.

Container diagram: the Flutter client calls a FastAPI backend, which splits and embeds the question, searches pgvector for the owner's chunks within a maximum distance, sends those chunks to Gemini with a prompt that forbids outside knowledge, and returns the answer with its sources. A CLI ingests the corpus and runs the eval through the same code.
Container view. A refused question never reaches the chat model: nothing close enough is decided in code, before the call.
05

Eval

53 questions, four kinds, three checks, all scored in code. No model judges the answers, so the numbers mean the same thing on every run.

KindQuestionsWhat it tests
direct20One document answers it, and the file that must be cited is named
multi-part12Compound phrasing where a single search finds only one half
near-miss12About the corpus, but asks for something it does not cover; must be refused
off-topic9Nothing to do with the corpus; must be refused

The three checks are refusal (refused exactly when the golden set says so), citation (the expected file is among the sources) and groundedness (at least half of the answer's distinct content words appear in the chunks it cites). The run of 3 Dec 2026 scored 53 of 53 on all three, with a mean of 4.1 seconds and a maximum of 18.4.

The two questions that failed, and the fix

The run before that one scored 51 of 53. Both failures were compound questions, and --show-chunks showed retrieval was not the cause: for one of them both halves were already in the seven chunks sent to the model, as examples rather than as plain words. The model had been told to refuse unless a single excerpt answered the question, and no single excerpt did.

The fix was in the prompt, not the retrieval: facts may be combined across excerpts, with the file name of each, and the refusal still applies unless the excerpts together cover every part. Three full runs after the change scored 52, 53 and 53. The same run also tested a wider net, five chunks per part under the same cap of eight, which brought the missing chunk in but pushed out the chunk with the model class, and passed 1 of 6. That change was reverted.

One question still sits on the model's threshold and refuses about one run in four. It is named in the report, and eval --check will call it out the day it fails after passing.

The gate, and why it is not in CI

eval --check runs the same 53 questions and exits 1 if a question that passed in the committed results now fails. It writes nothing, so a bad run cannot become the new baseline. It is a local command on purpose: every run spends real quota and reads the real database, and the free tier limits both. CI runs the 1,099 backend tests and the 155 client tests instead, on fakes and with no network.

06

Cost

Zero on the free tiers of the Gemini API and of Neon. One /ask is one embedding call plus at most one chat call, and a question with nothing close enough skips the chat call entirely.

  • In the logged runs a chat call used roughly 1,000 to 1,600 prompt tokens (the question plus five chunks) and a few dozen completion tokens. On a paid plan that is still a fraction of a cent per question, but no paid tier was used or measured.
  • A full eval run costs about 77 embeddings and at most 53 chat calls. That is why it pauses four seconds between questions and waits out 429 replies instead of hammering the limit.
  • Ingest sends small batches and waits out rate limits, so a first ingest of eight documents takes minutes rather than seconds. That is the real price of the free tier, and it is paid once.
07

Latency

From the server logs of a 25-question run, with every call logging its own latency:

StepMedian90th percentileMax
Embedding call0.5 s0.7 s0.8 s
Chat call0.9 s1.3 s1.4 s
Whole question, end to end4.1 s meann/a18.4 s

The end-to-end mean is four times the sum of the two calls, and the gap is the part that is easy to forget: the database query, and the model's own tail. The maximum belongs to the first two questions of that run, 13.1 and 18.4 seconds while the database was waking up, and the next one took 2.1.

A free Neon compute scales to zero after a few minutes without traffic. The first request after that wakes it and can take several seconds or fail once. The recording checklist says to run one search a minute before recording, for exactly that reason.

08

What I would change

  1. Put a corpus in it that a reader cares about. Eight documents about the tools it is built with prove the pipeline and nothing else. The next version ingests something with a real question behind it, where a wrong answer costs something.
  2. Real authentication. The owner is a name the client sends. Isolation between names works; proving who the caller is does not exist yet, and every deployment needs it.
  3. Fix the flaky question with chunking, not prompt wording. The chunk that explains field validators in plain words lands fourth for its half of the question. Better chunking beats a cleverer instruction.
  4. Run a small fixed subset in CI. The full eval cannot run on every push, but ten questions against a recorded set of chunks would catch the plumbing regressions that unit tests miss, and cost nothing.
  5. Rename the package. The distribution and the CLI are still python_ai from before the repo was renamed. It is cosmetic debt with a written note in docs/future.md, and it touches every import.
09

Demo

A question, a cited answer, a citation opened, a second question from another file, the refusal, and the documents list. One take, 58 seconds.
10

What this is not

A product. One corpus of eight Markdown files, users who are names rather than accounts, and a Flutter client built to show the API rather than to be shipped. The numbers say how this pipeline behaves on this corpus; they do not promise the same on a folder of PDFs.

Try it live · Source on GitHub · Eval report · All three projects