File size: 28,980 Bytes
4147729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
#!/usr/bin/env python3
"""RAGAS-based evaluation of retrieval quality for OpenCodeReview.

Computes **context_precision** and **context_recall** metrics from the
RAGAS framework (https://docs.ragas.io/) on the retrieved context chunks
produced by the ``retrieval_node``.

These metrics answer:
- **Context Precision**: Are the most relevant code chunks ranked first?
- **Context Recall**: Does the retrieved set contain all the information
  needed for the reviewers to produce accurate findings?

Usage
-----
    from eval_data.ragas_eval import compute_ragas_retrieval_scores

    score = compute_ragas_retrieval_scores(
        query="diff of PR ...",
        retrieved_contexts=["chunk1 text", "chunk2 text", ...],
        ground_truth="Human review comment text ...",
    )
    # score == {"context_precision": 0.85, "context_recall": 0.72}

Lazy imports minimise overhead when RAGAS is not installed.
"""

from __future__ import annotations

from contextvars import ContextVar
import logging
import os
import threading
import time
import sys
from pathlib import Path
from typing import Any, Optional

# Keep direct execution via ``python eval_data/ragas_eval.py`` working after
# backend modules were moved into the backend package.
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(_PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(_PROJECT_ROOT))

logger = logging.getLogger(__name__)

# ─── Lazy RAGAS imports with graceful fallback ──────────────────────────────

_RAGAS_AVAILABLE: bool | None = None


def _check_ragas() -> bool:
    """Return True if RAGAS is available.

    Note: ``litellm`` is NOT required because RAGAS scoring uses the
    project's own LLM factory (Gemini or Groq via LangChain), not
    litellm internally.
    """
    global _RAGAS_AVAILABLE
    if _RAGAS_AVAILABLE is not None:
        return _RAGAS_AVAILABLE
    try:
        import ragas  # noqa: F401
        _RAGAS_AVAILABLE = True
    except ImportError:
        logger.warning(
            "ragas not installed. Install with: pip install ragas"
        )
        _RAGAS_AVAILABLE = False
    return _RAGAS_AVAILABLE


# Seconds to sleep before every RAGAS LLM call. RAGAS scoring fires a
# burst of ~20-30 model calls per review (context-precision judgments,
# faithfulness verification, answer relevancy, MMR relevance checks).
# Spacing them keeps the burst under Groq/Gemini free-tier per-minute rate
# limits so scoring completes instead of tripping 429s β€” which previously
# caused long retry backoffs and 0.0000 scores. Override with the
# OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
_RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "0.5") or 0.5)
_ragas_throttle_lock = threading.Lock()
_metric_deadline = ContextVar("ragas_metric_deadline", default=None)


