Sdm0 commited on
Commit
3972748
Β·
verified Β·
1 Parent(s): 7444884

Isolate metric evaluator clients

Browse files
Files changed (2) hide show
  1. QUALITY_IMPROVEMENTS.md +25 -25
  2. eval_data/ragas_eval.py +661 -661
QUALITY_IMPROVEMENTS.md CHANGED
@@ -1,26 +1,26 @@
1
- # Review quality improvements
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- Implemented changes:
4
- - Group test suggestions separately, cap low/info, and exclude them from the risk score.
5
- - Check changed-file/line overlap and derive excerpts from actual source. Source grounding does not prove semantic correctness.
6
- - Compiler claims without diagnostics are flagged for verification and excluded from the score.
7
- - Explain risk-score deductions and disclose prompt truncation, reviewed files, Fast windows, incremental scope, and reviewer status.
8
- - Withhold ungrounded findings from GitHub posting and report the withheld count.
9
- - Record owner-scoped correct/incorrect/useful feedback on completed findings in the job database.
10
- - Edit/delete/default provider controls, with browser-local persistence and last successful connection/JSON test metadata.
11
- - RAGAS metrics have individual deadlines, independent result statuses, explicit skipped unsupported metrics, and bounded hosted inputs. No lexical fallback is labeled RAGAS.
12
- - Preserve per-metric successes/failures and evaluation configuration through polling and database persistence. Diff-proxy context is disclosed.
13
- - Distinguish provider-reported cost, estimates, free-model estimates, and unknown costs. Response latency is not mislabeled TTFT.
14
- - Offline regression tool compares stored predictions against located labels with one-to-one matching; partial gold labels do not yield precision claims.
15
-
16
- Run regression matching without inference:
17
-
18
- ```
19
- python -m eval_data.offline_regression --predictions review.json --fixture eval_data/curated_located_fixture.jsonl --output eval_data/regression_report.json
20
- ```
21
-
22
- The curated initial fixture is partial. Location/category/concept matches are evaluation proxies, not proof that a finding is correct. No local models are loaded.
23
-
24
- Validation: backend and frontend regression tests plus the production frontend build. Live verification is reported separately; no improvement percentages are claimed without a controlled benchmark.
25
-
26
- Live verification (2026-10-21): Vercel UI and HF backend; calcom/cal.diy PR #10600 with the saved MiniMax free endpoint in Fast mode completed in 40 seconds. All three reviewers completed. Results grouped 9 test suggestions separately from 3 low-severity findings; score breakdown excluded the suggestions. Feedback saved successfully. Provider connection test returned valid JSON in 1.2 seconds; default selection survived refresh. RAGAS context precision completed (1.000, using a truncated PR-diff proxy); faithfulness returned a provider connection error and the UI reported partial evaluation. This run is workflow evidence, not proof of finding correctness or retrieval accuracy.
 
1
+ # Review quality improvements
2
+
3
+ Implemented changes:
4
+ - Group test suggestions separately, cap low/info, and exclude them from the risk score.
5
+ - Check changed-file/line overlap and derive excerpts from actual source. Source grounding does not prove semantic correctness.
6
+ - Compiler claims without diagnostics are flagged for verification and excluded from the score.
7
+ - Explain risk-score deductions and disclose prompt truncation, reviewed files, Fast windows, incremental scope, and reviewer status.
8
+ - Withhold ungrounded findings from GitHub posting and report the withheld count.
9
+ - Record owner-scoped correct/incorrect/useful feedback on completed findings in the job database.
10
+ - Edit/delete/default provider controls, with browser-local persistence and last successful connection/JSON test metadata.
11
+ - RAGAS metrics have individual deadlines, independent result statuses, explicit skipped unsupported metrics, and bounded hosted inputs. No lexical fallback is labeled RAGAS.
12
+ - Preserve per-metric successes/failures and evaluation configuration through polling and database persistence. Diff-proxy context is disclosed.
13
+ - Distinguish provider-reported cost, estimates, free-model estimates, and unknown costs. Response latency is not mislabeled TTFT.
14
+ - Offline regression tool compares stored predictions against located labels with one-to-one matching; partial gold labels do not yield precision claims.
15
+
16
+ Run regression matching without inference:
17
+
18
+ ```
19
+ python -m eval_data.offline_regression --predictions review.json --fixture eval_data/curated_located_fixture.jsonl --output eval_data/regression_report.json
20
+ ```
21
+
22
+ The curated initial fixture is partial. Location/category/concept matches are evaluation proxies, not proof that a finding is correct. No local models are loaded.
23
+
24
+ Validation: backend and frontend regression tests plus the production frontend build. Live verification is reported separately; no improvement percentages are claimed without a controlled benchmark.
25
 
