首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >可运行的 RAG 答案忠实度组件:Claim 拆分、引用覆盖和拒答门禁

可运行的 RAG 答案忠实度组件:Claim 拆分、引用覆盖和拒答门禁

原创
作者头像
用户12114629
发布于 2026-11-29 07:13:04
发布于 2026-11-29 07:13:04
100
举报

RAG 系统只检查检索结果还不够。候选答案生成后,还需要逐句判断内容是否由上下文支持,尤其是制造售后知识库里的报警处理、复位条件、安全联锁和版本差异,不能让模型凭经验补充操作。

下面给出一个可直接改造的 Python 组件,覆盖 claim 拆分、事实句判定、引用覆盖率和发布门禁。

一、定义评估数据结构

代码语言:python
复制
from dataclasses import dataclass

@dataclass
class ClaimResult:
    sentence: str
    label: str  # supported / unsupported / contradictory / disputed
    score: float
    support: str | None = None
    contradiction: str | None = None

label 不建议只使用“基本正确”这类模糊结果。只要关键事实没有被上下文完全支持,就不能和 supported 放在同一类。

二、拆分候选答案

代码语言:python
复制
def split_claims(answer: str) -> list[str]:
    # 先按中文句号拆分,工程中可替换为 NLP 分句器
    return [sentence.strip() for sentence in answer.split("。") if sentence.strip()]

如果一个句子同时包含条件和动作,例如“断开负载后等待三分钟,再重新上电”,评估时需要确认两个动作都能在证据中找到。

三、计算忠实度和引用覆盖率

代码语言:python
复制
def grounded_rate(results: list[ClaimResult]) -> float:
    if not results:
        return 0.0
    return sum(item.label == "supported" for item in results) / len(results)

def citation_coverage(claims: list[str], cited_claims: set[str]) -> float:
    if not claims:
        return 0.0
    return len(cited_claims & set(claims)) / len(claims)

忠实度只统计完全 supported 的事实句。引用覆盖率用来检查关键结论是否都有对应引用,避免答案末尾只挂一个文档链接却没有逐句映射。

四、执行拒答门禁

代码语言:python
复制
def groundedness_gate(results: list[ClaimResult], threshold: float) -> str:
    score = grounded_rate(results)
    has_risk = any(item.label in {"unsupported", "contradictory"} for item in results)
    if score >= threshold and not has_risk:
        return "allow"
    return "abstain"

出现 contradictory 时,即使整体分数较高,也不应该继续返回确定答案。系统可以改为提示“当前资料存在冲突,已转人工核实”,并保留冲突片段。

五、组装一次完整评估

代码语言:python
复制
def evaluate_answer(answer: str, results: list[ClaimResult], threshold: float) -> dict:
    claims = split_claims(answer)
    return {
        "claim_count": len(claims),
        "grounded_rate": grounded_rate(results),
        "citation_coverage": citation_coverage(claims, {
            item.sentence for item in results if item.support
        }),
        "gate": groundedness_gate(results, threshold),
    }

返回结果建议写入评估日志,并额外保存上下文 ID、文档版本、设备型号、支持片段、冲突片段和拦截原因。

六、发布前核验指标

上线前固定记录以下指标:

  • groundedness / faithfulness:答案忠实度;
  • unsupported claim rate:无依据事实句占比;
  • contradictory claim count:冲突事实句数量;
  • disputed claim count:证据冲突数量;
  • citation precision 和 citation coverage:引用精确性与覆盖率;
  • threshold block rate:阈值拦截率;
  • grounding check P95 latency:校验延迟。

这套组件的价值在于把“答案看起来合理”变成可复算、可追溯、可拦截的工程判断。只要关键结论无法回到证据,就不应该把流畅文本当成可靠答案。

讨论问题:你会把忠实度组件放在发布前离线评估里,还是作为每次在线问答的强制门禁?

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

目录
  • 一、定义评估数据结构
  • 二、拆分候选答案
  • 三、计算忠实度和引用覆盖率
  • 四、执行拒答门禁
  • 五、组装一次完整评估
  • 六、发布前核验指标
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档