|
| 1 | +"""Faithfulness metric v2 - Modern implementation with function-based prompts.""" |
| 2 | + |
| 3 | +import typing as t |
| 4 | +from typing import List |
| 5 | + |
| 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.common import nli_statement_prompt, statement_generator_prompt |
| 11 | + |
| 12 | +if t.TYPE_CHECKING: |
| 13 | + from ragas.llms.base import InstructorBaseRagasLLM |
| 14 | + |
| 15 | + |
| 16 | +class StatementGeneratorOutput(BaseModel): |
| 17 | + """Structured output for statement generation.""" |
| 18 | + |
| 19 | + statements: List[str] |
| 20 | + |
| 21 | + |
| 22 | +class StatementFaithfulnessAnswer(BaseModel): |
| 23 | + """Individual statement with reason and verdict for NLI evaluation.""" |
| 24 | + |
| 25 | + statement: str |
| 26 | + reason: str |
| 27 | + verdict: int |
| 28 | + |
| 29 | + |
| 30 | +class NLIStatementOutput(BaseModel): |
| 31 | + """Structured output for NLI statement evaluation.""" |
| 32 | + |
| 33 | + statements: List[StatementFaithfulnessAnswer] |
| 34 | + |
| 35 | + |
| 36 | +class Faithfulness(BaseMetric): |
| 37 | + """ |
| 38 | + Modern v2 implementation of faithfulness evaluation. |
| 39 | +
|
| 40 | + Measures how factually consistent a response is with the retrieved context. |
| 41 | + A response is considered faithful if all its claims can be supported by the context. |
| 42 | +
|
| 43 | + The metric works by: |
| 44 | + 1. Breaking down the response into atomic statements |
| 45 | + 2. Checking each statement against the retrieved contexts using NLI |
| 46 | + 3. Computing faithfulness as the ratio of supported statements |
| 47 | +
|
| 48 | + This implementation uses modern instructor LLMs with structured output. |
| 49 | + Only supports modern components - legacy wrappers are rejected with clear error messages. |
| 50 | +
|
| 51 | + Usage: |
| 52 | + >>> import instructor |
| 53 | + >>> from openai import AsyncOpenAI |
| 54 | + >>> from ragas.llms.base import instructor_llm_factory |
| 55 | + >>> from ragas.metrics.collections import Faithfulness |
| 56 | + >>> |
| 57 | + >>> # Setup dependencies |
| 58 | + >>> client = AsyncOpenAI() |
| 59 | + >>> llm = instructor_llm_factory("openai", client=client, model="gpt-4o-mini") |
| 60 | + >>> |
| 61 | + >>> # Create metric instance |
| 62 | + >>> metric = Faithfulness(llm=llm) |
| 63 | + >>> |
| 64 | + >>> # Single evaluation |
| 65 | + >>> result = await metric.ascore( |
| 66 | + ... user_input="Where was Einstein born?", |
| 67 | + ... response="Einstein was born in Germany on 14th March 1879.", |
| 68 | + ... retrieved_contexts=["Albert Einstein was born in Germany..."] |
| 69 | + ... ) |
| 70 | + >>> print(f"Faithfulness Score: {result.value}") |
| 71 | +
|
| 72 | + Attributes: |
| 73 | + llm: Modern instructor-based LLM for statement generation and NLI evaluation |
| 74 | + name: The metric name |
| 75 | + allowed_values: Score range (0.0 to 1.0, higher is better) |
| 76 | + """ |
| 77 | + |
| 78 | + # Type hints for linter (attributes are set in __init__) |
| 79 | + llm: "InstructorBaseRagasLLM" |
| 80 | + |
| 81 | + def __init__( |
| 82 | + self, |
| 83 | + llm: "InstructorBaseRagasLLM", |
| 84 | + name: str = "faithfulness", |
| 85 | + **kwargs, |
| 86 | + ): |
| 87 | + """ |
| 88 | + Initialize Faithfulness metric with required components. |
| 89 | +
|
| 90 | + Args: |
| 91 | + llm: Modern instructor-based LLM for statement generation and NLI evaluation |
| 92 | + name: The metric name |
| 93 | + """ |
| 94 | + # Set attributes explicitly before calling super() |
| 95 | + self.llm = llm |
| 96 | + |
| 97 | + # Call super() for validation (without passing llm in kwargs) |
| 98 | + super().__init__(name=name, **kwargs) |
| 99 | + |
| 100 | + async def ascore( |
| 101 | + self, user_input: str, response: str, retrieved_contexts: List[str] |
| 102 | + ) -> MetricResult: |
| 103 | + """ |
| 104 | + Calculate faithfulness score. |
| 105 | +
|
| 106 | + Args: |
| 107 | + user_input: The original question |
| 108 | + response: The response to evaluate for faithfulness |
| 109 | + retrieved_contexts: The retrieved contexts to check against |
| 110 | +
|
| 111 | + Returns: |
| 112 | + MetricResult with faithfulness score (0.0-1.0, higher is better) |
| 113 | + """ |
| 114 | + # Input validation |
| 115 | + if not response: |
| 116 | + raise ValueError( |
| 117 | + "response is missing. Please add response to the test sample." |
| 118 | + ) |
| 119 | + if not user_input: |
| 120 | + raise ValueError( |
| 121 | + "user_input is missing. Please add user_input to the test sample." |
| 122 | + ) |
| 123 | + if not retrieved_contexts: |
| 124 | + raise ValueError( |
| 125 | + "retrieved_contexts is missing. Please add retrieved_contexts to the test sample." |
| 126 | + ) |
| 127 | + |
| 128 | + # Step 1: Break response into atomic statements |
| 129 | + statements = await self._create_statements(user_input, response) |
| 130 | + |
| 131 | + if not statements: |
| 132 | + # No statements generated - return NaN like legacy |
| 133 | + return MetricResult(value=float("nan")) |
| 134 | + |
| 135 | + # Step 2: Join all contexts and evaluate statements against them |
| 136 | + context_str = "\n".join(retrieved_contexts) |
| 137 | + verdicts = await self._create_verdicts(statements, context_str) |
| 138 | + |
| 139 | + # Step 3: Compute faithfulness score |
| 140 | + score = self._compute_score(verdicts) |
| 141 | + |
| 142 | + return MetricResult(value=float(score)) |
| 143 | + |
| 144 | + async def _create_statements(self, question: str, response: str) -> List[str]: |
| 145 | + """Break response into atomic statements using statement generator.""" |
| 146 | + prompt = statement_generator_prompt(question, response) |
| 147 | + result = await self.llm.agenerate(prompt, StatementGeneratorOutput) |
| 148 | + return result.statements |
| 149 | + |
| 150 | + async def _create_verdicts( |
| 151 | + self, statements: List[str], context: str |
| 152 | + ) -> NLIStatementOutput: |
| 153 | + """Evaluate statement faithfulness against context using NLI.""" |
| 154 | + prompt = nli_statement_prompt(context, statements) |
| 155 | + result = await self.llm.agenerate(prompt, NLIStatementOutput) |
| 156 | + return result |
| 157 | + |
| 158 | + def _compute_score(self, verdicts: NLIStatementOutput) -> float: |
| 159 | + """Compute faithfulness score as ratio of faithful statements.""" |
| 160 | + if not verdicts.statements: |
| 161 | + return float("nan") |
| 162 | + |
| 163 | + faithful_statements = sum( |
| 164 | + 1 if statement.verdict else 0 for statement in verdicts.statements |
| 165 | + ) |
| 166 | + num_statements = len(verdicts.statements) |
| 167 | + |
| 168 | + if num_statements > 0: |
| 169 | + score = faithful_statements / num_statements |
| 170 | + else: |
| 171 | + score = float("nan") |
| 172 | + |
| 173 | + return score |
0 commit comments