26
+ Live verification (2026-10-21): Vercel UI and HF backend; calcom/cal.diy PR #10600 with the saved MiniMax free endpoint in Fast mode completed in 40 seconds. All three reviewers completed. Results grouped 9 test suggestions separately from 3 low-severity findings; score breakdown excluded the suggestions. Feedback saved successfully. Provider connection test returned valid JSON in 1.2 seconds; default selection survived refresh. RAGAS context precision completed (1.000, using a truncated PR-diff proxy); faithfulness returned a provider connection error and the UI reported partial evaluation. This run is workflow evidence, not proof of finding correctness or retrieval accuracy.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eval_data/ragas_eval.py CHANGED
@@ -1,661 +1,661 @@
1
- #!/usr/bin/env python3
2
- """RAGAS-based evaluation of retrieval quality for OpenCodeReview.
3
-
4
- Computes **context_precision** and **context_recall** metrics from the
5
- RAGAS framework (https://docs.ragas.io/) on the retrieved context chunks
6
- produced by the ``retrieval_node``.
7
-
8
- These metrics answer:
9
- - **Context Precision**: Are the most relevant code chunks ranked first?
10
- - **Context Recall**: Does the retrieved set contain all the information
11
- needed for the reviewers to produce accurate findings?
12
-
13
- Usage
14
- -----
15
- from eval_data.ragas_eval import compute_ragas_retrieval_scores
16
-
17
- score = compute_ragas_retrieval_scores(
18
- query="diff of PR ...",
19
- retrieved_contexts=["chunk1 text", "chunk2 text", ...],
20
- ground_truth="Human review comment text ...",
21
- )
22
- # score == {"context_precision": 0.85, "context_recall": 0.72}
23
-
24
- Lazy imports minimise overhead when RAGAS is not installed.
25
- """
26
-
27
- from __future__ import annotations
28
-
29
- from contextvars import ContextVar
30
- import logging
31
- import os
32
- import threading
33
- import time
34
- from typing import Any, Optional
35
-
36
- logger = logging.getLogger(__name__)
37
-
38
- # ─── Lazy RAGAS imports with graceful fallback ──────────────────────────────
39
-
40
- _RAGAS_AVAILABLE: bool | None = None
41
-
42
-
43
- def _check_ragas() -> bool:
44
- """Return True if RAGAS is available.
45
-
46
- Note: ``litellm`` is NOT required because RAGAS scoring uses the
47
- project's own LLM factory (Gemini or Groq via LangChain), not
48
- litellm internally.
49
- """
50
- global _RAGAS_AVAILABLE
51
- if _RAGAS_AVAILABLE is not None:
52
- return _RAGAS_AVAILABLE
53
- try:
54
- import ragas # noqa: F401
55
- _RAGAS_AVAILABLE = True
56
- except ImportError:
57
- logger.warning(
58
- "ragas not installed. Install with: pip install ragas"
59
- )
60
- _RAGAS_AVAILABLE = False
61
- return _RAGAS_AVAILABLE
62
-
63
-
64
- # Seconds to sleep before every RAGAS LLM call. RAGAS scoring fires a
65
- # burst of ~20-30 model calls per review (context-precision judgments,
66
- # faithfulness verification, answer relevancy, MMR relevance checks).
67
- # Spacing them keeps the burst under Groq/Gemini free-tier per-minute rate
68
- # limits so scoring completes instead of tripping 429s β€” which previously
69
- # caused long retry backoffs and 0.0000 scores. Override with the
70
- # OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
71
- _RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
72
- _ragas_throttle_lock = threading.Lock()
73
- _metric_deadline = ContextVar("ragas_metric_deadline", default=None)
74
-
75
-
76
- class _ThrottledChatModel:
77
- """Wrap a LangChain chat model so every underlying API call RAGAS makes
78
- is spaced by a fixed interval.
79
-
80
- RAGAS's ``LangchainLLMWrapper`` (deprecated shim in 0.4.x, forwards to
81
- the langchain model) and the custom MMR path call the model through
82
- different entry points (sync/async, single/batched). Intercepting
83
- ``invoke`` / ``generate`` / ``ainvoke`` / ``agenerate`` here guarantees
84
- every request is throttled regardless of ragas version.
85
- """
86
-
87
- def __init__(self, model, interval: float | None = None):
88
- self._model = model
89
- self._interval = _RAGAS_INTERVAL if interval is None else interval
90
- self._quota_exhausted = False
91
-
92
- def _call(self, method, *args, **kwargs):
93
- try:
94
- return method(*args, **kwargs)
95
- except Exception as exc:
96
- if getattr(exc, "status_code", None) in {401, 403, 429} or any(value in str(exc).lower() for value in ("rate_limit_exceeded", "insufficient_quota")):
97
- self._quota_exhausted = True
98
- raise
99
-
100
- async def _acall(self, method, *args, **kwargs):
101
- try:
102
- return await method(*args, **kwargs)
103
- except Exception as exc:
104
- if getattr(exc, "status_code", None) in {401, 403, 429} or any(value in str(exc).lower() for value in ("rate_limit_exceeded", "insufficient_quota")):
105
- self._quota_exhausted = True
106
- raise
107
-
108
- def _wait(self) -> None:
109
- deadline = _metric_deadline.get()
110
- if deadline is not None and time.monotonic() >= deadline:
111
- raise TimeoutError("Metric deadline exceeded; no further judge calls")
112
- if self._quota_exhausted:
113
- raise RuntimeError("Evaluation stopped: provider authentication or quota limit; no further calls will be made for this evaluation.")
114
- if self._interval > 0:
115
- with _ragas_throttle_lock:
116
- time.sleep(self._interval)
117
-
118
- # ── Sync entry points ───────────────────────────────────────────────
119
- def invoke(self, *args, **kwargs):
120
- self._wait()
121
- return self._call(self._model.invoke, *args, **kwargs)
122
-
123
- def generate(self, messages, *args, **kwargs):
124
- # Serialize LangChain batch calls into individual throttled
125
- # requests so every underlying API call is spaced by the interval.
126
- if (
127
- isinstance(messages, list)
128
- and messages
129
- and isinstance(messages[0], list)
130
- ):
131
- from langchain_core.outputs import Generation, LLMResult
132
-
133
- generations = []
134
- for msgs in messages:
135
- self._wait()
136
- # invoke() does not accept callbacks/run_manager/config that
137
- # ragas may forward to generate() β€” drop them here.
138
- resp = self._call(self._model.invoke, msgs)
139
- text = resp.content if hasattr(resp, "content") else str(resp)
140
- generations.append([Generation(text=text, message=resp)])
141
- return LLMResult(generations=generations, llm_output=None)
142
- self._wait()
143
- return self._call(self._model.generate, messages, *args, **kwargs)
144
-
145
- # ── Async entry points ──────────────────────────────────────────────
146
- async def ainvoke(self, *args, **kwargs):
147
- self._wait()
148
- return await self._acall(self._model.ainvoke, *args, **kwargs)
149
-
150
- async def agenerate(self, messages, *args, **kwargs):
151
- if (
152
- isinstance(messages, list)
153
- and messages
154
- and isinstance(messages[0], list)
155
- ):
156
- from langchain_core.outputs import Generation, LLMResult
157
-
158
- generations = []
159
- for msgs in messages:
160
- self._wait()
161
- # Same kwargs caveat as generate(): ainvoke has no callbacks.
162
- resp = await self._acall(self._model.ainvoke, msgs)
163
- text = resp.content if hasattr(resp, "content") else str(resp)
164
- generations.append([Generation(text=text, message=resp)])
165
- return LLMResult(generations=generations, llm_output=None)
166
- self._wait()
167
- return await self._acall(self._model.agenerate, messages, *args, **kwargs)
168
-
169
- # ── Everything else passes through ──────────────────────────────────
170
- def __getattr__(self, name: str):
171
- return getattr(self._model, name)
172
-
173
-
174
- def _wrap_evaluator(llm):
175
- from ragas.llms import LangchainLLMWrapper
176
- from ragas.run_config import RunConfig
177
- return LangchainLLMWrapper(_ThrottledChatModel(llm), run_config=RunConfig(timeout=12, max_retries=1, max_wait=0, max_workers=1))
178
-
179
-
180
- def _get_evaluator_llm(endpoint: Optional[str] = None):
181
- """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
182
-
183
- Priority:
184
- 1. **Custom endpoint** β€” when *endpoint* names a configured
185
- ``OCR_ENDPOINT_*`` config, it is used (any provider the user added).
186
- 2. **Groq** (``llama-3.3-70b-versatile``) via ``GROQ_API_KEY``
187
- 3. **Google Gemini** (``gemini-3.1-flash-lite``) via ``GEMINI_API_KEY``
188
-
189
- Groq is preferred over Gemini because scoring fires many LLM calls per
190
- review and the Gemini free tier (15 req/min) is already shared with the
191
- main review pipeline β€” using Groq's separate quota pool avoids the 429
192
- rate-limit failures that used to zero out the metrics.
193
-
194
- RAGAS v0.3+ uses ``LangchainLLMWrapper`` to wrap LangChain models.
195
- """
196
- from ragas.llms import LangchainLLMWrapper
197
-
198
- try:
199
- if endpoint:
200
- from llm_factory import create_llm
201
- from endpoints import EndpointConfig, get_endpoint
202
- configured = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
203
- timeout = 15
204
- if configured and not getattr(configured, "builtin", False) and configured.provider not in {"google", "anthropic"}:
205
- import httpx
206
- # LangChain caches HTTP clients for hashable timeout values.
207
- # An unhashable Timeout forces a private pool for this loop.
208
- timeout = httpx.Timeout(15)
209
- llm = create_llm(endpoint=endpoint, temperature=0, timeout=timeout, max_retries=0)
210
- logger.info("RAGAS evaluator: using selected custom endpoint")
211
- return _wrap_evaluator(llm)
212
-
213
- from llm_factory import _get_groq_chat, _get_gemini_chat
214
-
215
- # Keep evaluation bounded: RAGAS runs several provider calls and
216
- # retrying each one can otherwise hold a review open for minutes.
217
- configured_model = os.getenv("RAGAS_MODEL", "").strip()
218
- if configured_model.startswith("groq/"):
219
- configured_model = configured_model.split("/", 1)[1]
220
- groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout": 15}
221
- if configured_model:
222
- groq_kwargs["model"] = configured_model
223
- llm = _get_groq_chat(**groq_kwargs)
224
- if llm is None:
225
- logger.info(
226
- "RAGAS evaluator: GROQ_API_KEY not set β€” falling back to Gemini"
227
- )
228
- llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=15)
229
- if llm is None:
230
- raise ValueError(
231
- "No LLM available for RAGAS scoring. "
232
- "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
233
- )
234
- logger.info(
235
- "RAGAS evaluator: using %s (throttled %ss)",
236
- type(llm).__name__,
237
- _RAGAS_INTERVAL,
238
- )
239
- return _wrap_evaluator(llm)
240
- except ValueError as exc:
241
- logger.warning("RAGAS evaluator: %s", exc)
242
- raise RuntimeError(
243
- "No LLM available for RAGAS scoring. "
244
- "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
245
- ) from exc
246
-
247
-
248
- # ─── Score computation ─────────────────────────────────────────────────────
249
-
250
-
251
- def _score_one_metric(name, sample, llm, timeout):
252
- from ragas import metrics
253
- from ragas.run_config import RunConfig
254
- classes = {"context_precision": "LLMContextPrecisionWithoutReference", "faithfulness": "Faithfulness", "context_recall": "ContextRecall"}
255
- scorer = getattr(metrics, classes[name])(llm=llm)
256
- scorer.init(RunConfig(timeout=timeout, max_retries=1, max_wait=0, max_workers=1))
257
- return float(scorer.single_turn_score(sample))
258
-
259
-
260
- def _safe_metric_error(exc):
261
- """Classify failures without exposing provider responses or credentials."""
262
- chain = []
263
- current = exc
264
- while current is not None and len(chain) < 5:
265
- chain.append(type(current).__name__.lower())
266
- current = current.__cause__ or current.__context__
267
- kinds = " ".join(chain)
268
- if "timeout" in kinds:
269
- return "timed_out", "Evaluator provider timed out. Retry or select a faster model."
270
- if "connection" in kinds or "connecterror" in kinds:
271
- return "failed", "Evaluator provider connection failed. Retry; check provider availability if it persists."
272
- if "ratelimit" in kinds:
273
- return "failed", "Evaluator provider rate limit reached. Wait or select another saved provider."
274
- if "authentication" in kinds or "permission" in kinds:
275
- return "failed", "Evaluator provider rejected access. Check the saved provider credentials and permissions."
276
- return "failed", type(exc).__name__
277
-
278
-
279
- def compute_ragas_report(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None, *, metric_timeout=None, progress_callback=None):
280
- """Run independent bounded RAGAS metrics, preserving successes and real failures.
281
-
282
- No local embedding model is loaded. Lexical overlap is never substituted for
283
- RAGAS. Input caps reduce judge latency and are disclosed in the report.
284
- """
285
- import math
286
- import queue
287
- from contextvars import copy_context
288
- started = time.monotonic()
289
- total_budget = max(1.0, float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "30")))
290
- per_metric = max(.05, float(metric_timeout or os.getenv("OCR_RAGAS_METRIC_TIMEOUT_SECONDS", "12")))
291
- names = ["context_precision", "faithfulness"]
292
- if ground_truth:
293
- names.append("context_recall")
294
- report = {"scores": {}, "metrics": {}, "evaluation": {"engine": "RAGAS", "local_models": False, "metric_timeout_seconds": per_metric, "input_truncated": len(query) > 6000 or len(answer or "") > 4000 or len(retrieved_contexts) > 2 or any(len(c) > 4000 for c in retrieved_contexts)}}
295
- def finish(name, status, value=None, error=None, duration=0):
296
- report["metrics"][name] = {"status": status, "value": value, "error": error, "duration_seconds": round(duration, 3)}
297
- if value is not None:
298
- report["scores"][name] = value
299
- if progress_callback:
300
- progress_callback(report)
301
- for name, reason in [("answer_relevancy", "Requires embeddings; local models are disabled"), ("mmr", "Extra judge calls disabled in hosted evaluation")]:
302
- finish(name, "skipped", error=reason)
303
- if not ground_truth:
304
- finish("context_recall", "skipped", error="No reference answer provided")
305
- if not answer or not retrieved_contexts:
306
- for name in names:
307
- finish(name, "skipped", error="A complete answer and context are required")
308
- return report
309
- try:
310
- if not _check_ragas():
311
- raise RuntimeError("RAGAS is not installed")
312
- from ragas.dataset_schema import SingleTurnSample
313
- sample = SingleTurnSample(user_input=query[:6000], response=answer[:4000], retrieved_contexts=[c[:4000] for c in retrieved_contexts[:2]], reference=ground_truth[:4000] if ground_truth else None)
314
- except Exception as exc:
315
- for name in names:
316
- finish(name, "failed", error=type(exc).__name__)
317
- return report
318
- pending = {}
319
- for name in names:
320
- remaining = total_budget - (time.monotonic() - started) - 1
321
- if remaining <= 0:
322
- finish(name, "timed_out", error="Evaluation setup exhausted deadline")
323
- continue
324
- deadline = time.monotonic() + min(per_metric, remaining)
325
- output = queue.Queue(maxsize=1)
326
- def run(metric=name, target=output, limit=min(per_metric, remaining)):
327
- metric_started = time.monotonic()
328
- token = _metric_deadline.set(metric_started + limit)
329
- try:
330
- # Each metric runs its own asyncio loop. Sharing an async HTTP
331
- # client across these threads can bind its pool to another loop.
332
- llm = _get_evaluator_llm(endpoint=endpoint)
333
- value = _score_one_metric(metric, sample, llm, limit)
334
- if not math.isfinite(value) or not 0 <= value <= 1:
335
- raise ValueError("Invalid metric value")
336
- target.put(("completed", round(value, 4), None, time.monotonic() - metric_started))
337
- except Exception as exc:
338
- status, error = _safe_metric_error(exc)
339
- logger.warning("RAGAS metric %s failed (%s)", metric, type(exc).__name__)
340
- target.put((status, None, error, time.monotonic() - metric_started))
341
- finally:
342
- _metric_deadline.reset(token)
343
- threading.Thread(target=copy_context().run, args=(run,), daemon=True).start()
344
- pending[name] = (output, deadline)
345
- while pending:
346
- for name, (output, deadline) in list(pending.items()):
347
- try:
348
- status, value, error, duration = output.get_nowait()
349
- except queue.Empty:
350
- if time.monotonic() < deadline:
351
- continue
352
- status, value, error, duration = "timed_out", None, "Metric deadline exceeded", per_metric
353
- finish(name, status, value, error, duration)
354
- del pending[name]
355
- if pending:
356
- time.sleep(.01)
357
- report["evaluation"]["duration_seconds"] = round(time.monotonic() - started, 3)
358
- return report
359
-
360
-
361
- def compute_ragas_retrieval_scores(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None):
362
- """Compatibility mapping. Failed/skipped metrics remain None, never invented scores."""
363
- report = compute_ragas_report(query, retrieved_contexts, ground_truth, answer, endpoint)
364
- return {name: metric["value"] for name, metric in report["metrics"].items()}
365
-
366
-
367
- def _create_ragas_embeddings():
368
- """Return a lightweight embedding object compatible with RAGAS metrics.
369
-
370
- Wraps the ChromaDB ONNX MiniLM embedding function so that metrics like
371
- ``ResponseRelevancy`` can compute cosine similarity between embeddings.
372
- The underlying ONNX model is cached globally and loads in <1 s.
373
- """
374
- if os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower() not in {"1", "true", "yes"}:
375
- logger.info("Local RAGAS embeddings disabled; skipping answer relevancy")
376
- return None
377
- try:
378
- from chromadb.utils import embedding_functions
379
-
380
- if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):
381
- ef = embedding_functions.ONNXMiniLM_L6_V2()
382
- else:
383
- ef = embedding_functions.SentenceTransformerEmbeddingFunction(
384
- model_name="all-MiniLM-L6-v2"
385
- )
386
-
387
- class _RagasEmbeddings:
388
- def __init__(self, ef):
389
- self._ef = ef
390
-
391
- def embed_query(self, text: str) -> list[float]:
392
- result = self._ef([text])[0]
393
- return list(result) if not isinstance(result, list) else result
394
-
395
- def embed_documents(self, texts: list[str]) -> list[list[float]]:
396
- results = self._ef(texts)
397
- return [list(r) if not isinstance(r, list) else r for r in results]
398
-
399
- return _RagasEmbeddings(ef)
400
- except Exception as exc:
401
- logger.warning("Cannot create RAGAS embeddings: %s", exc)
402
- return None
403
-
404
-
405
- def _compute_mmr(
406
- query: str,
407
- retrieved_contexts: list[str],
408
- llm: Any,
409
- ) -> float:
410
- """Compute Mean Reciprocal Rank β€” how early the first relevant chunk appears.
411
-
412
- Uses the LLM to judge each chunk's relevance to the query in order.
413
- The first chunk judged relevant determines the reciprocal rank:
414
- ``1 / rank_of_first_relevant``. Returns 0.0 if none are relevant.
415
-
416
- Parameters
417
- ----------
418
- query : str
419
- The search query (PR diff).
420
- retrieved_contexts : list[str]
421
- Ranked list of retrieved code chunks.
422
- llm : LangchainLLMWrapper
423
- RAGAS-wrapped LLM for relevance judgments.
424
-
425
- Returns
426
- -------
427
- float
428
- MMR score in [0, 1]; 0.0 when chunks were judged but none were
429
- relevant.
430
-
431
- Raises
432
- ------
433
- RuntimeError
434
- If every relevance judgment failed (e.g. LLM rate-limited) β€”
435
- callers treat this as a failed metric rather than a fake 0.0.
436
- """
437
- if not retrieved_contexts:
438
- return 0.0
439
-
440
- # Score up to the first 5 chunks for relevance using the LLM.
441
- # Top-5 MMR is standard β€” rank 5 yields 1/5 = 0.20, and
442
- # anything beyond rank 5 barely changes the score anyway.
443
- MAX_MMR_RANK = 2
444
- top_chunks = retrieved_contexts[:MAX_MMR_RANK]
445
-
446
- judged = 0
447
- for rank, chunk in enumerate(top_chunks, start=1):
448
- try:
449
- prompt = (
450
- f"Is the following code/document chunk relevant to the question?\n\n"
451
- f"Question: {query[:2_000]}\n\n"
452
- f"Chunk: {chunk[:2_000]}\n\n"
453
- f"Answer with exactly one word: YES or NO"
454
- )
455
- # Use the wrapped LangChain model for fast synchronous invoke.
456
- # LangchainLLMWrapper stores the model as .langchain_llm in ragas
457
- # 0.4.x and as .llm in 0.3.x β€” accept both.
458
- langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
459
- # Space the relevance judgments too β€” this unwrapped path bypasses
460
- # the model wrapper on some ragas versions, so sleep explicitly
461
- # (unless the wrapper is already in the path, to avoid double-sleep).
462
- if not isinstance(langchain_model, _ThrottledChatModel):
463
- time.sleep(_RAGAS_INTERVAL)
464
- raw = langchain_model.invoke(prompt)
465
- response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
466
- if response_text.startswith("Y"):
467
- return 1.0 / rank
468
- judged += 1 # judge responded β€” chunk deemed not relevant
469
- except Exception:
470
- continue
471
-
472
- if judged == 0:
473
- # Every relevance judgment failed (e.g. LLM rate-limited) β€” surface
474
- # this as a failed metric instead of a misleading 0.0.
475
- raise RuntimeError("all MMR relevance judgments failed")
476
-
477
- return 0.0
478
-
479
-
480
- def log_ragas_scores_to_langfuse(
481
- scores: dict[str, float | None],
482
- repo: str = "",
483
- pr_number: int = 0,
484
- handler: Any = None,
485
- ) -> None:
486
- """Log RAGAS metrics as Langfuse scores (linked to the review trace).
487
-
488
- Parameters
489
- ----------
490
- scores : dict
491
- Output of :func:`compute_ragas_retrieval_scores`.
492
- repo : str
493
- GitHub repository name (e.g. ``\"psf/requests\"``).
494
- pr_number : int
495
- Pull request number.
496
- handler : Langfuse CallbackHandler or None
497
- Handler from the current review run, used to link scores to the trace.
498
- """
499
- try:
500
- from observability import log_langfuse_score
501
- except ImportError:
502
- logger.debug("observability module not available β€” skipping Langfuse")
503
- return
504
-
505
- for metric_name, value in scores.items():
506
- if value is None:
507
- continue
508
- log_langfuse_score(
509
- name=f"ragas_{metric_name}",
510
- value=value,
511
- comment=f"{repo}#{pr_number} β€” {metric_name}",
512
- handler=handler,
513
- )
514
-
515
-
516
- # ─── Standalone CLI ─────────────────────────────────────────────────────────
517
-
518
-
519
- def main() -> None:
520
- """CLI entry point: compute RAGAS scores from a JSONL dataset.
521
-
522
- Usage::
523
-
524
- python eval_data/ragas_eval.py --data eval_data/prs.jsonl
525
- """
526
- import argparse
527
- import json
528
-
529
- parser = argparse.ArgumentParser(
530
- description="Compute RAGAS retrieval quality scores on evaluation data",
531
- )
532
- parser.add_argument(
533
- "--data", default=None,
534
- help="Path to JSONL dataset (same format as evaluate.py)",
535
- )
536
- parser.add_argument(
537
- "--output", default=None,
538
- help="Path to write per-PR RAGAS scores (JSON)",
539
- )
540
- parser.add_argument(
541
- "--max-prs", type=int, default=None,
542
- help="Max PRs to process",
543
- )
544
- parser.add_argument(
545
- "--log-to-observability", action="store_true",
546
- help="Log RAGAS scores to Langfuse",
547
- )
548
- args = parser.parse_args()
549
-
550
- logging.basicConfig(
551
- level=logging.INFO,
552
- format="%(asctime)s [%(levelname)s] %(name)s β€” %(message)s",
553
- )
554
-
555
- if not args.data:
556
- # If no data file specified, try default location
557
- default_path = os.path.join(
558
- os.path.dirname(__file__), "prs.jsonl"
559
- )
560
- if os.path.exists(default_path):
561
- args.data = default_path
562
- else:
563
- logger.error(
564
- "No --data provided and default not found at %s. "
565
- "Run eval_data/fetcher.py first.",
566
- default_path,
567
- )
568
- return
569
-
570
- with open(args.data, "r", encoding="utf-8") as f:
571
- entries = [json.loads(line) for line in f if line.strip()]
572
-
573
- if args.max_prs:
574
- entries = entries[: args.max_prs]
575
-
576
- all_scores: list[dict] = []
577
- for entry in entries:
578
- repo = entry.get("repo", "?")
579
- pr = entry.get("pr_number", 0)
580
- diff = entry.get("diff", "")
581
- ground_truth_list = entry.get("ground_truth", [])
582
-
583
- # Use the diff as the query, and first few human comments
584
- # as a proxy for "what the retrieval should have found"
585
- query = diff[:8_000] if diff else entry.get("title", "")
586
- gt_text = (
587
- " ".join(
588
- g.get("comment", "")
589
- for g in ground_truth_list[:5]
590
- )
591
- if ground_truth_list
592
- else None
593
- )
594
-
595
- # Retrieved contexts come from the graph run, but for the CLI
596
- # we don't re-run the graph β€” we just skip if no retrieval data
597
- # is available in the entry.
598
- stored_contexts = entry.get("retrieved_contexts", [])
599
- if not stored_contexts:
600
- logger.info(
601
- "[%s#%d] No stored retrieval contexts β€” skipping RAGAS",
602
- repo, pr,
603
- )
604
- continue
605
-
606
- logger.info("[%s#%d] Computing RAGAS scores …", repo, pr)
607
- try:
608
- scores = compute_ragas_retrieval_scores(
609
- query=query,
610
- retrieved_contexts=stored_contexts,
611
- ground_truth=gt_text,
612
- )
613
- except RuntimeError as exc:
614
- logger.warning("[%s#%d] %s", repo, pr, exc)
615
- break
616
-
617
- scores.update({"repo": repo, "pr_number": pr, "id": entry.get("id")})
618
- all_scores.append(scores)
619
-
620
- if args.log_to_observability:
621
- log_ragas_scores_to_langfuse(scores, repo=repo, pr_number=pr)
622
-
623
- print(
624
- f" {repo}#{pr}: "
625
- + " | ".join(
626
- f"{k}={v:.3f}" for k, v in scores.items()
627
- if k not in ("repo", "pr_number", "id") and v is not None
628
- )
629
- )
630
-
631
- # Print aggregate
632
- if all_scores:
633
- print()
634
- print("=" * 60)
635
- print(" Aggregate RAGAS scores")
636
- print("=" * 60)
637
- metrics = [
638
- k for k in all_scores[0].keys()
639
- if k not in ("repo", "pr_number", "id")
640
- ]
641
- for metric in metrics:
642
- values = [
643
- s.get(metric) for s in all_scores
644
- if s.get(metric) is not None
645
- ]
646
- if not values:
647
- print(f" {metric:30s}: n/a (no successful scores)")
648
- continue
649
- avg = sum(values) / len(values)
650
- print(f" {metric:30s}: {avg:.4f} (over {len(values)} PRs)")
651
- print()
652
-
653
- # Save output
654
- if args.output and all_scores:
655
- with open(args.output, "w", encoding="utf-8") as f:
656
- json.dump(all_scores, f, indent=2)
657
- logger.info("Saved RAGAS scores to %s", args.output)
658
-
659
-
660
- if __name__ == "__main__":
661
- main()
 