class _ThrottledChatModel:
    """Wrap a LangChain chat model so every underlying API call RAGAS makes
    is spaced by a fixed interval.

    RAGAS's ``LangchainLLMWrapper`` (deprecated shim in 0.4.x, forwards to
    the langchain model) and the custom MMR path call the model through
    different entry points (sync/async, single/batched).  Intercepting
    ``invoke`` / ``generate`` / ``ainvoke`` / ``agenerate`` here guarantees
    every request is throttled regardless of ragas version.
    """

    def __init__(self, model, interval: float | None = None):
        self._model = model
        self._interval = _RAGAS_INTERVAL if interval is None else interval
        self._quota_exhausted = False

    def _call(self, method, *args, **kwargs):
        try:
            return method(*args, **kwargs)
        except Exception as exc:
            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")):
                self._quota_exhausted = True
            raise

    async def _acall(self, method, *args, **kwargs):
        try:
            return await method(*args, **kwargs)
        except Exception as exc:
            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")):
                self._quota_exhausted = True
            raise

    def _wait(self) -> None:
        deadline = _metric_deadline.get()
        if deadline is not None and time.monotonic() >= deadline:
            raise TimeoutError("Metric deadline exceeded; no further judge calls")
        if self._quota_exhausted:
            raise RuntimeError("Evaluation stopped: provider authentication or quota limit; no further calls will be made for this evaluation.")
        if self._interval > 0:
            with _ragas_throttle_lock:
                time.sleep(self._interval)

    # ── Sync entry points ───────────────────────────────────────────────
    def invoke(self, *args, **kwargs):
        self._wait()
        return self._call(self._model.invoke, *args, **kwargs)

    def generate(self, messages, *args, **kwargs):
        # Serialize LangChain batch calls into individual throttled
        # requests so every underlying API call is spaced by the interval.
        if (
            isinstance(messages, list)
            and messages
            and isinstance(messages[0], list)
        ):
            from langchain_core.outputs import Generation, LLMResult

            generations = []
            for msgs in messages:
                self._wait()
                # invoke() does not accept callbacks/run_manager/config that
                # ragas may forward to generate() β€” drop them here.
                resp = self._call(self._model.invoke, msgs)
                text = resp.content if hasattr(resp, "content") else str(resp)
                generations.append([Generation(text=text, message=resp)])
            return LLMResult(generations=generations, llm_output=None)
        self._wait()
        return self._call(self._model.generate, messages, *args, **kwargs)

    # ── Async entry points ──────────────────────────────────────────────
    async def ainvoke(self, *args, **kwargs):
        self._wait()
        return await self._acall(self._model.ainvoke, *args, **kwargs)

    async def agenerate(self, messages, *args, **kwargs):
        if (
            isinstance(messages, list)
            and messages
            and isinstance(messages[0], list)
        ):
            from langchain_core.outputs import Generation, LLMResult

            generations = []
            for msgs in messages:
                self._wait()
                # Same kwargs caveat as generate(): ainvoke has no callbacks.
                resp = await self._acall(self._model.ainvoke, msgs)
                text = resp.content if hasattr(resp, "content") else str(resp)
                generations.append([Generation(text=text, message=resp)])
            return LLMResult(generations=generations, llm_output=None)
        self._wait()
        return await self._acall(self._model.agenerate, messages, *args, **kwargs)

    # ── Everything else passes through ──────────────────────────────────
    def __getattr__(self, name: str):
        return getattr(self._model, name)


def _wrap_evaluator(llm, timeout=12):
    from ragas.llms import LangchainLLMWrapper
    from ragas.run_config import RunConfig
    return LangchainLLMWrapper(_ThrottledChatModel(llm), run_config=RunConfig(timeout=max(1, int(timeout)), max_retries=0, max_wait=0, max_workers=1))


def _get_evaluator_llm(endpoint: Optional[str] = None, *, timeout=12):
    """Return a RAGAS-compatible LLM, reusing the project's LLM factory.

    Priority:
    1. **Custom endpoint** β€” when *endpoint* names a configured
       ``OCR_ENDPOINT_*`` config, it is used (any provider the user added).
    2. **Groq** (``llama-3.3-70b-versatile``) via ``GROQ_API_KEY``
    3. **Google Gemini** (``gemini-3.1-flash-lite``) via ``GEMINI_API_KEY``

    Groq is preferred over Gemini because scoring fires many LLM calls per
    review and the Gemini free tier (15 req/min) is already shared with the
    main review pipeline β€” using Groq's separate quota pool avoids the 429
    rate-limit failures that used to zero out the metrics.

    RAGAS v0.3+ uses ``LangchainLLMWrapper`` to wrap LangChain models.
    """
    from ragas.llms import LangchainLLMWrapper

    try:
        if endpoint:
            from backend.integrations.llm_factory import create_llm
            from backend.integrations.endpoints import EndpointConfig, get_endpoint
            configured = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
            request_timeout = timeout
            if configured and not getattr(configured, "builtin", False) and configured.provider not in {"google", "anthropic"}:
                import httpx
                # LangChain caches HTTP clients for hashable timeout values.
                # An unhashable Timeout forces a private pool for this loop.
                request_timeout = httpx.Timeout(timeout)
            llm = create_llm(endpoint=endpoint, temperature=0, timeout=request_timeout, max_retries=0)
            logger.info("RAGAS evaluator: using selected custom endpoint")
            return _wrap_evaluator(llm, timeout)

        from backend.integrations.llm_factory import _get_cloudflare_chat, _get_groq_chat, _get_gemini_chat

        llm = _get_cloudflare_chat(temperature=0, max_retries=0, timeout=timeout)
        if llm is not None:
            logger.info("RAGAS evaluator: using Cloudflare Workers AI")
            return _wrap_evaluator(llm, timeout)

        # Keep evaluation bounded: RAGAS runs several provider calls and
        # retrying each one can otherwise hold a review open for minutes.
        configured_model = os.getenv("RAGAS_MODEL", "").strip()
        if configured_model.startswith("groq/"):
            configured_model = configured_model.split("/", 1)[1]
        groq_kwargs = {"temperature": 0, "max_retries": 0, "timeout": timeout}
        if configured_model:
            groq_kwargs["model"] = configured_model
        llm = _get_groq_chat(**groq_kwargs)
        if llm is None:
            logger.info(
                "RAGAS evaluator: GROQ_API_KEY not set β€” falling back to Gemini"
            )
            llm = _get_gemini_chat(temperature=0, max_retries=0, timeout=timeout)
        if llm is None:
            raise ValueError(
                "No LLM available for RAGAS scoring. "
                "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
            )
        logger.info(
            "RAGAS evaluator: using %s (throttled %ss)",
            type(llm).__name__,
            _RAGAS_INTERVAL,
        )
        return _wrap_evaluator(llm, timeout)
    except ValueError as exc:
        logger.warning("RAGAS evaluator: %s", exc)
        raise RuntimeError(
            "No LLM available for RAGAS scoring. "
            "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
        ) from exc


