Prabu17 commited on
Commit
901cd4e
·
verified ·
1 Parent(s): 0572b5c

Upload folder using huggingface_hub

Browse files
app/config/settings.py CHANGED
@@ -114,10 +114,12 @@ class Settings(BaseSettings):
114
  openrouter_model: str = Field(default="nex-agi/nex-n2.5-mini:free")
115
  openrouter_base_url: str = Field(default="https://openrouter.ai/api/v1")
116
  llm_timeout_seconds: float = Field(
117
- default=60.0,
118
  description=(
119
- "HTTP timeout for LLM calls. Raise this if you switch to a "
120
- "reasoning model, which can spend 60s+ thinking before answering."
 
 
121
  ),
122
  )
123
  llm_max_retries: int = Field(default=2)
@@ -143,12 +145,12 @@ class Settings(BaseSettings):
143
 
144
  # ---- Grounding / answers ----------------------------------------------------
145
  max_answer_tokens: int = Field(
146
- default=8192,
147
  description=(
148
  "Max completion tokens for answer generation. Must cover the "
149
  "model's reasoning tokens (if any) plus the JSON answer, or the "
150
- "response is truncated mid-JSON and cannot be parsed. Raise this "
151
- "if you switch to a reasoning model."
152
  ),
153
  )
154
  confidence_threshold: float = Field(default=0.5)
 
114
  openrouter_model: str = Field(default="nex-agi/nex-n2.5-mini:free")
115
  openrouter_base_url: str = Field(default="https://openrouter.ai/api/v1")
116
  llm_timeout_seconds: float = Field(
117
+ default=180.0,
118
  description=(
119
+ "HTTP timeout for LLM calls. Must exceed the time needed to emit "
120
+ "MAX_ANSWER_TOKENS: a reasoning model producing ~16k tokens can "
121
+ "take well over a minute. Was 60s, which risked timing out before "
122
+ "a long answer finished."
123
  ),
124
  )
125
  llm_max_retries: int = Field(default=2)
 
145
 
146
  # ---- Grounding / answers ----------------------------------------------------
147
  max_answer_tokens: int = Field(
148
+ default=16384,
149
  description=(
150
  "Max completion tokens for answer generation. Must cover the "
151
  "model's reasoning tokens (if any) plus the JSON answer, or the "
152
+ "response is truncated mid-JSON and cannot be parsed. Raised from "
153
+ "8192 after observing finish_reason=length truncation in production."
154
  ),
155
  )
156
  confidence_threshold: float = Field(default=0.5)
app/evaluation/chunk_refs.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Resolve golden-dataset chunk references to the ids the pipeline actually emits.
2
+
3
+ Why this exists
4
+ ---------------
5
+ The golden dataset (``evals/dataset/golden.jsonl``) is authored by humans and
6
+ references evidence with *readable* chunk ids such as ``authentication-guide:2``
7
+ — a document slug plus a chunk index.
8
+
9
+ The ingestion pipeline, however, assigns document ids as
10
+ ``sha1(canonical_path)[:32]`` (see ``app.ingestion.pipeline._doc_id_from_path``)
11
+ and emits chunk ids of the form ``{doc_id}:{chunk_index}``. A slug therefore
12
+ never equals a stored document id, so comparing the two directly makes every
13
+ retrieval metric structurally zero — the harness silently measures nothing.
14
+
15
+ This module bridges the two by mapping each slug to the concrete document id(s)
16
+ that ingestion produced, so retrieval metrics compare like with like.
17
+
18
+ Duplicate slugs
19
+ ---------------
20
+ The corpus ships the same document in several formats (``markdown/``, ``pdf/``,
21
+ ``docx/``, ``html/``). Ten slugs therefore map to two document ids each. A
22
+ reference to such a slug is expanded to *all* of them: retrieving either format
23
+ counts as a hit, which is the honest interpretation — the evidence is present
24
+ regardless of which rendering the retriever surfaced.
25
+
26
+ Out-of-range indices
27
+ --------------------
28
+ The same document rendered in different formats yields a different number of
29
+ chunks (a 5-chunk markdown file may be a 2-chunk PDF). A reference such as
30
+ ``authentication-guide:2`` is therefore valid for one rendering and impossible
31
+ for another. Expanding blindly would inject *phantom* ids that can never be
32
+ retrieved, deflating recall for reasons that have nothing to do with retrieval
33
+ quality. The resolver therefore consults the real chunk count per document and
34
+ drops any expansion whose index is out of range.
35
+
36
+ Usage
37
+ -----
38
+ ::
39
+
40
+ resolver = ChunkRefResolver.from_database()
41
+ resolver.resolve("authentication-guide:2")
42
+ # -> ["ca0aa574...:2"] (the PDF rendering only has 2 chunks, so it is dropped)
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ import logging
48
+ from collections.abc import Iterable
49
+ from dataclasses import dataclass, field
50
+
51
+ logger = logging.getLogger(__name__)
52
+
53
+
54
+ @dataclass
55
+ class ChunkRefResolver:
56
+ """Maps human-readable ``slug:index`` references to concrete chunk ids.
57
+
58
+ Attributes
59
+ ----------
60
+ slug_to_doc_ids:
61
+ Mapping of document slug (e.g. ``"authentication-guide"``) to the
62
+ concrete document id(s) ingestion assigned. A slug may map to more
63
+ than one id when the corpus contains the same document in several
64
+ formats.
65
+ doc_id_to_chunk_count:
66
+ Number of chunks stored for each document id. Used to discard
67
+ expansions whose chunk index does not exist for that rendering.
68
+ When empty, no range filtering is applied.
69
+ """
70
+
71
+ slug_to_doc_ids: dict[str, list[str]] = field(default_factory=dict)
72
+ doc_id_to_chunk_count: dict[str, int] = field(default_factory=dict)
73
+
74
+ # ---- Construction ---------------------------------------------------
75
+
76
+ @classmethod
77
+ def from_database(cls) -> ChunkRefResolver:
78
+ """Build a resolver from the ``documents`` and ``chunks`` tables.
79
+
80
+ Document titles are used as slugs because ``scripts/ingest_corpus.py``
81
+ registers each file with ``title=path.stem``.
82
+ """
83
+ # Imported lazily so this module stays importable without a database.
84
+ from sqlalchemy import func, select
85
+
86
+ from app.db.models import Chunk, Document
87
+ from app.db.session import session_scope
88
+
89
+ mapping: dict[str, list[str]] = {}
90
+ counts: dict[str, int] = {}
91
+ with session_scope() as session:
92
+ rows = session.execute(select(Document.title, Document.document_id)).all()
93
+ for title, doc_id in rows:
94
+ if not title or not doc_id:
95
+ continue
96
+ mapping.setdefault(title, [])
97
+ if doc_id not in mapping[title]:
98
+ mapping[title].append(doc_id)
99
+
100
+ count_rows = session.execute(
101
+ select(Chunk.document_id, func.count(Chunk.id)).group_by(Chunk.document_id)
102
+ ).all()
103
+ counts = {doc_id: int(n) for doc_id, n in count_rows}
104
+
105
+ logger.info(
106
+ "ChunkRefResolver: %d slugs -> %d documents (%d with chunk counts)",
107
+ len(mapping),
108
+ sum(len(v) for v in mapping.values()),
109
+ len(counts),
110
+ )
111
+ return cls(slug_to_doc_ids=mapping, doc_id_to_chunk_count=counts)
112
+
113
+ @classmethod
114
+ def from_pairs(
115
+ cls,
116
+ pairs: Iterable[tuple[str, str]],
117
+ chunk_counts: dict[str, int] | None = None,
118
+ ) -> ChunkRefResolver:
119
+ """Build a resolver from ``(slug, doc_id)`` pairs (used in tests)."""
120
+ mapping: dict[str, list[str]] = {}
121
+ for slug, doc_id in pairs:
122
+ mapping.setdefault(slug, [])
123
+ if doc_id not in mapping[slug]:
124
+ mapping[slug].append(doc_id)
125
+ return cls(slug_to_doc_ids=mapping, doc_id_to_chunk_count=dict(chunk_counts or {}))
126
+
127
+ # ---- Resolution -----------------------------------------------------
128
+
129
+ def _in_range(self, doc_id: str, index: int) -> bool:
130
+ """True when *index* exists for *doc_id* (or when counts are unknown)."""
131
+ if not self.doc_id_to_chunk_count:
132
+ return True
133
+ count = self.doc_id_to_chunk_count.get(doc_id)
134
+ if count is None:
135
+ # Document has no recorded chunks — nothing to retrieve.
136
+ return False
137
+ return 0 <= index < count
138
+
139
+ def resolve(self, chunk_ref: str) -> list[str]:
140
+ """Expand a single ``slug:index`` reference into concrete chunk ids.
141
+
142
+ Expansions whose chunk index does not exist for a given rendering are
143
+ dropped. Returns an empty list when the slug is unknown or every
144
+ expansion is out of range, so callers can decide whether to treat that
145
+ as a hard error.
146
+ """
147
+ slug, sep, index_str = chunk_ref.rpartition(":")
148
+ if not sep:
149
+ # No index component — treat the whole string as a slug with no
150
+ # specific chunk, which cannot be resolved to a chunk id.
151
+ return []
152
+ doc_ids = self.slug_to_doc_ids.get(slug)
153
+ if not doc_ids:
154
+ return []
155
+ try:
156
+ index = int(index_str)
157
+ except ValueError:
158
+ return []
159
+ return [
160
+ f"{doc_id}:{index}"
161
+ for doc_id in doc_ids
162
+ if self._in_range(doc_id, index)
163
+ ]
164
+
165
+ def resolve_all(self, chunk_refs: Iterable[str]) -> set[str]:
166
+ """Expand many references into a flat set of concrete chunk ids."""
167
+ resolved: set[str] = set()
168
+ for ref in chunk_refs:
169
+ resolved.update(self.resolve(ref))
170
+ return resolved
171
+
172
+ def unknown_slugs(self, chunk_refs: Iterable[str]) -> set[str]:
173
+ """Return the slugs in *chunk_refs* that are not present in the corpus."""
174
+ missing: set[str] = set()
175
+ for ref in chunk_refs:
176
+ slug, sep, _ = ref.rpartition(":")
177
+ if not sep or slug not in self.slug_to_doc_ids:
178
+ missing.add(slug or ref)
179
+ return missing
180
+
181
+ @property
182
+ def is_empty(self) -> bool:
183
+ """True when no documents were loaded (resolver cannot resolve anything)."""
184
+ return not self.slug_to_doc_ids
app/evaluation/ragas_eval.py CHANGED
@@ -12,6 +12,8 @@ import logging
12
  from dataclasses import dataclass, field
13
  from typing import Any
14
 
 
 
15
  from app.config import get_settings
16
 
17
  logger = logging.getLogger(__name__)
@@ -62,6 +64,9 @@ class RagasEvaluator:
62
  self.mock = mock
63
  self._client: Any = None
64
  self._evaluator: Any = None
 
 
 
65
  self._initialized = False
66
 
67
  def _initialize(self) -> bool:
@@ -80,7 +85,8 @@ class RagasEvaluator:
80
  return False
81
 
82
  try:
83
- from ragas.evaluation import Evaluator
 
84
  from ragas.metrics import (
85
  answer_correctness,
86
  answer_relevancy,
@@ -89,15 +95,25 @@ class RagasEvaluator:
89
  faithfulness,
90
  )
