Search Tutorials
--Ads--Generation Metrics: Faithfulness and Answer Relevance
Measure groundedness, answer relevance and context precision and recall.
Retrieval metrics tell you whether the evidence was found. Generation metrics tell you what the model did with it. Because answers are free text, most generation metrics use an LLM as the evaluator. This lesson implements the core ones: faithfulness, answer relevance, context precision and context recall, following the definitions popularised by the RAGAS framework.
Faithfulness (groundedness)
Is every claim in the answer supported by the retrieved context? This is the most important generation metric for RAG, because unsupported claims are hallucinations from the user's point of view, even when they happen to be true. The standard method has two steps:
- Break the answer into individual factual claims.
- Check each claim against the context. Faithfulness = supported claims / total claims.
from typing import Literal
from pydantic import BaseModel
import anthropic
client = anthropic.Anthropic()
def judge(prompt: str, schema, effort: str = "low"):
response = client.messages.parse(
model="claude-opus-5-5", max_tokens=3000, output_config={"effort": effort},
messages=[{"role": "user", "content": prompt}], output_format=schema)
return response.parsed_output
class Claims(BaseModel):
claims: list[str]
class ClaimVerdict(BaseModel):
claim: str
verdict: Literal["supported", "not_supported"]
evidence: str # quote from the context, or "" if none
class Verdicts(BaseModel):
verdicts: list[ClaimVerdict]
def faithfulness(answer: str, contexts: list[str]) -> tuple[float, list[ClaimVerdict]]:
claims = judge(f"Break this answer into short, self-contained factual claims. Ignore "
f"greetings and statements that the information is unavailable.\n\n"
f"<answer>\n{answer}\n</answer>", Claims).claims
if not claims:
return 1.0, [] # nothing claimed, nothing unsupported
context = "\n\n".join(contexts)
result = judge(f"<context>\n{context}\n</context>\n\nFor each claim, decide whether the context "
f"supports it. Quote the supporting text.\n\nClaims:\n"
+ "\n".join(f"- {c}" for c in claims), Verdicts).verdicts
supported = sum(v.verdict == "supported" for v in result)
return supported / len(result), result
The per-claim verdicts are as useful as the score: they show exactly which sentence was invented.
Answer relevance
Does the answer address the question that was asked? An answer can be perfectly faithful and still miss the point ("Our leave policy was updated in March" in reply to "How many days do I get?"). A simple judge prompt with a small scale works well:
class Relevance(BaseModel):
reasoning: str
score: Literal[0, 1, 2] # 0 = off-topic, 1 = partial, 2 = fully addresses the question
def answer_relevance(question: str, answer: str) -> int:
r = judge(f"Question: {question}\n\nAnswer: {answer}\n\nDoes the answer address the question? "
"0 = does not address it, 1 = partly or with unnecessary content, 2 = fully and "
"directly. A clear statement that the information is not available counts as 2 "
"only if the question cannot be answered.", Relevance)
return r.score
RAGAS computes a similar metric differently: it generates questions from the answer and measures their embedding similarity to the original question. Both approaches estimate the same property.
Context precision
Of the retrieved chunks, how many were actually useful for answering? Low context precision means noisy prompts. Ask the judge to label each chunk; RAGAS additionally weights the result by rank so that useful chunks at the top count more.
class ChunkUseful(BaseModel):
useful: list[bool]
def context_precision(question: str, contexts: list[str], reference: str | None = None) -> float:
target = f"Reference answer: {reference}\n\n" if reference else ""
numbered = "\n\n".join(f"[{i}] {c}" for i, c in enumerate(contexts))
flags = judge(f"Question: {question}\n{target}\n{numbered}\n\nFor each numbered passage in order, "
"is it useful for answering the question? Return one boolean per passage.",
ChunkUseful).useful[:len(contexts)]
# rank-weighted average precision over the useful positions
hits, total = 0, 0.0
for rank, useful in enumerate(flags, start=1):
if useful:
hits += 1
total += hits / rank
return total / hits if hits else 0.0
Context recall
Does the retrieved context contain everything needed for the reference answer? This needs a reference answer. Split the reference into statements and check whether each is supported by the context; it is the generation-side counterpart of retrieval recall and works even without chunk-level labels.
def context_recall(reference: str, contexts: list[str]) -> float:
statements = judge(f"Break this reference answer into short factual statements.\n\n{reference}",
Claims).claims
if not statements:
return 1.0
verdicts = judge(f"<context>\n{chr(10).join(contexts)}\n</context>\n\nFor each statement, can it be "
"attributed to the context?\n\nStatements:\n" + "\n".join(f"- {s}" for s in statements),
Verdicts).verdicts
return sum(v.verdict == "supported" for v in verdicts) / len(verdicts)
Reading the metrics together
| Pattern | Likely cause | Where to look |
|---|---|---|
| Low context recall | Evidence not retrieved | Chunking, embeddings, hybrid search, query transformation |
| Good recall, low context precision | Too much noise | Reranking, smaller k, thresholds |
| Good context, low faithfulness | Model adds unsupported content | Prompt grounding rules, lower effort on creative tasks, citations |
| Faithful but low relevance | Answer misses the point | Prompt instructions, question understanding |
LLM-based metrics are themselves models that can be wrong. Before relying on them, compare their verdicts with human judgements on 30 to 50 examples, as described in LLM-as-Judge Evaluation.
Key takeaways
- Faithfulness splits the answer into claims and checks each against the context.
- Answer relevance checks whether the answer addresses the question.
- Context precision and context recall evaluate retrieval through the lens of the answer.
- Read the metrics together to locate failures, and validate LLM judges against humans.