RAG that knows when to stop
Author: Stan Miasnikov (c) 2025–2026
Calibrate retrieval for a dataset, then measure how a retrieval-and-answer loop behaves.
The first stage compares evidence admission against labelled references using cached
embeddings. The second runs an interpreter and a judge over Faraday's The Chemical
History of a Candle, measuring agreement or answer adequacy alongside hops and token use.
The experiments report observed scores and stopping behavior, not a proven irreducible
semantic floor or a prediction of next-hop gain.
The 18-slide presentation,
narration and abstract
are in presentation/. Corrected speaker notes are also embedded in the deck.
Explore the published results
Run notebooks from the repository root. These entry points need no model calls:
| Notebook |
What it shows |
Published inputs |
| comparison.ipynb |
Encoder and saved retrieval settings at a recall target or fragment budget |
results/local-Qwen3-Embedding-8B/, results/openai-embedding-3-large/ |
| view-results.ipynb |
Saved mutual- and question-mode plots with model/settings captions |
results/semantic-loop-memless1/ through memless4/ |
| floor.ipynb |
Conditional mean TV error on hits and the recall/cost choice of one more retrieval slot |
Saved cutoff exports; optional live database check |
comparison.ipynb has READ_ARCHIVES=True and explicit ARCHIVE_PATHS. It selects
among measured candidates; changing a target does not reconstruct an unsaved sweep.
archive_comparison.py validates and reads those exports without
modifying them. floor.ipynb prefers local results/out2/cutoff/ exports if present,
then the published OpenAI snapshot, then Qwen.
The calibration snapshots use Qwen3-Embedding-8B (4096 dimensions) and
text-embedding-3-large (3072 dimensions). BioASQ and MuSiQue use the same benchmark
selection. The synthetic probe sets use different generators and sampled questions,
so their cross-run differences do not isolate the encoder. These in-sample results
still need grouped held-out evaluation before selecting a configuration.
The Faraday loop and its saved runs
semantic_loop.ipynb is the rerunnable seven-question demo,
including a modern LED question unsupported by the book and a question with a false
premise. semantic_loop.py implements retrieval, calls, caching,
selection and reporting. Public notebook execution outputs are cleared; saved runs
contain the evidence for the talk.
All four published configurations use memoryless calls and local Qwen3-Embedding-8B:
Run root under results/ |
Interpreter |
Judge |
Presentation use |
| semantic-loop-memless1 |
local gpt-oss-120b |
local gpt-oss-120b |
Mutual Q4 failed before completing a hop; excluded from the slide comparison |
| semantic-loop-memless2 |
local gpt-oss-120b |
hosted gpt-6-luna |
Mutual comparison and trajectories, slides 11, 13–14 |
| semantic-loop-memless3 |
hosted gpt-6-luna |
hosted gpt-6-luna |
Mutual comparison; question-mode cost and Q1 example, slides 11–12, 15 |
| semantic-loop-memless4 |
hosted gpt-6-luna |
local gpt-oss-120b |
Mutual comparison and question-mode cost, slides 11–12 |
Each root has mutual-01/ and question-01/. A run includes run.json (settings,
prompts, source fragments, results and call records), per-question JSON, summary.csv,
rounds.csv, calls.csv, errors.csv, loop.png and a settings README. Read the error
records as well as the plots: memless2's question run records recoverable errors.
Call counts and tokens describe validated calls; failed attempts may add cost.
Common saved settings are answer/reading temperature 0.3, follow-up temperature
0.5, judge temperature 0, top_k=5 per search, up to three follow-up queries per
attempt, two follow-up attempts per prospective hop, and a ten-hop cap. The similarity
floor is 0.672931248812364 (fragment-pair quantile 0.90); the redundancy cutoff is
0.748126125179126 (quantile 0.98). Acceptance uses 0.95 and successive-answer
convergence uses 0.99.
With MEMORYLESS=True, readings and answers see the original question and all passages
retrieved so far. The question judge sees the question and current/previous answers.
Feedback affects the next search through the interpreter's follow-up calls. Each
search chooses up to top_k passages above the floor, removing near-duplicates within
that search, then the merged set drops already held IDs. It does not refill those
slots or compare cosine against all previously held passages. With MEMORYLESS=False,
prior structured outputs also enter the calls, and retrieval filters near-duplicates
against held evidence while selecting up to top_k new passages per hop.
| Mode |
Judge's information |
Selection and stops |
mutual (mutual-alignment-v2) |
Passages, a separately generated judge reading, and the interpreter response |
Select maximum agreement, earliest on ties. Stop after two hops without beating the best earlier agreement, successive-answer convergence, a retrieval plateau, no evidence, or the hop budget. |
question (independent-question-v1) |
Original question and current/previous responses; no passages or interpreter state |
From hop 2, acceptance requires alignment ≥ 0.95, cited claims and no requested retrieval; convergence requires cosine ≥ 0.99 with evidence present. These exits select the triggering response. A retrieval plateau selects the last completed answer. At the budget, select maximum alignment among gap-closed responses if available, otherwise among all responses; earliest tie. |
Hop 1 searches the original question. Later hops search interpreter-generated follow-ups;
search_with_question=True also includes the original question. If neither follow-up
attempt adds a fragment, no further answer hop is completed: the stop is
retrieval_plateau, or unanswerable if no evidence was ever admitted. Empty query
lists also add nothing. This is a limit of the attempted searches, not proof that the
corpus has no further useful evidence.
For the LED question in the three mutual runs shown in the talk, no passage clears
the floor. Both readings are the same fixed no_memory_answer; neither reading is
generated by an LLM. The judge still assesses them and follow-up calls still run.
Agreement 1.00 compares identical messages, and this case is included in slide 11's
means and zero-floor counts. Retrieval made the refusal. This result does not generalize
to every configuration: memless1's mutual run later admits passages for the LED query.
observed_floor in mutual mode is minimum observed 1 − agreement. In question mode,
question_floor is 1 − alignment at the selected response, which need not be the
minimum over the trajectory. floor_scope reports whether that selected response has
closed gaps or is provisional. Read answer_status and stop together: acceptance can
still be partial, and an answered response can stop at a plateau below 0.95. Q/A cosine
is a separate geometric diagnostic. A judge without passages cannot certify source
fidelity, and scores from different judges do not provide a common quality scale.
Each configuration has one trajectory per question on one corpus. Repeated runs and
held-out questions are needed to assess reliability; temperature zero alone does not
guarantee exact replay. Local call caches and embedding indexes are not published.
Saved outputs can be inspected without those caches, but fresh model calls may differ.
Run a fresh experiment
Install the dependencies in a Python 3.10+ environment:
python -m pip install numpy pandas matplotlib openai pydantic python-dotenv jupyter pytest huggingface_hub pyarrow
python -m pytest -q
jupyter notebook
In semantic_loop.ipynb, choose MODE, MEMORYLESS, model aliases and the independent
USE_LOCAL_INTERPRETER, USE_LOCAL_JUDGE and USE_LOCAL_EMBEDDINGS switches. Defaults
are question mode, memoryless calls, local gpt-oss-120b interpreter, hosted gpt-6-luna
judge and local Qwen3-Embedding-8B. The local generation endpoint is port 8080; embeddings
use 8081. Different local models need separate endpoints or a router. Change aliases
when changing model weights or quantization. Hosted calls use OPENAI_API_KEY from the
environment or data/.env; local authentication optionally uses LLAMA_API_KEY.
Hosted calls may incur charges.
Notebook outputs default to results/semantic-loop-live/<MODE>-01/, separate from the
published results. Change RUN_ID for fresh generation samples. With matching inputs,
reusing an ID and its local cache replays validated calls. Transient errors and malformed
responses have bounded retries; completed hops are checkpointed. Different protocols
cannot share an output directory. For batch runs, configurations.json
contains the four model pairings in both modes, writing under
results/semantic-loop-live/memless1/ through memless4/:
python run_semantic_loop.py configurations.json
The notebook downloads Faraday's public-domain text and indexes it on first use.
index_book.py reads the notebook settings and can build the index
without generation calls:
python index_book.py
python index_book.py --local --book /path/document.txt --embedding-model my-embedding-alias
Chunks reach 180 words, then extend to a sentence ending or paragraph end; original
paragraph IDs are retained. Index reuse checks the document and embedding settings.
For another text, update book_path, book_url=None and the questions in the notebook;
refit cutoffs and check answerable/unanswerable probes. Faraday may occur in model
training data, so this demo does not establish performance on unseen material.
After a local notebook run, clear its outputs before publishing:
jupyter nbconvert --ClearOutputPreprocessor.enabled=True --to notebook --inplace semantic_loop.ipynb
Rebuild the retrieval calibration
The executed calibration notebooks are also readable as saved examples:
| Notebook |
Measurement |
Inputs for a fresh run |
| cutoff.ipynb |
Score separation, floors, caps and recall/cost objectives |
data/bioasq.db |
| multihop.ipynb |
Complete evidence sets, expansion depth and routing |
data/musique.db and the selected cutoff policy |
| probes.ipynb |
Query drift, question/answer indexing and fused needs |
data/bioasq.db, data/probes.db and the selected cutoff policy |
Database files are not distributed. Follow data/README.md and configure
the builders for your encoder. data/build_bioasq.py downloads a pinned Hugging Face
source when its ignored CSV cache is absent; --download-only needs no API key.
That upstream source differs from the edited BioASQ data used in the saved snapshots,
so a fresh build requires fresh calibration; see the dataset README for details.
Building databases makes embedding calls; building the
synthetic probes also makes generation calls. Once built, the calibration notebooks
use the stored vectors without generation. They write local exports under results/out2/.
Run cutoff before floor, multihop and probes; then point comparison's ARCHIVE_PATHS to
the exports you want to compare. Do not mix embeddings from different encoders or pool
probe sets with different generation histories into an encoder ranking.
The methodology