91
 
92
- self._evaluator = Evaluator(
93
- metrics=[
94
- faithfulness,
95
- answer_correctness,
96
- answer_relevancy,
97
- context_precision,
98
- context_recall,
99
- ]
 
100
  )
 
 
 
 
 
 
 
 
 
101
  logger.info("RagasEvaluator: initialised successfully")
102
  return True
103
  except ImportError as e:
@@ -107,6 +123,34 @@ class RagasEvaluator:
107
  logger.warning(f"RagasEvaluator: initialisation failed — {e}")
108
  return False
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  def evaluate(
111
  self,
112
  question: str,
@@ -122,7 +166,7 @@ class RagasEvaluator:
122
  return result
123
 
124
  try:
125
- from ragas import EvaluationDataset
126
 
127
  # Build a ragas-compatible dataset with a single row
128
  row = {
@@ -131,12 +175,26 @@ class RagasEvaluator:
131
  "retrieved_contexts": contexts,
132
  "reference": "", # we don't have ground-truth answers here
133
  }
134
- dataset = EvaluationDataset([row])
135
-
136
- # Run evaluation
137
- scores = self._evaluator.evaluate(dataset)
 
 
 
 
 
 
 
138
 
139
- # Extract per-metric scores
 
 
 
 
 
 
 
140
  score_dict = scores.to_pandas().iloc[0].to_dict()
141
  metric_names = [
142
  "faithfulness",
 
12
  from dataclasses import dataclass, field
13
  from typing import Any
14
 
15
+ from pydantic import SecretStr
16
+
17
  from app.config import get_settings
18
 
19
  logger = logging.getLogger(__name__)
 
64
  self.mock = mock
65
  self._client: Any = None
66
  self._evaluator: Any = None
67
+ self._llm: Any = None
68
+ self._embeddings: Any = None
69
+ self._metrics: list[Any] = []
70
  self._initialized = False
71
 
72
  def _initialize(self) -> bool:
 
85
  return False
86
 
87
  try:
88
+ from langchain_openai import ChatOpenAI
89
+ from ragas.llms import LangchainLLMWrapper
90
  from ragas.metrics import (
91
  answer_correctness,
92
  answer_relevancy,
 
95
  faithfulness,
96
  )
97
 
98
+ # ragas 0.4 dropped the `Evaluator` class in favour of a module-level
99
+ # `evaluate()` that takes explicit llm/embeddings wrappers.
100
+ settings = get_settings()
101
+ judge_llm = ChatOpenAI(
102
+ model=settings.openrouter_model,
103
+ api_key=SecretStr(settings.openrouter_api_key),
104
+ base_url=settings.openrouter_base_url,
105
+ timeout=settings.llm_timeout_seconds,
106
+ temperature=0.0,
107
  )
108
+ self._llm = LangchainLLMWrapper(judge_llm)
109
+ self._embeddings = self._build_embeddings()
110
+ self._metrics = [
111
+ faithfulness,
112
+ answer_correctness,
113
+ answer_relevancy,
114
+ context_precision,
115
+ context_recall,
116
+ ]
117
  logger.info("RagasEvaluator: initialised successfully")
118
  return True
119
  except ImportError as e:
 
123
  logger.warning(f"RagasEvaluator: initialisation failed — {e}")
124
  return False
125
 
126
+ def _build_embeddings(self) -> Any:
127
+ """Build a ragas-compatible embeddings wrapper.
128
+
129
+ ``answer_relevancy`` needs embeddings. Prefer the local BGE-M3 model
130
+ (already downloaded for retrieval, no extra API cost); fall back to
131
+ OpenAI-compatible embeddings via OpenRouter when unavailable.
132
+ """
133
+ settings = get_settings()
134
+ try:
135
+ from langchain_community.embeddings import HuggingFaceEmbeddings
136
+ from ragas.embeddings import LangchainEmbeddingsWrapper
137
+
138
+ return LangchainEmbeddingsWrapper(
139
+ HuggingFaceEmbeddings(model_name=settings.embedding_model)
140
+ )
141
+ except Exception as e:
142
+ logger.warning(f"RagasEvaluator: local embeddings unavailable ({e}); using API embeddings")
143
+ from langchain_openai import OpenAIEmbeddings
144
+ from ragas.embeddings import LangchainEmbeddingsWrapper
145
+
146
+ return LangchainEmbeddingsWrapper(
147
+ OpenAIEmbeddings(
148
+ model="text-embedding-3-small",
149
+ api_key=SecretStr(settings.openrouter_api_key),
150
+ base_url=settings.openrouter_base_url,
151
+ )
152
+ )
153
+
154
  def evaluate(
155
  self,
156
  question: str,
 
166
  return result
167
 
168
  try:
169
+ from ragas import EvaluationDataset, evaluate
170
 
171
  # Build a ragas-compatible dataset with a single row
172
  row = {
 
175
  "retrieved_contexts": contexts,
176
  "reference": "", # we don't have ground-truth answers here
177
  }
178
+ dataset = EvaluationDataset.from_list([row])
179
+
180
+ # Run evaluation (ragas 0.4 module-level API)
181
+ scores = evaluate(
182
+ dataset,
183
+ metrics=self._metrics,
184
+ llm=self._llm,
185
+ embeddings=self._embeddings,
186
+ show_progress=False,
187
+ raise_exceptions=False,
188
+ )
189
 
190
+ # Extract per-metric scores. `evaluate()` is typed as returning
191
+ # `EvaluationResult | Executor`; only `EvaluationResult` is produced
192
+ # here, but narrow explicitly so the union is provably handled.
193
+ if not hasattr(scores, "to_pandas"):
194
+ raise TypeError(
195
+ f"ragas evaluate() returned {type(scores).__name__}, "
196
+ "expected EvaluationResult"
197
+ )
198
  score_dict = scores.to_pandas().iloc[0].to_dict()
199
  metric_names = [
200
  "faithfulness",
app/evaluation/run.py CHANGED
@@ -74,6 +74,15 @@ def parse_args() -> argparse.Namespace:
74
  action="store_true",
75
  help="Skip post-run regression check even when --baseline is provided",
76
  )
 
 
 
 
 
 
 
 
 
77
  return parser.parse_args()
78
 
79
 
@@ -89,6 +98,7 @@ def main() -> None:
89
  mock=args.mock,
90
  question_limit=args.question_limit,
91
  output_dir=args.output,
 
92
  )
93
  except Exception as e:
94
  logger.error(f"Evaluation failed: {e}")
 
74
  action="store_true",
75
  help="Skip post-run regression check even when --baseline is provided",
76
  )
77
+ parser.add_argument(
78
+ "--no-ragas",
79
+ action="store_true",
80
+ help=(
81
+ "Skip the ragas judge. Ragas makes ~15 extra LLM calls per question "
82
+ "and is slow/fragile on free-tier models. Retrieval and citation "
83
+ "metrics are unaffected."
84
+ ),
85
+ )
86
  return parser.parse_args()
87
 
88
 
 
98
  mock=args.mock,
99
  question_limit=args.question_limit,
100
  output_dir=args.output,
101
+ no_ragas=args.no_ragas,
102
  )
103
  except Exception as e:
104
  logger.error(f"Evaluation failed: {e}")
app/evaluation/runner.py CHANGED
@@ -17,19 +17,24 @@ import uuid
17
  from dataclasses import asdict, dataclass, field
18
  from datetime import UTC, datetime
19
  from pathlib import Path
20
- from typing import Any
 
 
 
21
 
22
  from app.config import Settings, get_settings
23
  from app.embeddings import Embedder
24
  from app.generation.client import LLMClient, MockLLM, OpenRouterClient
25
- from app.generation.schemas import AnswerResponse, Citation, GroundingStatus
26
  from app.generation.service import GenerationService
27
  from app.grounding import GroundingValidator
28
  from app.retrieval.bm25 import BM25Indexer
 
29
  from app.retrieval.hybrid import HybridRetriever
 
30
  from app.retrieval.reranker import Reranker
31
  from app.retrieval.vector import VectorStore
32
 
 
33
  from .citation_metrics import compute_citation_metrics
34
  from .datasets import GoldenDataset, GoldenExample, load_golden_dataset
35
  from .ragas_eval import RagasEvaluator
@@ -48,11 +53,19 @@ class ExperimentConfig:
48
  """Configuration for a single evaluation experiment."""
49
 
50
  experiment_name: str = "final"
 
 
 
 
51
  use_vector: bool = True
52
  use_bm25: bool = False
53
  use_reranker: bool = False
54
  use_evidence_selector: bool = False
55
  use_grounding: bool = False
 
 
 
 
56
  use_ragas: bool = False
57
  top_k: int = 20
58
  rerank_top_k: int = 10
@@ -60,16 +73,36 @@ class ExperimentConfig:
60
 
61
 
