Sdm0 commited on
Commit
3de2abc
Β·
verified Β·
1 Parent(s): a57782e

Deploy cdd9a7e7

Browse files
Files changed (3) hide show
  1. eval_data/evaluate.py +105 -9
  2. eval_data/ragas_eval.py +462 -0
  3. requirements.txt +2 -0
eval_data/evaluate.py CHANGED
@@ -177,10 +177,10 @@ def _fuzzy_match(
177
 
178
  def _run_graph_for_pr(
179
  entry: dict, graph,
180
- ) -> tuple[list[Finding], Optional[dict]]:
181
  """Run the full OpenCodeReview graph on a single PR.
182
 
183
- Returns ``(final_findings, verdict_dict_or_None)``.
184
  """
185
  thread_id = str(uuid.uuid4())
186
  config = {"configurable": {"thread_id": f"eval-{thread_id}"}}
@@ -206,21 +206,32 @@ def _run_graph_for_pr(
206
  tasks = state.tasks
207
  values = state.values
208
 
 
 
209
  if not tasks:
210
  # Graph completed without interrupt -- no findings to review
211
- return values.get("final_findings", []), values.get("verdict")
 
 
 
 
212
 
213
  # Auto-approve to continue through the executor
214
  try:
215
  graph.invoke(Command(resume={"action": "approve"}), config)
216
  except Exception as exc:
217
  logger.warning(" Resume error: %s", exc)
218
- return values.get("final_findings", []), values.get("verdict")
 
 
 
 
219
 
220
  final_state = graph.get_state(config)
221
  return (
222
  final_state.values.get("final_findings", []),
223
  final_state.values.get("verdict"),
 
224
  )
225
 
226
 
@@ -362,6 +373,11 @@ def main() -> None:
362
  "--log-to-observability", action="store_true",
363
  help="Log evaluation scores to LangSmith/Langfuse for quality-over-time tracking",
364
  )
 
 
 
 
 
365
  args = parser.parse_args()
366
 
367
  logging.basicConfig(
@@ -420,7 +436,7 @@ def main() -> None:
420
  )
421
 
422
  try:
423
- findings, verdict = _run_graph_for_pr(entry, graph)
424
  except Exception as exc:
425
  print(f"ERROR: {exc}")
426
  continue
@@ -435,6 +451,48 @@ def main() -> None:
435
  "pr_number": entry["pr_number"],
436
  "title": entry.get("title", ""),
437
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
438
  results.append(metrics)
439
 
440
  print(
@@ -518,11 +576,31 @@ def _log_to_observability(results: list[dict], dataset_name: str = "opencoderevi
518
  else 0.0
519
  )
520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521
  logger.info(
522
- "Logging eval results to observability "
523
- "(micro F1=%.3f, PRs=%d, LangSmith=%s, Langfuse=%s)",
524
- micro_f, len(results),
525
- is_langsmith_enabled(), is_langfuse_enabled(),
526
  )
527
 
528
  # ── Langfuse: create scores via SDK ──────────────────────────────────
@@ -541,6 +619,16 @@ def _log_to_observability(results: list[dict], dataset_name: str = "opencoderevi
541
  comment=f"{r.get('repo', '?')}#{r.get('pr_number', '?')}"
542
  f" β€” P={r['precision']:.3f} R={r['recall']:.3f}",
543
  )
 
 
 
 
 
 
 
 
 
 
544
 
545
  # Log aggregate scores
546
  lf.score(name=f"{dataset_name}/micro_f1", value=micro_f)
@@ -548,6 +636,14 @@ def _log_to_observability(results: list[dict], dataset_name: str = "opencoderevi
548
  lf.score(name=f"{dataset_name}/micro_recall", value=micro_r)
549
  lf.score(name=f"{dataset_name}/pr_count", value=len(results))
550
 
 
 
 
 
 
 
 
 
551
  # Flush to ensure scores are sent before process exits
552
  lf.flush()
553
  logger.info("Langfuse scores logged (run=%s)", run_name)
 
177
 
178
  def _run_graph_for_pr(
179
  entry: dict, graph,
180
+ ) -> tuple[list[Finding], Optional[dict], list]:
181
  """Run the full OpenCodeReview graph on a single PR.
182
 
183
+ Returns ``(final_findings, verdict_dict_or_None, context_chunks)``.
184
  """
185
  thread_id = str(uuid.uuid4())
186
  config = {"configurable": {"thread_id": f"eval-{thread_id}"}}
 
206
  tasks = state.tasks
207
  values = state.values
208
 
209
+ context_chunks = values.get("context_chunks", [])
210
+
211
  if not tasks:
212
  # Graph completed without interrupt -- no findings to review
213
+ return (
214
+ values.get("final_findings", []),
215
+ values.get("verdict"),
216
+ context_chunks,
217
+ )
218
 
219
  # Auto-approve to continue through the executor
220
  try:
221
  graph.invoke(Command(resume={"action": "approve"}), config)
222
  except Exception as exc:
223
  logger.warning(" Resume error: %s", exc)
224
+ return (
225
+ values.get("final_findings", []),
226
+ values.get("verdict"),
227
+ context_chunks,
228
+ )
229
 
230
  final_state = graph.get_state(config)
231
  return (
232
  final_state.values.get("final_findings", []),
233
  final_state.values.get("verdict"),
234
+ final_state.values.get("context_chunks", []),
235
  )
236
 
237
 
 
373
  "--log-to-observability", action="store_true",
374
  help="Log evaluation scores to LangSmith/Langfuse for quality-over-time tracking",
375
  )
376
+ parser.add_argument(
377
+ "--ragas", action="store_true",
378
+ help="Compute RAGAS retrieval & generation metrics (context_precision, context_recall, "
379
+ "faithfulness, answer_relevancy, mmr) in addition to standard precision/recall/F1",
380
+ )
381
  args = parser.parse_args()
382
 
383
  logging.basicConfig(
 
436
  )
437
 
438
  try:
439
+ findings, verdict, context_chunks = _run_graph_for_pr(entry, graph)
440
  except Exception as exc:
441
  print(f"ERROR: {exc}")
442
  continue
 
451
  "pr_number": entry["pr_number"],
452
  "title": entry.get("title", ""),
453
  })
