Kenneth W. Bingham AI Engineer

Project · Python · Postgres + pgvector · live on Cloudflare Workers AI + Vectorize

citeline

A retrieval augmented question answering service over the US National Primary Drinking Water Regulations. It answers with a citation to the exact regulation section, or it tells you it does not know. There is no third option, and that is enforced in code rather than requested in a prompt.

The live demo runs on Cloudflare. The same parser, chunker, prompt and citation rules, with the request path moved to a Worker: embeddings and answers from Workers AI, vector search in Vectorize, keyword search inside the Worker. No server to keep running, and nothing stored about who asked what.

The problem

A retrieval demo that answers every question looks impressive and is nearly worthless. The interesting question is not whether a system can answer when the answer is present. It is what the system does when the answer is absent, because that is the case that occurs constantly in real use and it is the case where a language model is most confident and most wrong.

I picked federal regulations as the corpus for exactly that reason. Regulatory text is dense with numeric thresholds, deadlines, defined terms and cross references. A confidently wrong contaminant limit is not an amusing error; it is the kind of error that gets a compliance tool thrown out. So the requirement is not "answer well". It is never assert anything that is not in the retrieved text, and prove that property rather than claim it.

The corpus. 40 CFR Part 141, the National Primary Drinking Water Regulations, ingested from the public eCFR API. United States federal regulations are in the public domain, which makes this legally clean to host and index. The edition is pinned, so a citation points at text that actually said that.

Why it is harder than it looks

Vector search alone quietly fails on regulations

Ask for the limit on arsenic and a dense index returns several passages about arsenic monitoring, sampling schedules and treatment technology. They are all genuinely about arsenic and semantically very close to the question. None of them contains the number. Embeddings blur exactly the tokens that matter here: numeric thresholds, units, and section identifiers.

So retrieval runs two ways at once. A dense vector search over pgvector handles paraphrase, and a Postgres full text search pins the exact terms. Their results are merged with reciprocal rank fusion, which combines by rank rather than score and therefore needs no normalisation between two retrievers whose numbers have nothing to do with each other.

Chunking on a fixed size destroys the answer

The contaminant limits live in tables. Slice those on a character count and you get a chunk holding a contaminant name whose number landed in the next chunk, and a chunk holding a number with nothing to say what it measures. Both look like fine retrieval results and both are useless. The chunker splits on paragraph boundaries first, falls back to sentence boundaries only when a single paragraph exceeds budget, and prefixes every chunk with its own section number and heading so a retrieved fragment is always attributable on its own.

A rank score is not a confidence score

This one cost me a rewrite, and it is the most useful thing on this page. My first version gated abstention on the fused retrieval score. That is wrong twice over.

First, arithmetically: with a fusion constant of 60 and two retrievers, the maximum achievable fused score is 2/61 = 0.0328. I had set the threshold to 0.045, which no result can ever reach, so the service would have abstained on every question ever asked.

Second, and worse, the approach could not have worked even with a reachable number. Reciprocal rank fusion is a rank statistic. A dense retriever returns its k nearest rows for any input whatsoever, so whatever is closest still lands at rank 1 and still scores 1/61. The top fused score for what is the capital of France looks almost identical to the top fused score for a question the corpus genuinely answers. It carries essentially no information about coverage.

The gate now tests absolute cosine similarity, which does move between those two cases, plus an independent requirement that the sparse retriever matched something at all. Fusion still decides the ordering. It just no longer pretends to measure confidence.

Similarity is not a coverage score either

Moving the service to the edge meant a new embedding model, so the threshold had to be measured again. This time the sweep said something different: on this corpus, cosine similarity does not separate the two cases at all. A real question scored as low as 0.64 and what is the maximum contaminant level for microplastics scored 0.73, because it reads exactly like a question the regulations answer. Every threshold above 0.64 only refused real questions.

What does separate them is vocabulary. "Microplastics", "OSHA", "caffeine" and "1,4-dioxane" appear nowhere in Part 141, and that alone says the corpus cannot answer. That check made 12 of the 15 correct refusals across both test sets. The other 3 use only words the corpus contains, and all three score under a low similarity floor of 0.60, so the two cheap checks stop all 15 before the model is ever asked. With the floor switched off, the model declined those 3 itself, so there is a third line behind the first two.

The evaluation found that every table was missing

The first edge run refused the arsenic question, and the reason was not the model. The eCFR serves tables as HTML rows, and the parser kept only paragraph elements, so all 139 tables in Part 141 had been dropped without a sound. The contaminant limits live in those tables. The arsenic limit was not in the index at all.

