Question answering over scientific papers (Qasper), served as a FastAPI service with cited answers and a Streamlit client.
- Retrieval: vector search plus BM25 keyword search, weighted RRF fusion in this project's code, optional cross-encoder rerank. It is evaluated with a protocol written before the test run. The app serves both searches from Qdrant Cloud; the results below were measured on the earlier local store (Chroma plus SQLite FTS5), which is still available (
ADVRAG_STORE=chroma). On the development split Qdrant was not shown non-inferior to it; it was adopted anyway so that no index has to be stored locally. - Answers: a gateway to Claude (
claude-sonnet-5-5) on Snowflake Cortex with timeouts, bounded retries, a circuit breaker and typed errors. Long answers are schema-constrained structured output: claims, each citing the passages it relies on with a word-for-word quote. The code checks every citation against the passages that were sent and looks every quote up in its passage. The model may abstain. - Service: async endpoints, Pydantic schemas, answers as server-sent events, per-key rate limits, strict input validation, auto-generated OpenAPI docs.
The interesting result is not a big number. On the held-out test split, hybrid retrieval and semantic chunking did not give a reliable gain, and the cross-encoder reranker did, at a latency cost. Every figure below can be traced to a saved run in docs/CLAIMS_LOG.md.
- Evidence rule: a performance number appears in this README only if it has a row in the claims log (metric, value, run folder, code fingerprint).
- Scope: a local demo. One process, one shared bearer token at most, no per-user accounts, and load tests of retrieval only, on one machine (see Limitations).
Setup: Qasper test split, 292 answerable questions from 124 papers, paper mode (the question's paper is given), retrieval only, all-MiniLM-L6-v2, local Chroma store. Metric: nDCG@10 with span-based relevance. Run folder: runs/eval/20261122T144233Z_3afc204d_test_paper. The test split was evaluated once (eval/test_ledger.jsonl), after the configuration was frozen (eval/test_freeze.json). Dev-split numbers are for development only and are not quoted here.
| Arm | Chunking | Retrieval | Reranker | nDCG@10 |
|---|---|---|---|---|
| A | recursive | vector only | no | 0.430 |
| D (frozen, served) | recursive | hybrid (RRF k=60, weights 1.0 / 0.7) | no | 0.456 |
| F | semantic | hybrid (RRF) | no | 0.463 |
| G | recursive | hybrid (RRF) | cross-encoder, top 20 | 0.514 |
Pre-registered comparisons (5,000 paper-clustered bootstrap resamples, Holm correction over the 3 comparisons):
| Comparison | Difference in nDCG@10 | Clustered 95% CI | Verdict |
|---|---|---|---|
| A vs D (vector-only vs hybrid) | A - D = -0.027 | [-0.051, -0.002] | not significant after Holm (p = 0.0320) |
| F vs D (semantic vs recursive chunks) | F - D = +0.006 | [-0.012, +0.024] | not significant (p = 0.5035) |
| D vs G (without vs with reranker) | D - G = -0.058 | [-0.084, -0.031] | significant after Holm (p = 0.0004), G is higher |
Other metrics for the frozen configuration D: MRR 0.434, HitRate@5 0.682, EvidenceRecall@10 0.705, EvidenceF1@5 0.210.
Retrieval latency, CPU only (no GPU, 4 logical CPUs), excluding any LLM call:
| Configuration | p50 | p95 |
|---|---|---|
| D (served) | 60 ms | 286 ms |
| G (D + rerank), total | 1,242 ms | 1,942 ms |
| G, rerank stage only | 1,191 ms | 1,848 ms |
What I took from it. The reranker is the only significant gain, but it costs about 1.2 s per query on this CPU, so it is a per-request switch (off by default) rather than part of the frozen configuration. The dev split had not shown a reranker gain and the test split did, so the dev result did not predict the test result.
Generation is measured only on the development split, with an uncalibrated judge. Baselines (no retrieval, the served retrieval, ten passages, oracle evidence) and RAGAS metrics are in docs/CLAIMS_LOG.md, labelled DEV/EXPLORATORY; they are not results to quote.
flowchart LR
UI[Streamlit UI] -->|POST /v1/ask, SSE| Q[Question]
Q --> G[Guards: validation, rate limit, daily budget]
G --> C{Answer cache}
C -- hit --> A
C -- miss --> E[Embed query: MiniLM]
E --> V[Qdrant vector search]
G --> L[Qdrant BM25 keyword search]
V --> F[Weighted RRF fusion]
L --> F
F --> R[Cross-encoder rerank, optional]
R --> X[Token-budgeted context]
F --> X
X --> LLM[LLM gateway: Claude Sonnet 5.5 on Snowflake]
LLM --> A[Structured claims with quotes, checked; or abstention]
A -->|sources, token..., done| UI
- Ingestion (rag/ingestion.py, scripts/ingest.py): offset-preserving chunking, deterministic chunk ids, incremental upserts, an ingest signature that refuses a store built with different chunking code, and a post-run check that the vector and lexical indexes hold the same ids.
- Retrieval (rag/retriever.py, rag/fusion.py): one
Retrieverclass used by both the service and the evaluation runner, so the evaluated system is the served system. Reports per-stage latency. - Generation (rag_core/):
LLMGatewaywith a per-call timeout, bounded retry with backoff and jitter, a circuit breaker, and typed errors. It accepts an ordered provider list (failover only before the first streamed token), but only the Snowflake SQL provider is configured, so no failover is in use. That route does not stream: the answer arrives as one piece. The long answer is requested with a per-request JSON schema whose source ids are exactly the ids that were sent (rag_core/claims.py); a reply that does not follow it is reported as invalid output and the passages are shown instead. Prompts are versioned with a local fallback. Only complete, cited, non-degraded answers are cached; the cache key includes the retrieval config, index version, embedder revision, prompt hash and model. - Safety and cost: prompt-injection escaping of questions and passages, a daily answer budget, per-key rate limits, masked tracing by default. API keys are read from the environment only and are never logged. The injection tests (test_prompt_injection.py, test_rag_core_prompts.py) check the trust boundaries around the model; they do not show that a real model resists an injection.
- Tracing: optional OpenTelemetry tracing (rag_core/otel_tracing.py), exported over OTLP to Langfuse, which shows it as an LLM trace, and optionally to any other OTLP backend (
tracing.exporters). Generation spans carry the OpenTelemetry GenAI attributes. The tracer is wrapped so that a tracing failure can never change an answer. - API (api/): FastAPI over the same
RagService; see API. - App (app/): Streamlit with chat, evaluation, observability and about tabs. It is a client of the API: it opens no index and holds no model or key (app/remote.py adapts the API to the interfaces the UI uses). The evaluation tab reads only
app_data/results.json, which is built from the claims log and refuses a number with no run folder.
Interactive docs at /docs (OpenAPI at /openapi.json) once the server is running. Errors are {"error": {"code", "message"}}.
| Method and path | What it does |
|---|---|
POST /v1/ask |
the answer as server-sent events: sources, then token events, then done (the full AnswerResult); a typed error event may precede done |
POST /v1/answer |
the same pipeline as one JSON body (AnswerResult) |
POST /v1/retrieve |
retrieval only: the best passages, no model call |
POST /v1/feedback |
a thumbs up or down for an answer (saved locally, forwarded to Langfuse when the answer was traced) |
GET /v1/health |
liveness |
GET /v1/ready |
readiness with the self-check (index, models, keys) |
GET /v1/meta |
what is running, the limits and the daily budget |
GET /v1/observability |
the shared Langfuse metrics snapshot |
- Order of checks for a query: authentication, readiness, per-key rate limit (429), question validation (422), queue limit (503), daily budget. A question over the daily budget is still answered with HTTP 200: the retrieved passages and a
daily_budget_reachederror, never a model call. - Concurrency and backpressure (rag/concurrency.py): the vector and lexical legs run at the same time; query embedding and reranking run in bounded worker pools, store reads in another (with the local store, one pooled SQLite connection per database worker). When
app.retrieval_max_in_flightrequests are already in retrieval, the next one gets HTTP 503overloadedwithRetry-After. With the local Chroma store, on one 8-CPU machine, the sustained rate of/v1/retrieveat p95 <= 300 ms went from 20 requests/s to 35 to 50 across two repeats (claims log; scripts/load_test.py). Against Qdrant Cloud from one machine, at p95 <= 1000 ms, it was 5 requests/s with 4 database workers (two runs) and 10 to 30 with 16 (four runs; same claims log). - Rate limiting (api/limits.py,
slowapi): keyed by theX-Session-Idheader when it is a well-formed id, else by client address.ask,answerandretrieveshare one bucket per key; feedback has its own. The client chooses that header, so a higher ceiling per client address applies as well (60 queries a minute and 500 a day by default; the UI sends all its visitors from one address; setapp.address_rate_limit_requests: 0for a load test). The numbers come fromapp.*in config.yaml. Limits are in memory and per process. - Validation (api/schemas.py): request bodies refuse unknown fields; paper, session, request and trace ids must be plain tokens; bodies over 16 KB are refused before they are read. Control and invisible characters are removed from the question.
- Authentication: none by default. Set
ADVRAG_API_TOKENon the server to requireAuthorization: Bearer <token>on everything except/v1/health.
Example (server-sent events; with the Snowflake SQL route the answer text arrives in one piece):
curl.exe -N -X POST http://127.0.0.1:8000/v1/ask -H "Content-Type: application/json" -d '{\"question\": \"What dataset do they use?\"}'Written down before the test run in eval/PREREGISTRATION.md (its sha256 is checked by the runner):
- Dev/test split by paper, not by question.
- Arms, metrics, comparisons and the decision rule fixed in advance; deviations are appended, never rewritten.
- The test split runs only with an explicit flag and a frozen config, and is recorded in a ledger. It has been run once.
- Paired, paper-clustered bootstrap with Holm correction (eval/compare.py).
- Retrieval evaluation calls only
Retriever.retrieve: no LLM, no network.
Python 3.13, FastAPI and uvicorn, Streamlit, Qdrant (or Chroma with SQLite FTS5), sentence-transformers (all-MiniLM-L6-v2 and a
cross-encoder), Claude on Snowflake Cortex, OpenTelemetry with Langfuse and Grafana Cloud, pytest with Hypothesis, ruff, mypy, Docker.
- Fusion in project code, not in the database, so every store ranks the same way.
- The UI is only a client: models, index and keys live in the API process.
- Citations are structured output, checked against the passages sent. A found quote does not show that it supports the claim.
- Qdrant is served although the pre-registered store comparison did not pass (no local index was wanted).
- The reranker is off by default because of its CPU latency.
- Every decision and its cost: PROJECT_CONTEXT.md.
Requires Python 3.13. The environment below follows the standing rules in CLAUDE.md: a venv outside OneDrive, packages from the configured index, and models loaded from the local HuggingFace cache only (pinned revisions in config.yaml; the code never downloads them).
python -m venv "$env:LOCALAPPDATA\advrag\venv"
& "$env:LOCALAPPDATA\advrag\venv\Scripts\python.exe" -m pip install -r requirements.lock
& "$env:LOCALAPPDATA\advrag\venv\Scripts\python.exe" -m pip install -e . --no-deps
# one-time: build the served Qdrant collection (needs QDRANT_CLUSTER_ENDPOINT and QDRANT_API_KEY; incremental; never clears a collection).
# For the local store instead, set $env:ADVRAG_STORE = "chroma" and $env:CHROMA_LOCAL_PATH to its folder.
& "$env:LOCALAPPDATA\advrag\venv\Scripts\python.exe" scripts\ingest.py --strategy recursive
# 1) start the API (opens the index and loads the models; set SNOWFLAKE_ACCOUNT_URL and SNOWFLAKE_PAT in the environment or in .env to enable answers)
& "$env:LOCALAPPDATA\advrag\venv\Scripts\python.exe" -m uvicorn api.main:app --host 127.0.0.1 --port 8000
# docs: http://127.0.0.1:8000/docs readiness: http://127.0.0.1:8000/v1/ready
# 2) in a second terminal: the Streamlit UI, a client of the API
& "$env:LOCALAPPDATA\advrag\venv\Scripts\python.exe" -m streamlit run app\streamlit_app.pyWithout Snowflake credentials the API still retrieves and the app shows the passages. If the UI cannot reach the API it shows an error screen with the failed check. Keep the API bound to 127.0.0.1 unless ADVRAG_API_TOKEN is set.
On macOS or Linux:
python3.13 -m venv .venv
.venv/bin/pip install -r requirements.lock && .venv/bin/pip install -e . --no-deps
.venv/bin/python -m uvicorn api.main:app --host 127.0.0.1 --port 8000 # terminal 1
.venv/bin/python -m streamlit run app/streamlit_app.py # terminal 2
.venv/bin/python -m pytest --fast -p no:cacheprovider -q -rs # testsAPP_ACCESS_CODE, ADVRAG_API_TOKEN, ADVRAG_API_URL, ADVRAG_STORE and ADVRAG_INDEX_DIR are not read from .env by the Python
entry points (only Docker Compose and Streamlit secrets supply them that way): export them in the shell.
Settings live in config.yaml. Environment variables (values are never printed; .env.example lists names only):
| Variable | Read by | Purpose |
|---|---|---|
QDRANT_CLUSTER_ENDPOINT, QDRANT_API_KEY |
API | the served index (runbook) |
ADVRAG_STORE |
API | optional: qdrant (default, from config.yaml) or chroma |
ADVRAG_INDEX_DIR or CHROMA_LOCAL_PATH |
API | chroma only: folder of the store (no default: nothing opens a store you did not name) |
CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_WORKERS_AI_TOKEN |
API | only if the served collection uses Qwen3 embeddings (it does not) |
SNOWFLAKE_ACCOUNT_URL, SNOWFLAKE_PAT |
API | answers (every LLM call goes to Snowflake AI_COMPLETE; answers arrive at once, not streamed) |
SNOWFLAKE_WAREHOUSE |
API | optional; otherwise the user's default warehouse |
LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, LANGFUSE_BASE_URL |
API | optional tracing and metrics |
ADVRAG_API_TOKEN |
API and UI | optional shared bearer token |
ADVRAG_API_URL |
UI | where the API is (default http://127.0.0.1:8000) |
APP_ACCESS_CODE |
UI | optional access code for the page |
pytest --fast -p no:cacheprovider -q -rs # everyday run, skips tests marked slow
pytest -p no:cacheprovider -q -rs # full run, more Hypothesis examplesThe suite is hermetic: it blocks non-loopback network access and chromadb.CloudClient, and uses fake providers instead of real keys.
Every push and pull request runs ci.yml: ruff, mypy on rag_core, the fast test subset (slow and model tests are skipped), the Qdrant and Postgres integration tests against service containers, a Docker build with a smoke test that indexes five papers and requires GET /v1/ready to report ready, and pip-audit on the runtime lock. Advisories that are ignored are listed with their reasons in pip-audit-ignore.txt. The badge does not cover answer quality: no model is called. CI also rebuilds runs/index.jsonl, one row per saved run (code fingerprint, config hash, split, metrics), and fails if the committed file is out of date; after adding a run, run python scripts/runs_index.py.
compose.yaml runs the API and the UI from one image. The build uses public PyPI at the locked versions plus PyTorch's public CPU wheel index; it needs no credentials. The image holds code and packages only: models, the index and API keys are supplied at run time.
# once: build the index (needs the pinned embedding model in your HuggingFace cache). By default this builds the served
# Qdrant collection (needs the QDRANT_* variables); `export ADVRAG_STORE=chroma` first to build into the data volume instead.
docker compose run --rm --build ingest
# API on http://127.0.0.1:8000/docs, UI on http://127.0.0.1:8501
docker compose up --build
docker compose down # stop (a local index stays in the volume)- Models: the host's HuggingFace cache is mounted read-only. The default is
~/.cache/huggingface; setHF_CACHE_DIRto the folder that holdshub/if yours is elsewhere (on Windows usually%USERPROFILE%\.cache\huggingface). The containers run offline and never download. Without the pinned reranker the app still runs, with reranking unavailable. - Keys: put
SNOWFLAKE_ACCOUNT_URL,SNOWFLAKE_PAT(and optionally the Langfuse names,ADVRAG_API_TOKEN,APP_ACCESS_CODE) in your shell or a.envfile; only the names listed incompose.yamlreach a container. Without Snowflake credentials retrieval works and no answer is generated.docker compose configprints the values, so check the file withdocker compose config --quiet. - Ports are published on
127.0.0.1only (API_PORT,UI_PORTchange them). - An index built on the host cannot be reused: ingest manifests record the store location, and the API checks it.
db/postgres.py puts Postgres behind the same VectorStore and LexicalIndex protocols as Chroma and FTS5: pgvector with an HNSW index for dense search, and either ParadeDB's pg_search (BM25) or Postgres full-text search (ts_rank_cd) for keywords. The app does not serve from Postgres. Only a server on this machine is accepted.
docker compose --env-file /dev/null -f compose.postgres.yaml up -d --wait # 127.0.0.1:5433, data in a volume
CHROMA_LOCAL_PATH=<store> python scripts/copy_store_to_postgres.py # same chunks and vectors; embeds nothing
# integration tests against two throwaway containers (5434: pgvector, 5435: ParadeDB)
docker compose --env-file /dev/null -f compose.postgres.yaml --profile test up -d --wait
ADVRAG_TEST_PG_DSN="host=127.0.0.1 port=5434 dbname=advrag user=postgres" \
ADVRAG_TEST_PARADEDB_DSN="host=127.0.0.1 port=5435 dbname=advrag user=postgres" pytest tests/integration -q -rsThe comparison of the two stores is pre-registered in eval/PREREGISTRATION_h7.md and runs on the development split only.
scripts/reindex_gemini.py writes the same chunks with Gemini Embedding 2 vectors into separate Postgres tables, within the quota set in config.yaml (embedding.gemini). It sends the public corpus text to the Gemini API and needs GEMINI_API_KEY. Run it with --dry-run first; if the daily quota runs out it saves its progress and a rerun resumes.
| Path | What it holds |
|---|---|
| rag/ | chunking, embedders, lexical (FTS5) index, fusion, retriever, reranker, ingestion |
| rag_core/ | answer path: service, gateway, prompts, structured claims, cache, tracing (OpenTelemetry) |
| api/ | FastAPI service (SSE streaming, schemas, rate limits) and its Python client |
| db/ | the stores: Qdrant (served), local Chroma, and Postgres (experiment) |
| observability/ | logging setup and the Grafana dashboard and alert rules |
| utils/ | the code fingerprint used by the claims log |
| app/ | Streamlit app (a client of the API) |
| eval/ | pre-registration, runners, metrics, paired comparison, datasets and the split |
| scripts/ | ingestion, lexical index build, artifact builder, diagnostics |
| tests/ | unit and property tests, Postgres integration tests |
| docs/ | the claims log and working notes |
| PROJECT_CONTEXT.md | decision log: why each choice was made and what it costs |
A hosted copy can run on Streamlit Community Cloud from app/cloud_app.py; it embeds questions with Qwen3 on Cloudflare (not the configured MiniLM): see docs/deploy_streamlit.md.
- Generation is not validated. It has been measured on the development split only, with an LLM judge that has not been compared with human labels. Repeating a run does not reproduce the answers exactly.
- One process. Retrieval runs concurrently, but in one process whose throughput is bounded by query embedding on the CPU. The queue limit covers retrieval only, not the number of answers being streamed by the model. Rate limits and the daily budget are in memory and per process. There is a single optional shared token and no accounts. The load test covers retrieval only, on one machine.
- Prompt injection is handled by escaping and delimiting untrusted text and by validating what comes back (the structured answer, its citations and quotes, abstention). That is tested with scripted providers; it has not been measured against a real model.
- Corpus scale. The corpus is small (200 papers). Behaviour at a larger scale has no saved measurement.
- Semantic chunking did not beat recursive chunking on the test split. The served index uses recursive chunks.
- Reranker is off by default because of its latency on CPU.
- Docker was run without API keys; a live answer and the reranker were not exercised in a container.