454
+
455
+ # ── Compute RAGAS retrieval & generation metrics (optional) ──
456
+ if args.ragas and context_chunks:
457
+ try:
458
+ from eval_data.ragas_eval import compute_ragas_retrieval_scores
459
+
460
+ query = entry.get("diff", "")[:8_000] or entry.get("title", "")
461
+ contexts = [c.content for c in context_chunks if c.content]
462
+ gt_text = " ".join(
463
+ g.get("comment", "")
464
+ for g in entry.get("ground_truth", [])[:5]
465
+ ) if entry.get("ground_truth") else None
466
+
467
+ # Build the generated answer text from findings + verdict
468
+ answer_lines = []
469
+ for f in findings:
470
+ answer_lines.append(
471
+ f"[{f.severity.value}] {f.file_path}:{f.line_start}-{f.line_end}: {f.comment}"
472
+ )
473
+ if verdict:
474
+ answer_lines.append(
475
+ f"Verdict: {verdict.recommendation} (score={verdict.overall_score}/10) β€” {verdict.summary}"
476
+ )
477
+ answer_text = "\n".join(answer_lines) if answer_lines else None
478
+
479
+ ragas_scores = compute_ragas_retrieval_scores(
480
+ query=query,
481
+ retrieved_contexts=contexts,
482
+ ground_truth=gt_text or None,
483
+ answer=answer_text,
484
+ )
485
+ metrics.update(ragas_scores)
486
+ print(
487
+ f" RAGAS: "
488
+ + " | ".join(
489
+ f"{k}={v:.3f}"
490
+ for k, v in ragas_scores.items()
491
+ )
492
+ )
493
+ except Exception as exc:
494
+ logger.warning("RAGAS computation failed: %s", exc)
495
+
496
  results.append(metrics)
497
 
498
  print(
 
576
  else 0.0
577
  )
578
 