The fix keeps each row with its column headers, Contaminant: (16) Arsenic; MCL (mg/l): 0.010, so a row still says what its number measures after chunking. A test now pins it, and that test fails on the old parser. Answerable questions answered correctly went from 8 of 21 to 16 of 21 on that change alone. The same check turned up one wrong label in the test set: it called PFOA out of scope, but this edition of 141.61 lists a PFOA limit of 0.0000040 mg/L, from the 2024 PFAS rule.

Architecture

Two paths through one system: a batch pipeline that builds the index, and a request path that serves it.

Ingestion pipeline The eCFR API is parsed into one document per section, then passes three rejection gates (document quality, chunk quality, embedding quality) before being written to Postgres in a single transaction. eCFR API public source parse 1 doc / section gate 1 short, reserved gate 2 chunk budget gate 3 dim, zero vector upsert 1 txn rejected, counted, and recorded with a reason SHA compare: an unchanged section is skipped, so a re-run is cheap
Ingestion. Three rejection gates, not one. Bad input is refused at the earliest point it can be recognised, and every rejection is counted with a reason rather than dropped silently, because an index that quietly lost a section is worse than one that failed loudly.
Query path A question is embedded and searched two ways at once, by vector similarity and by full text. The two ranked lists are fused with reciprocal rank fusion. The result passes a similarity gate, and only then is an answer generated and its citations verified. question vector search HNSW cosine, k=24 full text search tsvector, k=24 fuse (RRF) rank, not score similarity gate vocabulary + floor answer + verify citations invented refs rejected abstain and say what it looked at pass fail
Query path. Two searches run against the same question because they fail differently. Vector search understands that "how much lead is allowed" means the lead action level; full text search is the one that reliably finds 0.015 mg/L and 141.80. Fusing them means a passage has to satisfy only one of the two to survive, and the ones both agree on rise to the top.

The three gates

gate 1 · before the model

If a word of the question appears nowhere in the corpus, or nothing is even loosely similar, the language model is never invoked. This is the cheap gate and it catches the common case. What it checks was chosen by sweeping the labelled set, not by judgement.

gate 2 · the prompt

The model is instructed to reply with a fixed marker when the supplied excerpts do not answer the question. This is the weakest of the three, because it is the only one that depends on instruction following, which is why it is not the only one.

gate 3 · after the model

Every citation the model emitted is checked against the excerpts it was actually handed. A citation to an excerpt that was never supplied, a substantive sentence carrying none, or a number that is not in the passage it cites, fails the whole answer. It is discarded, not served with a warning attached.

Gate 3 is the one that matters most and it is the one people skip. Serving a questionable answer with a caveat bolted on is how a system teaches its users to ignore caveats. If the grounding cannot be verified, there is no answer to serve.

Engineering trade-offs

The decisions that shaped this, and what each one cost. None of them is the only defensible choice; these are the reasons for the ones I made.

DecisionChosenInstead ofWhy, and what it costs
Fusion Reciprocal rank fusion A cross-encoder re-ranker RRF combines ranks, so it needs no shared score scale between a cosine distance and a lexical relevance score, and no model. A re-ranker would likely order the top few better, but it adds a second model call, and its latency, to every request. The cost is real: RRF cannot tell that the third result is much better than the fourth, only that it ranked higher.
Abstention signal Vocabulary, plus a low similarity floor, measured A similarity threshold alone Swept against the eval set. The first attempt gated on the fused RRF score, which could never reach its own threshold. The second gated on cosine, which worked on the original model and stopped working on the edge one: covered and uncovered questions overlapped (0.64 against 0.73). Vocabulary separates them. The cost: a misspelled subject is refused, and the reason shown says which word was not found.
Chunking On section boundaries Fixed character windows A citation is only useful if it names something a reader can look up. Fixed windows split a limit away from the contaminant it applies to and produce citations that point at nothing. The cost is uneven chunk sizes and a few sections too long for one chunk.
Where it runs Two builds: local, and Cloudflare One hosted service The reference build runs everything locally (Postgres, nomic-embed-text, Ollama): no key to leak and no corpus text leaving the machine, the posture a regulated customer asks about. The live demo runs on Workers AI and Vectorize, because the small server it used to run on took over four minutes per answer. The cost of two builds is keeping them in step, so they share the parser, chunker, prompt and citation rules.
Answer model Llama 4 Scout, chosen by the eval The largest model available On the same retrieval, Llama 3.3 70B and Llama 4 Scout both answered 19 of 21. Scout was faster (1.1 s median against 1.7 s), and where it could not read the arsenic limit out of a table it refused, while Llama 3.3 served a muddled answer. gpt-oss-120b wrote citations in its own format, which the contract correctly refused.

