Sdm0 commited on
Commit
1530f02
Β·
verified Β·
1 Parent(s): 8d82c4a

Deploy 1c4d19b2

Browse files
Files changed (1) hide show
  1. eval_data/ragas_eval.py +713 -713
eval_data/ragas_eval.py CHANGED
@@ -1,713 +1,713 @@
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
- import logging
30
- import os
31
- import threading
32
- import time
33
- from typing import Any, Optional
34
-
35
- logger = logging.getLogger(__name__)
36
-
37
- # ─── Lazy RAGAS imports with graceful fallback ──────────────────────────────
38
-
39
- _RAGAS_AVAILABLE: bool | None = None
40
-
41
-
42
- def _check_ragas() -> bool:
43
- """Return True if RAGAS is available.
44
-
45
- Note: ``litellm`` is NOT required because RAGAS scoring uses the
46
- project's own LLM factory (Gemini or Groq via LangChain), not
47
- litellm internally.
48
- """
49
- global _RAGAS_AVAILABLE
50
- if _RAGAS_AVAILABLE is not None:
51
- return _RAGAS_AVAILABLE
52
- try:
53
- import ragas # noqa: F401
54
- _RAGAS_AVAILABLE = True
55
- except ImportError:
56
- logger.warning(
57
- "ragas not installed. Install with: pip install ragas"
58
- )
59
- _RAGAS_AVAILABLE = False
60
- return _RAGAS_AVAILABLE
61
-
62
-
63
- # Seconds to sleep before every RAGAS LLM call. RAGAS scoring fires a
64
- # burst of ~20-30 model calls per review (context-precision judgments,
65
- # faithfulness verification, answer relevancy, MMR relevance checks).
66
- # Spacing them keeps the burst under Groq/Gemini free-tier per-minute rate
67
- # limits so scoring completes instead of tripping 429s β€” which previously
68
- # caused long retry backoffs and 0.0000 scores. Override with the
69
- # OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
70
- _RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
71
- _ragas_throttle_lock = threading.Lock()
72
-
73
-
74
- class _ThrottledChatModel:
75
- """Wrap a LangChain chat model so every underlying API call RAGAS makes
76
- is spaced by a fixed interval.
77
-
78
- RAGAS's ``LangchainLLMWrapper`` (deprecated shim in 0.4.x, forwards to
79
- the langchain model) and the custom MMR path call the model through
80
- different entry points (sync/async, single/batched). Intercepting
81
- ``invoke`` / ``generate`` / ``ainvoke`` / ``agenerate`` here guarantees
82
- every request is throttled regardless of ragas version.
83
- """
84
-
85
- def __init__(self, model, interval: float | None = None):
86
- self._model = model
87
- self._interval = _RAGAS_INTERVAL if interval is None else interval
88
-
89
- def _wait(self) -> None:
90
- if self._interval > 0:
91
- with _ragas_throttle_lock:
92
- time.sleep(self._interval)
93
-
94
- # ── Sync entry points ───────────────────────────────────────────────
95
- def invoke(self, *args, **kwargs):
96
- self._wait()
97
- return self._model.invoke(*args, **kwargs)
98
-
99
- def generate(self, messages, *args, **kwargs):
100
- # Serialize LangChain batch calls into individual throttled
101
- # requests so every underlying API call is spaced by the interval.
102
- if (
103
- isinstance(messages, list)
104
- and messages
105
- and isinstance(messages[0], list)
106
- ):
107
- from langchain_core.outputs import Generation, LLMResult
108
-
109
- generations = []
110
- for msgs in messages:
111
- self._wait()
112
- # invoke() does not accept callbacks/run_manager/config that
113
- # ragas may forward to generate() β€” drop them here.
114
- resp = self._model.invoke(msgs)
115
- text = resp.content if hasattr(resp, "content") else str(resp)
116
- generations.append([Generation(text=text, message=resp)])
117
- return LLMResult(generations=generations, llm_output=None)
118
- self._wait()
119
- return self._model.generate(messages, *args, **kwargs)
120
-
121
- # ── Async entry points ──────────────────────────────────────────────
122
- async def ainvoke(self, *args, **kwargs):
123
- self._wait()
124
- return await self._model.ainvoke(*args, **kwargs)
125
-
126
- async def agenerate(self, messages, *args, **kwargs):
127
- if (
128
- isinstance(messages, list)
129
- and messages
130
- and isinstance(messages[0], list)
131
- ):
132
- from langchain_core.outputs import Generation, LLMResult
133
-
134
- generations = []
135
- for msgs in messages:
136
- self._wait()
137
- # Same kwargs caveat as generate(): ainvoke has no callbacks.
138
- resp = await self._model.ainvoke(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 await self._model.agenerate(messages, *args, **kwargs)
144
-
145
- # ── Everything else passes through ──────────────────────────────────
146
- def __getattr__(self, name: str):
147
- return getattr(self._model, name)
148
-
149
-
150
- def _get_evaluator_llm(endpoint: Optional[str] = None):
151
- """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
152
-
153
- Priority:
154
- 1. **Custom endpoint** β€” when *endpoint* names a configured
155
- ``OCR_ENDPOINT_*`` config, it is used (any provider the user added).
156
- 2. **Groq** (``llama-3.3-70b-versatile``) via ``GROQ_API_KEY``
157
- 3. **Google Gemini** (``gemini-3.1-flash-lite``) via ``GEMINI_API_KEY``
158
-
159
- Groq is preferred over Gemini because scoring fires many LLM calls per
160
- review and the Gemini free tier (15 req/min) is already shared with the
161
- main review pipeline β€” using Groq's separate quota pool avoids the 429
162
- rate-limit failures that used to zero out the metrics.
163
-
164
- RAGAS v0.3+ uses ``LangchainLLMWrapper`` to wrap LangChain models.
165
- """
166
- from ragas.llms import LangchainLLMWrapper
167
-
168
- try:
169
- if endpoint:
170
- from llm_factory import create_llm
171
-
172
- llm = create_llm(endpoint=endpoint, temperature=0)
173
- logger.info("RAGAS evaluator: using custom endpoint %s", endpoint)
174
- return LangchainLLMWrapper(_ThrottledChatModel(llm))
175
-
176
- from llm_factory import _get_groq_chat, _get_gemini_chat
177
-
178
- # Keep evaluation bounded: RAGAS runs several provider calls and
179
- # retrying each one can otherwise hold a review open for minutes.
180
- configured_model = os.getenv("RAGAS_MODEL", "").strip()
181
- if configured_model.startswith("groq/"):
182
- configured_model = configured_model.split("/", 1)[1]
183
- groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout": 15}
184
- if configured_model:
185
- groq_kwargs["model"] = configured_model
186
- llm = _get_groq_chat(**groq_kwargs)
187
- if llm is None:
188
- logger.info(
189
- "RAGAS evaluator: GROQ_API_KEY not set β€” falling back to Gemini"
190
- )
191
- llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=15)
192
- if llm is None:
193
- raise ValueError(
194
- "No LLM available for RAGAS scoring. "
195
- "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
196
- )
197
- logger.info(
198
- "RAGAS evaluator: using %s (throttled %ss)",
199
- type(llm).__name__,
200
- _RAGAS_INTERVAL,
201
- )
202
- return LangchainLLMWrapper(_ThrottledChatModel(llm))
203
- except ValueError as exc:
204
- logger.warning("RAGAS evaluator: %s", exc)
205
- raise RuntimeError(
206
- "No LLM available for RAGAS scoring. "
207
- "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
208
- ) from exc
209
-
210
-
211
- # ─── Score computation ─────────────────────────────────────────────────────
212
-
213
-
214
- def compute_ragas_retrieval_scores(
215
- query: str,
216
- retrieved_contexts: list[str],
217
- ground_truth: Optional[str] = None,
218
- answer: Optional[str] = None,
219
- endpoint: Optional[str] = None,
220
- ) -> dict[str, float | None]:
221
- """Compute RAGAS retrieval & generation quality metrics.
222
-
223
- Computes up to five metrics depending on available inputs:
224
-
225
- +---------------------------+------------------------------------------+
226
- | Metric | Required inputs |
227
- +===========================+==========================================+
228
- | ``context_precision`` | query, retrieved_contexts |
229
- | ``context_recall`` | query, retrieved_contexts, ground_truth |
230
- | ``faithfulness`` | query, retrieved_contexts, answer |
231
- | ``answer_relevancy`` | query, answer |
232
- | ``mmr`` (Mean Reciprocal | query, retrieved_contexts |
233
- | Rank) | (custom LLM-judged) |
234
- +---------------------------+------------------------------------------+
235
-
236
- Parameters
237
- ----------
238
- query : str
239
- The search query β€” in OpenCodeReview this is the PR diff text.
240
- retrieved_contexts : list[str]
241
- The code/document chunks returned by the retrieval node.
242
- ground_truth : str or None
243
- Ground-truth reference text (e.g. human review comment). Required
244
- for ``context_recall``.
245
- answer : str or None
246
- The generated answer (e.g. concatenated review findings / verdict).
247
- Required for ``faithfulness`` and ``answer_relevancy``.
248
- endpoint : str or None
249
- Optional name of a configured custom LLM endpoint
250
- (``OCR_ENDPOINT_*``) to score with. ``None`` uses the built-in
251
- Groq β†’ Gemini priority.
252
-
253
- Returns
254
- -------
255
- dict
256
- Mapping of metric name β†’ score (0–1 range, higher is better),
257
- or ``None`` when that metric's computation failed (e.g. LLM
258
- rate limit / error). Possible keys: ``context_precision``,
259
- ``context_recall``, ``faithfulness``, ``answer_relevancy``,
260
- ``mmr``.
261
-
262
- Raises
263
- ------
264
- RuntimeError
265
- If RAGAS or a suitable LLM backend is not available.
266
- """
267
- if not _check_ragas():
268
- raise RuntimeError(
269
- "RAGAS is not installed. Run: pip install ragas litellm"
270
- )
271
-
272
- if not retrieved_contexts:
273
- logger.warning("No retrieved contexts β€” RAGAS scores set to 0.0")
274
- result: dict[str, float] = {"context_precision": 0.0, "mmr": 0.0}
275
- if ground_truth:
276
- result["context_recall"] = 0.0
277
- if answer:
278
- result["faithfulness"] = 0.0
279
- result["answer_relevancy"] = 0.0
280
- return result
281
-
282
- from ragas.dataset_schema import SingleTurnSample
283
-
284
- llm = _get_evaluator_llm(endpoint=endpoint)
285
- scores: dict[str, float | None] = {}
286
-
287
- # ── Context Precision (reference-free) ───────────────────────────
288
- # Uses LLMContextPrecisionWithoutReference which needs user_input +
289
- # response + retrieved_contexts (no ground-truth reference required).
290
- if answer:
291
- try:
292
- from ragas.metrics import LLMContextPrecisionWithoutReference
293
-
294
- scorer = LLMContextPrecisionWithoutReference(llm=llm)
295
- sample = SingleTurnSample(
296
- user_input=query,
297
- response=answer,
298
- retrieved_contexts=retrieved_contexts,
299
- )
300
- result = scorer.single_turn_score(sample)
301
- scores["context_precision"] = round(float(result), 4)
302
- logger.info("RAGAS context_precision: %.4f", scores["context_precision"])
303
- except Exception as exc:
304
- logger.warning("RAGAS context_precision failed: %s", exc)
305
- scores["context_precision"] = None
306
-
307
- # ── Context Recall (requires ground_truth) ───────────────────────
308
- if ground_truth:
309
- try:
310
- from ragas.metrics import ContextRecall
311
-
312
- recall_scorer = ContextRecall(llm=llm)
313
- recall_sample = SingleTurnSample(
314
- user_input=query,
315
- retrieved_contexts=retrieved_contexts,
316
- reference=ground_truth,
317
- )
318
- recall_result = recall_scorer.single_turn_score(recall_sample)
319
- scores["context_recall"] = round(float(recall_result), 4)
320
- logger.info("RAGAS context_recall: %.4f", scores["context_recall"])
321
- except Exception as exc:
322
- logger.warning("RAGAS context_recall failed: %s", exc)
323
- scores["context_recall"] = None
324
-
325
- # ── Faithfulness ─────────────────────────────────────────────────
326
- if answer:
327
- try:
328
- from ragas.metrics import Faithfulness
329
-
330
- faithfulness_scorer = Faithfulness(llm=llm)
331
- faithful_sample = SingleTurnSample(
332
- user_input=query,
333
- response=answer,
334
- retrieved_contexts=retrieved_contexts,
335
- )
336
- faithful_result = faithfulness_scorer.single_turn_score(faithful_sample)
337
- scores["faithfulness"] = round(float(faithful_result), 4)
338
- logger.info("RAGAS faithfulness: %.4f", scores["faithfulness"])
339
- except Exception as exc:
340
- logger.warning("RAGAS faithfulness failed: %s", exc)
341
- scores["faithfulness"] = None
342
-
343
- # ── Answer Relevancy (ResponseRelevancy) ─────────────────────────
344
- if answer:
345
- try:
346
- from ragas.metrics import ResponseRelevancy
347
-
348
- # ResponseRelevancy also needs an embedding model for cosine
349
- # similarity. We create a lightweight one from the project's
350
- # ChromaDB embedding function (ONNX MiniLM, already cached).
351
- embeddings = _create_ragas_embeddings()
352
- if embeddings is None:
353
- raise RuntimeError(
354
- "No embedding model available for ResponseRelevancy β€” "
355
- "install chromadb"
356
- )
357
-
358
- relevancy_scorer = ResponseRelevancy(
359
- llm=llm,
360
- embeddings=embeddings,
361
- strictness=1, # Groq only supports n=1
362
- )
363
- relevancy_sample = SingleTurnSample(
364
- user_input=query,
365
- response=answer,
366
- )
367
- relevancy_result = relevancy_scorer.single_turn_score(relevancy_sample)
368
- scores["answer_relevancy"] = round(float(relevancy_result), 4)
369
- logger.info("RAGAS answer_relevancy: %.4f", scores["answer_relevancy"])
370
- except Exception as exc:
371
- logger.warning("RAGAS answer_relevancy failed: %s", exc)
372
- scores["answer_relevancy"] = None
373
-
374
- # ── MMR (Mean Reciprocal Rank) β€” custom implementation ───────────
375
- try:
376
- mmr = _compute_mmr(query, retrieved_contexts, llm)
377
- scores["mmr"] = round(mmr, 4)
378
- logger.info("RAGAS mmr: %.4f", scores["mmr"])
379
- except Exception as exc:
380
- logger.warning("RAGAS mmr failed: %s", exc)
381
- scores["mmr"] = None
382
-
383
- # ── Context Precision (reference-based, fallback when no answer) ─
384
- if "context_precision" not in scores and ground_truth:
385
- try:
386
- from ragas.metrics import ContextPrecision
387
-
388
- scorer = ContextPrecision(llm=llm)
389
- sample = SingleTurnSample(
390
- user_input=query,
391
- retrieved_contexts=retrieved_contexts,
392
- reference=ground_truth,
393
- )
394
- result = scorer.single_turn_score(sample)
395
- scores["context_precision"] = round(float(result), 4)
396
- logger.info("RAGAS context_precision: %.4f", scores["context_precision"])
397
- except Exception as exc:
398
- logger.warning("RAGAS context_precision failed: %s", exc)
399
- scores["context_precision"] = None
400
-
401
- # Deterministic fallback: retrieval-only reviews may not have an answer or
402
- # reference, and provider-backed judges can fail or rate-limit. Preserve a
403
- # truthful numeric signal from lexical query/context coverage instead of
404
- # returning an empty score map.
405
- if not any(value is not None for value in scores.values()):
406
- query_terms = {term.lower() for term in query.split() if len(term) >= 4}
407
- overlaps = []
408
- for context in retrieved_contexts:
409
- context_terms = {term.lower() for term in context.split() if len(term) >= 4}
410
- overlaps.append(len(query_terms & context_terms) / max(1, len(query_terms)))
411
- coverage = round(sum(overlaps) / max(1, len(overlaps)), 4)
412
- first_relevant = next((index for index, value in enumerate(overlaps, 1) if value > 0), None)
413
- scores["context_precision"] = coverage
414
- scores["mmr"] = round(1 / first_relevant, 4) if first_relevant else 0.0
415
- logger.info("RAGAS deterministic fallback: context_precision=%.4f mmr=%.4f", scores["context_precision"], scores["mmr"])
416
- return scores
417
-
418
-
419
- def _create_ragas_embeddings():
420
- """Return a lightweight embedding object compatible with RAGAS metrics.
421
-
422
- Wraps the ChromaDB ONNX MiniLM embedding function so that metrics like
423
- ``ResponseRelevancy`` can compute cosine similarity between embeddings.
424
- The underlying ONNX model is cached globally and loads in <1 s.
425
- """
426
- if os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower() not in {"1", "true", "yes"}:
427
- logger.info("Local RAGAS embeddings disabled; skipping answer relevancy")
428
- return None
429
- try:
430
- from chromadb.utils import embedding_functions
431
-
432
- if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):
433
- ef = embedding_functions.ONNXMiniLM_L6_V2()
434
- else:
435
- ef = embedding_functions.SentenceTransformerEmbeddingFunction(
436
- model_name="all-MiniLM-L6-v2"
437
- )
438
-
439
- class _RagasEmbeddings:
440
- def __init__(self, ef):
441
- self._ef = ef
442
-
443
- def embed_query(self, text: str) -> list[float]:
444
- result = self._ef([text])[0]
445
- return list(result) if not isinstance(result, list) else result
446
-
447
- def embed_documents(self, texts: list[str]) -> list[list[float]]:
448
- results = self._ef(texts)
449
- return [list(r) if not isinstance(r, list) else r for r in results]
450
-
451
- return _RagasEmbeddings(ef)
452
- except Exception as exc:
453
- logger.warning("Cannot create RAGAS embeddings: %s", exc)
454
- return None
455
-
456
-
457
- def _compute_mmr(
458
- query: str,
459
- retrieved_contexts: list[str],
460
- llm: Any,
461
- ) -> float:
462
- """Compute Mean Reciprocal Rank β€” how early the first relevant chunk appears.
463
-
464
- Uses the LLM to judge each chunk's relevance to the query in order.
465
- The first chunk judged relevant determines the reciprocal rank:
466
- ``1 / rank_of_first_relevant``. Returns 0.0 if none are relevant.
467
-
468
- Parameters
469
- ----------
470
- query : str
471
- The search query (PR diff).
472
- retrieved_contexts : list[str]
473
- Ranked list of retrieved code chunks.
474
- llm : LangchainLLMWrapper
475
- RAGAS-wrapped LLM for relevance judgments.
476
-
477
- Returns
478
- -------
479
- float
480
- MMR score in [0, 1]; 0.0 when chunks were judged but none were
481
- relevant.
482
-
483
- Raises
484
- ------
485
- RuntimeError
486
- If every relevance judgment failed (e.g. LLM rate-limited) β€”
487
- callers treat this as a failed metric rather than a fake 0.0.
488
- """
489
- if not retrieved_contexts:
490
- return 0.0
491
-
492
- # Score up to the first 5 chunks for relevance using the LLM.
493
- # Top-5 MMR is standard β€” rank 5 yields 1/5 = 0.20, and
494
- # anything beyond rank 5 barely changes the score anyway.
495
- MAX_MMR_RANK = 2
496
- top_chunks = retrieved_contexts[:MAX_MMR_RANK]
497
-
498
- judged = 0
499
- for rank, chunk in enumerate(top_chunks, start=1):
500
- try:
501
- prompt = (
502
- f"Is the following code/document chunk relevant to the question?\n\n"
503
- f"Question: {query[:2_000]}\n\n"
504
- f"Chunk: {chunk[:2_000]}\n\n"
505
- f"Answer with exactly one word: YES or NO"
506
- )
507
- # Use the wrapped LangChain model for fast synchronous invoke.
508
- # LangchainLLMWrapper stores the model as .langchain_llm in ragas
509
- # 0.4.x and as .llm in 0.3.x β€” accept both.
510
- langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
511
- # Space the relevance judgments too β€” this unwrapped path bypasses
512
- # the model wrapper on some ragas versions, so sleep explicitly
513
- # (unless the wrapper is already in the path, to avoid double-sleep).
514
- if not isinstance(langchain_model, _ThrottledChatModel):
515
- time.sleep(_RAGAS_INTERVAL)
516
- raw = langchain_model.invoke(prompt)
517
- response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
518
- if response_text.startswith("Y"):
519
- return 1.0 / rank
520
- judged += 1 # judge responded β€” chunk deemed not relevant
521
- except Exception:
522
- continue
523
-
524
- if judged == 0:
525
- # Every relevance judgment failed (e.g. LLM rate-limited) β€” surface
526
- # this as a failed metric instead of a misleading 0.0.
527
- raise RuntimeError("all MMR relevance judgments failed")
528
-
529
- return 0.0
530
-
531
-
532
- def log_ragas_scores_to_langfuse(
533
- scores: dict[str, float | None],
534
- repo: str = "",
535
- pr_number: int = 0,
536
- handler: Any = None,
537
- ) -> None:
538
- """Log RAGAS metrics as Langfuse scores (linked to the review trace).
539
-
540
- Parameters
541
- ----------
542
- scores : dict
543
- Output of :func:`compute_ragas_retrieval_scores`.
544
- repo : str
545
- GitHub repository name (e.g. ``\"psf/requests\"``).
546
- pr_number : int
547
- Pull request number.
548
- handler : Langfuse CallbackHandler or None
549
- Handler from the current review run, used to link scores to the trace.
550
- """
551
- try:
552
- from observability import log_langfuse_score
553
- except ImportError:
554
- logger.debug("observability module not available β€” skipping Langfuse")
555
- return
556
-
557
- for metric_name, value in scores.items():
558
- if value is None:
559
- continue
560
- log_langfuse_score(
561
- name=f"ragas_{metric_name}",
562
- value=value,
563
- comment=f"{repo}#{pr_number} β€” {metric_name}",
564
- handler=handler,
565
- )
566
-
567
-
568
- # ─── Standalone CLI ─────────────────────────────────────────────────────────
569
-
570
-
571
- def main() -> None:
572
- """CLI entry point: compute RAGAS scores from a JSONL dataset.
573
-
574
- Usage::
575
-
576
- python eval_data/ragas_eval.py --data eval_data/prs.jsonl
577
- """
578
- import argparse
579
- import json
580
-
581
- parser = argparse.ArgumentParser(
582
- description="Compute RAGAS retrieval quality scores on evaluation data",
583
- )
584
- parser.add_argument(
585
- "--data", default=None,
586
- help="Path to JSONL dataset (same format as evaluate.py)",
587
- )
588
- parser.add_argument(
589
- "--output", default=None,
590
- help="Path to write per-PR RAGAS scores (JSON)",
591
- )
592
- parser.add_argument(
593
- "--max-prs", type=int, default=None,
594
- help="Max PRs to process",
595
- )
596
- parser.add_argument(
597
- "--log-to-observability", action="store_true",
598
- help="Log RAGAS scores to Langfuse",
599
- )
600
- args = parser.parse_args()
601
-
602
- logging.basicConfig(
603
- level=logging.INFO,
604
- format="%(asctime)s [%(levelname)s] %(name)s β€” %(message)s",
605
- )
606
-
607
- if not args.data:
608
- # If no data file specified, try default location
609
- default_path = os.path.join(
610
- os.path.dirname(__file__), "prs.jsonl"
611
- )
612
- if os.path.exists(default_path):
613
- args.data = default_path
614
- else:
615
- logger.error(
616
- "No --data provided and default not found at %s. "
617
- "Run eval_data/fetcher.py first.",
618
- default_path,
619
- )
620
- return
621
-
622
- with open(args.data, "r", encoding="utf-8") as f:
623
- entries = [json.loads(line) for line in f if line.strip()]
624
-
625
- if args.max_prs:
626
- entries = entries[: args.max_prs]
627
-
628
- all_scores: list[dict] = []
629
- for entry in entries:
630
- repo = entry.get("repo", "?")
631
- pr = entry.get("pr_number", 0)
632
- diff = entry.get("diff", "")
633
- ground_truth_list = entry.get("ground_truth", [])
634
-
635
- # Use the diff as the query, and first few human comments
636
- # as a proxy for "what the retrieval should have found"
637
- query = diff[:8_000] if diff else entry.get("title", "")
638
- gt_text = (
639
- " ".join(
640
- g.get("comment", "")
641
- for g in ground_truth_list[:5]
642
- )
643
- if ground_truth_list
644
- else None
645
- )
646
-
647
- # Retrieved contexts come from the graph run, but for the CLI
648
- # we don't re-run the graph β€” we just skip if no retrieval data
649
- # is available in the entry.
650
- stored_contexts = entry.get("retrieved_contexts", [])
651
- if not stored_contexts:
652
- logger.info(
653
- "[%s#%d] No stored retrieval contexts β€” skipping RAGAS",
654
- repo, pr,
655
- )
656
- continue
657
-
658
- logger.info("[%s#%d] Computing RAGAS scores …", repo, pr)
659
- try:
660
- scores = compute_ragas_retrieval_scores(
661
- query=query,
662
- retrieved_contexts=stored_contexts,
663
- ground_truth=gt_text,
664
- )
665
- except RuntimeError as exc:
666
- logger.warning("[%s#%d] %s", repo, pr, exc)
667
- break
668
-
669
- scores.update({"repo": repo, "pr_number": pr, "id": entry.get("id")})
670
- all_scores.append(scores)
671
-
672
- if args.log_to_observability:
673
- log_ragas_scores_to_langfuse(scores, repo=repo, pr_number=pr)
674
-
675
- print(
676
- f" {repo}#{pr}: "
677
- + " | ".join(
678
- f"{k}={v:.3f}" for k, v in scores.items()
679
- if k not in ("repo", "pr_number", "id") and v is not None
680
- )
681
- )
682
-
683
- # Print aggregate
684
- if all_scores:
685
- print()
686
- print("=" * 60)
687
- print(" Aggregate RAGAS scores")
688
- print("=" * 60)
689
- metrics = [
690
- k for k in all_scores[0].keys()
691
- if k not in ("repo", "pr_number", "id")
692
- ]
693
- for metric in metrics:
694
- values = [
695
- s.get(metric) for s in all_scores
696
- if s.get(metric) is not None
697
- ]
698
- if not values:
699
- print(f" {metric:30s}: n/a (no successful scores)")
700
- continue
701
- avg = sum(values) / len(values)
702
- print(f" {metric:30s}: {avg:.4f} (over {len(values)} PRs)")
703
- print()
704
-
705
- # Save output
706
- if args.output and all_scores:
707
- with open(args.output, "w", encoding="utf-8") as f:
708
- json.dump(all_scores, f, indent=2)
709
- logger.info("Saved RAGAS scores to %s", args.output)
710
-
711
-
712
- if __name__ == "__main__":
713
- 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
+ import logging
30
+ import os
31
+ import threading
32
+ import time
33
+ from typing import Any, Optional
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ # ─── Lazy RAGAS imports with graceful fallback ──────────────────────────────
38
+
39
+ _RAGAS_AVAILABLE: bool | None = None
40
+
41
+
42
+ def _check_ragas() -> bool:
43
+ """Return True if RAGAS is available.
44
+
45
+ Note: ``litellm`` is NOT required because RAGAS scoring uses the
46
+ project's own LLM factory (Gemini or Groq via LangChain), not
47
+ litellm internally.
48
+ """
49
+ global _RAGAS_AVAILABLE
50
+ if _RAGAS_AVAILABLE is not None:
51
+ return _RAGAS_AVAILABLE
52
+ try:
53
+ import ragas # noqa: F401
54
+ _RAGAS_AVAILABLE = True
55
+ except ImportError:
56
+ logger.warning(
57
+ "ragas not installed. Install with: pip install ragas"
58
+ )
59
+ _RAGAS_AVAILABLE = False
60
+ return _RAGAS_AVAILABLE
61
+
62
+
63
+ # Seconds to sleep before every RAGAS LLM call. RAGAS scoring fires a
64
+ # burst of ~20-30 model calls per review (context-precision judgments,
65
+ # faithfulness verification, answer relevancy, MMR relevance checks).
66
+ # Spacing them keeps the burst under Groq/Gemini free-tier per-minute rate
67
+ # limits so scoring completes instead of tripping 429s β€” which previously
68
+ # caused long retry backoffs and 0.0000 scores. Override with the
69
+ # OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
70
+ _RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
71
+ _ragas_throttle_lock = threading.Lock()
72
+
73
+
74
+ class _ThrottledChatModel:
75
+ """Wrap a LangChain chat model so every underlying API call RAGAS makes
76
+ is spaced by a fixed interval.
77
+
78
+ RAGAS's ``LangchainLLMWrapper`` (deprecated shim in 0.4.x, forwards to
79
+ the langchain model) and the custom MMR path call the model through
80
+ different entry points (sync/async, single/batched). Intercepting
81
+ ``invoke`` / ``generate`` / ``ainvoke`` / ``agenerate`` here guarantees
82
+ every request is throttled regardless of ragas version.
83
+ """
84
+
85
+ def __init__(self, model, interval: float | None = None):
86
+ self._model = model
87
+ self._interval = _RAGAS_INTERVAL if interval is None else interval
88
+
89
+ def _wait(self) -> None:
90
+ if self._interval > 0:
91
+ with _ragas_throttle_lock:
92
+ time.sleep(self._interval)
93
+
94
+ # ── Sync entry points ───────────────────────────────────────────────
95
+ def invoke(self, *args, **kwargs):
96
+ self._wait()
97
+ return self._model.invoke(*args, **kwargs)
98
+
99
+ def generate(self, messages, *args, **kwargs):
100
+ # Serialize LangChain batch calls into individual throttled
101
+ # requests so every underlying API call is spaced by the interval.
102
+ if (
103
+ isinstance(messages, list)
104
+ and messages
105
+ and isinstance(messages[0], list)
106
+ ):
107
+ from langchain_core.outputs import Generation, LLMResult
108
+
109
+ generations = []
110
+ for msgs in messages:
111
+ self._wait()
112
+ # invoke() does not accept callbacks/run_manager/config that
113
+ # ragas may forward to generate() β€” drop them here.
114
+ resp = self._model.invoke(msgs)
115
+ text = resp.content if hasattr(resp, "content") else str(resp)
116
+ generations.append([Generation(text=text, message=resp)])
117
+ return LLMResult(generations=generations, llm_output=None)
118
+ self._wait()
119
+ return self._model.generate(messages, *args, **kwargs)
120
+
121
+ # ── Async entry points ──────────────────────────────────────────────
122
+ async def ainvoke(self, *args, **kwargs):
123
+ self._wait()
124
+ return await self._model.ainvoke(*args, **kwargs)
125
+
126
+ async def agenerate(self, messages, *args, **kwargs):
127
+ if (
128
+ isinstance(messages, list)
129
+ and messages
130
+ and isinstance(messages[0], list)
131
+ ):
132
+ from langchain_core.outputs import Generation, LLMResult
133
+
134
+ generations = []
135
+ for msgs in messages:
136
+ self._wait()
137
+ # Same kwargs caveat as generate(): ainvoke has no callbacks.
138
+ resp = await self._model.ainvoke(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 await self._model.agenerate(messages, *args, **kwargs)
144
+
145
+ # ── Everything else passes through ──────────────────────────────────
146
+ def __getattr__(self, name: str):
147
+ return getattr(self._model, name)
148
+
149
+
150
+ def _get_evaluator_llm(endpoint: Optional[str] = None):
151
+ """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
152
+
153
+ Priority:
154
+ 1. **Custom endpoint** β€” when *endpoint* names a configured
155
+ ``OCR_ENDPOINT_*`` config, it is used (any provider the user added).
156
+ 2. **Groq** (``llama-3.3-70b-versatile``) via ``GROQ_API_KEY``
157
+ 3. **Google Gemini** (``gemini-3.1-flash-lite``) via ``GEMINI_API_KEY``
158
+
159
+ Groq is preferred over Gemini because scoring fires many LLM calls per
160
+ review and the Gemini free tier (15 req/min) is already shared with the
161
+ main review pipeline β€” using Groq's separate quota pool avoids the 429
162
+ rate-limit failures that used to zero out the metrics.
163
+
164
+ RAGAS v0.3+ uses ``LangchainLLMWrapper`` to wrap LangChain models.
165
+ """
166
+ from ragas.llms import LangchainLLMWrapper
167
+
168
+ try:
169
+ if endpoint:
170
+ from llm_factory import create_llm
171
+
172
+ llm = create_llm(endpoint=endpoint, temperature=0)
173
+ logger.info("RAGAS evaluator: using custom endpoint %s", endpoint)
174
+ return LangchainLLMWrapper(_ThrottledChatModel(llm))
175
+
176
+ from llm_factory import _get_groq_chat, _get_gemini_chat
177
+
178
+ # Keep evaluation bounded: RAGAS runs several provider calls and
179
+ # retrying each one can otherwise hold a review open for minutes.
180
+ configured_model = os.getenv("RAGAS_MODEL", "").strip()
181
+ if configured_model.startswith("groq/"):
182
+ configured_model = configured_model.split("/", 1)[1]
183
+ groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout": 15}
184
+ if configured_model:
185
+ groq_kwargs["model"] = configured_model
186
+ llm = _get_groq_chat(**groq_kwargs)
187
+ if llm is None:
188
+ logger.info(
189
+ "RAGAS evaluator: GROQ_API_KEY not set β€” falling back to Gemini"
190
+ )
191
+ llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=15)
192
+ if llm is None:
193
+ raise ValueError(
194
+ "No LLM available for RAGAS scoring. "
195
+ "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
196
+ )
197
+ logger.info(
198
+ "RAGAS evaluator: using %s (throttled %ss)",
199
+ type(llm).__name__,
200
+ _RAGAS_INTERVAL,
201
+ )
202
+ return LangchainLLMWrapper(_ThrottledChatModel(llm))
203
+ except ValueError as exc:
204
+ logger.warning("RAGAS evaluator: %s", exc)
205
+ raise RuntimeError(
206
+ "No LLM available for RAGAS scoring. "
207
+ "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
208
+ ) from exc
209
+
210
+
211
+ # ─── Score computation ─────────────────────────────────────────────────────
212
+
213
+
214
+ def compute_ragas_retrieval_scores(
215
+ query: str,
216
+ retrieved_contexts: list[str],
217
+ ground_truth: Optional[str] = None,
218
+ answer: Optional[str] = None,
219
+ endpoint: Optional[str] = None,
220
+ ) -> dict[str, float | None]:
221
+ """Compute RAGAS retrieval & generation quality metrics.
222
+
223
+ Computes up to five metrics depending on available inputs:
224
+
225
+ +---------------------------+------------------------------------------+
226
+ | Metric | Required inputs |
227
+ +===========================+==========================================+
228
+ | ``context_precision`` | query, retrieved_contexts |
229
+ | ``context_recall`` | query, retrieved_contexts, ground_truth |
230
+ | ``faithfulness`` | query, retrieved_contexts, answer |
231
+ | ``answer_relevancy`` | query, answer |
232
+ | ``mmr`` (Mean Reciprocal | query, retrieved_contexts |
233
+ | Rank) | (custom LLM-judged) |
234
+ +---------------------------+------------------------------------------+
235
+
236
+ Parameters
237
+ ----------
238
+ query : str
239
+ The search query β€” in OpenCodeReview this is the PR diff text.
240
+ retrieved_contexts : list[str]
241
+ The code/document chunks returned by the retrieval node.
242
+ ground_truth : str or None
243
+ Ground-truth reference text (e.g. human review comment). Required
244
+ for ``context_recall``.
245
+ answer : str or None
246
+ The generated answer (e.g. concatenated review findings / verdict).
247
+ Required for ``faithfulness`` and ``answer_relevancy``.
248
+ endpoint : str or None
249
+ Optional name of a configured custom LLM endpoint
250
+ (``OCR_ENDPOINT_*``) to score with. ``None`` uses the built-in
251
+ Groq β†’ Gemini priority.
252
+
253
+ Returns
254
+ -------
255
+ dict
256
+ Mapping of metric name β†’ score (0–1 range, higher is better),
257
+ or ``None`` when that metric's computation failed (e.g. LLM
258
+ rate limit / error). Possible keys: ``context_precision``,
259
+ ``context_recall``, ``faithfulness``, ``answer_relevancy``,
260
+ ``mmr``.
261
+
262
+ Raises
263
+ ------
264
+ RuntimeError
265
+ If RAGAS or a suitable LLM backend is not available.
266
+ """
267
+ if not _check_ragas():
268
+ raise RuntimeError(
269
+ "RAGAS is not installed. Run: pip install ragas litellm"
270
+ )
271
+
272
+ if not retrieved_contexts:
273
+ logger.warning("No retrieved contexts β€” RAGAS scores set to 0.0")
274
+ result: dict[str, float] = {"context_precision": 0.0, "mmr": 0.0}
275
+ if ground_truth:
276
+ result["context_recall"] = 0.0
277
+ if answer:
278
+ result["faithfulness"] = 0.0
279
+ result["answer_relevancy"] = 0.0
280
+ return result
281
+
282
+ from ragas.dataset_schema import SingleTurnSample
283
+
284
+ llm = _get_evaluator_llm(endpoint=endpoint)
285
+ scores: dict[str, float | None] = {}
286
+
287
+ # ── Context Precision (reference-free) ───────────────────────────
288
+ # Uses LLMContextPrecisionWithoutReference which needs user_input +
289
+ # response + retrieved_contexts (no ground-truth reference required).
290
+ if answer:
291
+ try:
292
+ from ragas.metrics import LLMContextPrecisionWithoutReference
293
+
294
+ scorer = LLMContextPrecisionWithoutReference(llm=llm)
295
+ sample = SingleTurnSample(
296
+ user_input=query,
297
+ response=answer,
298
+ retrieved_contexts=retrieved_contexts,
299
+ )
300
+ result = scorer.single_turn_score(sample)
301
+ scores["context_precision"] = round(float(result), 4)
302
+ logger.info("RAGAS context_precision: %.4f", scores["context_precision"])
303
+ except Exception as exc:
304
+ logger.warning("RAGAS context_precision failed: %s", exc)
305
+ scores["context_precision"] = None
306
+
307
+ # ── Context Recall (requires ground_truth) ───────────────────────
308
+ if ground_truth:
309
+ try:
310
+ from ragas.metrics import ContextRecall
311
+
312
+ recall_scorer = ContextRecall(llm=llm)
313
+ recall_sample = SingleTurnSample(
314
+ user_input=query,
315
+ retrieved_contexts=retrieved_contexts,
316
+ reference=ground_truth,
317
+ )
318
+ recall_result = recall_scorer.single_turn_score(recall_sample)
319
+ scores["context_recall"] = round(float(recall_result), 4)
320
+ logger.info("RAGAS context_recall: %.4f", scores["context_recall"])
321
+ except Exception as exc:
322
+ logger.warning("RAGAS context_recall failed: %s", exc)
323
+ scores["context_recall"] = None
324
+
325
+ # ── Faithfulness ─────────────────────────────────────────────────
326
+ if answer:
327
+ try:
328
+ from ragas.metrics import Faithfulness
329
+
330
+ faithfulness_scorer = Faithfulness(llm=llm)
331
+ faithful_sample = SingleTurnSample(
332
+ user_input=query,
333
+ response=answer,
334
+ retrieved_contexts=retrieved_contexts,
335
+ )
336
+ faithful_result = faithfulness_scorer.single_turn_score(faithful_sample)
337
+ scores["faithfulness"] = round(float(faithful_result), 4)
338
+ logger.info("RAGAS faithfulness: %.4f", scores["faithfulness"])
339
+ except Exception as exc:
340
+ logger.warning("RAGAS faithfulness failed: %s", exc)
341
+ scores["faithfulness"] = None
342
+
343
+ # ── Answer Relevancy (ResponseRelevancy) ─────────────────────────
344
+ if answer:
345
+ try:
346
+ from ragas.metrics import ResponseRelevancy
347
+
348
+ # ResponseRelevancy also needs an embedding model for cosine
349
+ # similarity. We create a lightweight one from the project's
350
+ # ChromaDB embedding function (ONNX MiniLM, already cached).
351
+ embeddings = _create_ragas_embeddings()
352
+ if embeddings is None:
353
+ raise RuntimeError(
354
+ "No embedding model available for ResponseRelevancy β€” "
355
+ "install chromadb"
356
+ )
357
+
358
+ relevancy_scorer = ResponseRelevancy(
359
+ llm=llm,
360
+ embeddings=embeddings,
361
+ strictness=1, # Groq only supports n=1
362
+ )
363
+ relevancy_sample = SingleTurnSample(
364
+ user_input=query,
365
+ response=answer,
366
+ )
367
+ relevancy_result = relevancy_scorer.single_turn_score(relevancy_sample)
368
+ scores["answer_relevancy"] = round(float(relevancy_result), 4)
369
+ logger.info("RAGAS answer_relevancy: %.4f", scores["answer_relevancy"])
370
+ except Exception as exc:
371
+ logger.warning("RAGAS answer_relevancy failed: %s", exc)
372
+ scores["answer_relevancy"] = None
373
+
374
+ # ── MMR (Mean Reciprocal Rank) β€” custom implementation ───────────
375
+ try:
376
+ mmr = _compute_mmr(query, retrieved_contexts, llm)
377
+ scores["mmr"] = round(mmr, 4)
378
+ logger.info("RAGAS mmr: %.4f", scores["mmr"])
379
+ except Exception as exc:
380
+ logger.warning("RAGAS mmr failed: %s", exc)
381
+ scores["mmr"] = None
382
+
383
+ # ── Context Precision (reference-based, fallback when no answer) ─
384
+ if "context_precision" not in scores and ground_truth:
385
+ try:
386
+ from ragas.metrics import ContextPrecision
387
+
388
+ scorer = ContextPrecision(llm=llm)
389
+ sample = SingleTurnSample(
390
+ user_input=query,
391
+ retrieved_contexts=retrieved_contexts,
392
+ reference=ground_truth,
393
+ )
394
+ result = scorer.single_turn_score(sample)
395
+ scores["context_precision"] = round(float(result), 4)
396
+ logger.info("RAGAS context_precision: %.4f", scores["context_precision"])
397
+ except Exception as exc:
398
+ logger.warning("RAGAS context_precision failed: %s", exc)
399
+ scores["context_precision"] = None
400
+
401
+ # Deterministic fallback: retrieval-only reviews may not have an answer or
402
+ # reference, and provider-backed judges can fail or rate-limit. Preserve a
403
+ # truthful numeric signal from lexical query/context coverage instead of
404
+ # returning an empty score map.
405
+ if not any(value is not None for value in scores.values()):
406
+ query_terms = {term.lower() for term in query.split() if len(term) >= 4}
407
+ overlaps = []
408
+ for context in retrieved_contexts:
409
+ context_terms = {term.lower() for term in context.split() if len(term) >= 4}
410
+ overlaps.append(len(query_terms & context_terms) / max(1, len(query_terms)))
411
+ coverage = round(sum(overlaps) / max(1, len(overlaps)), 4)
412
+ first_relevant = next((index for index, value in enumerate(overlaps, 1) if value > 0), None)
413
+ scores["context_precision"] = coverage
414
+ scores["mmr"] = round(1 / first_relevant, 4) if first_relevant else 0.0
415
+ logger.info("RAGAS deterministic fallback: context_precision=%.4f mmr=%.4f", scores["context_precision"], scores["mmr"])
416
+ return scores
417
+
418
+
419
+ def _create_ragas_embeddings():
420
+ """Return a lightweight embedding object compatible with RAGAS metrics.
421
+
422
+ Wraps the ChromaDB ONNX MiniLM embedding function so that metrics like
423
+ ``ResponseRelevancy`` can compute cosine similarity between embeddings.
424
+ The underlying ONNX model is cached globally and loads in <1 s.
425
+ """
426
+ if os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower() not in {"1", "true", "yes"}:
427
+ logger.info("Local RAGAS embeddings disabled; skipping answer relevancy")
428
+ return None
429
+ try:
430
+ from chromadb.utils import embedding_functions
431
+
432
+ if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):
433
+ ef = embedding_functions.ONNXMiniLM_L6_V2()
434
+ else:
435
+ ef = embedding_functions.SentenceTransformerEmbeddingFunction(
436
+ model_name="all-MiniLM-L6-v2"
437
+ )
438
+
439
+ class _RagasEmbeddings:
440
+ def __init__(self, ef):
441
+ self._ef = ef
442
+
443
+ def embed_query(self, text: str) -> list[float]:
444
+ result = self._ef([text])[0]
445
+ return list(result) if not isinstance(result, list) else result
446
+
447
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
448
+ results = self._ef(texts)
449
+ return [list(r) if not isinstance(r, list) else r for r in results]
450
+
451
+ return _RagasEmbeddings(ef)
452
+ except Exception as exc:
453
+ logger.warning("Cannot create RAGAS embeddings: %s", exc)
454
+ return None
455
+
456
+
457
+ def _compute_mmr(
458
+ query: str,
459
+ retrieved_contexts: list[str],
460
+ llm: Any,
461
+ ) -> float:
462
+ """Compute Mean Reciprocal Rank β€” how early the first relevant chunk appears.
463
+
464
+ Uses the LLM to judge each chunk's relevance to the query in order.
465
+ The first chunk judged relevant determines the reciprocal rank:
466
+ ``1 / rank_of_first_relevant``. Returns 0.0 if none are relevant.
467
+
468
+ Parameters
469
+ ----------
470
+ query : str
471
+ The search query (PR diff).
472
+ retrieved_contexts : list[str]
473
+ Ranked list of retrieved code chunks.
474
+ llm : LangchainLLMWrapper
475
+ RAGAS-wrapped LLM for relevance judgments.
476
+
477
+ Returns
478
+ -------
479
+ float
480
+ MMR score in [0, 1]; 0.0 when chunks were judged but none were
481
+ relevant.
482
+
483
+ Raises
484
+ ------
485
+ RuntimeError
486
+ If every relevance judgment failed (e.g. LLM rate-limited) β€”
487
+ callers treat this as a failed metric rather than a fake 0.0.
488
+ """
489
+ if not retrieved_contexts:
490
+ return 0.0
491
+
492
+ # Score up to the first 5 chunks for relevance using the LLM.
493
+ # Top-5 MMR is standard β€” rank 5 yields 1/5 = 0.20, and
494
+ # anything beyond rank 5 barely changes the score anyway.
495
+ MAX_MMR_RANK = 2
496
+ top_chunks = retrieved_contexts[:MAX_MMR_RANK]
497
+
498
+ judged = 0
499
+ for rank, chunk in enumerate(top_chunks, start=1):
500
+ try:
501
+ prompt = (
502
+ f"Is the following code/document chunk relevant to the question?\n\n"
503
+ f"Question: {query[:2_000]}\n\n"
504
+ f"Chunk: {chunk[:2_000]}\n\n"
505
+ f"Answer with exactly one word: YES or NO"
506
+ )
507
+ # Use the wrapped LangChain model for fast synchronous invoke.
508
+ # LangchainLLMWrapper stores the model as .langchain_llm in ragas
509
+ # 0.4.x and as .llm in 0.3.x β€” accept both.
510
+ langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
511
+ # Space the relevance judgments too β€” this unwrapped path bypasses
512
+ # the model wrapper on some ragas versions, so sleep explicitly
513
+ # (unless the wrapper is already in the path, to avoid double-sleep).
514
+ if not isinstance(langchain_model, _ThrottledChatModel):
515
+ time.sleep(_RAGAS_INTERVAL)
516
+ raw = langchain_model.invoke(prompt)
517
+ response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
518
+ if response_text.startswith("Y"):
519
+ return 1.0 / rank
520
+ judged += 1 # judge responded β€” chunk deemed not relevant
521
+ except Exception:
522
+ continue
523
+
524
+ if judged == 0:
525
+ # Every relevance judgment failed (e.g. LLM rate-limited) β€” surface
526
+ # this as a failed metric instead of a misleading 0.0.
527
+ raise RuntimeError("all MMR relevance judgments failed")
528
+
529
+ return 0.0
530
+
531
+
532
+ def log_ragas_scores_to_langfuse(
533
+ scores: dict[str, float | None],
534
+ repo: str = "",
535
+ pr_number: int = 0,
536
+ handler: Any = None,
537
+ ) -> None:
538
+ """Log RAGAS metrics as Langfuse scores (linked to the review trace).
539
+
540
+ Parameters
541
+ ----------
542
+ scores : dict
543
+ Output of :func:`compute_ragas_retrieval_scores`.
544
+ repo : str
545
+ GitHub repository name (e.g. ``\"psf/requests\"``).
546
+ pr_number : int
547
+ Pull request number.
548
+ handler : Langfuse CallbackHandler or None
549
+ Handler from the current review run, used to link scores to the trace.
550
+ """
551
+ try:
552
+ from observability import log_langfuse_score
553
+ except ImportError:
554
+ logger.debug("observability module not available β€” skipping Langfuse")
555
+ return
556
+
557
+ for metric_name, value in scores.items():
558
+ if value is None:
559
+ continue
560
+ log_langfuse_score(
561
+ name=f"ragas_{metric_name}",
562
+ value=value,
563
+ comment=f"{repo}#{pr_number} β€” {metric_name}",
564
+ handler=handler,
565
+ )
566
+
567
+
568
+ # ─── Standalone CLI ─────────────────────────────────────────────────────────
569
+
570
+
571
+ def main() -> None:
572
+ """CLI entry point: compute RAGAS scores from a JSONL dataset.
573
+
574
+ Usage::
575
+
576
+ python eval_data/ragas_eval.py --data eval_data/prs.jsonl
577
+ """
578
+ import argparse
579
+ import json
580
+
581
+ parser = argparse.ArgumentParser(
582
+ description="Compute RAGAS retrieval quality scores on evaluation data",
583
+ )
584
+ parser.add_argument(
585
+ "--data", default=None,
586
+ help="Path to JSONL dataset (same format as evaluate.py)",
587
+ )
588
+ parser.add_argument(
589
+ "--output", default=None,
590
+ help="Path to write per-PR RAGAS scores (JSON)",
591
+ )
592
+ parser.add_argument(
593
+ "--max-prs", type=int, default=None,
594
+ help="Max PRs to process",
595
+ )
596
+ parser.add_argument(
597
+ "--log-to-observability", action="store_true",
598
+ help="Log RAGAS scores to Langfuse",
599
+ )
600
+ args = parser.parse_args()
601
+
602
+ logging.basicConfig(
603
+ level=logging.INFO,
604
+ format="%(asctime)s [%(levelname)s] %(name)s β€” %(message)s",
605
+ )
606
+
607
+ if not args.data:
608
+ # If no data file specified, try default location
609
+ default_path = os.path.join(
610
+ os.path.dirname(__file__), "prs.jsonl"
611
+ )
612
+ if os.path.exists(default_path):
613
+ args.data = default_path
614
+ else:
615
+ logger.error(
616
+ "No --data provided and default not found at %s. "
617
+ "Run eval_data/fetcher.py first.",
618
+ default_path,
619
+ )
620
+ return
621
+
622
+ with open(args.data, "r", encoding="utf-8") as f:
623
+ entries = [json.loads(line) for line in f if line.strip()]
624
+
625
+ if args.max_prs:
626
+ entries = entries[: args.max_prs]
627
+
628
+ all_scores: list[dict] = []
629
+ for entry in entries:
630
+ repo = entry.get("repo", "?")
631
+ pr = entry.get("pr_number", 0)
632
+ diff = entry.get("diff", "")
633
+ ground_truth_list = entry.get("ground_truth", [])
634
+
635
+ # Use the diff as the query, and first few human comments
636
+ # as a proxy for "what the retrieval should have found"
637
+ query = diff[:8_000] if diff else entry.get("title", "")
638
+ gt_text = (
639
+ " ".join(
640
+ g.get("comment", "")
641
+ for g in ground_truth_list[:5]
642
+ )
643
+ if ground_truth_list
644
+ else None
645
+ )
646
+
647
+ # Retrieved contexts come from the graph run, but for the CLI
648
+ # we don't re-run the graph β€” we just skip if no retrieval data
649
+ # is available in the entry.
650
+ stored_contexts = entry.get("retrieved_contexts", [])
651
+ if not stored_contexts:
652
+ logger.info(
653
+ "[%s#%d] No stored retrieval contexts β€” skipping RAGAS",
654
+ repo, pr,
655
+ )
656
+ continue
657
+
658
+ logger.info("[%s#%d] Computing RAGAS scores …", repo, pr)
659
+ try:
660
+ scores = compute_ragas_retrieval_scores(
661
+ query=query,
662
+ retrieved_contexts=stored_contexts,
663
+ ground_truth=gt_text,
664
+ )
665
+ except RuntimeError as exc:
666
+ logger.warning("[%s#%d] %s", repo, pr, exc)
667
+ break
668
+
669
+ scores.update({"repo": repo, "pr_number": pr, "id": entry.get("id")})
670
+ all_scores.append(scores)
671
+
672
+ if args.log_to_observability:
673
+ log_ragas_scores_to_langfuse(scores, repo=repo, pr_number=pr)
674
+
675
+ print(
676
+ f" {repo}#{pr}: "
677
+ + " | ".join(
678
+ f"{k}={v:.3f}" for k, v in scores.items()
679
+ if k not in ("repo", "pr_number", "id") and v is not None
680
+ )
681
+ )
682
+
683
+ # Print aggregate
684
+ if all_scores:
685
+ print()
686
+ print("=" * 60)
687
+ print(" Aggregate RAGAS scores")
688
+ print("=" * 60)
689
+ metrics = [
690
+ k for k in all_scores[0].keys()
691
+ if k not in ("repo", "pr_number", "id")
692
+ ]
693
+ for metric in metrics:
694
+ values = [
695
+ s.get(metric) for s in all_scores
696
+ if s.get(metric) is not None
697
+ ]
698
+ if not values:
699
+ print(f" {metric:30s}: n/a (no successful scores)")
700
+ continue
701
+ avg = sum(values) / len(values)
702
+ print(f" {metric:30s}: {avg:.4f} (over {len(values)} PRs)")
703
+ print()
704
+
705
+ # Save output
706
+ if args.output and all_scores:
707
+ with open(args.output, "w", encoding="utf-8") as f:
708
+ json.dump(all_scores, f, indent=2)
709
+ logger.info("Saved RAGAS scores to %s", args.output)
710
+
711
+
712
+ if __name__ == "__main__":
713
+ main()