|
| 1 | +"""Context Recall metric v2 - Class-based implementation with modern components.""" |
| 2 | + |
| 3 | +import typing as t |
| 4 | + |
| 5 | +import numpy as np |
| 6 | +from pydantic import BaseModel |
| 7 | + |
| 8 | +from ragas.metrics.collections.base import BaseMetric |
| 9 | +from ragas.metrics.result import MetricResult |
| 10 | +from ragas.prompt.metrics.context_recall import context_recall_prompt |
| 11 | + |
| 12 | +if t.TYPE_CHECKING: |
| 13 | + from ragas.llms.base import InstructorBaseRagasLLM |
| 14 | + |
| 15 | + |
| 16 | +class ContextRecallClassification(BaseModel): |
| 17 | + """Structured output for a single statement classification.""" |
| 18 | + |
| 19 | + statement: str |
| 20 | + reason: str |
| 21 | + attributed: int |
| 22 | + |
| 23 | + |
| 24 | +class ContextRecallOutput(BaseModel): |
| 25 | + """Structured output for context recall classifications.""" |
| 26 | + |
| 27 | + classifications: t.List[ContextRecallClassification] |
| 28 | + |
| 29 | + |
| 30 | +class ContextRecall(BaseMetric): |
| 31 | + """ |
| 32 | + Evaluate context recall by classifying if statements can be attributed to context. |
| 33 | +
|
| 34 | + This implementation uses modern instructor LLMs with structured output. |
| 35 | + Only supports modern components - legacy wrappers are rejected with clear error messages. |
| 36 | +
|
| 37 | + Usage: |
| 38 | + >>> import instructor |
| 39 | + >>> from openai import AsyncOpenAI |
| 40 | + >>> from ragas.llms.base import instructor_llm_factory |
| 41 | + >>> from ragas.metrics.collections import ContextRecall |
| 42 | + >>> |
| 43 | + >>> # Setup dependencies |
| 44 | + >>> client = AsyncOpenAI() |
| 45 | + >>> llm = instructor_llm_factory("openai", client=client, model="gpt-4o-mini") |
| 46 | + >>> |
| 47 | + >>> # Create metric instance |
| 48 | + >>> metric = ContextRecall(llm=llm) |
| 49 | + >>> |
| 50 | + >>> # Single evaluation |
| 51 | + >>> result = await metric.ascore( |
| 52 | + ... user_input="What is the capital of France?", |
| 53 | + ... retrieved_contexts=["Paris is the capital of France."], |
| 54 | + ... reference="Paris is the capital and largest city of France." |
| 55 | + ... ) |
| 56 | + >>> print(f"Score: {result.value}") |
| 57 | + >>> |
| 58 | + >>> # Batch evaluation |
| 59 | + >>> results = await metric.abatch_score([ |
| 60 | + ... {"user_input": "Q1", "retrieved_contexts": ["C1"], "reference": "A1"}, |
| 61 | + ... {"user_input": "Q2", "retrieved_contexts": ["C2"], "reference": "A2"}, |
| 62 | + ... ]) |
| 63 | +
|
| 64 | + Attributes: |
| 65 | + llm: Modern instructor-based LLM for classification |
| 66 | + name: The metric name |
| 67 | + allowed_values: Score range (0.0 to 1.0) |
| 68 | + """ |
| 69 | + |
| 70 | + # Type hints for linter (attributes are set in __init__) |
| 71 | + llm: "InstructorBaseRagasLLM" |
| 72 | + |
| 73 | + def __init__( |
| 74 | + self, |
| 75 | + llm: "InstructorBaseRagasLLM", |
| 76 | + name: str = "context_recall", |
| 77 | + **kwargs, |
| 78 | + ): |
| 79 | + """Initialize ContextRecall metric with required components.""" |
| 80 | + # Set attributes explicitly before calling super() |
| 81 | + self.llm = llm |
| 82 | + |
| 83 | + # Call super() for validation |
| 84 | + super().__init__(name=name, **kwargs) |
| 85 | + |
| 86 | + async def ascore( |
| 87 | + self, |
| 88 | + user_input: str, |
| 89 | + retrieved_contexts: t.List[str], |
| 90 | + reference: str, |
| 91 | + ) -> MetricResult: |
| 92 | + """ |
| 93 | + Calculate context recall score asynchronously. |
| 94 | +
|
| 95 | + Components are guaranteed to be validated and non-None by the base class. |
| 96 | +
|
| 97 | + Args: |
| 98 | + user_input: The original question |
| 99 | + retrieved_contexts: List of retrieved context strings |
| 100 | + reference: The reference answer to evaluate |
| 101 | +
|
| 102 | + Returns: |
| 103 | + MetricResult with recall score (0.0-1.0) |
| 104 | + """ |
| 105 | + # Combine contexts into a single string |
| 106 | + context = "\n".join(retrieved_contexts) if retrieved_contexts else "" |
| 107 | + |
| 108 | + # Generate prompt |
| 109 | + prompt = context_recall_prompt( |
| 110 | + question=user_input, context=context, answer=reference |
| 111 | + ) |
| 112 | + |
| 113 | + # Get classifications from LLM |
| 114 | + result = await self.llm.agenerate(prompt, ContextRecallOutput) |
| 115 | + |
| 116 | + # Calculate score |
| 117 | + if not result.classifications: |
| 118 | + return MetricResult(value=np.nan) |
| 119 | + |
| 120 | + # Count attributions |
| 121 | + attributions = [c.attributed for c in result.classifications] |
| 122 | + score = sum(attributions) / len(attributions) if attributions else np.nan |
| 123 | + |
| 124 | + return MetricResult(value=float(score)) |
0 commit comments