579
+ # RAGAS metric keys available
580
+ RAGAS_METRICS = [
581
+ "context_precision", "context_recall",
582
+ "faithfulness", "answer_relevancy", "mmr",
583
+ ]
584
+
585
+ # Check which RAGAS scores were computed
586
+ has_ragas = bool(results and any(k in results[0] for k in RAGAS_METRICS))
587
+ ragas_avgs: dict[str, float] = {}
588
+ if has_ragas:
589
+ for metric in RAGAS_METRICS:
590
+ values = [r.get(metric, 0.0) for r in results if metric in r]
591
+ ragas_avgs[metric] = sum(values) / len(values) if values else 0.0
592
+
593
+ log_parts = [f"micro F1={micro_f:.3f}"]
594
+ if has_ragas:
595
+ for metric, avg in ragas_avgs.items():
596
+ log_parts.append(f"RAGAS_{metric}={avg:.3f}")
597
+ log_parts.append(f"PRs={len(results)}")
598
+ log_parts.append(f"LangSmith={is_langsmith_enabled()}")
599
+ log_parts.append(f"Langfuse={is_langfuse_enabled()}")
600
+
601
  logger.info(
602
+ "Logging eval results to observability (%s)",
603
+ ", ".join(log_parts),
 
 
604
  )
605
 
606
  # ── Langfuse: create scores via SDK ──────────────────────────────────
 
619
  comment=f"{r.get('repo', '?')}#{r.get('pr_number', '?')}"
620
  f" β€” P={r['precision']:.3f} R={r['recall']:.3f}",
621
  )
622
+ # Log per-PR RAGAS scores (context_precision, context_recall,
623
+ # faithfulness, answer_relevancy, mmr)
624
+ for ragas_key in ("context_precision", "context_recall",
625
+ "faithfulness", "answer_relevancy", "mmr"):
626
+ if ragas_key in r:
627
+ lf.score(
628
+ name=f"{dataset_name}/{r.get('id', 'unknown')}/{ragas_key}",
629
+ value=r[ragas_key],
630
+ comment=f"{r.get('repo', '?')}#{r.get('pr_number', '?')}",
631
+ )
632
 
633
  # Log aggregate scores
634
  lf.score(name=f"{dataset_name}/micro_f1", value=micro_f)
 
636
  lf.score(name=f"{dataset_name}/micro_recall", value=micro_r)
637
  lf.score(name=f"{dataset_name}/pr_count", value=len(results))
638
 
639
+ # Log aggregate RAGAS scores (all available metrics)
640
+ if has_ragas:
641
+ for metric, avg in ragas_avgs.items():
642
+ lf.score(
643
+ name=f"{dataset_name}/{metric}",
644
+ value=avg,
645
+ )
646
+
647
  # Flush to ensure scores are sent before process exits
648
  lf.flush()
649
  logger.info("Langfuse scores logged (run=%s)", run_name)
