|
| 1 | +"""Context Precision metric v2 - Modern implementation with instructor LLMs.""" |
| 2 | + |
| 3 | +import typing as t |
| 4 | + |
| 5 | +import numpy as np |
| 6 | +from pydantic import BaseModel, Field |
| 7 | + |
| 8 | +from ragas.metrics.collections.base import BaseMetric |
| 9 | +from ragas.metrics.result import MetricResult |
| 10 | +from ragas.prompt.metrics.context_precision import context_precision_prompt |
| 11 | + |
| 12 | +if t.TYPE_CHECKING: |
| 13 | + from ragas.llms.base import InstructorBaseRagasLLM |
| 14 | + |
| 15 | + |
| 16 | +class ContextPrecisionVerification(BaseModel): |
| 17 | + """Structured output for context precision verification.""" |
| 18 | + |
| 19 | + reason: str = Field(..., description="Reason for the verdict") |
| 20 | + verdict: int = Field(..., description="Binary verdict: 1 if useful, 0 if not") |
| 21 | + |
| 22 | + |
| 23 | +class ContextPrecision(BaseMetric): |
| 24 | + """ |
| 25 | + Evaluate context precision using Average Precision metric. |
| 26 | +
|
| 27 | + This metric evaluates whether all relevant items (contexts) are ranked higher |
| 28 | + by checking if each context was useful in arriving at the given answer. |
| 29 | +
|
| 30 | + This implementation uses modern instructor LLMs with structured output. |
| 31 | + Only supports modern components - legacy wrappers are rejected with clear error messages. |
| 32 | +
|
| 33 | + Usage: |
| 34 | + >>> from openai import AsyncOpenAI |
| 35 | + >>> from ragas.llms.base import instructor_llm_factory |
| 36 | + >>> from ragas.metrics.collections import ContextPrecision |
| 37 | + >>> |
| 38 | + >>> # Setup dependencies |
| 39 | + >>> client = AsyncOpenAI() |
| 40 | + >>> llm = instructor_llm_factory("openai", client=client, model="gpt-4o-mini") |
| 41 | + >>> |
| 42 | + >>> # Create metric instance |
| 43 | + >>> metric = ContextPrecision(llm=llm) |
| 44 | + >>> |
| 45 | + >>> # Single evaluation |
| 46 | + >>> result = await metric.ascore( |
| 47 | + ... user_input="What is the capital of France?", |
| 48 | + ... retrieved_contexts=["Paris is the capital of France.", "London is in England."], |
| 49 | + ... reference="Paris" |
| 50 | + ... ) |
| 51 | + >>> print(f"Score: {result.value}") |
| 52 | + >>> |
| 53 | + >>> # Batch evaluation |
| 54 | + >>> results = await metric.abatch_score([ |
| 55 | + ... {"user_input": "Q1", "retrieved_contexts": ["C1", "C2"], "reference": "A1"}, |
| 56 | + ... {"user_input": "Q2", "retrieved_contexts": ["C1", "C2"], "reference": "A2"}, |
| 57 | + ... ]) |
| 58 | +
|
| 59 | + Attributes: |
| 60 | + llm: Modern instructor-based LLM for verification |
| 61 | + name: The metric name |
| 62 | + allowed_values: Score range (0.0 to 1.0) |
| 63 | + """ |
| 64 | + |
| 65 | + # Type hints for linter (attributes are set in __init__) |
| 66 | + llm: "InstructorBaseRagasLLM" |
| 67 | + |
| 68 | + def __init__( |
| 69 | + self, |
| 70 | + llm: "InstructorBaseRagasLLM", |
| 71 | + name: str = "context_precision", |
| 72 | + **kwargs, |
| 73 | + ): |
| 74 | + """Initialize ContextPrecision metric with required components.""" |
| 75 | + # Set attributes explicitly before calling super() |
| 76 | + self.llm = llm |
| 77 | + |
| 78 | + # Call super() for validation |
| 79 | + super().__init__(name=name, **kwargs) |
| 80 | + |
| 81 | + async def ascore( |
| 82 | + self, |
| 83 | + user_input: str, |
| 84 | + retrieved_contexts: t.List[str], |
| 85 | + reference: str, |
| 86 | + ) -> MetricResult: |
| 87 | + """ |
| 88 | + Calculate context precision score asynchronously. |
| 89 | +
|
| 90 | + The metric evaluates each retrieved context to determine if it was useful |
| 91 | + for arriving at the reference answer, then calculates average precision. |
| 92 | +
|
| 93 | + Args: |
| 94 | + user_input: The original question |
| 95 | + retrieved_contexts: List of retrieved context strings (in ranked order) |
| 96 | + reference: The reference answer to evaluate against |
| 97 | +
|
| 98 | + Returns: |
| 99 | + MetricResult with average precision score (0.0-1.0) |
| 100 | + """ |
| 101 | + # Handle edge cases |
| 102 | + if not retrieved_contexts: |
| 103 | + return MetricResult(value=0.0) |
| 104 | + |
| 105 | + if not reference or not user_input: |
| 106 | + return MetricResult(value=0.0) |
| 107 | + |
| 108 | + # Evaluate each context |
| 109 | + verdicts = [] |
| 110 | + for context in retrieved_contexts: |
| 111 | + # Generate prompt for this context |
| 112 | + prompt = context_precision_prompt( |
| 113 | + question=user_input, context=context, answer=reference |
| 114 | + ) |
| 115 | + |
| 116 | + # Get verification from LLM |
| 117 | + verification = await self.llm.agenerate( |
| 118 | + prompt, ContextPrecisionVerification |
| 119 | + ) |
| 120 | + |
| 121 | + # Store binary verdict (1 if useful, 0 if not) |
| 122 | + verdicts.append(1 if verification.verdict else 0) |
| 123 | + |
| 124 | + # Calculate average precision |
| 125 | + score = self._calculate_average_precision(verdicts) |
| 126 | + |
| 127 | + return MetricResult(value=float(score)) |
| 128 | + |
| 129 | + def _calculate_average_precision(self, verdict_list: t.List[int]) -> float: |
| 130 | + """ |
| 131 | + Calculate average precision from list of binary verdicts. |
| 132 | +
|
| 133 | + Average Precision formula: |
| 134 | + AP = (sum of (precision@k * relevance@k)) / (total relevant items) |
| 135 | +
|
| 136 | + Where: |
| 137 | + - precision@k = (relevant items in top k) / k |
| 138 | + - relevance@k = 1 if item k is relevant, 0 otherwise |
| 139 | +
|
| 140 | + Args: |
| 141 | + verdict_list: List of binary verdicts (1 for relevant, 0 for not) |
| 142 | +
|
| 143 | + Returns: |
| 144 | + Average precision score (0.0-1.0), or nan if no relevant items |
| 145 | + """ |
| 146 | + # Count total relevant items |
| 147 | + denominator = sum(verdict_list) + 1e-10 |
| 148 | + |
| 149 | + # Calculate sum of precision at each relevant position |
| 150 | + numerator = sum( |
| 151 | + [ |
| 152 | + (sum(verdict_list[: i + 1]) / (i + 1)) * verdict_list[i] |
| 153 | + for i in range(len(verdict_list)) |
| 154 | + ] |
| 155 | + ) |
| 156 | + |
| 157 | + score = numerator / denominator |
| 158 | + |
| 159 | + # Return nan if score is invalid |
| 160 | + if np.isnan(score): |
| 161 | + return np.nan |
| 162 | + |
| 163 | + return score |
0 commit comments