62
  EXPERIMENTS: dict[str, ExperimentConfig] = {
63
- "vector": ExperimentConfig(experiment_name="A — Vector Only", use_vector=True, use_bm25=False),
64
- "bm25": ExperimentConfig(experiment_name="B — BM25 Only", use_vector=False, use_bm25=True),
65
- "hybrid": ExperimentConfig(experiment_name="C — Hybrid", use_vector=True, use_bm25=True),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  "final": ExperimentConfig(
67
  experiment_name="D — Full Pipeline",
 
68
  use_vector=True,
69
  use_bm25=True,
70
  use_reranker=True,
71
  use_evidence_selector=True,
72
  use_grounding=True,
 
73
  use_ragas=True,
74
  top_k=20,
75
  rerank_top_k=10,
@@ -166,6 +199,8 @@ class EvaluationRunner:
166
  self._gen_service: GenerationService | None = None
167
  self._grounding: GroundingValidator | None = None
168
  self._ragas: RagasEvaluator | None = None
 
 
169
  # Allow injected mock components for testing
170
  if _retriever is not None:
171
  self._retriever = _retriever
@@ -240,17 +275,59 @@ class EvaluationRunner:
240
  if self._ragas is None and self.cfg.use_ragas:
241
  self._ragas = RagasEvaluator(disabled=not self.settings.openrouter_api_key, mock=self.mock)
242
 
 
 
 
 
243
  # ------------------------------------------------------------------
244
  # Per-question evaluation
245
  # ------------------------------------------------------------------
246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  def _evaluate_question(
248
  self, example: GoldenExample
249
  ) -> QuestionResult:
250
  """Evaluate a single question through the configured pipeline."""
251
  qid = example.id
252
  question = example.question
253
- expected_chunks = set(example.relevant_chunk_ids)
 
 
 
254
  answerable = example.answerable
255
  start_time = time.perf_counter()
256
 
@@ -272,35 +349,50 @@ class EvaluationRunner:
272
  reranked = self._reranker.rerank(question, retrieved, top_k=self.cfg.rerank_top_k)
273
  reranked_chunk_ids = [r.chunk_id for r in reranked]
274
 
 
 
 
 
 
 
 
 
 
 
 
275
  # ---- Generation + Grounding ----
276
  generated_answer = ""
277
  citations: list[dict[str, Any]] = []
278
  if self.cfg.use_grounding:
279
  self._init_grounding()
280
- # Build a minimal AnswerResponse from retrieved chunks for validation
 
 
 
 
281
  chunks_to_use = reranked_chunk_ids or result.retrieved_chunk_ids
282
- chunks_for_grounding = [r for r in retrieved if r.chunk_id in chunks_to_use]
283
- response_for_validation = AnswerResponse(
284
- answer="",
285
- citations=[
286
- Citation(citation_id=f"[C{i}]", chunk_id=r.chunk_id, text=r.text)
287
- for i, r in enumerate(chunks_for_grounding, start=1)
288
- ],
289
- grounding_status=GroundingStatus.PARTIALLY_GROUNDED,
290
- )
291
  assert self._grounding is not None
292
- grounded_response = self._grounding.validate(response_for_validation)
293
  generated_answer = grounded_response.answer
294
  citations = [
295
  {"citation_id": c.citation_id, "chunk_id": c.chunk_id, "text": c.text}
296
  for c in grounded_response.citations
297
  ]
298
  else:
299
- self._init_generation()
300
- assert self._gen_service is not None
301
- candidates_for_gen = [r for r in retrieved if r.chunk_id in result.retrieved_chunk_ids]
302
- gen_output = self._gen_service.generate(question, candidates=candidates_for_gen)
303
- generated_answer = gen_output.answer
 
 
 
 
 
304
 
305
  # ---- Citation / Grounding metrics ----
306
  citation_metrics = compute_citation_metrics(
@@ -393,11 +485,11 @@ class EvaluationRunner:
393
  all_retrieval.append(qr.retrieval_metrics)
394
  all_citation.append(qr.citation_metrics)
395
  if qr.ragas_scores is not None:
396
- # RagasResult is a dataclass; extract numeric values
397
- for k in ("faithfulness", "answer_correctness", "answer_relevance", "context_precision"):
398
- v = qr.ragas_scores.get(k)
399
- if v is not None:
400
- all_ragas.append({k: float(v)})
401
  difficulty = str(qr.example.difficulty.value)
402
  if difficulty not in per_difficulty:
403
  per_difficulty[difficulty] = []
@@ -445,7 +537,7 @@ class EvaluationRunner:
445
  if output_dir is None:
446
  output_dir = Path("evals/results/")
447
  output_dir.mkdir(parents=True, exist_ok=True)
448
- out_file = output_dir / f"experiment_{self.cfg.experiment_name}_{experiment_id}.json"
449
  with open(out_file, "w", encoding="utf-8") as f:
450
  json.dump(experiment_results.to_dict(), f, indent=2, ensure_ascii=False)
451
  logger.info(f"Results written to {out_file}")
@@ -458,6 +550,28 @@ class EvaluationRunner:
458
  # ----------------------------------------------------------------------
459
 
460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  def _aggregate_metric_list(metrics_list: list[dict[str, float]]) -> dict[str, float]:
462
  """Compute mean of each key across a list of metric dicts."""
463
  if not metrics_list:
@@ -483,14 +597,21 @@ def run_evaluation(
483
  mock: bool = False,
484
  question_limit: int | None = None,
485
  output_dir: str | None = None,
 
486
  ) -> ExperimentResults:
487
  """
488
  Convenience wrapper around EvaluationRunner.run().
489
 
490
  Loads the default dataset and runs the requested experiment.
 
 
 
 
491
  """
492
  settings = get_settings()
493
  dataset = load_golden_dataset(settings.eval_dataset_path)
494
  runner = EvaluationRunner(experiment=experiment, mock=mock, settings=settings)
 
 
495
  out_path = Path(output_dir) if output_dir else None
496
  return runner.run(dataset, question_limit=question_limit, output_dir=out_path)
 
17
  from dataclasses import asdict, dataclass, field
18
  from datetime import UTC, datetime
19
  from pathlib import Path
20
+ from typing import TYPE_CHECKING, Any
21
+
22
+ if TYPE_CHECKING:
23
+ from collections.abc import Iterator
24
 
25
  from app.config import Settings, get_settings
26
  from app.embeddings import Embedder
27
  from app.generation.client import LLMClient, MockLLM, OpenRouterClient
 
28
  from app.generation.service import GenerationService
29
  from app.grounding import GroundingValidator
30
  from app.retrieval.bm25 import BM25Indexer
31
+ from app.retrieval.evidence import EvidenceSelector
32
  from app.retrieval.hybrid import HybridRetriever
33
+ from app.retrieval.models import RetrievalResult
34
  from app.retrieval.reranker import Reranker
35
  from app.retrieval.vector import VectorStore
36
 
37
+ from .chunk_refs import ChunkRefResolver
38
  from .citation_metrics import compute_citation_metrics
39
  from .datasets import GoldenDataset, GoldenExample, load_golden_dataset
40
  from .ragas_eval import RagasEvaluator
 
53
  """Configuration for a single evaluation experiment."""
54
 
55
  experiment_name: str = "final"
56
+ # Short machine-readable key ("final", "hybrid", ...). Used for result
57
+ # filenames so tooling can glob `experiment_<key>_*.json`. Kept separate
58
+ # from `experiment_name`, which is a human-readable label.
59
+ experiment_key: str = "final"
60
  use_vector: bool = True
61
  use_bm25: bool = False
62
  use_reranker: bool = False
63
  use_evidence_selector: bool = False
64
  use_grounding: bool = False
65
+ # Retrieval-only experiments (A/B/C) do not need generated answers. Skipping
66
+ # generation keeps ablations fast and free — and avoids conflating retrieval
67
+ # quality with LLM quality when reading Recall@K / NDCG@K.
68
+ use_generation: bool = False
69
  use_ragas: bool = False
70
  top_k: int = 20
71
  rerank_top_k: int = 10
 
73
 
74
 
75
  EXPERIMENTS: dict[str, ExperimentConfig] = {
76
+ "vector": ExperimentConfig(
77
+ experiment_name="A — Vector Only",
78
+ experiment_key="vector",
79
+ use_vector=True,
80
+ use_bm25=False,
81
+ use_generation=False,
82
+ ),
83
+ "bm25": ExperimentConfig(
84
+ experiment_name="B — BM25 Only",
85
+ experiment_key="bm25",
86
+ use_vector=False,
87
+ use_bm25=True,
88
+ use_generation=False,
89
+ ),
90
+ "hybrid": ExperimentConfig(
91
+ experiment_name="C — Hybrid",
92
+ experiment_key="hybrid",
93
+ use_vector=True,
94
+ use_bm25=True,
95
+ use_generation=False,
96
+ ),
97
  "final": ExperimentConfig(
98
  experiment_name="D — Full Pipeline",
99
+ experiment_key="final",
100
  use_vector=True,
101
  use_bm25=True,
102
  use_reranker=True,
103
  use_evidence_selector=True,
104
  use_grounding=True,
105
+ use_generation=True,
106
  use_ragas=True,
107
  top_k=20,
108
  rerank_top_k=10,
 
199
  self._gen_service: GenerationService | None = None
200
  self._grounding: GroundingValidator | None = None
201
  self._ragas: RagasEvaluator | None = None
202
+ self._chunk_refs: ChunkRefResolver | None = None
203
+ self._evidence_selector: EvidenceSelector | None = None
204
  # Allow injected mock components for testing
205
  if _retriever is not None:
206
  self._retriever = _retriever
 
275
  if self._ragas is None and self.cfg.use_ragas:
276
  self._ragas = RagasEvaluator(disabled=not self.settings.openrouter_api_key, mock=self.mock)
277
 
278
+ def _init_evidence_selector(self) -> None:
279
+ if self._evidence_selector is None and self.cfg.use_evidence_selector:
280
+ self._evidence_selector = EvidenceSelector(settings=self.settings)
281
+
282
  # ------------------------------------------------------------------
283
  # Per-question evaluation
284
  # ------------------------------------------------------------------
285
 
286
+ def _resolve_expected_chunks(self, example: GoldenExample) -> set[str]:
287
+ """Map a golden example's slug references to concrete chunk ids.
288
+
289
+ Falls back to the raw references when no resolver is available (e.g.
290
+ unit tests that inject mock components and never touch the database),
291
+ so behaviour is unchanged in that case.
292
+ """
293
+ raw = list(example.relevant_chunk_ids)
294
+ if not raw:
295
+ return set()
296
+ if self._chunk_refs is None:
297
+ try:
298
+ self._chunk_refs = ChunkRefResolver.from_database()
299
+ except Exception as exc: # pragma: no cover - depends on DB availability
300
+ logger.warning(
301
+ "Could not build chunk-ref resolver (%s); "
302
+ "retrieval metrics will compare raw references.",
303
+ exc,
304
+ )
305
+ self._chunk_refs = ChunkRefResolver()
306
+ if self._chunk_refs.is_empty:
307
+ return set(raw)
308
+ resolved = self._chunk_refs.resolve_all(raw)
309
+ if not resolved:
310
+ # Every reference was unresolvable — surface it rather than
311
+ # silently reporting a zero score.
312
+ missing = self._chunk_refs.unknown_slugs(raw)
313
+ logger.warning(
314
+ "Question %s: no chunk references resolved (unknown slugs: %s)",
315
+ example.id,
316
+ sorted(missing),
317
+ )
318
+ return set(raw)
319
+ return resolved
320
+
321
  def _evaluate_question(
322
  self, example: GoldenExample
323
  ) -> QuestionResult:
324
  """Evaluate a single question through the configured pipeline."""
325
  qid = example.id
326
  question = example.question
327
+ # The golden dataset references evidence by human-readable slug
328
+ # (e.g. "authentication-guide:2"); the pipeline emits hash-based ids.
329
+ # Resolve before comparing, otherwise every retrieval metric is 0.
330
+ expected_chunks = self._resolve_expected_chunks(example)
331
  answerable = example.answerable
332
  start_time = time.perf_counter()
333
 
 
349
  reranked = self._reranker.rerank(question, retrieved, top_k=self.cfg.rerank_top_k)
350
  reranked_chunk_ids = [r.chunk_id for r in reranked]
351
 
352
+ # ---- Evidence selection ----
353
+ # Without this the generator receives every retrieved chunk
354
+ # (top_k=20), which inflates prompt size and latency. The full
355
+ # pipeline is supposed to narrow to FINAL_CONTEXT_K chunks.
356
+ evidence: list[RetrievalResult] = []
357
+ if self.cfg.use_evidence_selector:
358
+ self._init_evidence_selector()
359
+ assert self._evidence_selector is not None
360
+ pool = reranked if reranked_chunk_ids else retrieved
361
+ evidence = self._evidence_selector.select(pool)
362
+
363
  # ---- Generation + Grounding ----
364
  generated_answer = ""
365
  citations: list[dict[str, Any]] = []
366
  if self.cfg.use_grounding:
367
  self._init_grounding()
368
+ # Generate a real answer first, then validate it. Passing an
369
+ # empty answer to the validator would make every citation
370
+ # metric meaningless (no claims -> nothing to ground).
371
+ self._init_generation()
372
+ assert self._gen_service is not None
373
  chunks_to_use = reranked_chunk_ids or result.retrieved_chunk_ids
374
+ chunks_for_grounding = evidence or [
375
+ r for r in retrieved if r.chunk_id in chunks_to_use
376
+ ]
377
+ gen_output = self._gen_service.generate(question, candidates=chunks_for_grounding)
 
 
 
 
 
378
  assert self._grounding is not None
379
+ grounded_response = self._grounding.validate(gen_output)
380
  generated_answer = grounded_response.answer
381
  citations = [
382
  {"citation_id": c.citation_id, "chunk_id": c.chunk_id, "text": c.text}
383
  for c in grounded_response.citations
384
  ]
385
  else:
386
+ if self.cfg.use_generation:
387
+ self._init_generation()
388
+ assert self._gen_service is not None
389
+ candidates_for_gen = evidence or [
390
+ r for r in retrieved if r.chunk_id in result.retrieved_chunk_ids
391
+ ]
392
+ gen_output = self._gen_service.generate(
393
+ question, candidates=candidates_for_gen
394
+ )
395
+ generated_answer = gen_output.answer
396
 
397
  # ---- Citation / Grounding metrics ----
398
  citation_metrics = compute_citation_metrics(
 
485
  all_retrieval.append(qr.retrieval_metrics)
486
  all_citation.append(qr.citation_metrics)
487
  if qr.ragas_scores is not None:
488
+ # RagasResult.to_dict() nests scores as
489
+ # {"metrics": {name: {"value": v, "error": e}}}. Flatten to
490
+ # {name: float} so aggregation sees real numbers.
491
+ for name, score in _iter_ragas_scores(qr.ragas_scores):
492
+ all_ragas.append({name: score})
493
  difficulty = str(qr.example.difficulty.value)
494
  if difficulty not in per_difficulty:
495
  per_difficulty[difficulty] = []
 
537
  if output_dir is None:
538
  output_dir = Path("evals/results/")
539
  output_dir.mkdir(parents=True, exist_ok=True)
540
+ out_file = output_dir / f"experiment_{self.cfg.experiment_key}_{experiment_id}.json"
541
  with open(out_file, "w", encoding="utf-8") as f:
542
  json.dump(experiment_results.to_dict(), f, indent=2, ensure_ascii=False)
543
  logger.info(f"Results written to {out_file}")
 
550
  # ----------------------------------------------------------------------
551
 
552
 
553
+ def _iter_ragas_scores(ragas_scores: dict[str, Any]) -> Iterator[tuple[str, float]]:
554
+ """Yield ``(metric_name, value)`` pairs from a serialized RagasResult.
555
+
556
+ ``RagasResult.to_dict()`` nests scores as
557
+ ``{"metrics": {name: {"value": v, "error": e}}}``. This flattens that
558
+ structure, skipping metrics that errored or produced no numeric value.
559
+ """
560
+ metrics = ragas_scores.get("metrics")
561
+ if not isinstance(metrics, dict):
562
+ return
563
+ for name, payload in metrics.items():
564
+ value: Any = payload
565
+ if isinstance(payload, dict):
566
+ value = payload.get("value")
567
+ if value is None:
568
+ continue
569
+ try:
570
+ yield name, float(value)
571
+ except (TypeError, ValueError):
572
+ continue
573
+
574
+
575
  def _aggregate_metric_list(metrics_list: list[dict[str, float]]) -> dict[str, float]:
576
  """Compute mean of each key across a list of metric dicts."""
577
  if not metrics_list:
 
597
  mock: bool = False,
598
  question_limit: int | None = None,
599
  output_dir: str | None = None,
600
+ no_ragas: bool = False,
601
  ) -> ExperimentResults:
602
  """
603
  Convenience wrapper around EvaluationRunner.run().
604
 
605
  Loads the default dataset and runs the requested experiment.
606
+
607
+ ``no_ragas`` disables the ragas judge. Ragas issues ~15 extra LLM calls per
608
+ question, which is slow and fragile on free-tier models; disabling it keeps
609
+ retrieval/citation metrics (the ones that need no judge) intact.
610
  """
611
  settings = get_settings()
612
  dataset = load_golden_dataset(settings.eval_dataset_path)
613
  runner = EvaluationRunner(experiment=experiment, mock=mock, settings=settings)
614
+ if no_ragas:
615
+ runner.cfg.use_ragas = False
616
  out_path = Path(output_dir) if output_dir else None
617
  return runner.run(dataset, question_limit=question_limit, output_dir=out_path)
app/observability/cost.py CHANGED
@@ -1,127 +1,130 @@
1
- """LLM cost tracking: pricing table + usage aggregation (no external deps).
2
-
3
- Token counts are reported by every OpenRouter response, but nothing summed
4
- them — this module closes that gap. :func:`record_llm_usage` is called by the
5
- LLM client on every completion (generation, grounding judge, agent turns);
6
- :func:`usage_summary` feeds ``GET /metrics`` so spend is visible next to
7
- latency. Process-local like the timing registry: resets on restart.
8
-
9
- Prices are USD per 1M tokens (prompt, completion) and are approximate —
10
- OpenRouter adjusts them per provider. Unknown models record tokens with
11
- ``cost_usd=None`` (unpriced) rather than a made-up number.
12
- """
13
-
14
- from __future__ import annotations
15
-
16
- import threading
17
-
18
- # (prompt $/1M, completion $/1M). Verified against OpenRouter listings;
19
- # ":free" variants are $0. Revisit when switching default models.
20
- MODEL_PRICES_USD_PER_M: dict[str, tuple[float, float]] = {
21
- "nex-agi/nex-n2.5-mini": (0.0, 0.0),
22
- "openai/gpt-4o-mini": (0.15, 0.60),
23
- "openai/gpt-4o": (2.50, 10.00),
24
- "anthropic/claude-3-5-haiku": (0.80, 4.00),
25
- "google/gemini-2.0-flash-001": (0.10, 0.40),
26
- "deepseek/deepseek-chat": (0.27, 1.10),
27
- "meta-llama/llama-3.3-70b-instruct": (0.12, 0.30),
28
- }
29
-
30
-
31
- def normalize_model_id(model: str | None) -> str:
32
- """Lowercase + strip provider routing suffixes (``:free``, ``:nitro``…)."""
33
- if not model:
34
- return ""
35
- base = model.strip().lower()
36
- for suffix in (":free", ":nitro", ":floor", ":extended"):
37
- if base.endswith(suffix):
38
- base = base[: -len(suffix)]
39
- break
40
- return base
41
-
42
-
43
- def estimate_cost_usd(
44
- model: str | None,
45
- prompt_tokens: int | None,
46
- completion_tokens: int | None,
47
- ) -> float | None:
48
- """Return the estimated USD cost, or None when unpriced/unknown."""
49
- prices = MODEL_PRICES_USD_PER_M.get(normalize_model_id(model))
50
- if prices is None or prompt_tokens is None or completion_tokens is None:
51
- return None
52
- prompt_rate, completion_rate = prices
53
- return round(prompt_tokens * prompt_rate / 1_000_000 + completion_tokens * completion_rate / 1_000_000, 6)
54
-
55
-
56
- _lock = threading.Lock()
57
- _totals: dict[str, dict[str, float]] = {}
58
-
59
-
60
- def _bucket(label: str, model: str | None) -> str:
61
- return f"{label}::{normalize_model_id(model) or 'unknown'}"
62
-
63
-
64
- def record_llm_usage(
65
- label: str,
66
- model: str | None,
67
- prompt_tokens: int | None,
68
- completion_tokens: int | None,
69
- ) -> float | None:
70
- """Aggregate one completion's tokens + cost (thread-safe, never raises).
71
-
72
- Returns the estimated cost so callers can attach it to responses.
73
- """
74
- try:
75
- cost = estimate_cost_usd(model, prompt_tokens, completion_tokens)
76
- key = _bucket(label, model)
77
- with _lock:
78
- entry = _totals.setdefault(
79
- key,
80
- {"calls": 0, "prompt_tokens": 0, "completion_tokens": 0, "cost_usd": 0.0},
81
- )
82
- entry["calls"] += 1
83
- entry["prompt_tokens"] += prompt_tokens or 0
84
- entry["completion_tokens"] += completion_tokens or 0
85
- entry["cost_usd"] += cost or 0.0
86
- return cost
87
- except Exception:
88
- return None
89
-
90
-
91
- def usage_summary() -> dict:
92
- """Return per-label/model token + cost totals (JSON-serializable)."""
93
- with _lock:
94
- entries = {
95
- key: {
96
- "calls": int(val["calls"]),
97
- "prompt_tokens": int(val["prompt_tokens"]),
98
- "completion_tokens": int(val["completion_tokens"]),
99
- "total_tokens": int(val["prompt_tokens"] + val["completion_tokens"]),
100
- "cost_usd": round(val["cost_usd"], 6),
101
- }
102
- for key, val in sorted(_totals.items())
103
- }
104
- totals = {
105
- "calls": sum(e["calls"] for e in entries.values()),
106
- "prompt_tokens": sum(e["prompt_tokens"] for e in entries.values()),
107
- "completion_tokens": sum(e["completion_tokens"] for e in entries.values()),
108
- "cost_usd": round(sum(e["cost_usd"] for e in entries.values()), 6),
109
- }
110
- totals["total_tokens"] = totals["prompt_tokens"] + totals["completion_tokens"]
111
- return {"by_usage": entries, "totals": totals}
112
-
113
-
114
- def reset_usage() -> None:
115
- """Clear all usage samples (tests)."""
116
- with _lock:
117
- _totals.clear()
118
-
119
-
120
- __all__ = [
121
- "MODEL_PRICES_USD_PER_M",
122
- "estimate_cost_usd",
123
- "normalize_model_id",
124
- "record_llm_usage",
125
- "reset_usage",
126
- "usage_summary",
127
- ]
 
 
 
 
1
+ """LLM cost tracking: pricing table + usage aggregation (no external deps).
2
+
3
+ Token counts are reported by every OpenRouter response, but nothing summed
4
+ them — this module closes that gap. :func:`record_llm_usage` is called by the
5
+ LLM client on every completion (generation, grounding judge, agent turns);
6
+ :func:`usage_summary` feeds ``GET /metrics`` so spend is visible next to
7
+ latency. Process-local like the timing registry: resets on restart.
8
+
9
+ Prices are USD per 1M tokens (prompt, completion) and are approximate —
10
+ OpenRouter adjusts them per provider. Unknown models record tokens with
11
+ ``cost_usd=None`` (unpriced) rather than a made-up number.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import threading
17
+
18
+ # (prompt $/1M, completion $/1M). Verified against OpenRouter listings;
19
+ # ":free" variants are $0. Revisit when switching default models.
20
+ MODEL_PRICES_USD_PER_M: dict[str, tuple[float, float]] = {
21
+ "nex-agi/nex-n2.5-mini": (0.0, 0.0),
22
+ "nex-agi/nex-n2.5-pro": (0.0, 0.0),
23
+ "liquid/lfm-2.5-2.6b": (0.0, 0.0),
24
+ "z-ai/glm-5.2": (0.0, 0.0),
25
+ "openai/gpt-4o-mini": (0.15, 0.60),
26
+ "openai/gpt-4o": (2.50, 10.00),
27
+ "anthropic/claude-3-5-haiku": (0.80, 4.00),
28
+ "google/gemini-2.0-flash-001": (0.10, 0.40),
29
+ "deepseek/deepseek-chat": (0.27, 1.10),
30
+ "meta-llama/llama-3.3-70b-instruct": (0.12, 0.30),
31
+ }
32
+
33
+
34
+ def normalize_model_id(model: str | None) -> str:
35
+ """Lowercase + strip provider routing suffixes (``:free``, ``:nitro``…)."""
36
+ if not model:
37
+ return ""
38
+ base = model.strip().lower()
39
+ for suffix in (":free", ":nitro", ":floor", ":extended"):
40
+ if base.endswith(suffix):
41
+ base = base[: -len(suffix)]
42
+ break
43
+ return base
44
+
45
+
46
+ def estimate_cost_usd(
47
+ model: str | None,
48
+ prompt_tokens: int | None,
49
+ completion_tokens: int | None,
50
+ ) -> float | None:
51
+ """Return the estimated USD cost, or None when unpriced/unknown."""
52
+ prices = MODEL_PRICES_USD_PER_M.get(normalize_model_id(model))
53
+ if prices is None or prompt_tokens is None or completion_tokens is None:
54
+ return None
55
+ prompt_rate, completion_rate = prices
56
+ return round(prompt_tokens * prompt_rate / 1_000_000 + completion_tokens * completion_rate / 1_000_000, 6)
57
+
58
+
59
+ _lock = threading.Lock()
60
+ _totals: dict[str, dict[str, float]] = {}
61
+
62
+
63
+ def _bucket(label: str, model: str | None) -> str:
64
+ return f"{label}::{normalize_model_id(model) or 'unknown'}"
65
+
66
+
67
+ def record_llm_usage(
68
+ label: str,
69
+ model: str | None,
70
+ prompt_tokens: int | None,
71
+ completion_tokens: int | None,
72
+ ) -> float | None:
73
+ """Aggregate one completion's tokens + cost (thread-safe, never raises).
74
+
75
+ Returns the estimated cost so callers can attach it to responses.
76
+ """
77
+ try:
78
+ cost = estimate_cost_usd(model, prompt_tokens, completion_tokens)
79
+ key = _bucket(label, model)
80
+ with _lock:
81
+ entry = _totals.setdefault(
82
+ key,
83
+ {"calls": 0, "prompt_tokens": 0, "completion_tokens": 0, "cost_usd": 0.0},
84
+ )
85
+ entry["calls"] += 1
86
+ entry["prompt_tokens"] += prompt_tokens or 0
87
+ entry["completion_tokens"] += completion_tokens or 0
88
+ entry["cost_usd"] += cost or 0.0
89
+ return cost
90
+ except Exception:
91
+ return None
92
+
93
+
94
+ def usage_summary() -> dict:
95
+ """Return per-label/model token + cost totals (JSON-serializable)."""
96
+ with _lock:
97
+ entries = {
98
+ key: {
99
+ "calls": int(val["calls"]),
100
+ "prompt_tokens": int(val["prompt_tokens"]),
101
+ "completion_tokens": int(val["completion_tokens"]),
102
+ "total_tokens": int(val["prompt_tokens"] + val["completion_tokens"]),
103
+ "cost_usd": round(val["cost_usd"], 6),
104
+ }
105
+ for key, val in sorted(_totals.items())
106
+ }
107
+ totals = {
108
+ "calls": sum(e["calls"] for e in entries.values()),
109
+ "prompt_tokens": sum(e["prompt_tokens"] for e in entries.values()),
110
+ "completion_tokens": sum(e["completion_tokens"] for e in entries.values()),
111
+ "cost_usd": round(sum(e["cost_usd"] for e in entries.values()), 6),
112
+ }
113
+ totals["total_tokens"] = totals["prompt_tokens"] + totals["completion_tokens"]
114
+ return {"by_usage": entries, "totals": totals}
115
+
116
+
117
+ def reset_usage() -> None:
118
+ """Clear all usage samples (tests)."""
119
+ with _lock:
120
+ _totals.clear()
121
+
122
+
123
+ __all__ = [
124
+ "MODEL_PRICES_USD_PER_M",
125
+ "estimate_cost_usd",
126
+ "normalize_model_id",
127
+ "record_llm_usage",
128
+ "reset_usage",
129
+ "usage_summary",
130
+ ]
frontend/next-env.d.ts CHANGED
@@ -1,7 +1,7 @@
1
  /// <reference types="next" />
2
  /// <reference types="next/image-types/global" />
3
- import "./.next/types/routes.d.ts";
4
- import "./.next/types/root-params.d.ts";
5
 
6
  // NOTE: This file should not be edited
7
  // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
 
1
  /// <reference types="next" />
2
  /// <reference types="next/image-types/global" />
3
+ import "./.next/dev/types/routes.d.ts";
4
+ import "./.next/dev/types/root-params.d.ts";
5
 
6
  // NOTE: This file should not be edited
7
  // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
frontend/src/lib/useSpeechRecognition.ts CHANGED
@@ -104,6 +104,14 @@ export function useSpeechRecognition({
104
  // True while the user wants to be listening, so `onend` can auto-restart
105
  // (Chrome ends the session after a pause even with continuous = true).
106
  const wantListeningRef = useRef(false);
 
 
 
 
 
 
 
 
107
 
108
  useEffect(() => {
109
  onTranscriptRef.current = onTranscript;
@@ -148,37 +156,68 @@ export function useSpeechRecognition({
148
  switch (event.error) {
149
  case "not-allowed":
150
  case "service-not-allowed":
 
151
  setPermissionDenied(true);
152
  setError(
153
- "Microphone access was blocked. If this app is embedded in a page, open it directly and allow the microphone."
154
  );
155
  break;
156
  case "no-speech":
 
157
  setError("No speech detected — try again.");
158
  break;
159
  case "audio-capture":
160
- setError("No microphone was found.");
 
161
  break;
162
  case "network":
163
- setError("Speech recognition needs a network connection.");
 
 
 
 
 
 
164
  break;
165
  case "aborted":
166
  // Fired by our own stop(); not an error worth showing.
167
  break;
 
 
 
 
168
  default:
 
169
  setError(`Speech recognition error: ${event.error}`);
170
  }
171
  };
172
 
173
  recognition.onend = () => {
174
  setInterim("");
175
- if (wantListeningRef.current) {
176
- // Restart seamlessly so a pause doesn't end the session.
177
- try {
178
- recognition.start();
179
- return;
180
- } catch {
181
- // start() throws if already started; fall through to stopped state.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  }
183
  }
184
  setListening(false);
@@ -206,6 +245,11 @@ export function useSpeechRecognition({
206
  if (!recognition) return;
207
  setError(null);
208
  setPermissionDenied(false);
 
 
 
 
 
209
  wantListeningRef.current = true;
210
  try {
211
  recognition.start();
 
104
  // True while the user wants to be listening, so `onend` can auto-restart
105
  // (Chrome ends the session after a pause even with continuous = true).
106
  const wantListeningRef = useRef(false);
107
+ // Set when a failure is not recoverable by restarting. Without this, `onend`
108
+ // restarts after every error and the recogniser spins in a silent loop: the
109
+ // UI keeps saying "Listening…" while no audio is ever transcribed and the
110
+ // real error never surfaces. Cleared on each start().
111
+ const fatalErrorRef = useRef(false);
112
+ // Guards against a tight restart loop when the recogniser ends immediately.
113
+ const restartCountRef = useRef(0);
114
+ const lastRestartRef = useRef(0);
115
 
116
  useEffect(() => {
117
  onTranscriptRef.current = onTranscript;
 
156
  switch (event.error) {
157
  case "not-allowed":
158
  case "service-not-allowed":
159
+ fatalErrorRef.current = true;
160
  setPermissionDenied(true);
161
  setError(
162
+ "Microphone access was blocked. Allow the microphone for this site, and if the app is embedded in another page, open it directly."
163
  );
164
  break;
165
  case "no-speech":
166
+ // Recoverable: the user simply did not speak. Let onend restart.
167
  setError("No speech detected — try again.");
168
  break;
169
  case "audio-capture":
170
+ fatalErrorRef.current = true;
171
+ setError("No microphone was found. Check that one is connected and enabled.");
172
  break;
173
  case "network":
174
+ // Chrome's recogniser talks to Google's speech service. If that is
175
+ // unreachable (offline, blocked, or unreachable region) recognition
176
+ // cannot work — restarting only loops silently, so stop retrying.
177
+ fatalErrorRef.current = true;
178
+ setError(
179
+ "Speech recognition could not reach the browser's speech service. Check your connection, or type your question instead."
180
+ );
181
  break;
182
  case "aborted":
183
  // Fired by our own stop(); not an error worth showing.
184
  break;
185
+ case "language-not-supported":
186
+ fatalErrorRef.current = true;
187
+ setError("Speech recognition does not support this language.");
188
+ break;
189
  default:
190
+ fatalErrorRef.current = true;
191
  setError(`Speech recognition error: ${event.error}`);
192
  }
193
  };
194
 
195
  recognition.onend = () => {
196
  setInterim("");
197
+ // Never auto-restart after a fatal error, and never restart in a tight
198
+ // loop: if sessions keep ending within a second of starting, back off.
199
+ if (wantListeningRef.current && !fatalErrorRef.current) {
200
+ const now = Date.now();
201
+ if (now - lastRestartRef.current < 1000) {
202
+ restartCountRef.current += 1;
203
+ } else {
204
+ restartCountRef.current = 0;
205
+ }
206
+ lastRestartRef.current = now;
207
+
208
+ if (restartCountRef.current < 3) {
209
+ try {
210
+ recognition.start();
211
+ return;
212
+ } catch {
213
+ // start() throws if already started; fall through to stopped state.
214
+ }
215
+ } else {
216
+ // Repeated immediate restarts mean the recogniser cannot run here.
217
+ wantListeningRef.current = false;
218
+ setError(
219
+ "Speech recognition keeps stopping immediately and cannot be used here. Please type your question instead."
220
+ );
221
  }
222
  }
223
  setListening(false);
 
245
  if (!recognition) return;
246
  setError(null);
247
  setPermissionDenied(false);
248
+ // A fresh user action clears any previous fatal state so the user can
249
+ // retry after fixing the cause (e.g. granting the microphone).
250
+ fatalErrorRef.current = false;
251
+ restartCountRef.current = 0;
252
+ lastRestartRef.current = 0;
253
  wantListeningRef.current = true;
254
  try {
255
  recognition.start();
frontend/tsconfig.tsbuildinfo CHANGED
The diff for this file is too large to render. See raw diff
 
pyproject.toml CHANGED
@@ -38,7 +38,14 @@ dependencies = [
38
  "langfuse>=2.42",
39
 
40
  # Evaluation
41
- "ragas>=0.2.11",
 
 
 
 
 
 
 
42
  "numpy>=1.26",
43
  "pandas>=2.2",
44
 
 
38
  "langfuse>=2.42",
39
 
40
  # Evaluation
41
+ # `RagasEvaluator` is written against the ragas 0.4 API: the module-level
42
+ # `evaluate()` plus `ragas.llms.LangchainLLMWrapper` /
43
+ # `ragas.embeddings.LangchainEmbeddingsWrapper` (ragas 0.4 dropped the
44
+ # `Evaluator` class). Pin to 0.4.x so a fresh install matches the code.
45
+ # ragas 0.2.x also imports `langchain_community.chat_models.vertexai`,
46
+ # removed in langchain-community 0.4, hence the upper bound there.
47
+ "ragas>=0.4,<0.5",
48
+ "langchain-community<0.4",
49
  "numpy>=1.26",
50
  "pandas>=2.2",
51
 
scripts/measure_performance.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Measure end-to-end query latency, cost, and throughput.
2
+
3
+ Produces the numbers the README quotes. Everything here is *measured* on the
4
+ local stack — nothing is estimated or copied from a vendor datasheet.
5
+
6
+ What it measures
7
+ ----------------
8
+ - **Latency**: per-query wall time for the full pipeline (retrieval → rerank →
9
+ evidence selection → generation → grounding), reported as p50/p95/p99.
10
+ - **Cost**: USD per query, from the token counts OpenRouter returns and the
11
+ pricing table in ``app.observability.cost``.
12
+ - **Throughput**: queries per minute, measured by running a fixed number of
13
+ queries sequentially and dividing.
14
+
15
+ Usage
16
+ -----
17
+ ::
18
+
19
+ python scripts/measure_performance.py --questions 20
20
+ python scripts/measure_performance.py --questions 20 --output evals/reports/performance.json
21
+
22
+ Requires a running stack (Postgres + Qdrant) with an ingested corpus and a
23
+ valid ``OPENROUTER_API_KEY``.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import statistics
31
+ import sys
32
+ import time
33
+ from datetime import UTC, datetime
34
+ from pathlib import Path
35
+
36
+ ROOT = Path(__file__).resolve().parent.parent
37
+ sys.path.insert(0, str(ROOT))
38
+
39
+ from app.config import get_settings # noqa: E402
40
+ from app.evaluation.datasets import load_golden_dataset # noqa: E402
41
+ from app.generation.client import OpenRouterClient # noqa: E402
42
+ from app.generation.service import GenerationService # noqa: E402
43
+ from app.observability import cost # noqa: E402
44
+ from app.retrieval.evidence import EvidenceSelector # noqa: E402
45
+ from app.retrieval.hybrid import HybridRetriever # noqa: E402
46
+ from app.retrieval.reranker import Reranker # noqa: E402
47
+
48
+
49
+ def _percentile(values: list[float], pct: float) -> float:
50
+ """Nearest-rank percentile (no numpy dependency)."""
51
+ if not values:
52
+ return 0.0
53
+ ordered = sorted(values)
54
+ if len(ordered) == 1:
55
+ return ordered[0]
56
+ rank = (pct / 100.0) * (len(ordered) - 1)
57
+ lower = int(rank)
58
+ upper = min(lower + 1, len(ordered) - 1)
59
+ frac = rank - lower
60
+ return ordered[lower] + (ordered[upper] - ordered[lower]) * frac
61
+
62
+
63
+ def main() -> int:
64
+ parser = argparse.ArgumentParser(description="Measure query latency, cost, and throughput.")
65
+ parser.add_argument("--questions", type=int, default=20, help="Number of questions to run.")
66
+ parser.add_argument("--output", type=str, default=None, help="Write JSON results here.")
67
+ parser.add_argument("--warmup", type=int, default=1, help="Warm-up queries excluded from stats.")
68
+ args = parser.parse_args()
69
+
70
+ settings = get_settings()
71
+ if not settings.openrouter_api_key:
72
+ print("ERROR: OPENROUTER_API_KEY is not set.", file=sys.stderr)
73
+ return 1
74
+
75
+ dataset = load_golden_dataset(settings.eval_dataset_path)
76
+ answerable = [ex for ex in dataset.examples if ex.answerable]
77
+ questions = [ex.question for ex in answerable[: args.questions]]
78
+ if not questions:
79
+ print("ERROR: no answerable questions in the golden dataset.", file=sys.stderr)
80
+ return 1
81
+
82
+ print(f"Model: {settings.openrouter_model}")
83
+ print(f"Questions: {len(questions)} (+{args.warmup} warm-up)")
84
+ print("Loading models and connecting to stores...")
85
+
86
+ retriever = HybridRetriever(settings=settings)
87
+ reranker = Reranker(settings=settings) if settings.enable_reranker else None
88
+ selector = EvidenceSelector(settings=settings)
89
+ service = GenerationService(client=OpenRouterClient(settings=settings))
90
+
91
+ cost.reset_usage()
92
+
93
+ latencies: list[float] = []
94
+ failures = 0
95
+ total = args.warmup + len(questions)
96
+
97
+ for i in range(total):
98
+ question = questions[i % len(questions)]
99
+ is_warmup = i < args.warmup
100
+ start = time.perf_counter()
101
+ try:
102
+ retrieved = retriever.retrieve(question, top_k=settings.hybrid_top_k)
103
+ if reranker is not None:
104
+ retrieved = reranker.rerank(question, retrieved, top_k=settings.rerank_top_k)
105
+ evidence = selector.select(retrieved)
106
+ output = service.generate(question, candidates=evidence)
107
+ elapsed = time.perf_counter() - start
108
+ failed = output.answer.startswith("Generation failed")
109
+ if failed:
110
+ failures += 1
111
+ if not is_warmup:
112
+ latencies.append(elapsed)
113
+ label = "warmup" if is_warmup else f"{i - args.warmup + 1}/{len(questions)}"
114
+ status = "FAIL" if failed else "ok"
115
+ print(f" [{label}] {elapsed:6.2f}s {status} {question[:60]}")
116
+ except Exception as exc:
117
+ elapsed = time.perf_counter() - start
118
+ failures += 1
119
+ if not is_warmup:
120
+ latencies.append(elapsed)
121
+ print(f" [{i}] {elapsed:6.2f}s ERROR {type(exc).__name__}: {str(exc)[:80]}")
122
+
123
+ if not latencies:
124
+ print("ERROR: no successful measurements.", file=sys.stderr)
125
+ return 1
126
+
127
+ usage = cost.usage_summary()
128
+ totals = usage["totals"]
129
+ n = len(latencies)
130
+ total_seconds = sum(latencies)
131
+
132
+ results = {
133
+ "measured_at": datetime.now(UTC).isoformat(),
134
+ "model": settings.openrouter_model,
135
+ "questions_measured": n,
136
+ "failures": failures,
137
+ "latency_seconds": {
138
+ "mean": round(statistics.fmean(latencies), 3),
139
+ "median": round(statistics.median(latencies), 3),
140
+ "p95": round(_percentile(latencies, 95), 3),
141
+ "p99": round(_percentile(latencies, 99), 3),
142
+ "min": round(min(latencies), 3),
143
+ "max": round(max(latencies), 3),
144
+ },
145
+ "throughput_queries_per_minute": round(n / total_seconds * 60, 2) if total_seconds else 0.0,
146
+ "tokens": {
147
+ "prompt_total": totals["prompt_tokens"],
148
+ "completion_total": totals["completion_tokens"],
149
+ "per_query": round(totals["total_tokens"] / n, 1),
150
+ },
151
+ "cost_usd": {
152
+ "total": totals["cost_usd"],
153
+ "per_query": round(totals["cost_usd"] / n, 6),
154
+ },
155
+ "llm_calls": totals["calls"],
156
+ }
157
+
158
+ print()
159
+ print("=" * 62)
160
+ print("MEASURED RESULTS")
161
+ print("=" * 62)
162
+ lat = results["latency_seconds"]
163
+ print(f" Queries measured : {n} ({failures} failures)")
164
+ print(f" Latency mean / median : {lat['mean']:.2f}s / {lat['median']:.2f}s")
165
+ print(f" Latency p95 / p99 : {lat['p95']:.2f}s / {lat['p99']:.2f}s")
166
+ print(f" Throughput : {results['throughput_queries_per_minute']:.2f} queries/min")
167
+ print(f" Tokens per query : {results['tokens']['per_query']:.0f}")
168
+ print(f" Cost per query : ${results['cost_usd']['per_query']:.6f}")
169
+ print(f" Total cost : ${results['cost_usd']['total']:.6f}")
170
+ print("=" * 62)
171
+
172
+ if args.output:
173
+ out = Path(args.output)
174
+ out.parent.mkdir(parents=True, exist_ok=True)
175
+ out.write_text(json.dumps(results, indent=2), encoding="utf-8")
176
+ print(f"Written to {out}")
177
+
178
+ return 0
179
+
180
+
181
+ if __name__ == "__main__":
182
+ raise SystemExit(main())
scripts/model_benchmark.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Benchmark cheap OpenRouter models against AskMyDocs' real answer contract.
2
+
3
+ The app does not just need valid JSON — the grounding pipeline splits the answer
4
+ into claims and verifies each against its cited evidence, so the model MUST emit
5
+ inline ``[C1]``/``[C2]`` markers inside the answer text. A model that returns a
6
+ ``citations`` array but no inline markers silently breaks grounding, which a
7
+ casual test will miss.
8
+
9
+ Scores each model on:
10
+ * json_ok — response parses as the expected JSON object
11
+ * inline — number of [Cn] markers inside `answer` (must be > 0)
12
+ * claims — extracted claims array length
13
+ * latency — seconds
14
+ * cost — USD for the run's token usage
15
+
16
+ Usage:
17
+ python scripts/model_benchmark.py # default shortlist
18
+ python scripts/model_benchmark.py --top 12 # shortlist by price
19
+ python scripts/model_benchmark.py --trials 2
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import os
27
+ import time
28
+
29
+ import httpx
30
+ from dotenv import load_dotenv
31
+
32
+ OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
33
+
34
+ SYSTEM_PROMPT = (
35
+ "You answer strictly from the provided evidence. "
36
+ 'Respond with a single JSON object: {"answer": string, "citations": [string], '
37
+ '"claims": [{"claim": string, "citation_ids": [string]}]}. '
38
+ "Every factual sentence in `answer` must end with an inline marker like [C1] "
39
+ "referring to the evidence item it came from. "
40
+ "If the evidence is insufficient, refuse instead of guessing."
41
+ )
42
+
43
+ # Realistic multi-claim questions with evidence drawn from the project's own docs.
44
+ CASES = [
45
+ {
46
+ "question": "What dominates ingestion latency, and how is chunk identity preserved?",
47
+ "evidence": (
48
+ "[C1] The ingestion pipeline runs parsing, cleaning, chunking, "
49
+ "embedding, vector upsert and keyword indexing.\n"
50
+ "[C2] On CPU, embedding dominates: 46,977 ms of a 47.1 s run for a "
51
+ "4-chunk document.\n"
52
+ "[C3] Chunk IDs are deterministic hashes derived from the document id "
53
+ "and chunk index, so they match across Postgres, Qdrant and the "
54
+ "tsvector postings."
55
+ ),
56
+ },
57
+ {
58
+ "question": "How are API keys secured and what happens when they expire?",
59
+ "evidence": (
60
+ "[C1] API keys are prefixed with `amsk_` and are shown only once at "
61
+ "creation time.\n"
62
+ "[C2] Keys expire after 90 days and can be revoked at any time from "
63
+ "the Admin Console.\n"
64
+ "[C3] A key can be scoped to a set of permissions using the "
65
+ "permissions claim; scoping is strongly recommended."
66
+ ),
67
+ },
68
+ ]
69
+
70
+
71
+ def fetch_models(api_key: str) -> list[dict]:
72
+ r = httpx.get("https://openrouter.ai/api/v1/models", timeout=60)
73
+ r.raise_for_status()
74
+ return r.json()["data"]
75
+
76
+
77
+ def price_of(model: dict) -> tuple[float, float] | None:
78
+ p = model.get("pricing") or {}
79
+ try:
80
+ pin = float(p.get("prompt", "0")) * 1_000_000
81
+ pout = float(p.get("completion", "0")) * 1_000_000
82
+ except (TypeError, ValueError):
83
+ return None
84
+ if pin < 0 or pout < 0:
85
+ return None # variable-priced router entries
86
+ return pin, pout
87
+
88
+
89
+ def run_case(api_key: str, model_id: str, case: dict) -> dict:
90
+ payload = {
91
+ "model": model_id,
92
+ "messages": [
93
+ {"role": "system", "content": SYSTEM_PROMPT},
94
+ {
95
+ "role": "user",
96
+ "content": f"Question: {case['question']}\n\nEvidence:\n{case['evidence']}",
97
+ },
98
+ ],
99
+ "max_tokens": 900,
100
+ "temperature": 0.2,
101
+ "response_format": {"type": "json_object"},
102
+ }
103
+ start = time.time()
104
+ try:
105
+ r = httpx.post(
106
+ OPENROUTER_URL,
107
+ headers={
108
+ "Authorization": f"Bearer {api_key}",
109
+ "Content-Type": "application/json",
110
+ },
111
+ json=payload,
112
+ timeout=180,
113
+ )
114
+ except Exception as exc: # noqa: BLE001
115
+ return {"ok": False, "error": type(exc).__name__, "secs": time.time() - start}
116
+
117
+ secs = time.time() - start
118
+ if r.status_code != 200:
119
+ return {"ok": False, "error": f"HTTP {r.status_code}", "secs": secs}
120
+
121
+ data = r.json()
122
+ choices = data.get("choices") or []
123
+ if not choices:
124
+ return {"ok": False, "error": "no choices", "secs": secs}
125
+
126
+ content = (choices[0].get("message") or {}).get("content") or ""
127
+ usage = data.get("usage") or {}
128
+ result = {
129
+ "ok": True,
130
+ "secs": secs,
131
+ "finish": choices[0].get("finish_reason"),
132
+ "prompt_tokens": usage.get("prompt_tokens", 0),
133
+ "completion_tokens": usage.get("completion_tokens", 0),
134
+ "empty": not content.strip(),
135
+ }
136
+ try:
137
+ obj = json.loads(content)
138
+ answer = obj.get("answer") or ""
139
+ markers = sum(answer.count(m) for m in ("[C1]", "[C2]", "[C3]"))
140
+ result.update(
141
+ {
142
+ "json": True,
143
+ "inline": markers,
144
+ "claims": len(obj.get("claims") or []),
145
+ "answer_len": len(answer),
146
+ }
147
+ )
148
+ except Exception: # noqa: BLE001
149
+ result.update({"json": False, "inline": 0, "claims": 0, "answer_len": 0})
150
+ return result
151
+
152
+
153
+ def main() -> int:
154
+ load_dotenv()
155
+ parser = argparse.ArgumentParser(description="Benchmark cheap OpenRouter models.")
156
+ parser.add_argument("--top", type=int, default=10, help="How many cheap paid models to test.")
157
+ parser.add_argument("--trials", type=int, default=1, help="Runs per model per case.")
158
+ parser.add_argument(
159
+ "--max-out-price",
160
+ type=float,
161
+ default=0.45,
162
+ help="Max completion price (USD per 1M) to consider 'dead cheap'.",
163
+ )
164
+ parser.add_argument("--only", nargs="*", help="Explicit model ids to test.")
165
+ parser.add_argument(
166
+ "--include-free",
167
+ action="store_true",
168
+ help="Also test free (:free) variants.",
169
+ )
170
+ args = parser.parse_args()
171
+
172
+ api_key = os.getenv("OPENROUTER_API_KEY")
173
+ if not api_key:
174
+ print("OPENROUTER_API_KEY not set")
175
+ return 1
176
+
177
+ models = fetch_models(api_key)
178
+
179
+ if args.only:
180
+ candidates = [m for m in models if m["id"] in args.only]
181
+ else:
182
+ priced = []
183
+ for m in models:
184
+ pr = price_of(m)
185
+ if pr is None:
186
+ continue
187
+ pin, pout = pr
188
+ if pin == 0 and pout == 0 and not args.include_free:
189
+ continue
190
+ if pout > args.max_out_price:
191
+ continue
192
+ if (m.get("context_length") or 0) < 32_000:
193
+ continue
194
+ priced.append((pout, pin, m["id"], m))
195
+ priced.sort(key=lambda t: (t[0], t[1], t[2]))
196
+ candidates = [t[3] for t in priced[: args.top]]
197
+
198
+ print(f"Testing {len(candidates)} model(s), {len(CASES)} case(s), {args.trials} trial(s)\n")
199
+
200
+ rows = []
201
+ for model in candidates:
202
+ mid = model["id"]
203
+ pr = price_of(model) or (0.0, 0.0)
204
+ runs = []
205
+ for _ in range(args.trials):
206
+ for case in CASES:
207
+ runs.append(run_case(api_key, mid, case))
208
+ good = [r for r in runs if r.get("ok")]
209
+ total_cost = sum(
210
+ (r.get("prompt_tokens", 0) / 1e6) * pr[0]
211
+ + (r.get("completion_tokens", 0) / 1e6) * pr[1]
212
+ for r in good
213
+ )
214
+ rows.append(
215
+ {
216
+ "model": mid,
217
+ "in": pr[0],
218
+ "out": pr[1],
219
+ "runs": len(runs),
220
+ "ok": len(good),
221
+ "json": sum(1 for r in good if r.get("json")),
222
+ "cited": sum(1 for r in good if (r.get("inline") or 0) > 0),
223
+ "empty": sum(1 for r in good if r.get("empty")),
224
+ "claims": sum(r.get("claims", 0) for r in good),
225
+ "avg_s": round(sum(r["secs"] for r in good) / len(good), 1) if good else None,
226
+ "cost": total_cost,
227
+ }
228
+ )
229
+
230
+ hdr = (
231
+ f"{'model':44s} {'$/1M in/out':>14s} {'json':>5s} {'cited':>6s} "
232
+ f"{'empty':>6s} {'claims':>7s} {'avg s':>6s} {'$/query':>9s}"
233
+ )
234
+ print(hdr)
235
+ print("-" * len(hdr))
236
+ for r in rows:
237
+ print(
238
+ f"{r['model']:44s} {r['in']:6.3f}/{r['out']:<7.3f} "
239
+ f"{r['json']:>3d}/{r['runs']:<2d} {r['cited']:>4d}/{r['runs']:<2d} "
240
+ f"{r['empty']:>4d}/{r['runs']:<2d} {r['claims']:>7d} "
241
+ f"{str(r['avg_s']):>6s} {r['cost']/max(1, r['runs']):>9.6f}"
242
+ )
243
+ return 0
244
+
245
+
246
+ if __name__ == "__main__":
247
+ raise SystemExit(main())
scripts/reasoning_quality_test.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Does LLM_REASONING_EFFORT=none reduce answer quality?
2
+
3
+ Isolates the one variable that matters: given IDENTICAL evidence, does the model
4
+ produce a less correct answer with reasoning disabled?
5
+
6
+ Each case defines the required facts a correct answer must state. A case scores
7
+ 1.0 if every required fact appears and no forbidden (hallucinated) fact appears,
8
+ otherwise a partial score. Run both settings, compare mean accuracy.
9
+
10
+ Usage:
11
+ python scripts/reasoning_quality_test.py
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import re
19
+ import time
20
+
21
+ import httpx
22
+ from dotenv import load_dotenv
23
+
24
+ URL = "https://openrouter.ai/api/v1/chat/completions"
25
+
26
+ SYSTEM = (
27
+ "You answer strictly from the provided evidence. Respond with a single JSON "
28
+ 'object: {"answer": string, "citations": [string], "claims": '
29
+ '[{"claim": string, "citation_ids": [string]}]}. '
30
+ "Every factual sentence in `answer` must end with an inline marker like [C1]. "
31
+ "If the evidence is insufficient, refuse instead of guessing."
32
+ )
33
+
34
+ # `must` = facts a correct answer contains; `forbidden` = claims NOT supported by
35
+ # the evidence (appearing means the model hallucinated).
36
+ CASES = [
37
+ {
38
+ "q": "How long do API keys last and what happens at expiry?",
39
+ "evidence": "[C1] API keys are prefixed with amsk_ and shown only once.\n"
40
+ "[C2] Keys expire after 90 days and can be revoked from the Admin Console.",
41
+ "must": ["90 day", "revoke"],
42
+ "forbidden": ["never expire", "365 day", "one year"],
43
+ },
44
+ {
45
+ "q": "What dominates ingestion latency on CPU?",
46
+ "evidence": "[C1] Pipeline stages: parse, clean, chunk, embed, upsert, keyword index.\n"
47
+ "[C2] Embedding took 46,977 ms of a 47.1 s run.",
48
+ "must": ["embed"],
49
+ "forbidden": ["parsing dominates", "chunking dominates", "qdrant dominates"],
50
+ },
51
+ {
52
+ "q": "How is chunk identity preserved across stores?",
53
+ "evidence": "[C1] Chunk IDs are deterministic hashes of the document id and "
54
+ "chunk index, so they match across Postgres, Qdrant and tsvector.",
55
+ "must": ["deterministic", "hash"],
56
+ "forbidden": ["random", "uuid"],
57
+ },
58
+ {
59
+ "q": "What does the safety question gate block?",
60
+ "evidence": "[C1] The deterministic question gate refuses disallowed requests "
61
+ "(explosives, malware, hacking how-tos) and instruction-takeover phrasing, "
62
+ "before any retrieval or model spend.",
63
+ "must": ["malware", "refus"],
64
+ "forbidden": ["calls the llm first", "always allows"],
65
+ },
66
+ {
67
+ "q": "Why does the app refuse instead of answering when evidence is missing?",
68
+ "evidence": "[C1] The answer contract requires every claim to carry a citation "
69
+ "the judge can verify; unsupported claims make the status ungrounded, so the "
70
+ "system refuses rather than guessing.",
71
+ "must": ["citation", "refus"],
72
+ "forbidden": ["always answers", "guesses"],
73
+ },
74
+ {
75
+ "q": "What is the final context budget and why is it bounded?",
76
+ "evidence": "[C1] FINAL_CONTEXT_K selects 5 chunks and MAX_CONTEXT_TOKENS caps "
77
+ "the prompt at 3000 tokens so generation cost and latency stay bounded.",
78
+ "must": ["5 chunk", "3000"],
79
+ "forbidden": ["10 chunk", "unbounded"],
80
+ },
81
+ ]
82
+
83
+
84
+ def score(answer: str, case: dict) -> float:
85
+ low = answer.lower()
86
+ hits = sum(1 for m in case["must"] if m.lower() in low)
87
+ penalties = sum(1 for f in case["forbidden"] if f.lower() in low)
88
+ base = hits / len(case["must"])
89
+ return max(0.0, base - 0.5 * penalties)
90
+
91
+
92
+ def run(api_key: str, model: str, effort: str, case: dict) -> dict:
93
+ payload = {
94
+ "model": model,
95
+ "messages": [
96
+ {"role": "system", "content": SYSTEM},
97
+ {"role": "user", "content": f"Question: {case['q']}\n\nEvidence:\n{case['evidence']}"},
98
+ ],
99
+ "max_tokens": 900,
100
+ "temperature": 0.2,
101
+ "response_format": {"type": "json_object"},
102
+ }
103
+ if effort != "default":
104
+ payload["reasoning"] = {"effort": effort}
105
+ start = time.time()
106
+ r = httpx.post(
107
+ URL,
108
+ headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
109
+ json=payload,
110
+ timeout=180,
111
+ )
112
+ secs = time.time() - start
113
+ if r.status_code != 200:
114
+ return {"error": f"HTTP {r.status_code}", "score": 0.0, "secs": secs}
115
+ d = r.json()
116
+ ch = (d.get("choices") or [{}])[0]
117
+ content = (ch.get("message") or {}).get("content") or ""
118
+ usage = d.get("usage") or {}
119
+ det = usage.get("completion_tokens_details") or {}
120
+ try:
121
+ obj = json.loads(content)
122
+ answer = obj.get("answer") or ""
123
+ s = score(answer, case)
124
+ return {
125
+ "score": s,
126
+ "secs": secs,
127
+ "reasoning": det.get("reasoning_tokens"),
128
+ "completion": usage.get("completion_tokens"),
129
+ "markers": len(re.findall(r"\[C\d\]", answer)),
130
+ "answer": answer[:120],
131
+ }
132
+ except Exception: # noqa: BLE001
133
+ return {"score": 0.0, "secs": secs, "error": "not json", "answer": content[:80]}
134
+
135
+
136
+ def main() -> int:
137
+ load_dotenv()
138
+ key = os.getenv("OPENROUTER_API_KEY")
139
+ model = os.getenv("OPENROUTER_MODEL", "nex-agi/nex-n2.5-mini:free")
140
+ if not key:
141
+ print("OPENROUTER_API_KEY not set")
142
+ return 1
143
+
144
+ print(f"model: {model}\n")
145
+ summary = {}
146
+ for effort in ("high", "none"):
147
+ scores, secs, reas, marks = [], [], [], []
148
+ print(f"=== reasoning effort: {effort} ===")
149
+ for case in CASES:
150
+ r = run(key, model, effort, case)
151
+ scores.append(r.get("score", 0.0))
152
+ secs.append(r.get("secs", 0))
153
+ if r.get("reasoning") is not None:
154
+ reas.append(r["reasoning"])
155
+ marks.append(r.get("markers", 0))
156
+ flag = "OK " if r.get("score", 0) >= 1.0 else "PARTIAL"
157
+ print(f" [{flag}] score={r.get('score',0):.2f} {r.get('secs',0):5.1f}s "
158
+ f"reasoning={r.get('reasoning')} markers={r.get('markers')} :: {str(r.get('answer'))[:70]}")
159
+ summary[effort] = {
160
+ "mean": sum(scores) / len(scores),
161
+ "perfect": sum(1 for s in scores if s >= 1.0),
162
+ "avg_s": sum(secs) / len(secs),
163
+ "avg_reasoning": (sum(reas) / len(reas)) if reas else 0,
164
+ "avg_markers": sum(marks) / len(marks),
165
+ }
166
+ print()
167
+
168
+ print("=== SUMMARY ===")
169
+ print(
170
+ f"{'effort':8s} {'mean acc':>9s} {'perfect':>8s} {'avg s':>7s} "
171
+ f"{'reasoning tok':>14s} {'markers':>8s}"
172
+ )
173
+ for eff, s in summary.items():
174
+ print(f"{eff:8s} {s['mean']:9.2f} {s['perfect']:>5d}/6 {s['avg_s']:7.1f} "
175
+ f"{s['avg_reasoning']:14.0f} {s['avg_markers']:8.1f}")
176
+ return 0
177
+
178
+
179
+ if __name__ == "__main__":
180
+ raise SystemExit(main())
scripts/repair_chunk_refs.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Repair golden-dataset chunk references against the *stored* chunks.
2
+
3
+ Why this exists
4
+ ---------------
5
+ ``evals/dataset/golden.jsonl`` references evidence as ``slug:index``. The
6
+ indices were authored by hand (or against an older chunking configuration), so
7
+ a subset point past the end of the document — e.g. ``oauth-guide:6`` when the
8
+ markdown rendering produced only 6 chunks (indices 0-5). Those references can
9
+ never be retrieved, which deflates recall for reasons unrelated to retrieval
10
+ quality.
11
+
12
+ ``scripts/resolve_relevant_chunks.py`` re-derives references from the *markdown*
13
+ rendering only, so it cannot repair references whose slug is stored under a
14
+ different format. This script instead asks the database for the chunks that were
15
+ actually ingested and rewrites each bad reference to the chunk whose text best
16
+ matches the question and expected answer.
17
+
18
+ Every rewrite is printed with before/after so the change is auditable.
19
+
20
+ Usage
21
+ -----
22
+ ::
23
+
24
+ python scripts/repair_chunk_refs.py # dry run
25
+ python scripts/repair_chunk_refs.py --write # rewrite golden.jsonl
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import json
32
+ import re
33
+ import sys
34
+ from collections import defaultdict
35
+ from pathlib import Path
36
+
37
+ ROOT = Path(__file__).resolve().parent.parent
38
+ sys.path.insert(0, str(ROOT))
39
+
40
+ from app.db.models import Chunk, Document # noqa: E402
41
+ from app.db.session import session_scope # noqa: E402
42
+ from sqlalchemy import select # noqa: E402
43
+
44
+ STOPWORDS = {
45
+ "the", "a", "an", "of", "for", "to", "and", "or", "in", "on", "is", "are",
46
+ "what", "which", "how", "does", "do", "whats", "your", "with", "that",
47
+ "this", "from", "be", "by", "as", "it", "at", "can",
48
+ }
49
+
50
+
51
+ def _tokens(text: str) -> set[str]:
52
+ return set(re.findall(r"[a-z0-9_]+", (text or "").lower()))
53
+
54
+
55
+ def _words(text: str) -> list[str]:
56
+ return re.findall(r"[a-z0-9_]+", (text or "").lower())
57
+
58
+
59
+ def _keywords(text: str) -> set[str]:
60
+ return _tokens(text) - STOPWORDS
61
+
62
+
63
+ def _score(chunk_text: str, keywords: set[str]) -> float:
64
+ """Fraction of keywords present in the chunk (0 when nothing overlaps)."""
65
+ chunk_tokens = _tokens(chunk_text)
66
+ if not keywords or not chunk_tokens:
67
+ return 0.0
68
+ return len(keywords & chunk_tokens) / len(keywords)
69
+
70
+
71
+ def _phrase_bonus(chunk_text: str, expected_answer: str) -> float:
72
+ """Reward contiguous phrase matches from the expected answer.
73
+
74
+ Bag-of-words overlap alone is too weak: ``403 permission_denied`` shares
75
+ generic tokens ("token", "error") with every chunk of the error reference,
76
+ so the wrong chunk wins. Counting the longest shared word n-gram instead
77
+ surfaces the chunk that literally contains the answer sentence.
78
+ """
79
+ expected = _words(expected_answer)
80
+ chunk = _words(chunk_text)
81
+ if len(expected) < 3 or not chunk:
82
+ return 0.0
83
+ chunk_ngrams: set[str] = set()
84
+ for n in range(2, 9):
85
+ for i in range(len(chunk) - n + 1):
86
+ chunk_ngrams.add(" ".join(chunk[i : i + n]))
87
+ for n in range(8, 1, -1):
88
+ for i in range(len(expected) - n + 1):
89
+ if " ".join(expected[i : i + n]) in chunk_ngrams:
90
+ return float(n) / len(expected)
91
+ return 0.0
92
+
93
+
94
+ def _match_score(chunk_text: str, keywords: set[str], expected_answer: str) -> float:
95
+ """Combined score: phrase containment first, then keyword overlap."""
96
+ phrase = _phrase_bonus(chunk_text, expected_answer)
97
+ return phrase * 10.0 + _score(chunk_text, keywords)
98
+
99
+
100
+ def main() -> int:
101
+ parser = argparse.ArgumentParser(description="Repair out-of-range chunk references.")
102
+ parser.add_argument("--write", action="store_true", help="Rewrite golden.jsonl in place")
103
+ parser.add_argument("--dataset", default="evals/dataset/golden.jsonl")
104
+ args = parser.parse_args()
105
+
106
+ dataset_path = ROOT / args.dataset
107
+
108
+ # Load stored chunks grouped by slug (document title).
109
+ by_slug: dict[str, list[tuple[int, str]]] = defaultdict(list)
110
+ with session_scope() as session:
111
+ rows = session.execute(
112
+ select(Document.title, Chunk.chunk_index, Chunk.text)
113
+ .join(Chunk, Chunk.document_id == Document.document_id)
114
+ ).all()
115
+ for title, index, text in rows:
116
+ by_slug[title].append((int(index), text or ""))
117
+ for slug in by_slug:
118
+ by_slug[slug].sort()
119
+
120
+ print(f"Loaded chunks for {len(by_slug)} documents from the database.")
121
+
122
+ lines = dataset_path.read_text(encoding="utf-8").splitlines()
123
+ updated: list[str] = []
124
+ repairs: list[str] = []
125
+ unrepaired: list[str] = []
126
+
127
+ for line in lines:
128
+ if not line.strip():
129
+ continue
130
+ record = json.loads(line)
131
+ refs: list[str] = list(record.get("relevant_chunk_ids", []))
132
+ if not refs:
133
+ updated.append(json.dumps(record, ensure_ascii=False))
134
+ continue
135
+
136
+ new_refs: list[str] = []
137
+ for ref in refs:
138
+ slug, sep, index_str = ref.rpartition(":")
139
+ if not sep or slug not in by_slug:
140
+ new_refs.append(ref)
141
+ continue
142
+ indices = {i for i, _ in by_slug[slug]}
143
+ index = int(index_str)
144
+ if index in indices:
145
+ new_refs.append(ref)
146
+ continue
147
+
148
+ # Out of range — pick the best-matching stored chunk instead.
149
+ expected = record.get("expected_answer", "")
150
+ keywords = _keywords(expected) | _keywords(record.get("question", ""))
151
+ best = max(
152
+ by_slug[slug],
153
+ key=lambda pair: (_match_score(pair[1], keywords, expected), -pair[0]),
154
+ )
155
+ replacement = f"{slug}:{best[0]}"
156
+ if replacement in new_refs:
157
+ repairs.append(
158
+ f" {record['id']}: {ref} -> dropped (duplicate of {replacement})"
159
+ )
160
+ continue
161
+ new_refs.append(replacement)
162
+ repairs.append(
163
+ f" {record['id']}: {ref} ({index} out of range, max "
164
+ f"{max(indices)}) -> {replacement} (score "
165
+ f"{_match_score(best[1], keywords, expected):.2f})"
166
+ )
167
+
168
+ if not new_refs:
169
+ unrepaired.append(f" {record['id']}: no replacement found for {refs}")
170
+ if new_refs != refs:
171
+ record["relevant_chunk_ids"] = new_refs
172
+ updated.append(json.dumps(record, ensure_ascii=False))
173
+
174
+ print()
175
+ print(f"Repairs: {len(repairs)}")
176
+ for r in repairs:
177
+ print(r)
178
+ if unrepaired:
179
+ print()
180
+ print(f"Unrepaired: {len(unrepaired)}")
181
+ for u in unrepaired:
182
+ print(u)
183
+
184
+ if args.write:
185
+ dataset_path.write_text("\n".join(updated) + "\n", encoding="utf-8")
186
+ print()
187
+ print(f"Wrote {dataset_path}")
188
+ else:
189
+ print()
190
+ print("Dry run — re-run with --write to apply.")
191
+
192
+ return 0
193
+
194
+
195
+ if __name__ == "__main__":
196
+ raise SystemExit(main())