# ─── Score computation ─────────────────────────────────────────────────────


def _score_one_metric(name, sample, llm, timeout):
    from ragas import metrics
    from ragas.run_config import RunConfig
    classes = {"context_precision": "LLMContextPrecisionWithoutReference", "faithfulness": "Faithfulness", "context_recall": "ContextRecall"}
    scorer = getattr(metrics, classes[name])(llm=llm)
    scorer.init(RunConfig(timeout=timeout, max_retries=1, max_wait=0, max_workers=1))
    return float(scorer.single_turn_score(sample))


def _safe_metric_error(exc):
    """Classify failures without exposing provider responses or credentials."""
    chain = []
    current = exc
    while current is not None and len(chain) < 5:
        chain.append(type(current).__name__.lower())
        current = current.__cause__ or current.__context__
    kinds = " ".join(chain)
    if "timeout" in kinds:
        return "timed_out", "Evaluator provider timed out. Retry or select a faster model."
    if "connection" in kinds or "connecterror" in kinds:
        return "failed", "Evaluator provider connection failed. Retry; check provider availability if it persists."
    if "ratelimit" in kinds:
        return "failed", "Evaluator provider rate limit reached. Wait or select another saved provider."
    if "authentication" in kinds or "permission" in kinds:
        return "failed", "Evaluator provider rejected access. Check the saved provider credentials and permissions."
    return "failed", type(exc).__name__


def ragas_time_limits(endpoint=None):
    """Account for paced, remote Cloudflare inference in both deadlines."""
    total = max(1.0, float(os.getenv("OCR_RAGAS_TIMEOUT_SECONDS", "90")))
    per_metric = max(.05, float(os.getenv("OCR_RAGAS_METRIC_TIMEOUT_SECONDS", "30")))
    name = endpoint if isinstance(endpoint, str) else getattr(endpoint, "name", "")
    uses_cloudflare = str(name).lower() == "cloudflare" or (
        not endpoint and bool(os.getenv("CLOUDFLARE_API_TOKEN") and os.getenv("CLOUDFLARE_ACCOUNT_ID"))
    )
    if uses_cloudflare:
        total = max(total, float(os.getenv("OCR_CLOUDFLARE_RAGAS_TIMEOUT_SECONDS", "210")))
        per_metric = max(per_metric, float(os.getenv("OCR_CLOUDFLARE_RAGAS_METRIC_TIMEOUT_SECONDS", "150")))
    return total, per_metric