eval_data/ragas_eval.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import Any, Optional
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ # ─── Lazy RAGAS imports with graceful fallback ──────────────────────────────
36
+
37
+ _RAGAS_AVAILABLE: bool | None = None
38
+
39
+
40
+ def _check_ragas() -> bool:
41
+ """Return True if RAGAS and litellm are available."""
42
+ global _RAGAS_AVAILABLE
43
+ if _RAGAS_AVAILABLE is not None:
44
+ return _RAGAS_AVAILABLE
45
+ try:
46
+ import ragas # noqa: F401
47
+ import litellm # noqa: F401
48
+ _RAGAS_AVAILABLE = True
49
+ except ImportError:
50
+ logger.warning(
51
+ "ragas or litellm not installed. Install with: "
52
+ "pip install ragas litellm"
53
+ )
54
+ _RAGAS_AVAILABLE = False
55
+ return _RAGAS_AVAILABLE
56
+
57
+
58
+ def _get_evaluator_llm():
59
+ """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
60
+
61
+ Follows the same priority as the main pipeline:
62
+ 1. Google Gemini (``gemini-3.1-flash-lite``) via ``GEMINI_API_KEY``
63
+ 2. Groq (``llama-3.3-70b-versatile``) via ``GROQ_API_KEY``
64
+
65
+ RAGAS v0.3+ uses ``LangchainLLMWrapper`` to wrap LangChain models.
66
+ """
67
+ from ragas.llms import LangchainLLMWrapper
68
+
69
+ try:
70
+ from llm_factory import create_llm
71
+ llm = create_llm(temperature=0)
72
+ logger.info(
73
+ "RAGAS evaluator: using %s",
74
+ type(llm).__name__,
75
+ )
76
+ return LangchainLLMWrapper(llm)
77
+ except ValueError as exc:
78
+ logger.warning("RAGAS evaluator: %s", exc)
79
+ raise RuntimeError(
80
+ "No LLM available for RAGAS scoring. "
81
+ "Set GEMINI_API_KEY or GROQ_API_KEY."
82
+ ) from exc
83
+
84
+
85
+ # ─── Score computation ─────────────────────────────────────────────────────
86
+
87
+
88
+ def compute_ragas_retrieval_scores(
89
+ query: str,
90
+ retrieved_contexts: list[str],
91
+ ground_truth: Optional[str] = None,
92
+ answer: Optional[str] = None,
93
+ ) -> dict[str, float]:
94
+ """Compute RAGAS retrieval & generation quality metrics.
95
+
96
+ Computes up to five metrics depending on available inputs:
97
+
98
+ +---------------------------+------------------------------------------+
99
+ | Metric | Required inputs |
100
+ +===========================+==========================================+
101
+ | ``context_precision`` | query, retrieved_contexts |
102
+ | ``context_recall`` | query, retrieved_contexts, ground_truth |
103
+ | ``faithfulness`` | query, retrieved_contexts, answer |
104
+ | ``answer_relevancy`` | query, answer |
105
+ | ``mmr`` (Mean Reciprocal | query, retrieved_contexts |
106
+ | Rank) | (custom LLM-judged) |
107
+ +---------------------------+------------------------------------------+
108
+
109
+ Parameters
110
+ ----------
111
+ query : str
112
+ The search query β€” in OpenCodeReview this is the PR diff text.
113
+ retrieved_contexts : list[str]
114
+ The code/document chunks returned by the retrieval node.
115
+ ground_truth : str or None
116
+ Ground-truth reference text (e.g. human review comment). Required
117
+ for ``context_recall``.
118
+ answer : str or None
119
+ The generated answer (e.g. concatenated review findings / verdict).
120
+ Required for ``faithfulness`` and ``answer_relevancy``.
121
+
122
+ Returns
123
+ -------
124
+ dict
125
+ Mapping of metric name β†’ score (0–1 range, higher is better).
126
+ Possible keys: ``context_precision``, ``context_recall``,
127
+ ``faithfulness``, ``answer_relevancy``, ``mmr``.
128
+
129
+ Raises
130
+ ------
131
+ RuntimeError
132
+ If RAGAS or a suitable LLM backend is not available.
133
+ """
134
+ if not _check_ragas():
135
+ raise RuntimeError(
136
+ "RAGAS is not installed. Run: pip install ragas litellm"
137
+ )
138
+
139
+ if not retrieved_contexts:
140
+ logger.warning("No retrieved contexts β€” RAGAS scores set to 0.0")
141
+ result: dict[str, float] = {"context_precision": 0.0, "mmr": 0.0}
142
+ if ground_truth:
143
+ result["context_recall"] = 0.0
144
+ if answer:
145
+ result["faithfulness"] = 0.0
146
+ result["answer_relevancy"] = 0.0
147
+ return result
148
+
149
+ from ragas.dataset_schema import SingleTurnSample
150
+
151
+ llm = _get_evaluator_llm()
152
+ scores: dict[str, float] = {}
153
+
154
+ # ── Context Precision ────────────────────────────────────────────
155
+ try:
156
+ from ragas.metrics.collections import ContextPrecision
157
+
158
+ scorer = ContextPrecision(llm=llm)
159
+ sample = SingleTurnSample(
160
+ user_input=query,
161
+ retrieved_contexts=retrieved_contexts,
162
+ )
163
+ result = scorer.score(sample)
164
+ scores["context_precision"] = round(float(result.value), 4)
165
+ logger.info("RAGAS context_precision: %.4f", scores["context_precision"])
166
+ except Exception as exc:
167
+ logger.warning("RAGAS context_precision failed: %s", exc)
168
+ scores["context_precision"] = 0.0
169
+
170
+ # ── Context Recall ───────────────────────────────────────────────
171
+ if ground_truth:
172
+ try:
173
+ from ragas.metrics.collections import ContextRecall
174
+
175
+ recall_scorer = ContextRecall(llm=llm)
176
+ recall_sample = SingleTurnSample(
177
+ user_input=query,
178
+ retrieved_contexts=retrieved_contexts,
179
+ reference=ground_truth,
180
+ )
181
+ recall_result = recall_scorer.score(recall_sample)
182
+ scores["context_recall"] = round(float(recall_result.value), 4)
183
+ logger.info("RAGAS context_recall: %.4f", scores["context_recall"])
184
+ except Exception as exc:
185
+ logger.warning("RAGAS context_recall failed: %s", exc)
186
+ scores["context_recall"] = 0.0
187
+
188
+ # ── Faithfulness ─────────────────────────────────────────────────
189
+ if answer:
190
+ try:
191
+ from ragas.metrics import Faithfulness
192
+
193
+ faithfulness_scorer = Faithfulness(llm=llm)
194
+ faithful_sample = SingleTurnSample(
195
+ user_input=query,
196
+ response=answer,
197
+ retrieved_contexts=retrieved_contexts,
198
+ )
199
+ faithful_result = faithfulness_scorer.score(faithful_sample)
200
+ scores["faithfulness"] = round(float(faithful_result.value), 4)
201
+ logger.info("RAGAS faithfulness: %.4f", scores["faithfulness"])
202
+ except Exception as exc:
203
+ logger.warning("RAGAS faithfulness failed: %s", exc)
204
+ scores["faithfulness"] = 0.0
205
+
206
+ # ── Answer Relevancy (ResponseRelevancy) ─────────────────────────
207
+ if answer:
208
+ try:
209
+ from ragas.metrics import ResponseRelevancy
210
+
211
+ relevancy_scorer = ResponseRelevancy(llm=llm)
212
+ relevancy_sample = SingleTurnSample(
213
+ user_input=query,
214
+ response=answer,
215
+ )
216
+ relevancy_result = relevancy_scorer.score(relevancy_sample)
217
+ scores["answer_relevancy"] = round(float(relevancy_result.value), 4)
218
+ logger.info("RAGAS answer_relevancy: %.4f", scores["answer_relevancy"])
219
+ except Exception as exc:
220
+ logger.warning("RAGAS answer_relevancy failed: %s", exc)
221
+ scores["answer_relevancy"] = 0.0
222
+
223
+ # ── MMR (Mean Reciprocal Rank) β€” custom implementation ───────────
224
+ try:
225
+ mmr = _compute_mmr(query, retrieved_contexts, llm)
226
+ scores["mmr"] = round(mmr, 4)
227
+ logger.info("RAGAS mmr: %.4f", scores["mmr"])
228
+ except Exception as exc:
229
+ logger.warning("RAGAS mmr failed: %s", exc)
230
+ scores["mmr"] = 0.0
231
+
232
+ return scores
233
+
234
+
235
+ def _compute_mmr(
236
+ query: str,
237
+ retrieved_contexts: list[str],
238
+ llm: Any,
239
+ ) -> float:
240
+ """Compute Mean Reciprocal Rank β€” how early the first relevant chunk appears.
241
+
242
+ Uses the LLM to judge each chunk's relevance to the query in order.
243
+ The first chunk judged relevant determines the reciprocal rank:
244
+ ``1 / rank_of_first_relevant``. Returns 0.0 if none are relevant.
245
+
246
+ Parameters
247
+ ----------
248
+ query : str
249
+ The search query (PR diff).
250
+ retrieved_contexts : list[str]
251
+ Ranked list of retrieved code chunks.
252
+ llm : LangchainLLMWrapper
253
+ RAGAS-wrapped LLM for relevance judgments.
254
+
255
+ Returns
256
+ -------
257
+ float
258
+ MMR score in [0, 1].
259
+ """
260
+ if not retrieved_contexts:
261
+ return 0.0
262
+
263
+ # Score up to the first 5 chunks for relevance using the LLM.
264
+ # Top-5 MMR is standard β€” rank 5 yields 1/5 = 0.20, and
265
+ # anything beyond rank 5 barely changes the score anyway.
266
+ MAX_MMR_RANK = 5
267
+ top_chunks = retrieved_contexts[:MAX_MMR_RANK]
268
+
269
+ for rank, chunk in enumerate(top_chunks, start=1):
270
+ try:
271
+ prompt = (
272
+ f"Is the following code/document chunk relevant to the question?\n\n"
273
+ f"Question: {query[:2_000]}\n\n"
274
+ f"Chunk: {chunk[:2_000]}\n\n"
275
+ f"Answer with exactly one word: YES or NO"
276
+ )
277
+ # Use the wrapped LangChain model for fast synchronous invoke.
278
+ # LangchainLLMWrapper stores the LangChain model as .llm.
279
+ raw = llm.llm.invoke(prompt)
280
+ response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
281
+ if response_text.startswith("Y"):
282
+ return 1.0 / rank
283
+ except Exception:
284
+ continue
285
+
286
+ return 0.0
287
+
288
+
289
+ def log_ragas_scores_to_langfuse(
290
+ scores: dict[str, float],
291
+ repo: str = "",
292
+ pr_number: int = 0,
293
+ handler: Any = None,
294
+ ) -> None:
295
+ """Log RAGAS metrics as Langfuse scores (linked to the review trace).
296
+
297
+ Parameters
298
+ ----------
299
+ scores : dict
300
+ Output of :func:`compute_ragas_retrieval_scores`.
301
+ repo : str
302
+ GitHub repository name (e.g. ``\"psf/requests\"``).
303
+ pr_number : int
304
+ Pull request number.
305
+ handler : Langfuse CallbackHandler or None
306
+ Handler from the current review run, used to link scores to the trace.
307
+ """
308
+ try:
309
+ from observability import log_langfuse_score
310
+ except ImportError:
311
+ logger.debug("observability module not available β€” skipping Langfuse")
312
+ return
313
+
314
+ for metric_name, value in scores.items():
315
+ log_langfuse_score(
316
+ name=f"ragas_{metric_name}",
317
+ value=value,
318
+ comment=f"{repo}#{pr_number} β€” {metric_name}",
319
+ handler=handler,
320
+ )
321
+
322
+
323
+ # ─── Standalone CLI ─────────────────────────────────────────────────────────
324
+
325
+
326
+ def main() -> None:
327
+ """CLI entry point: compute RAGAS scores from a JSONL dataset.
328
+
329
+ Usage::
330
+
331
+ python eval_data/ragas_eval.py --data eval_data/prs.jsonl
332
+ """
333
+ import argparse
334
+ import json
335
+
336
+ parser = argparse.ArgumentParser(
337
+ description="Compute RAGAS retrieval quality scores on evaluation data",
338
+ )
339
+ parser.add_argument(
340
+ "--data", default=None,
341
+ help="Path to JSONL dataset (same format as evaluate.py)",
342
+ )
343
+ parser.add_argument(
344
+ "--output", default=None,
345
+ help="Path to write per-PR RAGAS scores (JSON)",
346
+ )
347
+ parser.add_argument(
348
+ "--max-prs", type=int, default=None,
349
+ help="Max PRs to process",
350
+ )
351
+ parser.add_argument(
352
+ "--log-to-observability", action="store_true",
353
+ help="Log RAGAS scores to Langfuse",
354
+ )
355
+ args = parser.parse_args()
356
+
357
+ logging.basicConfig(
358
+ level=logging.INFO,
359
+ format="%(asctime)s [%(levelname)s] %(name)s β€” %(message)s",
360
+ )
361
+
362
+ if not args.data:
363
+ # If no data file specified, try default location
364
+ default_path = os.path.join(
365
+ os.path.dirname(__file__), "prs.jsonl"
366
+ )
367
+ if os.path.exists(default_path):
368
+ args.data = default_path
369
+ else:
370
+ logger.error(
371
+ "No --data provided and default not found at %s. "
372
+ "Run eval_data/fetcher.py first.",
373
+ default_path,
374
+ )
375
+ return
376
+
377
+ with open(args.data, "r", encoding="utf-8") as f:
378
+ entries = [json.loads(line) for line in f if line.strip()]
379
+
380
+ if args.max_prs:
381
+ entries = entries[: args.max_prs]
382
+
383
+ all_scores: list[dict] = []
384
+ for entry in entries:
385
+ repo = entry.get("repo", "?")
386
+ pr = entry.get("pr_number", 0)
387
+ diff = entry.get("diff", "")
388
+ ground_truth_list = entry.get("ground_truth", [])
389
+
390
+ # Use the diff as the query, and first few human comments
391
+ # as a proxy for "what the retrieval should have found"
392
+ query = diff[:8_000] if diff else entry.get("title", "")
393
+ gt_text = (
394
+ " ".join(
395
+ g.get("comment", "")
396
+ for g in ground_truth_list[:5]
397
+ )
398
+ if ground_truth_list
399
+ else None
400
+ )
401
+
402
+ # Retrieved contexts come from the graph run, but for the CLI
403
+ # we don't re-run the graph β€” we just skip if no retrieval data
404
+ # is available in the entry.
405
+ stored_contexts = entry.get("retrieved_contexts", [])
406
+ if not stored_contexts:
407
+ logger.info(
408
+ "[%s#%d] No stored retrieval contexts β€” skipping RAGAS",
409
+ repo, pr,
410
+ )
411
+ continue
412
+
413
+ logger.info("[%s#%d] Computing RAGAS scores …", repo, pr)
414
+ try:
415
+ scores = compute_ragas_retrieval_scores(
416
+ query=query,
417
+ retrieved_contexts=stored_contexts,
418
+ ground_truth=gt_text,
419
+ )
420
+ except RuntimeError as exc:
421
+ logger.warning("[%s#%d] %s", repo, pr, exc)
422
+ break
423
+
424
+ scores.update({"repo": repo, "pr_number": pr, "id": entry.get("id")})
425
+ all_scores.append(scores)
426
+
427
+ if args.log_to_observability:
428
+ log_ragas_scores_to_langfuse(scores, repo=repo, pr_number=pr)
429
+
430
+ print(
431
+ f" {repo}#{pr}: "
432
+ + " | ".join(
433
+ f"{k}={v:.3f}" for k, v in scores.items()
434
+ if k not in ("repo", "pr_number", "id")
435
+ )
436
+ )
437
+
438
+ # Print aggregate
439
+ if all_scores:
440
+ print()
441
+ print("=" * 60)
442
+ print(" Aggregate RAGAS scores")
443
+ print("=" * 60)
444
+ metrics = [
445
+ k for k in all_scores[0].keys()
446
+ if k not in ("repo", "pr_number", "id")
447
+ ]
448
+ for metric in metrics:
449
+ values = [s.get(metric, 0.0) for s in all_scores]
450
+ avg = sum(values) / len(values)
451
+ print(f" {metric:30s}: {avg:.4f} (over {len(values)} PRs)")
452
+ print()
453
+
454
+ # Save output
455
+ if args.output and all_scores:
456
+ with open(args.output, "w", encoding="utf-8") as f:
457
+ json.dump(all_scores, f, indent=2)
458
+ logger.info("Saved RAGAS scores to %s", args.output)
459
+
460
+
461
+ if __name__ == "__main__":
462
+ main()
requirements.txt CHANGED
@@ -12,3 +12,5 @@ chromadb
12
  langsmith>=0.7
13
  langfuse
14
  requests-cache>=1.2
 
 
 
12
  langsmith>=0.7
13
  langfuse
14
  requests-cache>=1.2
15
+ ragas>=0.3
16
+ litellm