1
+ #!/usr/bin/env python3
2
+ """RAGAS-based evaluation of retrieval quality for OpenCodeReview.
3
+
4
+ Computes **context_precision** and **context_recall** metrics from the
5
+ RAGAS framework (https://docs.ragas.io/) on the retrieved context chunks
6
+ produced by the ``retrieval_node``.
7
+
8
+ These metrics answer:
9
+ - **Context Precision**: Are the most relevant code chunks ranked first?
10
+ - **Context Recall**: Does the retrieved set contain all the information
11
+ needed for the reviewers to produce accurate findings?
12
+
13
+ Usage
14
+ -----
15
+ from eval_data.ragas_eval import compute_ragas_retrieval_scores
16
+
17
+ score = compute_ragas_retrieval_scores(
18
+ query="diff of PR ...",
19
+ retrieved_contexts=["chunk1 text", "chunk2 text", ...],
20
+ ground_truth="Human review comment text ...",
21
+ )
22
+ # score == {"context_precision": 0.85, "context_recall": 0.72}
23
+
24
+ Lazy imports minimise overhead when RAGAS is not installed.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from contextvars import ContextVar
30
+ import logging
31
+ import os
32
+ import threading
33
+ import time
34
+ from typing import Any, Optional
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+ # ─── Lazy RAGAS imports with graceful fallback ──────────────────────────────
39
+
40
+ _RAGAS_AVAILABLE: bool | None = None
41
+
42
+
43
+ def _check_ragas() -> bool:
44
+ """Return True if RAGAS is available.
45
+
46
+ Note: ``litellm`` is NOT required because RAGAS scoring uses the
47
+ project's own LLM factory (Gemini or Groq via LangChain), not
48
+ litellm internally.
49
+ """
50
+ global _RAGAS_AVAILABLE
51
+ if _RAGAS_AVAILABLE is not None:
52
+ return _RAGAS_AVAILABLE
53
+ try:
54
+ import ragas # noqa: F401
55
+ _RAGAS_AVAILABLE = True
56
+ except ImportError:
57
+ logger.warning(
58
+ "ragas not installed. Install with: pip install ragas"
59
+ )
60
+ _RAGAS_AVAILABLE = False
61
+ return _RAGAS_AVAILABLE
62
+
63
+
64
+ # Seconds to sleep before every RAGAS LLM call. RAGAS scoring fires a
65
+ # burst of ~20-30 model calls per review (context-precision judgments,
66
+ # faithfulness verification, answer relevancy, MMR relevance checks).
67
+ # Spacing them keeps the burst under Groq/Gemini free-tier per-minute rate
68
+ # limits so scoring completes instead of tripping 429s β€” which previously
69
+ # caused long retry backoffs and 0.0000 scores. Override with the
70
+ # OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
71
+ _RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
72
+ _ragas_throttle_lock = threading.Lock()
73
+ _metric_deadline = ContextVar("ragas_metric_deadline", default=None)
74
+
75
+
76
+ class _ThrottledChatModel:
77
+ """Wrap a LangChain chat model so every underlying API call RAGAS makes
78
+ is spaced by a fixed interval.
79
+
80
+ RAGAS's ``LangchainLLMWrapper`` (deprecated shim in 0.4.x, forwards to
81
+ the langchain model) and the custom MMR path call the model through
82
+ different entry points (sync/async, single/batched). Intercepting
83
+ ``invoke`` / ``generate`` / ``ainvoke`` / ``agenerate`` here guarantees
84
+ every request is throttled regardless of ragas version.
85
+ """
86
+
87
+ def __init__(self, model, interval: float | None = None):
88
+ self._model = model
89
+ self._interval = _RAGAS_INTERVAL if interval is None else interval
90
+ self._quota_exhausted = False
91
+
92
+ def _call(self, method, *args, **kwargs):
93
+ try:
94
+ return method(*args, **kwargs)
95
+ except Exception as exc:
96
+ if getattr(exc, "status_code", None) in {401, 403, 429} or any(value in str(exc).lower() for value in ("rate_limit_exceeded", "insufficient_quota")):
97
+ self._quota_exhausted = True
98
+ raise
99
+
100
+ async def _acall(self, method, *args, **kwargs):
101
+ try:
102
+ return await method(*args, **kwargs)
103
+ except Exception as exc:
104
+ if getattr(exc, "status_code", None) in {401, 403, 429} or any(value in str(exc).lower() for value in ("rate_limit_exceeded", "insufficient_quota")):
105
+ self._quota_exhausted = True
106
+ raise
107
+
108
+ def _wait(self) -> None:
109
+ deadline = _metric_deadline.get()
110
+ if deadline is not None and time.monotonic() >= deadline:
111
+ raise TimeoutError("Metric deadline exceeded; no further judge calls")
112
+ if self._quota_exhausted:
113
+ raise RuntimeError("Evaluation stopped: provider authentication or quota limit; no further calls will be made for this evaluation.")
114
+ if self._interval > 0:
115
+ with _ragas_throttle_lock:
116
+ time.sleep(self._interval)
117
+
118
+ # ── Sync entry points ───────────────────────────────────────────────
119
+ def invoke(self, *args, **kwargs):
120
+ self._wait()
121
+ return self._call(self._model.invoke, *args, **kwargs)
122
+
123
+ def generate(self, messages, *args, **kwargs):
124
+ # Serialize LangChain batch calls into individual throttled
125
+ # requests so every underlying API call is spaced by the interval.
126
+ if (
127
+ isinstance(messages, list)
128
+ and messages
129
+ and isinstance(messages[0], list)
130
+ ):
131
+ from langchain_core.outputs import Generation, LLMResult
132
+
133
+ generations = []
134
+ for msgs in messages:
135
+ self._wait()
136
+ # invoke() does not accept callbacks/run_manager/config that
137
+ # ragas may forward to generate() β€” drop them here.
138
+ resp = self._call(self._model.invoke, msgs)
139
+ text = resp.content if hasattr(resp, "content") else str(resp)
140
+ generations.append([Generation(text=text, message=resp)])
141
+ return LLMResult(generations=generations, llm_output=None)
142
+ self._wait()
143
+ return self._call(self._model.generate, messages, *args, **kwargs)
144
+
145
+ # ── Async entry points ──────────────────────────────────────────────
146
+ async def ainvoke(self, *args, **kwargs):
147
+ self._wait()
148
+ return await self._acall(self._model.ainvoke, *args, **kwargs)
149
+
150
+ async def agenerate(self, messages, *args, **kwargs):
151
+ if (
152
+ isinstance(messages, list)
153
+ and messages
154
+ and isinstance(messages[0], list)
155
+ ):
156
+ from langchain_core.outputs import Generation, LLMResult
157
+
158
+ generations = []
159
+ for msgs in messages:
160
+ self._wait()
161
+ # Same kwargs caveat as generate(): ainvoke has no callbacks.
162
+ resp = await self._acall(self._model.ainvoke, msgs)
163
+ text = resp.content if hasattr(resp, "content") else str(resp)
164
+ generations.append([Generation(text=text, message=resp)])
165
+ return LLMResult(generations=generations, llm_output=None)
166
+ self._wait()
167
+ return await self._acall(self._model.agenerate, messages, *args, **kwargs)
168
+
169
+ # ── Everything else passes through ──────────────────────────────────
170
+ def __getattr__(self, name: str):
171
+ return getattr(self._model, name)
172
+
173
+
174
+ def _wrap_evaluator(llm):
175
+ from ragas.llms import LangchainLLMWrapper
176
+ from ragas.run_config import RunConfig
177
+ return LangchainLLMWrapper(_ThrottledChatModel(llm), run_config=RunConfig(timeout=12, max_retries=1, max_wait=0, max_workers=1))
178
+
179
+
180
+ def _get_evaluator_llm(endpoint: Optional[str] = None):
181
+ """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
182
+
183
+ Priority:
184
+ 1. **Custom endpoint** β€” when *endpoint* names a configured
185
+ ``OCR_ENDPOINT_*`` config, it is used (any provider the user added).
186
+ 2. **Groq** (``llama-3.3-70b-versatile``) via ``GROQ_API_KEY``
187
+ 3. **Google Gemini** (``gemini-3.1-flash-lite``) via ``GEMINI_API_KEY``
188
+
189
+ Groq is preferred over Gemini because scoring fires many LLM calls per
190
+ review and the Gemini free tier (15 req/min) is already shared with the
191
+ main review pipeline β€” using Groq's separate quota pool avoids the 429
192
+ rate-limit failures that used to zero out the metrics.
193
+
194
+ RAGAS v0.3+ uses ``LangchainLLMWrapper`` to wrap LangChain models.
195
+ """
196
+ from ragas.llms import LangchainLLMWrapper
197
+
198
+ try:
199
+ if endpoint:
200
+ from llm_factory import create_llm
201
+ from endpoints import EndpointConfig, get_endpoint
202
+ configured = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
203
+ timeout = 15
204
+ if configured and not getattr(configured, "builtin", False) and configured.provider not in {"google", "anthropic"}:
205
+ import httpx
206
+ # LangChain caches HTTP clients for hashable timeout values.
207
+ # An unhashable Timeout forces a private pool for this loop.
208
+ timeout = httpx.Timeout(15)
209
+ llm = create_llm(endpoint=endpoint, temperature=0, timeout=timeout, max_retries=0)
210
+ logger.info("RAGAS evaluator: using selected custom endpoint")
211
+ return _wrap_evaluator(llm)
212
+
213
+ from llm_factory import _get_groq_chat, _get_gemini_chat
214
+
215
+ # Keep evaluation bounded: RAGAS runs several provider calls and
216
+ # retrying each one can otherwise hold a review open for minutes.
217
+ configured_model = os.getenv("RAGAS_MODEL", "").strip()
218
+ if configured_model.startswith("groq/"):
219
+ configured_model = configured_model.split("/", 1)[1]
220
+ groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout": 15}
221
+ if configured_model:
222
+ groq_kwargs["model"] = configured_model
223
+ llm = _get_groq_chat(**groq_kwargs)
224
+ if llm is None:
225
+ logger.info(
226
+ "RAGAS evaluator: GROQ_API_KEY not set β€” falling back to Gemini"
227
+ )
228
+ llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=15)
229
+ if llm is None:
230
+ raise ValueError(
231
+ "No LLM available for RAGAS scoring. "
232
+ "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
233
+ )
234
+ logger.info(
235
+ "RAGAS evaluator: using %s (throttled %ss)",
236
+ type(llm).__name__,
237
+ _RAGAS_INTERVAL,
238
+ )
239
+ return _wrap_evaluator(llm)
240
+ except ValueError as exc:
241
+ logger.warning("RAGAS evaluator: %s", exc)
242
+ raise RuntimeError(
243
+ "No LLM available for RAGAS scoring. "
244
+ "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
245
+ ) from exc
246
+
247
+
248
+ # ─── Score computation ─────────────────────────────────────────────────────
249
+
250
+
251
+ def _score_one_metric(name, sample, llm, timeout):
252
+ from ragas import metrics
253
+ from ragas.run_config import RunConfig
254
+ classes = {"context_precision": "LLMContextPrecisionWithoutReference", "faithfulness": "Faithfulness", "context_recall": "ContextRecall"}
255
+ scorer = getattr(metrics, classes[name])(llm=llm)
256
+ scorer.init(RunConfig(timeout=timeout, max_retries=1, max_wait=0, max_workers=1))
257
+ return float(scorer.single_turn_score(sample))
258
+
259
+
260
+ def _safe_metric_error(exc):
261
+ """Classify failures without exposing provider responses or credentials."""
262
+ chain = []
263
+ current = exc
264
+ while current is not None and len(chain) < 5:
265
+ chain.append(type(current).__name__.lower())
266
+ current = current.__cause__ or current.__context__
267
+ kinds = " ".join(chain)
268
+ if "timeout" in kinds:
269
+ return "timed_out", "Evaluator provider timed out. Retry or select a faster model."
270
+ if "connection" in kinds or "connecterror" in kinds:
271
+ return "failed", "Evaluator provider connection failed. Retry; check provider availability if it persists."
272
+ if "ratelimit" in kinds:
273
+ return "failed", "Evaluator provider rate limit reached. Wait or select another saved provider."
274
+ if "authentication" in kinds or "permission" in kinds:
275
+ return "failed", "Evaluator provider rejected access. Check the saved provider credentials and permissions."
276
+ return "failed", type(exc).__name__
277
+
278
+
279
+ def compute_ragas_report(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None, *, metric_timeout=None, progress_callback=None):
280
+ """Run independent bounded RAGAS metrics, preserving successes and real failures.
281
+
282
+ No local embedding model is loaded. Lexical overlap is never substituted for
283
+ RAGAS. Input caps reduce judge latency and are disclosed in the report.
284
+ """
285
+ import math
286
+ import queue
287
+ from contextvars import copy_context
288
+ started = time.monotonic()
289
+ total_budget = max(1.0, float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "30")))
290
+ per_metric = max(.05, float(metric_timeout or os.getenv("OCR_RAGAS_METRIC_TIMEOUT_SECONDS", "12")))
291
+ names = ["context_precision", "faithfulness"]
292
+ if ground_truth:
293
+ names.append("context_recall")
294
+ report = {"scores": {}, "metrics": {}, "evaluation": {"engine": "RAGAS", "local_models": False, "metric_timeout_seconds": per_metric, "input_truncated": len(query) > 6000 or len(answer or "") > 4000 or len(retrieved_contexts) > 2 or any(len(c) > 4000 for c in retrieved_contexts)}}
295
+ def finish(name, status, value=None, error=None, duration=0):
296
+ report["metrics"][name] = {"status": status, "value": value, "error": error, "duration_seconds": round(duration, 3)}
297
+ if value is not None:
298
+ report["scores"][name] = value
299
+ if progress_callback:
300
+ progress_callback(report)
301
+ for name, reason in [("answer_relevancy", "Requires embeddings; local models are disabled"), ("mmr", "Extra judge calls disabled in hosted evaluation")]:
302
+ finish(name, "skipped", error=reason)
303
+ if not ground_truth:
304
+ finish("context_recall", "skipped", error="No reference answer provided")
305
+ if not answer or not retrieved_contexts:
306
+ for name in names:
307
+ finish(name, "skipped", error="A complete answer and context are required")
308
+ return report
309
+ try:
310
+ if not _check_ragas():
311
+ raise RuntimeError("RAGAS is not installed")
312
+ from ragas.dataset_schema import SingleTurnSample
313
+ sample = SingleTurnSample(user_input=query[:6000], response=answer[:4000], retrieved_contexts=[c[:4000] for c in retrieved_contexts[:2]], reference=ground_truth[:4000] if ground_truth else None)
314
+ except Exception as exc:
315
+ for name in names:
316
+ finish(name, "failed", error=type(exc).__name__)
317
+ return report
318
+ pending = {}
319
+ for name in names:
320
+ remaining = total_budget - (time.monotonic() - started) - 1
321
+ if remaining <= 0:
322
+ finish(name, "timed_out", error="Evaluation setup exhausted deadline")
323
+ continue
324
+ deadline = time.monotonic() + min(per_metric, remaining)
325
+ output = queue.Queue(maxsize=1)
326
+ def run(metric=name, target=output, limit=min(per_metric, remaining)):
327
+ metric_started = time.monotonic()
328
+ token = _metric_deadline.set(metric_started + limit)
329
+ try:
330
+ # Each metric runs its own asyncio loop. Sharing an async HTTP
331
+ # client across these threads can bind its pool to another loop.
332
+ llm = _get_evaluator_llm(endpoint=endpoint)
333
+ value = _score_one_metric(metric, sample, llm, limit)
334
+ if not math.isfinite(value) or not 0 <= value <= 1:
335
+ raise ValueError("Invalid metric value")
336
+ target.put(("completed", round(value, 4), None, time.monotonic() - metric_started))
337
+ except Exception as exc:
338
+ status, error = _safe_metric_error(exc)
339
+ logger.warning("RAGAS metric %s failed (%s)", metric, type(exc).__name__)
340
+ target.put((status, None, error, time.monotonic() - metric_started))
341
+ finally:
342
+ _metric_deadline.reset(token)
343
+ threading.Thread(target=copy_context().run, args=(run,), daemon=True).start()
344
+ pending[name] = (output, deadline)
345
+ while pending:
346
+ for name, (output, deadline) in list(pending.items()):
347
+ try:
348
+ status, value, error, duration = output.get_nowait()
349
+ except queue.Empty:
350
+ if time.monotonic() < deadline:
351
+ continue
352
+ status, value, error, duration = "timed_out", None, "Metric deadline exceeded", per_metric
353
+ finish(name, status, value, error, duration)
354
+ del pending[name]
355
+ if pending:
356
+ time.sleep(.01)
357
+ report["evaluation"]["duration_seconds"] = round(time.monotonic() - started, 3)
358
+ return report
359
+
360
+
361
+ def compute_ragas_retrieval_scores(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None):
362
+ """Compatibility mapping. Failed/skipped metrics remain None, never invented scores."""
363
+ report = compute_ragas_report(query, retrieved_contexts, ground_truth, answer, endpoint)
364
+ return {name: metric["value"] for name, metric in report["metrics"].items()}
365
+
366
+
367
+ def _create_ragas_embeddings():
368
+ """Return a lightweight embedding object compatible with RAGAS metrics.
369
+
370
+ Wraps the ChromaDB ONNX MiniLM embedding function so that metrics like
371
+ ``ResponseRelevancy`` can compute cosine similarity between embeddings.
372
+ The underlying ONNX model is cached globally and loads in <1 s.
373
+ """
374
+ if os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower() not in {"1", "true", "yes"}:
375
+ logger.info("Local RAGAS embeddings disabled; skipping answer relevancy")
376
+ return None
377
+ try:
378
+ from chromadb.utils import embedding_functions
379
+
380
+ if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):
381
+ ef = embedding_functions.ONNXMiniLM_L6_V2()
382
+ else:
383
+ ef = embedding_functions.SentenceTransformerEmbeddingFunction(
384
+ model_name="all-MiniLM-L6-v2"
385
+ )
386
+
387
+ class _RagasEmbeddings:
388
+ def __init__(self, ef):
389
+ self._ef = ef
390
+
391
+ def embed_query(self, text: str) -> list[float]:
392
+ result = self._ef([text])[0]
393
+ return list(result) if not isinstance(result, list) else result
394
+
395
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
396
+ results = self._ef(texts)
397
+ return [list(r) if not isinstance(r, list) else r for r in results]
398
+
399
+ return _RagasEmbeddings(ef)
400
+ except Exception as exc:
401
+ logger.warning("Cannot create RAGAS embeddings: %s", exc)
402
+ return None
403
+
404
+
405
+ def _compute_mmr(
406
+ query: str,
407
+ retrieved_contexts: list[str],
408
+ llm: Any,
409
+ ) -> float:
410
+ """Compute Mean Reciprocal Rank β€” how early the first relevant chunk appears.
411
+
412
+ Uses the LLM to judge each chunk's relevance to the query in order.
413
+ The first chunk judged relevant determines the reciprocal rank:
414
+ ``1 / rank_of_first_relevant``. Returns 0.0 if none are relevant.
415
+
416
+ Parameters
417
+ ----------
418
+ query : str
419
+ The search query (PR diff).
420
+ retrieved_contexts : list[str]
421
+ Ranked list of retrieved code chunks.
422
+ llm : LangchainLLMWrapper
423
+ RAGAS-wrapped LLM for relevance judgments.
424
+
425
+ Returns
426
+ -------
427
+ float
428
+ MMR score in [0, 1]; 0.0 when chunks were judged but none were
429
+ relevant.
430
+
431
+ Raises
432
+ ------
433
+ RuntimeError
434
+ If every relevance judgment failed (e.g. LLM rate-limited) β€”
435
+ callers treat this as a failed metric rather than a fake 0.0.
436
+ """
437
+ if not retrieved_contexts:
438
+ return 0.0
439
+
440
+ # Score up to the first 5 chunks for relevance using the LLM.
441
+ # Top-5 MMR is standard β€” rank 5 yields 1/5 = 0.20, and
442
+ # anything beyond rank 5 barely changes the score anyway.
443
+ MAX_MMR_RANK = 2
444
+ top_chunks = retrieved_contexts[:MAX_MMR_RANK]
445
+
446
+ judged = 0
447
+ for rank, chunk in enumerate(top_chunks, start=1):
448
+ try:
449
+ prompt = (
450
+ f"Is the following code/document chunk relevant to the question?\n\n"
451
+ f"Question: {query[:2_000]}\n\n"
452
+ f"Chunk: {chunk[:2_000]}\n\n"
453
+ f"Answer with exactly one word: YES or NO"
454
+ )
455
+ # Use the wrapped LangChain model for fast synchronous invoke.
456
+ # LangchainLLMWrapper stores the model as .langchain_llm in ragas
457
+ # 0.4.x and as .llm in 0.3.x β€” accept both.
458
+ langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
459
+ # Space the relevance judgments too β€” this unwrapped path bypasses
460
+ # the model wrapper on some ragas versions, so sleep explicitly
461
+ # (unless the wrapper is already in the path, to avoid double-sleep).
462
+ if not isinstance(langchain_model, _ThrottledChatModel):
463
+ time.sleep(_RAGAS_INTERVAL)
464
+ raw = langchain_model.invoke(prompt)
465
+ response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
466
+ if response_text.startswith("Y"):
467
+ return 1.0 / rank
468
+ judged += 1 # judge responded β€” chunk deemed not relevant
469
+ except Exception:
470
+ continue
471
+
472
+ if judged == 0:
473
+ # Every relevance judgment failed (e.g. LLM rate-limited) β€” surface
474
+ # this as a failed metric instead of a misleading 0.0.
475
+ raise RuntimeError("all MMR relevance judgments failed")
476
+
477
+ return 0.0
478
+
479
+
480
+ def log_ragas_scores_to_langfuse(
481
+ scores: dict[str, float | None],
482
+ repo: str = "",
483
+ pr_number: int = 0,
484
+ handler: Any = None,
485
+ ) -> None:
486
+ """Log RAGAS metrics as Langfuse scores (linked to the review trace).
487
+
488
+ Parameters
489
+ ----------
490
+ scores : dict
491
+ Output of :func:`compute_ragas_retrieval_scores`.
492
+ repo : str
493
+ GitHub repository name (e.g. ``\"psf/requests\"``).
494
+ pr_number : int
495
+ Pull request number.
496
+ handler : Langfuse CallbackHandler or None
497
+ Handler from the current review run, used to link scores to the trace.
498
+ """
499
+ try:
500
+ from observability import log_langfuse_score
501
+ except ImportError:
502
+ logger.debug("observability module not available β€” skipping Langfuse")
503
+ return
504
+
505
+ for metric_name, value in scores.items():
506
+ if value is None:
507
+ continue
508
+ log_langfuse_score(
509
+ name=f"ragas_{metric_name}",
510
+ value=value,
511
+ comment=f"{repo}#{pr_number} β€” {metric_name}",
512
+ handler=handler,
513
+ )
514
+
515
+
516
+ # ─── Standalone CLI ─────────────────────────────────────────────────────────
517
+
518
+
519
+ def main() -> None:
520
+ """CLI entry point: compute RAGAS scores from a JSONL dataset.
521
+
522
+ Usage::
523
+
524
+ python eval_data/ragas_eval.py --data eval_data/prs.jsonl
525
+ """
526
+ import argparse
527
+ import json
528
+
529
+ parser = argparse.ArgumentParser(
530
+ description="Compute RAGAS retrieval quality scores on evaluation data",
531
+ )
532
+ parser.add_argument(
533
+ "--data", default=None,
534
+ help="Path to JSONL dataset (same format as evaluate.py)",
535
+ )
536
+ parser.add_argument(
537
+ "--output", default=None,
538
+ help="Path to write per-PR RAGAS scores (JSON)",
539
+ )
540
+ parser.add_argument(
541
+ "--max-prs", type=int, default=None,
542
+ help="Max PRs to process",
543
+ )
544
+ parser.add_argument(
545
+ "--log-to-observability", action="store_true",
546
+ help="Log RAGAS scores to Langfuse",
547
+ )
548
+ args = parser.parse_args()
549
+
550
+ logging.basicConfig(
551
+ level=logging.INFO,
552
+ format="%(asctime)s [%(levelname)s] %(name)s β€” %(message)s",
553
+ )
554
+
555
+ if not args.data:
556
+ # If no data file specified, try default location
557
+ default_path = os.path.join(
558
+ os.path.dirname(__file__), "prs.jsonl"
559
+ )
560
+ if os.path.exists(default_path):
561
+ args.data = default_path
562
+ else:
563
+ logger.error(
564
+ "No --data provided and default not found at %s. "
565
+ "Run eval_data/fetcher.py first.",
566
+ default_path,
567
+ )
568
+ return
569
+
570
+ with open(args.data, "r", encoding="utf-8") as f:
571
+ entries = [json.loads(line) for line in f if line.strip()]
572
+
573
+ if args.max_prs:
574
+ entries = entries[: args.max_prs]
575
+
576
+ all_scores: list[dict] = []
577
+ for entry in entries:
578
+ repo = entry.get("repo", "?")
579
+ pr = entry.get("pr_number", 0)
580
+ diff = entry.get("diff", "")
581
+ ground_truth_list = entry.get("ground_truth", [])
582
+
583
+ # Use the diff as the query, and first few human comments
584
+ # as a proxy for "what the retrieval should have found"
585
+ query = diff[:8_000] if diff else entry.get("title", "")
586
+ gt_text = (
587
+ " ".join(
588
+ g.get("comment", "")
589
+ for g in ground_truth_list[:5]
590
+ )
591
+ if ground_truth_list
592
+ else None
593
+ )
594
+
595
+ # Retrieved contexts come from the graph run, but for the CLI
596
+ # we don't re-run the graph β€” we just skip if no retrieval data
597
+ # is available in the entry.
598
+ stored_contexts = entry.get("retrieved_contexts", [])
599
+ if not stored_contexts:
600
+ logger.info(
601
+ "[%s#%d] No stored retrieval contexts β€” skipping RAGAS",
602
+ repo, pr,
603
+ )
604
+ continue
605
+
606
+ logger.info("[%s#%d] Computing RAGAS scores …", repo, pr)
607
+ try:
608
+ scores = compute_ragas_retrieval_scores(
609
+ query=query,
610
+ retrieved_contexts=stored_contexts,
611
+ ground_truth=gt_text,
612
+ )
613
+ except RuntimeError as exc:
614
+ logger.warning("[%s#%d] %s", repo, pr, exc)
615
+ break
616
+
617
+ scores.update({"repo": repo, "pr_number": pr, "id": entry.get("id")})
618
+ all_scores.append(scores)
619
+
620
+ if args.log_to_observability:
621
+ log_ragas_scores_to_langfuse(scores, repo=repo, pr_number=pr)
622
+
623
+ print(
624
+ f" {repo}#{pr}: "
625
+ + " | ".join(
626
+ f"{k}={v:.3f}" for k, v in scores.items()
627
+ if k not in ("repo", "pr_number", "id") and v is not None
628
+ )
629
+ )
630
+
631
+ # Print aggregate
632
+ if all_scores:
633
+ print()
634
+ print("=" * 60)
635
+ print(" Aggregate RAGAS scores")
636
+ print("=" * 60)
637
+ metrics = [
638
+ k for k in all_scores[0].keys()
639
+ if k not in ("repo", "pr_number", "id")
640
+ ]
641
+ for metric in metrics:
642
+ values = [
643
+ s.get(metric) for s in all_scores
644
+ if s.get(metric) is not None
645
+ ]
646
+ if not values:
647
+ print(f" {metric:30s}: n/a (no successful scores)")
648
+ continue
649
+ avg = sum(values) / len(values)
650
+ print(f" {metric:30s}: {avg:.4f} (over {len(values)} PRs)")
651
+ print()
652
+
653
+ # Save output
654
+ if args.output and all_scores:
655
+ with open(args.output, "w", encoding="utf-8") as f:
656
+ json.dump(all_scores, f, indent=2)
657
+ logger.info("Saved RAGAS scores to %s", args.output)
658
+
659
+
660
+ if __name__ == "__main__":
661
+ main()