def compute_ragas_report(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None, *, metric_timeout=None, progress_callback=None):
    """Run independent bounded RAGAS metrics, preserving successes and real failures.

    No local embedding model is loaded. Lexical overlap is never substituted for
    RAGAS. Input caps reduce judge latency and are disclosed in the report.
    """
    import math
    import queue
    from contextvars import copy_context
    started = time.monotonic()
    total_budget, default_metric_timeout = ragas_time_limits(endpoint)
    per_metric = max(.05, float(metric_timeout if metric_timeout is not None else default_metric_timeout))
    names = ["context_precision", "faithfulness"]
    if ground_truth:
        names.append("context_recall")
    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)}}
    def finish(name, status, value=None, error=None, duration=0):
        report["metrics"][name] = {"status": status, "value": value, "error": error, "duration_seconds": round(duration, 3)}
        if value is not None:
            report["scores"][name] = value
        if progress_callback:
            progress_callback(report)
    for name, reason in [("answer_relevancy", "Requires embeddings; local models are disabled"), ("mmr", "Extra judge calls disabled in hosted evaluation")]:
        finish(name, "skipped", error=reason)
    if not ground_truth:
        finish("context_recall", "skipped", error="No reference answer provided")
    if not answer or not retrieved_contexts:
        for name in names:
            finish(name, "skipped", error="A complete answer and context are required")
        return report
    try:
        if not _check_ragas():
            raise RuntimeError("RAGAS is not installed")
        from ragas.dataset_schema import SingleTurnSample
        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)
    except Exception as exc:
        for name in names:
            finish(name, "failed", error=type(exc).__name__)
        return report
    pending = {}
    for name in names:
        remaining = total_budget - (time.monotonic() - started) - 1
        if remaining <= 0:
            finish(name, "timed_out", error="Evaluation setup exhausted deadline")
            continue
        deadline = time.monotonic() + min(per_metric, remaining)
        output = queue.Queue(maxsize=1)
        def run(metric=name, target=output, limit=min(per_metric, remaining)):
            metric_started = time.monotonic()
            token = _metric_deadline.set(metric_started + limit)
            try:
                # Each metric runs its own asyncio loop. Sharing an async HTTP
                # client across these threads can bind its pool to another loop.
                # Keep the provider request timeout and RAGAS RunConfig aligned
                # with this metric's actual deadline.
                llm = _get_evaluator_llm(endpoint=endpoint, timeout=limit)
                value = _score_one_metric(metric, sample, llm, limit)
                if not math.isfinite(value) or not 0 <= value <= 1:
                    raise ValueError("Invalid metric value")
                target.put(("completed", round(value, 4), None, time.monotonic() - metric_started))
            except Exception as exc:
                status, error = _safe_metric_error(exc)
                logger.warning("RAGAS metric %s failed (%s)", metric, type(exc).__name__)
                target.put((status, None, error, time.monotonic() - metric_started))
            finally:
                _metric_deadline.reset(token)
        threading.Thread(target=copy_context().run, args=(run,), daemon=True).start()
        pending[name] = (output, deadline)
    while pending:
        for name, (output, deadline) in list(pending.items()):
            try:
                status, value, error, duration = output.get_nowait()
            except queue.Empty:
                if time.monotonic() < deadline:
                    continue
                status, value, error, duration = "timed_out", None, "Metric deadline exceeded", per_metric
            finish(name, status, value, error, duration)
            del pending[name]
        if pending:
            time.sleep(.01)
    report["evaluation"]["duration_seconds"] = round(time.monotonic() - started, 3)
    return report


def compute_ragas_retrieval_scores(query, retrieved_contexts, ground_truth=None, answer=None, endpoint=None):
    """Compatibility mapping. Failed/skipped metrics remain None, never invented scores."""
    report = compute_ragas_report(query, retrieved_contexts, ground_truth, answer, endpoint)
    return {name: metric["value"] for name, metric in report["metrics"].items()}


def _create_ragas_embeddings():
    """Return a lightweight embedding object compatible with RAGAS metrics.

    Wraps the ChromaDB ONNX MiniLM embedding function so that metrics like
    ``ResponseRelevancy`` can compute cosine similarity between embeddings.
    The underlying ONNX model is cached globally and loads in <1 s.
    """
    if os.getenv("OPENCODEREVIEW_ALLOW_LOCAL_EMBEDDINGS", "false").lower() not in {"1", "true", "yes"}:
        logger.info("Local RAGAS embeddings disabled; skipping answer relevancy")
        return None
    try:
        from chromadb.utils import embedding_functions

        if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):
            ef = embedding_functions.ONNXMiniLM_L6_V2()
        else:
            ef = embedding_functions.SentenceTransformerEmbeddingFunction(
                model_name="all-MiniLM-L6-v2"
            )

        class _RagasEmbeddings:
            def __init__(self, ef):
                self._ef = ef

            def embed_query(self, text: str) -> list[float]:
                result = self._ef([text])[0]
                return list(result) if not isinstance(result, list) else result

            def embed_documents(self, texts: list[str]) -> list[list[float]]:
                results = self._ef(texts)
                return [list(r) if not isinstance(r, list) else r for r in results]

        return _RagasEmbeddings(ef)
    except Exception as exc:
        logger.warning("Cannot create RAGAS embeddings: %s", exc)
        return None


