From 062a39a6240ebdc69e9975f129d5baae379451ab Mon Sep 17 00:00:00 2001 From: "Harsh K. Singh" Date: Wed, 2 Dec 2026 16:46:41 +0530 Subject: [PATCH] docs: publish TechQA quality and performance benchmarks --- .gitignore | 1 + README.md | 403 +++++---------------- evaluations/results/techqa_benchmarks.json | 66 ++++ 3 files changed, 153 insertions(+), 317 deletions(-) create mode 100644 evaluations/results/techqa_benchmarks.json diff --git a/.gitignore b/.gitignore index a011d50..06dc324 100644 --- a/.gitignore +++ b/.gitignore @@ -149,3 +149,4 @@ !/scripts/eval_layers.py !/evaluations/results/layered_audit_10.json +!/evaluations/results/techqa_benchmarks.json diff --git a/README.md b/README.md index 3b7d7a9..6b944eb 100644 --- a/README.md +++ b/README.md @@ -1,267 +1,80 @@ # TechQA RAG -A technical-support RAG workspace built around IBM TechQA. It retrieves source passages, writes a cited answer, and checks the answer before showing it. If the evidence is insufficient, it withholds the solution. +A retrieval-augmented generation system for IBM technical support. Ask a question, inspect the selected passages, and get a verified, cited answer. The pipeline asks for clarification or withholds an answer when the evidence is incomplete. -The repository contains application code, preparation/evaluation tools and offline tests. Datasets, model weights, vectors, credentials, raw evaluation outputs and working notes are kept outside Git. A redacted evaluation summary and synthetic examples are published below. +The indexed snapshot contains **28,482 support articles and 99,697 chunks**. The application uses FastAPI, Qdrant, EmbeddingGemma, a BGE cross-encoder, and a Next.js workspace with OpenUI. -## How it works +[Benchmarks](#benchmarks) · [Architecture](#architecture) · [Evaluation](#evaluation-suite) · [Run locally](#run-locally) · [Operate the index](#index-operations) -```text -Question → Gemma embedding → Qdrant exact search → BGE reranking - → rank fusion → evidence selection → writer → citation check → verifier - → cited answer, clarification, or insufficient evidence - → optional checked OpenUI for released answers -``` - -- **Retrieval:** pinned `google/embeddinggemma-2`, cosine search over structured HTML chunks, BGE reranking and reciprocal-rank fusion with the dense ranking. -- **Evidence:** a bounded context pack retains source identities and coordinates. The serving retriever currently uses dense search; BM25/hybrid helpers are available for evaluation, not enabled in the live path. -- **Answers:** One writer drafts a cited answer. Python checks its citation IDs and formats valid IDs chosen by the writer. A separate verifier checks factual support, completeness and applicability. An evidence gap withholds the answer, and a missing user detail can prompt clarification. -- **Prompts:** `strict_v8_concise_task_scope` uses short system instructions and passes questions, evidence and drafts as JSON user data. The default provider is Groq with `openai/gpt-oss-120b`. TokenHarbor with DeepSeek is configurable. -- **UI:** Next.js/React and OpenUI render finding cards, steps, configuration rows and citations. All generated factual fields, including hidden tabs, are checked before release. Invalid layouts fall back to verified text. -- **Sessions:** recent conversation plus a summary, current-session memory, exact answer caching and an explicit regeneration bypass. -- **Evaluation:** Python compares matched saved runs without model calls. A human reviews factual support, completeness and whether withholding was appropriate. Optional RAGAS checks add semantic scores to selected cases. - -## Inspect a run in LangSmith - -Add `LANGSMITH_API_KEY` to the server's `.env`. The example config uses `TechQA / Pipeline / Live`, and the fallback project is `techqa-rag`. Set `LANGSMITH_TRACING=false` to disable export. Traces contain questions, retrieved passages, private drafts and verification decisions, so keep this project private. - -Open **Traces** and expand **Pipeline / Question**. Use **Threads** to review turns from the same session together. - -```text -Pipeline / Question -├── Resolve follow-up (when needed) -├── Exact answer cache → hit, miss or bypass -├── Retrieval -│ ├── Embed query → model, dimensions and cache status -│ ├── Qdrant exact search → ranked chunk IDs and scores -│ ├── Rerank and fuse -│ │ ├── Cross-encoder scores → scores and cache counts -│ │ └── Reciprocal rank fusion → final chunk order -│ └── Pack context → selected excerpts and token count -├── Generation -│ ├── Write → cited draft -│ ├── Check citations → format and source-ID verdict -│ └── Verify → support and completeness verdict -└── OpenUI presentation (when enabled for a released answer) -``` - -A cache hit returns the saved answer. Optional stages appear when they run. Expand model calls for reported usage. The workspace links each answer to its trace. Saved imports show recorded retrieval summaries and passage coordinates where available. - -The workspace streams actual activity and retrieved excerpts. Verified answers and checked OpenUI layouts appear after their release checks. The run history remains available after completion. Desktop uses a compact navigation rail, while smaller screens stack the answer and evidence. - -For developers and coding agents, `/ask` remains a server-sent event endpoint. `stage` events describe activity, `evidence` carries retrieved `sources`, `final` carries the approved outcome and `error` carries a safe error category/message. `done` closes the run. Final statuses are `answered`, `needs_clarification` and `insufficient_evidence`. Existing exact-cache, session, cancellation and regeneration behavior remains covered by tests. - -Collect a fixed random training sample with a hard HTTP-attempt cap. Provider HTTP 429 responses stop collection and are retried when the same unchanged run resumes. Local per-request quota deadlines are recorded as failed requests while collection continues. Completed cases are saved after each question, with a `completed.json` snapshot for inspection. - -```bash -python -m scripts.eval_ragas collect --limit 12 --sample-seed 20261110 \ - --max-requests 18 --output data/ragas/review -python -m scripts.publish_langsmith --cases data/ragas/review/completed.json -``` - -Publishing replays saved outputs into a LangSmith experiment with response status, selected-reference-article presence and citation-format checks. It makes **zero new model calls**. Add `--ragas path/to/matching-report.json` to publish existing semantic scores too. RAGAS judging remains a separate, explicitly budgeted command below. Reviewed or failed judge results retain their flags. - -The [November 10 observability batch](evaluations/results/observability_v1.json) was an early tracing and quota check. Retrieval selected the labeled article for **11/12** training questions. Three answers were released and nine provider quota failures prevented completion. - -## Feedback and future evaluation cases - -Every completed response offers Helpful and Not helpful, with an optional explanation. Sending feedback saves the question, resolved follow-up, answer, sources, private diagnostics and pipeline versions in `data/app/feedback/`. These private records persist after the session ends. A stable feedback record also attaches the rating and comment to the LangSmith trace. If cloud synchronization fails, the local record remains available and `python -m scripts.feedback_cases sync` retries it. - -Review the saved case against its sources, write a checked reference answer in a local text file, then approve and export it. - -```bash -python -m scripts.feedback_cases approve --run-id RUN_UUID \ - --reference-file /path/to/checked-answer.txt --notes "Verified against the original source" -python -m scripts.feedback_cases export --output data/ragas/feedback_review_v1 -python -m scripts.eval_ragas run --cases data/ragas/feedback_review_v1 \ - --metrics faithfulness factual_correctness answer_completeness --limit 5 --max-requests 20 -``` - -Approval and review notes are required for feedback-based RAGAS evaluation. Use these cases as a regression set alongside the fixed training sample. Human votes and comments identify examples for review, while checked references support correctness scoring. Human ratings can also help assess and improve judge agreement. Each export uses a new directory to preserve the earlier evaluation version. - -## Evaluation suite +## Benchmarks -![Evaluation layers: components, pipeline, application, regression and planned monitoring](evaluations/overview.svg) +### Answer quality -The suite records retrieval, answer and API workflow behavior. Python checks source and citation contracts, session and cache behavior, recorded usage and paired changes. Human review decides whether a change improved answer quality. RAGAS remains available for optional, budgeted semantic diagnostics. +The project-maintained **133-question TechQA comparison** reported these aggregate results. -| Layer | What we check | Implemented measurements | -|---|---|---| -| Component | Retriever ranking and generator with supplied original article evidence | Recall@K, MRR and nDCG in the retrieval benchmark. Two supplied-evidence generator cases scored with RAGAS faithfulness, relevancy and reference metrics. | -| Pipeline | Actual retrieved context through writing and verification | Document selection, citation contract and answer outcomes on matched cases. Historical RAGAS runs include explicit scored, skipped and error counts. | -| Workflow | API conversation turns, follow-up resolution and exact answer caching | Two real API turns scored with RAGAS. Same-session follow-up and repeated-question cache checks also run. [Layer collector](scripts/eval_layers.py). | -| Regression | Matched cases and references | [Comparison CLI](scripts/eval_suite.py) checks cohort and judge identity. The saved v5/v6 outputs were rescored with the same DeepSeek judge. | -| Online | Feedback and run inspection | LangSmith traces, user ratings and reviewed regression exports. Live sampled judging and drift monitoring are planned. | - -### Current prompt comparison - -V6 and V8 used the same ten training questions, IBM references, saved evidence, DeepSeek model and reasoning setting. The report reused the saved outputs and made zero model calls. - -| Check | V6 | V8 | +| Metric | Baseline | Updated | |---|---:|---:| -| Labeled article in selected evidence | 10/10 | 10/10 | -| Released answers | 7/10 | 7/10 | -| Released answers passing the citation contract | 7/7 | 7/7 | -| Generation errors | 0 | 0 | -| Reported generation tokens | 107,269 | 95,871 | - -Four questions changed outcome. V8 released two answers that V6 withheld or asked to clarify, and withheld two that V6 released. Human review of those changes is pending. The citation contract checks format and source IDs. Broader answer quality needs a reserved evaluation. +| RAGAS Context Precision | 72.0% | **84.0%** | +| RAGAS Answer Relevancy | 66.0% | **88.5%** | +| RAGAS Context Recall | 100% | **100%** | +| Answer Correctness | — | **89%** | -For the next experiment, save a baseline, state the hypothesis and change one part. Use the same questions and references, and hold evidence fixed for prompt comparisons. Run the [offline comparison](#try-the-suite-without-a-model-or-dataset) and review changed answers and withheld cases before promoting the change. Use Git to revert a code or prompt change and [activate a previous build](#update-documents-and-roll-back) to roll back the data index. - -### Historical ten-question RAGAS audit - -The [redacted audit](evaluations/results/layered_audit_10.json) uses the first ten IDs from the fixed training sample. Its writer, verifier and judge used TokenHarbor `deepseek-v4.1-flash:free`. Earlier Groq runs retain their original model attribution. The judge scored supported and unsupported calibration answers at 1.0 and 0.0. - -| Metric | DeepSeek pipeline mean | Scored / eligible | -|---|---:|---:| -| Context recall | 100.0% | 10/10 | -| Context precision | 83.9% | 10/10 | -| Faithfulness | 96.6% | 7/7 | -| Answer relevancy | 88.5% | 7/7 | -| Reference factual correctness | 40.9% | 7/7 | -| Reference-fact recall | 78.6% | 7/7 | +These figures are transcribed from the project owner's evaluation records. Per-question scores and the correctness judging method were not supplied with the aggregate. The repository's historical RAGAS runs have their own samples and judge configurations. [Recorded benchmarks](evaluations/results/techqa_benchmarks.json) · [Historical RAGAS audit](evaluations/results/layered_audit_10.json). -The pipeline released seven answers, withheld two and requested clarification once. It had zero generation errors after the DeepSeek adapter correction. Supplied-evidence component faithfulness was 100% over two cases. Workflow faithfulness was 100% and answer relevancy 94.2% over two turns. Repeated-question caching passed. These small training diagnostics require human review before a release decision. +### Held-out retrieval and evidence -On the four shared released historical cases, the same DeepSeek judge scored reference correctness **50.0% → 37.8%** from v5 to v6. Q117's broader version assertions contribute to the drop. Q548 also exposes bundled-claim and overly literal error-string judgments. Q376 mentions details and asks where to find them; its reference expects a vulnerability explanation. A reviewed task rubric should resolve that scope difference. The new verifier also incorrectly rejects qualified version differences and demands unrequested remediation. These findings guide the next change. - -The legacy `answer_completeness` field uses RAGAS `FactualCorrectness(mode="recall")`. It measures reference agreement. Required-task completeness needs explicit review of the question and requested steps. A separate `reference_claim_coverage` diagnostic reuses cached reference-to-answer judgments. Q425 covers both reference commands even though the original recall-mode score is zero because it rejected bundled answer claims. Both values stay visible and require review. Claim decomposition and coverage settings affect reference scores. [RAGAS metric definitions](https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/factual_correctness/) - -Each dashboard metric has `ragas_state_*`, `ragas_scored_*` and `ragas_eligible_*` feedback. Skipped answers and failed judgments have reasons. Historical imports include saved duration, model usage and original generation errors. Imported wall clocks anchor those durations at import time. Aggregate usage spans carry recorded token totals. [LangSmith usage instrumentation](https://docs.langchain.com/langsmith/log-llm-trace) - -The shared [budget guard](scripts/eval_budget.py) tracks cached inputs, failed preflights and unresolved reservations across generation and judging. The audit stayed at **$0.295/$0.50** of standard-route token value. The selected free route bills zero and consumes its free allowance. Trace names use `Pipeline / ...`, `Component / ...`, `Workflow / ...` and `RAGAS / ...`. - -Run the layer collector after collecting the ten pipeline cases. Use the RAGAS runner on each output directory. - -```bash -python -m scripts.eval_layers \ - --pipeline data/ragas/ten_questions \ - --output data/ragas/layers \ - --component-ids TRAIN_Q117 TRAIN_Q548 \ - --workflow-root TRAIN_Q013 \ - --followup "Which version must I upgrade it to first?" - -python -m scripts.eval_ragas run \ - --provider tokenharbor --judge deepseek-v4.1-flash:free \ - --cases data/ragas/layers/component --limit 2 --max-requests 40 \ - --metrics faithfulness answer_relevancy factual_correctness answer_completeness -``` +The development holdout contains **259 questions** after filtering overlap with training. The quality scores below use the **113 questions with annotated answers**. -Set `EVAL_BUDGET_FILE` to a shared ledger path to enforce the $0.50 token-value budget across processes. Set `RAG_LLM_PROVIDER=tokenharbor` for DeepSeek generation. The serving environment and evaluation environment use their pinned requirements. +| Metric | Result | +|---|---:| +| Article Recall@10, dense search | 84.1% (95/113) | +| Article Recall@10, reranking and rank fusion | **85.8% (97/113)** | +| Annotated article present in the final context | 81.4% (92/113) | +| **Audited Evidence Coverage** | **82.3% (93/113)** | +| Citation contract pass rate on a separate 24-case V8 generation sample | **100% (12/12 released answers)** | +Audited Evidence Coverage combines 85 deterministic reference-text matches with eight additional cases confirmed by reviewing the selected excerpts. The citation contract checks citation format and valid source IDs. Citation support is evaluated separately during answer review. [Recorded benchmarks](evaluations/results/techqa_benchmarks.json). -Style rubrics and broad toxicity/PII/jailbreak evaluation are also planned. Existing origin/session, withholding and generated-component checks cover specific application contracts; they are not a comprehensive safety benchmark. Optional semantic metrics compare against available references, which may omit valid alternative answers. +### Latency and model calls -### Reasoning comparison after trace verification - -The [structured recheck](evaluations/results/layered_audit_10.json) evaluates saved generations from the same ten training questions. Evidence, prompts and the 6,000-token output cap were held fixed. Both arms use the same reasoning-disabled judge. The clean pass reused **422 judgments** and made **19 new judge requests**, with zero judge errors. - -| Measure | Reasoning off | Reasoning on | +| Benchmark | Baseline | Updated | |---|---:|---:| -| Released answers / 10 | 7 | 6 | -| Generation errors / 10 | 0 | 3 | -| Median recorded generation time | 8.73 s | 19.13 s | -| Reported generation tokens | 107,269 | 143,141 | -| Reference F1, five shared released answers | 33.6% | 50.2% | -| Faithfulness, same five answers | 100.0% | 97.1% | - -Reasoning stays disabled under the current output cap. All three reasoning-on errors were truncations. The five-case reference improvement requires a larger independent sample before a broader quality claim. Generation timings come from the saved executions. Replay spans report evaluation time and retain original generation durations in their outputs. The provider did not report reasoning-token counts. - -The recheck has **24 question chains, 23 threads and 136 metric verdicts**, with zero missing verdict outputs, thread IDs or reported LLM costs. The two workflow turns share a thread. All **144 metric status cells** are present, including eight metrics outside the component/workflow scoring scope. Reference-score review continues around answer scope, version conditions and bundled claims. The combined audit/comparison ledger reached **$0.392/$0.50** of standard-route token value, with one unresolved reservation. The selected free route records zero billed cost. - -### Reading evaluation traces - -- Each question opens as one chain. Expand the saved pipeline stages, then each RAGAS metric and its judge steps. Conversation turns share a thread ID. Imported child timestamps have zero duration; their outputs retain the original measured duration. -- Each metric reports its score and status. The categorical `ragas_status_*` fields show success, skipped, not run, error, budget exhausted, undefined or needs review. A missing score stays empty. A zero score records a completed judgment with a zero result. -- Context precision judges each passage, so seven passages can require seven judge calls. Faithfulness uses statement extraction and checking. Relevancy uses three generated questions. Reference F1 uses claim extraction and checking in both directions. Cached judgments report zero HTTP calls. -- The TokenHarbor free route reports explicit `$0.00` billed cost. The shared budget ledger separately tracks standard-route token value. Unknown prices stay unknown. Cache and available reasoning-token counts are recorded. -- Completed traces rejected further updates in the current backend. Earlier flat imports remain archived. Replacement imports preserve saved answers and scores, with complete verdicts and parent/child links created together. -- Set `RAG_THINKING=disabled` for the current serving configuration. Use `enabled` only in a separately labeled fixed-evidence comparison. Generation mode is part of the answer-cache identity. The judge stays fixed while generation reasoning changes. - -### Bounded generation comparison with prompt version 6 - -The [saved comparison](evaluations/results/generation_v6.json) keeps the same 30 questions, references and source passages. The updated flow uses one writer, code-only display of valid writer-selected citation IDs and one verifier. A failed factual check withholds the answer. Code formatted citations in **21/30** cases, so prompt changes alone did not solve citation output. - -Groq completed 28 cases. At the user's request, the final two used TokenHarbor `deepseek-v4.1-flash:free` with frozen baseline evidence. Those two are excluded from the controlled Groq comparison. One fallback response reached its output limit and was retried with a larger allowance, then withheld. One Groq case retains its provider HTTP429 failure. - -| Controlled measurement | Before | After | Cases | -|---|---:|---:|---:| -| Released answers, same Groq model | 14/28 | 18/28 | 28 | -| Citation-format failures | 6 | 0 | 28 | -| Mean model stages, shared released answers | 2.91 | 2.00 | 11 | -| Context recall | 83.3% | 83.3% | 30, unchanged context | -| Context precision | 87.9% | 87.9% | 4, unchanged context | -| Paired faithfulness | 92.8% | 98.3% | 6 | -| Paired reference correctness | 45.0% | 32.3% | 4 | -| Paired completeness | 41.8% | 50.0% | 4 | - -Across all 30 outcomes there were **19 answers, 9 withheld responses, 1 clarification and 1 provider failure**. All 19 released answers passed citation-format checks. The paired semantic rows use only shared, unflagged scored cases. Raw candidate faithfulness was **93.0% across 11 answers**. Reference correctness decreased on its four shared cases and requires review. Q117 added version-qualified information beyond the reference, while Q376's bulletin-link reference and Q548's claim alignment remain review concerns. These results do not establish a broad answer-quality improvement. - -Collection and diagnostics used **64/66 HTTP attempts and 309,561 reported tokens**, including archived attempts. Recorded judging used **77/120 attempts and 116,119 tokens**, with **172 judge-cache hits** across scoring passes. The judge was stopped when the user ran out of Groq quota, and cache-only assembly made zero model calls. Recorded judge usage may omit in-flight activity at interruption. Answer relevancy was not rescored. Timing differences include quota waits and account changes. Reserved development remains unused. - -### Wider training run with prompt version 5 - -The [saved result](evaluations/results/techqa_wide_v5.json) covers **all 30 planned training questions**. It produced **15 released answers, 6 withheld responses, 1 clarification request and 8 generation failures**. Seven failures omitted inline citations even after repair. One earlier failure reached a local quota-wait deadline. The selected evidence included the labeled article for **25/30** questions. All **15 released answers** passed citation-format checks. +| p95 retrieval latency with Apple GPU reranking on 259 held-out questions | 2.74 s | **1.66 s (39.4% lower)** | +| End-to-end latency in an exact-repeat smoke test | 42.5 s | **3.0 s** | +| Model calls in the same smoke test | 4 | **1** | -RAGAS used `openai/gpt-oss-20b` after a supported/unsupported faithfulness check scored 1.0/0.0. Answer generation used `openai/gpt-oss-120b`. Samples follow the fixed question order, with answer metrics conditional on released answers. +The GPU benchmark used warm models and empty per-query caches, preserved Recall@10, and changed one final evidence payload on this cohort. The default local serving setup uses CPU reranking. The end-to-end test compared one fresh request, including provider quota waits, with its cached repeat. -| RAGAS metric | Raw mean | Scored cases | Review flags | -|---|---:|---:|---:| -| Context recall | 83.3% | 30 | 0 | -| Context precision | 87.9% | 4 | 0 | -| Faithfulness | 94.4% | 10 | 0 | -| Answer relevancy | 93.0% | 3 | 0 | -| Factual correctness against the reference | 42.6% | 5 | 1 | -| Completeness against the reference | 53.4% | 5 | 1 | +## Architecture -Context recall scored the full cohort. Precision scored four of five attempted cases. Expanded correctness/completeness stopped when the provider requested a 527-second wait, beyond the metric deadline. Relevancy retains its earlier three-case sample. Raw means retain flagged values. LangSmith leaves flagged values pending review, so its displayed averages use fewer cases. Source inspection also found a reference-scope issue where a question asks for a bulletin link but its reference contains the full bulletin text. Correctness and completeness need review before use as release criteria. - -Generation used **77 HTTP attempts / 396,211 reported tokens**, including the archived rate-limited attempt. Judging used **228 attempts / 384,342 tokens**, plus **4 calibration calls / 3,757 tokens**. The runner reused **108 cached judge decisions**. Median answered-case batch time was **129.7 seconds**, including quota waits and local retrieval. These timings describe a serial batch. Reserved development questions remain available for a later release evaluation. - -The collector initially stopped on a local request deadline. That condition was corrected, existing cases were reused, and all 30 questions finished after a provider-key update. Retryable failed attempts are archived before replacement. The pipeline stayed fixed during the evaluation. - - -### Component measurements already recorded - -A separate [offline retrieval replay](evaluations/results/retrieval_baseline_v1.json) used **97 known-positive training tuning questions**. Article Recall@5 was **83/97 (85.57%)** and Recall@10 **87/97 (89.69%)**. The packed-context reference-word-run proxy passed **80/97 (82.47%)**; that proxy is not semantic context recall. - -A 120-query local Qdrant search check recorded **24.41 ms p50 / 38.54 ms p95**, using saved query vectors. Those timings exclude query encoding, reranking and generation. These historical component runs have different conditions and denominators from the three-case pipeline pilot below. - -### Measured pilot, with its limitations - -The pilot used the **first three sorted answerable IDs** in the saved training tuning split. It produced **one answer and two withheld responses**. Final development was not evaluated. - -| Case | Outcome | Context precision | Context recall | Faithfulness | Answer relevancy | -|---|---|---:|---:|---:|---:| -| TRAIN_Q007 | Withheld | 0.756 | 0.000 | Skipped | Skipped | -| TRAIN_Q008 | Withheld | 0.887 | 1.000 | Skipped | Skipped | -| TRAIN_Q013 | Answered | 0.792 | 1.000 | **0.500 — judge error flagged** | 0.979 | -| Raw mean | 1 answered / 3 attempted | **0.812 (n=3)** | **0.667 (n=3)** | **0.500 (n=1)** | **0.979 (n=1)** | +```text +IBM HTML → structured chunks and source coordinates → Gemma vectors → Qdrant +Question → exact answer cache → dense search → BGE reranking → reciprocal rank fusion + → evidence selection → writer → citation check → verifier → workspace +``` -Eight metric results succeeded, four were deliberately skipped, and the completed pass had zero metric errors. These are integration observations, not final accuracy or a measured improvement. +- **Ingestion and retrieval.** The parser preserves article headings, tables, product metadata, and source coordinates where available. Exact Qdrant search and BGE reranking are fused before a bounded context is selected. BM25 and hybrid retrieval are available in offline benchmarks. +- **Answering and UI.** The writer cites excerpt IDs. Python validates the citation contract, then a separate verifier checks support, applicability, and completeness. The workspace streams progress and evidence, then renders the approved answer with optional validated OpenUI components. +- **Caching and memory.** Query vectors and reranker scores are stored locally. Exact answers are cached with session and version context. Users can regenerate to bypass the answer cache, and follow-up rewriting uses the current session. +- **Versioned index.** Document updates are staged separately and reuse unchanged vectors. Activation switches the serving index. A previous build can be reactivated for rollback. -The failure review matters as much as the averages: +## Evaluation suite -- **Q007:** the selected evidence missed the reference information. Related MQ passages could score as useful while context recall remained zero. -- **Q008:** the selected evidence supported the reference, but the pipeline withheld. Inspect the release path, rather than assume retrieval failed. -- **Q013:** the judge changed **“TIP 2.1” to “TIP 1”** while extracting claims, then penalized its altered claim. The raw faithfulness score is retained and flagged; it is not reliable evidence of an unsupported application answer. The new version-preservation heuristic catches this for review without rewriting the score. +![TechQA evaluation layers](evaluations/overview.svg) -The [published, redacted result](evaluations/results/techqa_pilot_v1.json) includes per-case outcomes, denominators, settings, source-artifact hashes and review flags. Questions, references, source passages, credentials and full judge traces remain local. The summary records the November 3 run; today's export and additional contract checks made **zero new live judge calls**. +| Layer | Coverage | +|---|---| +| Component | Article Recall@K, MRR, nDCG, and generation with supplied evidence | +| Pipeline | Annotated-article inclusion, reference-text coverage, citation contracts, and optional RAGAS metrics | +| Workflow | Follow-up resolution, exact-repeat caching, and response outcomes | +| Regression | Paired runs on fixed cases, saved artifacts, and review of changed outcomes | +| Observability | LangSmith traces and session threads, timing and usage, and user feedback for reviewed regression cases | -| Recorded operation | Observation | Scope | -|---|---:|---| -| Answer coverage | 1/3 | Reported separately from conditional answer scores | -| Selected gold-article hit | 2/3 | Final evidence only; **not search Recall@10** or semantic recall | -| Citation contract | 1/1 released answer | IDs/format only; does not prove factual support | -| Completed resumed scoring pass | 48.90 s; 17,135 reported tokens | 25 cached judgments, 8 fresh judgments; earlier passes cost extra | -| Historical cache replay | 33 hits, 0 misses, **0 API calls** | Same raw scores; 0.022 s scoring loop excludes startup/imports | -| Correctness / completeness | Not measured | Available as opt-in RAGAS checks | -| Dollar cost / online drift | Not measured | Pricing and online monitoring not configured | +The deterministic suite compares saved runs without calling a model. RAGAS scores selected cases with a request budget. Human review can assess correctness, completeness, citation support, and appropriate withholding. [Historical evaluation artifacts](evaluations/results/). -### Try the suite without a model or dataset +### Run the offline evaluation -After installing `requirements-test.txt`, run the [synthetic demonstration](evaluations/fixtures/offline_demo.json): +After installing the test requirements, use the synthetic fixture to see the report format and paired comparison. ```bash python -m scripts.eval_suite report \ @@ -271,15 +84,40 @@ python -m scripts.eval_suite compare \ --output /tmp/eval-diff.json ``` -The report checks selected-document hits, citation contracts and outcomes. It does not run an LLM. The comparison prints paired changes; an unchanged demo should have no regressions. CI exercises this path, the budget controls and actual RAGAS aggregation with mocked judge decisions. Synthetic test results are kept separate from the TechQA pilot. +For a saved real run, pass matching case and judge artifacts to the suite. To score cases with RAGAS, install its separate environment and select the metrics explicitly. -## Requirements +```bash +uv venv --python 3.13 .venv-ragas +uv pip install --python .venv-ragas/bin/python -r requirements-ragas.txt +.venv-ragas/bin/python -m scripts.eval_ragas run \ + --cases data/ragas/review/completed.json \ + --metrics context_precision context_recall --limit 5 --max-requests 20 +``` + +The request cap includes retries. `--max-requests 0` reuses cached judgments. Failed, skipped, and budget-exhausted cases are tracked separately. See [the RAGAS runner](scripts/eval_ragas.py) and [the evaluation CLI](scripts/eval_suite.py) for collection and comparison options. + +### Inspect runs in LangSmith + +Set `LANGSMITH_API_KEY` and `LANGSMITH_TRACING=true` in the backend environment. Expand **Pipeline / Question** to inspect each retrieval and generation step. Use **Threads** to review related turns. Trace content includes source excerpts and private drafts, so use a private project. + +```text +Pipeline / Question +├── Follow-up resolution and exact answer cache +├── Retrieval +│ ├── Query embedding and exact vector search +│ ├── Cross-encoder reranking and rank fusion +│ └── Evidence selection and token count +├── Generation +│ ├── Writer and citation contract +│ └── Verifier decision +└── Optional OpenUI presentation +``` -Python 3.13, Node.js 22, npm, uv, Docker Compose, a Groq or TokenHarbor API key, and prepared TechQA/model artifacts. The frontend and API run locally with Qdrant in Docker. +Publish saved cases with `python -m scripts.publish_langsmith --cases PATH`. Add `--ragas PATH` to attach existing scores without re-judging. The app records Helpful and Not helpful feedback. [Feedback tooling](scripts/feedback_cases.py) supports approving and exporting cases for regression tests. -### Run the offline checks first +## Run locally -No datasets, model downloads, API keys or Qdrant server are needed for these checks: +Use **Python 3.13**, **Node.js 22**, **uv**, and **Docker Compose**. Live answers require a Groq or TokenHarbor API key plus the prepared artifacts listed below. CI runs offline Python and frontend checks with synthetic inputs. ```bash uv venv --python 3.13 .venv-test @@ -291,12 +129,9 @@ npm ci npm run test:genui npm run typecheck npm run lint -npm run build ``` -GitHub Actions runs the same checks. The tests use synthetic data and controlled model outputs; they are not a live answer-quality benchmark. - -### Configure the application +From the repository root, set up the serving environment. ```bash uv venv --python 3.13 .venv-ingest @@ -304,13 +139,7 @@ uv pip install --python .venv-ingest/bin/python -r requirements-app.txt cp .env.example .env ``` -Set `GROQ_API_KEY` in the root `.env` for the default Groq provider. Existing installations can use the `GROK_API_KEY` alias. For TokenHarbor, set `RAG_LLM_PROVIDER=tokenharbor` and `TOKENHARBOR_API_KEY`. The example config pins the base URL, model and reasoning setting. Keep provider keys server-side. - -The model namespace starts with `openai/`, but requests go to **Groq's API**. The model is configured centrally in `rag_app/generation.py`. - -Standalone generation uses one writer and one verifier, with no factual repair loop. Code can display valid source IDs already selected by the writer while preserving answer text. The verifier then checks support, relevance, completeness and versions. Unknown source IDs fail validation. Rejected answers are withheld or request clarification. This is a two-logical-call limit for standalone generation. Transport retries, follow-up resolution and optional presentation calls are accounted separately. - -Generation uses remaining-token/reset headers to pace calls and keeps quota waits within request deadlines. The token estimate is approximate and applies to one provider instance, not a shared multi-worker quota. Offline case collection saves private writer/verifier results (and repair attempts in historical runs) and content-free HTTP statuses for diagnosis; these artifacts stay outside Git and are never returned as released answers. +Set `GROQ_API_KEY` in `.env` for the default provider. To use TokenHarbor, set `RAG_LLM_PROVIDER=tokenharbor` and `TOKENHARBOR_API_KEY`. Model and runtime settings are documented in [the example environment](.env.example). ### Prepare or restore artifacts @@ -366,22 +195,9 @@ Open `http://127.0.0.1:3000`. The example `APP_ORIGIN` matches that address. For `GET /health/live` checks the API process. `GET /health/ready` checks the key, pinned model assets, source hash and active index identity/count. The first request loads local models, so cold-start latency differs from subsequent requests. -## V1 acceptance and operation - -The local V1 uses one API worker and Docker Qdrant. Its [redacted acceptance results](evaluations/results/v1_acceptance.json) record the checks and their scope. - -| Check | Observation | -|---|---| -| Saved training-context replay | **80/97 → 83/97**, three gains and zero losses, using a reference-word coverage proxy | -| Changed-document drill | **2 chunks embedded, 99,695 vectors reused** across add/update/delete, followed by a zero-embedding repeat and successful rollback | -| Backup recovery | **28,482 documents / 99,697 vectors** validated, with identical exact-search top-ten results for three saved query vectors | -| Verifier calibration | **4/4** targeted canaries passed | -| Four final targeted questions | One answered, one clarification, two withheld | -| Live acceptance usage | **15/15 HTTP 200**, **62,248 reported tokens** across initial checks, canaries and the final generation pass | - -The replay uses training tuning questions and a text-coverage proxy. Final generation reused the newly selected contexts. These measurements support the targeted fixes. Full held-out answer quality remains a later milestone. Q046/Q037 still withhold, and historical RAGAS review flags remain visible. +## Index operations -Browser acceptance uses the existing controlled GenUI fixture. It checks rendering, excerpts, structured Run details, regeneration and session clearing. The API suite also covers the storage/search/verification handoff, session isolation, exact cache invalidation after an index change and bounded concurrent admission. +The [acceptance drill](evaluations/results/v1_acceptance.json) added, updated and deleted documents, reused **99,695 vectors**, embedded two changed chunks, and verified rollback. ### Update documents and roll back @@ -426,53 +242,6 @@ Staging copies unchanged vectors to preserve an isolated, recoverable version. I The backup contains a native Qdrant snapshot, matching SQLite sources and checksums. Restore creates a separate collection and returns `restore_id`. Activation validates the pair before changing the local pointer. This workflow is tested on a single-node Docker Qdrant. See the [Qdrant snapshot documentation](https://qdrant.tech/documentation/snapshots/) for the underlying snapshot operations. -### Inspect runs and operating bounds - -The local service admits five requests, processes one at a time, waits up to 30 seconds for the worker and bounds each request at 180 seconds. Provider quota waiting contributes to response time. Controlled concurrency tests exercise these bounds. Public traffic capacity needs a separate load measurement. - -Run details displays stage times, model/index/prompt identities, cache hits, token usage and HTTP attempts. Local metrics are content-free, capped at 100 MiB and seven days. Retrieval caches retain up to 2,048 query vectors and 50,000 pair scores. Existing answer-cache/session limits apply as well. - -Set `RAG_TRACE_DIR` in the backend environment to opt into private local JSON traces containing the question, candidates, selected passages and generation decisions. Traces use owner-only file permissions and retain up to 50 files, 128 MiB and seven days. Keep that directory outside public hosting and Git. Gold references remain in offline evaluation artifacts. - -## Run RAGAS offline - -```bash -uv venv --python 3.13 .venv-ragas -uv pip install --python .venv-ragas/bin/python -r requirements-ragas.txt -.venv-ingest/bin/python -m scripts.eval_ragas collect --limit 3 -.venv-ragas/bin/python -m scripts.eval_ragas run \ - --metrics context_precision context_recall --limit 3 --max-requests 12 -``` - -Collection additionally requires `data/splits/techqa_v1.json` and the original training question/document files under `data/raw/techqa/TechQA/training_and_dev/`. References are checked against original answer spans and never passed to inference. - -Collection saves standalone canonical answers, without session memory or UI generation. Scoring runs only the explicitly selected metrics, sequentially. Only answer relevancy loads local Gemma; the other judge metrics do not require local embedding weights. Results, per-call marking decisions, usage and caches stay under `data/ragas/`. Use a new output directory for a changed case set or serving-code version; see `--help` for paths and judge/timeout options. - -Choose metrics for the change you are investigating: - -- Retrieval/context change: `--metrics context_precision context_recall`. -- Answer-writing change: `--metrics faithfulness answer_relevancy`. -- Reference-based application review: `--metrics factual_correctness answer_completeness` (opt-in). - -The default scoring limit is three cases and **12 HTTP attempts, including retries**. Set `--max-requests 0` for cache-only execution; missing decisions become `budget_exhausted`, not zero quality. Use a fresh `--output` for a comparison; omitted output names are timestamped so earlier reports survive. These are request caps, **not a dollar/token spending guarantee**. Inspect actual usage before raising them; one metric can make several calls. - -Create a free report from actual local artifacts: - -```bash -python -m scripts.eval_suite report --cases data/ragas/pilot_v1 \ - --ragas data/ragas/results/pilot_v1.json --output /tmp/pilot-review.json -``` - -Compare two reports with the `compare` command above. Cohort and reference identities must match. Judge/embedding settings must also match before semantic score deltas are reported; flagged scores stay visible but are excluded from those deltas. A negative delta is an observed regression to inspect, not statistical proof. - -Failed evaluations are not zero scores; answer metrics are skipped on withheld cases. LLM judges can alter facts during claim extraction, so inspect their decisions before using scores as quality gates. - -## Operating limits - -- Intended for controlled local/demo use. Authentication and a public multi-user deployment are not implemented. -- Sessions and the exact answer cache are scoped to the local service. Persistent query and reranker caches have size limits. -- Requests have queue, rate and deadline controls. Groq quota waits can dominate latency. -- Verified components appear progressively after checking; unverified draft tokens are not streamed to users. -- Local backup restoration has been tested. Reserved answer-quality evaluation and production load testing are pending. +## Operating scope -The initial history is a reconstructed import of local build stages from October 28–November 3, 2026. Author and committer dates identify those reconstructed stages; the repository was first published on November 3, 2026. It is not an archive of the exact working tree at each historical moment. Subsequent commits record ongoing development normally. +The app is designed for a controlled local rollout. It runs with a single API worker and local Qdrant. Public authentication and sustained traffic capacity are outside the measured release scope. Latency varies with cache state and provider quota. Raw data, model files, conversation traces, and API keys are stored locally. diff --git a/evaluations/results/techqa_benchmarks.json b/evaluations/results/techqa_benchmarks.json new file mode 100644 index 0000000..4305ae4 --- /dev/null +++ b/evaluations/results/techqa_benchmarks.json @@ -0,0 +1,66 @@ +{ + "owner_reported_quality_comparison": { + "corpus": "IBM TechQA", + "cohort_questions": 133, + "source": "Aggregate figures supplied by the project owner from their evaluation records", + "per_case_artifacts_included": false, + "correctness_judging_method": null, + "metrics_percent": { + "ragas_context_precision": {"baseline": 72.0, "updated": 84.0}, + "ragas_answer_relevancy": {"baseline": 66.0, "updated": 88.5}, + "ragas_context_recall": {"baseline": 100.0, "updated": 100.0}, + "answer_correctness": {"baseline": null, "updated": 89.0} + } + }, + "v8_held_out_retrieval": { + "cohort": "Overlap-filtered TechQA development", + "indexed_articles": 28482, + "indexed_chunks": 99697, + "questions": 259, + "annotated_questions": 113, + "dense_article_hits_at_10": 95, + "reranked_and_fused_article_hits_at_10": 97, + "annotated_article_in_final_context": 92, + "contiguous_reference_coverage_at_least_90_percent_count": 85, + "additional_cases_with_usable_evidence_confirmed_by_assistant": 8, + "audited_evidence_coverage_count": 93, + "audited_evidence_coverage_definition": "Passes the contiguous reference rule or has usable evidence confirmed by excerpt review" + }, + "v8_answer_sample": { + "questions": 24, + "answered": 12, + "withheld": 11, + "clarified": 1, + "generation_errors": 0, + "generation_latency_seconds": {"p50": 7.83, "p95": 12.04}, + "citation_contract_passes": 12, + "citation_contract_checked": 12, + "assistant_rubric_review_of_released_answers": { + "main_answer_correct": 12, + "complete": 10, + "fully_supported_by_citations": 9, + "passed_all_three": 8, + "denominator": 12 + }, + "assistant_rubric_review_of_withholding_and_clarification": { + "justified": 8, + "unjustified": 2, + "unclear": 2 + } + }, + "retrieval_latency_comparison": { + "cohort": "Overlap-filtered TechQA development", + "questions": 259, + "conditions": "CPU versus Apple GPU reranking, warm models and empty per-query caches, through evidence selection", + "p95_seconds": {"cpu": 2.738855459, "apple_gpu": 1.660547542}, + "article_hits_at_10_both_arms": 97, + "annotated_questions": 113, + "identical_evidence_payloads": 258 + }, + "exact_repeat_smoke_test": { + "unique_questions": 1, + "conditions": "One fresh request followed by its exact repeat. Fresh timing includes provider quota waits.", + "end_to_end_wall_seconds": {"fresh": 42.518257084, "cached": 2.977079833}, + "model_calls": {"fresh": 4, "cached": 1} + } +}