Query it

This is the running service, not a recording. Try a question the regulations answer, then try one they do not, and watch it decline. Every answer lists the passages it cites, with the text, so you can check it.

The dashed ones are outside the corpus, and two of them are near misses. Microplastics reads exactly like a question these regulations answer, and its similarity score is higher than some real questions get. Glyphosate is in these regulations, with a drinking water limit, so asking about soil uses only words the corpus contains. The first is refused because the word appears nowhere; the second scores just under the similarity floor, and with the floor off, the model declines it too.

Evaluation

A labelled set of 28 questions: 20 the regulations answer, with the section that answers each one, and 8 they do not. Scoring asserts specific strings rather than asking a model to grade, so the result is reproducible and cannot drift with a grader's mood.

SetAnswerable, answered correctlyOut of scope, answered anywayRight section in the top 4
The original 28 (one label corrected)19 of 210 of 720 of 21
Held out: 22 new questions, written after all tuning14 of 140 of 814 of 14

Measured on the live Cloudflare build, 14 October 2026. The second set was written only after every change was made, with each expected answer checked against the regulation text first, so it is the real test of whether the tuning carried over to questions it had never seen. The two misses on the first set: arsenic is refused (the model did not read the limit out of the table it was given), and fluoride is answered "4 mg/l" from 141.208, the right value, but not the "4.0" from 141.62 that the strict scorer asks for.

What is measured, and why both halves matter

Retrieval quality

  • recall@k: did the correct section appear in the top k at all
  • hit@1: was it ranked first
  • MRR: mean reciprocal rank of the correct section
  • latency: p50 and p95, measured end to end

Answer integrity

  • accuracy: answered, contained the required fact, cited the right section
  • abstention recall: share of unanswerable questions correctly refused
  • false answer rate: unanswerable questions that got an answer anyway. This is the hallucination rate, and it is the number the whole design exists to hold down
The two error types are not weighted equally, on purpose. A wrong answer to a question the corpus cannot answer undermines trust in every other answer the system gives. A refusal on a question it could have answered is visible, annoying and recoverable. So the threshold sweep picks the point that eliminates false answers first, then keeps as many real answers as it can.

Run it yourself

The repository is self contained. Docker brings up Postgres with pgvector; the models run locally through Ollama, so there is no API key and nothing leaves the machine.

git clone https://github.com/kenbin64
cd citeline

docker compose up -d              # postgres 16 + pgvector
ollama pull nomic-embed-text      # embeddings, 768-d
ollama pull llama3.2:3b           # generation

make install                      # venv + dependencies
make migrate                      # apply the schema
make ingest                       # fetch, gate, chunk, embed, index

make check                        # ruff + mypy + 41 unit tests
make eval                         # regenerate the numbers above

citeline search "MCL for arsenic" # retrieval only
citeline ask    "MCL for arsenic" # full pipeline

make ingest is idempotent. Run it twice and the second run writes nothing, reporting every chunk as skipped, because each document is compared by content hash before any work is done.

Limits

Things this does not do, stated plainly so nobody has to discover them.

The right section is found more often than it is ranked first. It is in the top four for 34 of 35 answerable questions, but first for only about half. The model is given all four, so this costs little most of the time. Arsenic is the case where it does: an expired 2006 limit in 141.11 outranks the current one in 141.62, and the model refuses rather than choose.
  • No reranker. A cross encoder would likely fix most of the ranking gap above. It is the next change worth measuring, and the first one that would add a second model call to every request.
  • A misspelled subject is refused. "arsnic" is not a word in the corpus. The refusal says why, so the fix is obvious to the person asking.
  • The eval sets are small. 50 questions in two sets, written by one person. That is enough to catch a broken gate, a dropped table and a wrong label, which it did, and not enough to claim a general accuracy figure. Treat the numbers as a regression baseline, not a benchmark.
  • One corpus, one part. Part 141 only. Nothing about the design is specific to it, but no other body of text has been tested, so no claim is made about them.
  • Gate 3 verifies grounding, not correctness. It proves every claim carries a citation to a passage that was actually supplied, and that every number stated is in that passage. It does not prove the model drew the right conclusion from it. That is a real gap, and it is why the answer always shows its sources for a human to check.
  • Abstention has a cost. A tighter gate refuses some questions the corpus genuinely answers. That trade is deliberate: a refusal is visible and recoverable, and a confident wrong answer is neither. The threshold sweep, run on every change, shows exactly what each setting costs.