def _compute_mmr(
    query: str,
    retrieved_contexts: list[str],
    llm: Any,
) -> float:
    """Compute Mean Reciprocal Rank β€” how early the first relevant chunk appears.

    Uses the LLM to judge each chunk's relevance to the query in order.
    The first chunk judged relevant determines the reciprocal rank:
    ``1 / rank_of_first_relevant``.  Returns 0.0 if none are relevant.

    Parameters
    ----------
    query : str
        The search query (PR diff).
    retrieved_contexts : list[str]
        Ranked list of retrieved code chunks.
    llm : LangchainLLMWrapper
        RAGAS-wrapped LLM for relevance judgments.

    Returns
    -------
    float
        MMR score in [0, 1]; 0.0 when chunks were judged but none were
        relevant.

    Raises
    ------
    RuntimeError
        If every relevance judgment failed (e.g. LLM rate-limited) β€”
        callers treat this as a failed metric rather than a fake 0.0.
    """
    if not retrieved_contexts:
        return 0.0

    # Score up to the first 5 chunks for relevance using the LLM.
    # Top-5 MMR is standard β€” rank 5 yields 1/5 = 0.20, and
    # anything beyond rank 5 barely changes the score anyway.
    MAX_MMR_RANK = 2
    top_chunks = retrieved_contexts[:MAX_MMR_RANK]

    judged = 0
    for rank, chunk in enumerate(top_chunks, start=1):
        try:
            prompt = (
                f"Is the following code/document chunk relevant to the question?\n\n"
                f"Question: {query[:2_000]}\n\n"
                f"Chunk: {chunk[:2_000]}\n\n"
                f"Answer with exactly one word: YES or NO"
            )
            # Use the wrapped LangChain model for fast synchronous invoke.
            # LangchainLLMWrapper stores the model as .langchain_llm in ragas
            # 0.4.x and as .llm in 0.3.x β€” accept both.
            langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
            # Space the relevance judgments too β€” this unwrapped path bypasses
            # the model wrapper on some ragas versions, so sleep explicitly
            # (unless the wrapper is already in the path, to avoid double-sleep).
            if not isinstance(langchain_model, _ThrottledChatModel):
                time.sleep(_RAGAS_INTERVAL)
            raw = langchain_model.invoke(prompt)
            response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
            if response_text.startswith("Y"):
                return 1.0 / rank
            judged += 1  # judge responded β€” chunk deemed not relevant
        except Exception:
            continue

    if judged == 0:
        # Every relevance judgment failed (e.g. LLM rate-limited) β€” surface
        # this as a failed metric instead of a misleading 0.0.
        raise RuntimeError("all MMR relevance judgments failed")

    return 0.0


def log_ragas_scores_to_langfuse(
    scores: dict[str, float | None],
    repo: str = "",
    pr_number: int = 0,
    handler: Any = None,
) -> None:
    """Log RAGAS metrics as Langfuse scores (linked to the review trace).

    Parameters
    ----------
    scores : dict
        Output of :func:`compute_ragas_retrieval_scores`.
    repo : str
        GitHub repository name (e.g. ``\"psf/requests\"``).
    pr_number : int
        Pull request number.
    handler : Langfuse CallbackHandler or None
        Handler from the current review run, used to link scores to the trace.
    """
    try:
        from backend.observability import log_langfuse_score
    except ImportError:
        logger.debug("observability module not available β€” skipping Langfuse")
        return

    for metric_name, value in scores.items():
        if value is None:
            continue
        log_langfuse_score(
            name=f"ragas_{metric_name}",
            value=value,
            comment=f"{repo}#{pr_number} β€” {metric_name}",
            handler=handler,
        )


# ─── Standalone CLI ─────────────────────────────────────────────────────────


def main() -> None:
    """CLI entry point: compute RAGAS scores from a JSONL dataset.

    Usage::

        python eval_data/ragas_eval.py --data eval_data/prs.jsonl
    """
    import argparse
    import json

    parser = argparse.ArgumentParser(
        description="Compute RAGAS retrieval quality scores on evaluation data",
    )
    parser.add_argument(
        "--data", default=None,
        help="Path to JSONL dataset (same format as evaluate.py)",
    )
    parser.add_argument(
        "--output", default=None,
        help="Path to write per-PR RAGAS scores (JSON)",
    )
    parser.add_argument(
        "--max-prs", type=int, default=None,
        help="Max PRs to process",
    )
    parser.add_argument(
        "--log-to-observability", action="store_true",
        help="Log RAGAS scores to Langfuse",
    )
    args = parser.parse_args()

    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [%(levelname)s] %(name)s β€” %(message)s",
    )

    if not args.data:
        # If no data file specified, try default location
        default_path = os.path.join(
            os.path.dirname(__file__), "prs.jsonl"
        )
        if os.path.exists(default_path):
            args.data = default_path
        else:
            logger.error(
                "No --data provided and default not found at %s. "
                "Run eval_data/fetcher.py first.",
                default_path,
            )
            return

    with open(args.data, "r", encoding="utf-8") as f:
        entries = [json.loads(line) for line in f if line.strip()]

    if args.max_prs:
        entries = entries[: args.max_prs]

    all_scores: list[dict] = []
    for entry in entries:
        repo = entry.get("repo", "?")
        pr = entry.get("pr_number", 0)
        diff = entry.get("diff", "")
        ground_truth_list = entry.get("ground_truth", [])

        # Use the diff as the query, and first few human comments
        # as a proxy for "what the retrieval should have found"
        query = diff[:8_000] if diff else entry.get("title", "")
        gt_text = (
            " ".join(
                g.get("comment", "")
                for g in ground_truth_list[:5]
            )
            if ground_truth_list
            else None
        )

        # Retrieved contexts come from the graph run, but for the CLI
        # we don't re-run the graph β€” we just skip if no retrieval data
        # is available in the entry.
        stored_contexts = entry.get("retrieved_contexts", [])
        if not stored_contexts:
            logger.info(
                "[%s#%d] No stored retrieval contexts β€” skipping RAGAS",
                repo, pr,
            )
            continue

        logger.info("[%s#%d] Computing RAGAS scores …", repo, pr)
        try:
            scores = compute_ragas_retrieval_scores(
                query=query,
                retrieved_contexts=stored_contexts,
                ground_truth=gt_text,
            )
        except RuntimeError as exc:
            logger.warning("[%s#%d] %s", repo, pr, exc)
            break

        scores.update({"repo": repo, "pr_number": pr, "id": entry.get("id")})
        all_scores.append(scores)

        if args.log_to_observability:
            log_ragas_scores_to_langfuse(scores, repo=repo, pr_number=pr)

        print(
            f"  {repo}#{pr}: "
            + " | ".join(
                f"{k}={v:.3f}" for k, v in scores.items()
                if k not in ("repo", "pr_number", "id") and v is not None
            )
        )

    # Print aggregate
    if all_scores:
        print()
        print("=" * 60)
        print("  Aggregate RAGAS scores")
        print("=" * 60)
        metrics = [
            k for k in all_scores[0].keys()
            if k not in ("repo", "pr_number", "id")
        ]
        for metric in metrics:
            values = [
                s.get(metric) for s in all_scores
                if s.get(metric) is not None
            ]
            if not values:
                print(f"  {metric:30s}: n/a  (no successful scores)")
                continue
            avg = sum(values) / len(values)
            print(f"  {metric:30s}: {avg:.4f}  (over {len(values)} PRs)")
        print()

    # Save output
    if args.output and all_scores:
        with open(args.output, "w", encoding="utf-8") as f:
            json.dump(all_scores, f, indent=2)
        logger.info("Saved RAGAS scores to %s", args.output)


if __name__ == "__main__":
    main()