跳到正文
Agent Field Notes
课程目录展开方向,选择要学习的课程。

SYSTEMATIC LEARNING / 分层专题

RAG 证据:适用性、完整上下文与声明支撑

跟踪退货规则与电池例外经过过滤、排序和上下文组装,再拒绝有引用却被证据反驳的声明。

学习目标:找到最早丢失必要证据的阶段,区分检索相关性、引用成员关系和有界声明支撑。

内容核对2026-10-11 · 每层有独立讲解、任务与检查

按这个知识点的熟悉程度选择起点。当前层:资深 · 解释取舍。完成任务后可以继续下一层;阅读与自检不自动代表掌握。

本层学习目录

先补齐必要概念

适合:需要跨服务、时间和故障边界选择保证的工程师。

召回
从资料库找出可能相关的候选,不表示它们最终进入模型输入。
重排
重新排列候选的优先级,影响有限上下文中先放哪些材料。
必要证据
足以支持本问题结论的材料集合,可能同时需要正文和例外条款。
证据支持
结论是否被实际材料及适用条件支持;有引用链接也可能没有支持。

原理怎样一步步成立?

证据追踪:从适用性到实际上下文与声明支撑
  1. 1
    语料

    为主规则和例外附租户、组、版本和有效区间。

  2. 2
    可信查询上下文

    排名融合前过滤有权读取且适用的 ID。

  3. 3
    排名

    融合两条编写排名,保留阶段 ID。

  4. 4
    组装

    扩展有权读取的同版本条款,保留完整证据包或拒答。

  5. 5
    验证器

    检查上下文成员和有界条件,自由文本保持 not_scored。

本实验使用编写排名。关联的既有 RAG 流水线保留独立记录的真实本地 Embedding 来源。

逐步解释原理
  1. 确认资料

    原始资料存在、有效且有权使用。

  2. 召回与排序

    记录候选标识及排名。

  3. 组装上下文

    保留必要材料、条件与来源标识。

  4. 生成与核对

    检查每项结论及拒答是否符合证据。

资深 · 解释取舍

改变时间、权限与证据体积

本层目标:适用性在运行中变化或必要证据放不进一条 prompt 时,选择证据与拒答机制。

图解 · 同时保留主规则与例外

同时保留主规则与例外

引用成员检查只证明标识进入上下文。结论还须完整、适用的证据,并检查是否与条款矛盾;把两个引用都写上不保证正确。 点图可打开原图放大查看。

改变条件:历史政策问题、运行中权限撤销、必要证据大于 prompt 预算的多文档决策。一个相关性阈值不能同时解决三者。

历史问题要分开业务有效时间与索引入库时间。选择当时适用的主规则和例外,标注 as-of 基础,不把当前主规则与旧例外混用。更晚入库不自动替代更早却适用的政策。冲突来源需要明确优先级,或报告未解决冲突。

候选 ACL 快照有利于诊断,却不能保证稍后答案交付仍有权限。按风险在受保护读取/组装/交付边界复核,把缓存按租户与权限代次隔离,并定义权限变化后的行为。代价是额外读取和可用性损失;选择并说明真正执行策略的边界。

证据过大时比较完整包拒答、针对性二次检索和保留条件的结构化提取。完整包拒答简单但损失覆盖;二次检索增加延迟与停止规则;提取省上下文,但需来源 span 与例外保留测试。蕴含裁判可辅助自由文本审查,但必须校准,不能替代业务回执或 ACL。同时报告可回答覆盖和无依据错误,不能用增加拒答掩盖退化。

一个具体设计输入与应有决定

假设历史问题问at=150,交付前当前组权限被撤销,prompt只能放100字符而必要v2证据有163字符。不能因为v3更短更新就替换历史v2例外;从不分范围缓存返回旧答案也绕过当前读取权限。

先检查所选当前交付/读取策略,拒绝时不交付受保护文本。权限仍允许时,比较针对性二次检索与保留主规则/例外条件的可追踪结构化提取。两者都无法在预算内提供可验证的充分材料,就将依赖它的资格决策标为不支持。一般窗口只有在来源仍有权限且明确缺口时,才可作为部分回答。

运行实验,观察反例

编写的语料、排名、案例事实和候选声明;实际过滤/组装/规则检查。没有 Embedding、模型生成、任意自由文本蕴含或实时 ACL 服务。

Python 3.10+ · 默认运行只使用标准库 · 在你的电脑运行

  1. 比较故障与修复的阶段 ID 和完整上下文。
  2. 测试预算不足与空权限集合。
  3. 运行 RagTests,区分引用成员关系与规则支撑。
下载完整应用实验包(含数据与依赖脚本) ↓
python3 -B rag_evidence_deep_dive.py
查看本入口脚本
"""Bounded RAG experiment: authored rankings and claims, real local checks.

The score fixtures are not embeddings. The claim verifier is a narrow rule
checker, not an entailment model or an evaluation of free-form prose.
"""
import json
from dataclasses import dataclass


@dataclass(frozen=True)
class Chunk:
    id: str
    tenant: str
    group: str
    version: int
    valid_from: int
    valid_to: int
    policy: str
    text: str


CORPUS = (
    Chunk('returns-v1-base', 'tenant-a', 'retail', 1, 0, 100, 'returns', 'Old policy: unused products may be returned within 60 days.'),
    Chunk('returns-v2-base', 'tenant-a', 'retail', 2, 100, 300, 'returns', 'Current policy: unused products may be returned within 30 days. Product exceptions apply.'),
    Chunk('returns-v2-exception', 'tenant-a', 'retail', 2, 100, 300, 'returns', 'Opened batteries cannot be returned unless defective, even within 30 days.'),
    Chunk('returns-v3-base', 'tenant-a', 'retail', 3, 300, 999, 'returns', 'Future policy: unused products may be returned within 45 days.'),
    Chunk('tenant-b-base', 'tenant-b', 'retail', 2, 100, 300, 'returns', 'A different tenant accepts returns within 90 days.'),
)
INDEX = {chunk.id: chunk for chunk in CORPUS}
AUTHORED_VECTOR_ORDER = ['tenant-b-base', 'returns-v1-base', 'returns-v2-base', 'returns-v3-base', 'returns-v2-exception']
AUTHORED_LEXICAL_ORDER = ['returns-v2-base', 'returns-v2-exception', 'tenant-b-base', 'returns-v1-base', 'returns-v3-base']
FACTS = {'product': 'battery', 'opened': True, 'defective': False, 'age_days': 20}


def eligible(chunk, tenant, groups, at):
    return chunk.tenant == tenant and chunk.group in groups and chunk.valid_from <= at < chunk.valid_to


def rrf(rankings, k=60):
    scores = {}
    for ranking in rankings:
        if len(ranking) != len(set(ranking)):
            raise ValueError('duplicate_rank_id')
        for rank, item_id in enumerate(ranking, 1):
            scores[item_id] = scores.get(item_id, 0) + 1 / (k + rank)
    return [i for i, _ in sorted(scores.items(), key=lambda pair: (-pair[1], pair[0]))]


def assemble(tenant='tenant-a', groups=('retail',), at=150, budget=300, include_exception=True):
    allowed = {c.id for c in CORPUS if eligible(c, tenant, groups, at)}
    rankings = [[i for i in ranking if i in allowed] for ranking in (AUTHORED_VECTOR_ORDER, AUTHORED_LEXICAL_ORDER)]
    fused = rrf(rankings)
    selected = fused[:1]
    expanded = list(selected)
    if selected and include_exception:
        seed = INDEX[selected[0]]
        # Expansion repeats the authorization/time checks. Do not fetch a raw parent by ID.
        for c in CORPUS:
            if c.id in allowed and c.policy == seed.policy and c.version == seed.version and c.id not in expanded:
                expanded.append(c.id)
    chars = sum(len(INDEX[i].text) for i in expanded)
    # Preserve the complete bundle or abstain. Never silently truncate the exception.
    assembled = expanded if chars <= budget else []
    return {'query': 'opened battery return at 20 days', 'tenant': tenant, 'at': at,
            'eligible_ids': sorted(allowed), 'rankings': rankings, 'fused_ids': fused,
            'selected_ids': selected, 'expanded_ids': expanded, 'required_chars': chars,
            'budget_chars': budget, 'assembled_ids': assembled,
            'assembly_status': 'budget_exceeded' if expanded and not assembled else ('assembled' if assembled else 'no_evidence'),
            'context': [{'id': i, 'version': INDEX[i].version, 'text': INDEX[i].text} for i in assembled]}


def verify_claims(answer, trace, facts=FACTS):
    if type(answer) is not dict or set(answer) != {'claims'} or type(answer['claims']) is not list or not answer['claims']:
        return {'accepted': False, 'reason': 'answer_shape'}
    assembled = set(trace['assembled_ids'])
    if not assembled:
        return {'accepted': False, 'reason': 'no_assembled_evidence'}
    for claim in answer['claims']:
        if type(claim) is not dict or set(claim) != {'field', 'value', 'citations'}:
            return {'accepted': False, 'reason': 'claim_shape'}
        citations = claim['citations']
        if type(citations) is not list or not citations or any(type(i) is not str or i not in assembled for i in citations):
            return {'accepted': False, 'reason': 'citation_not_in_context'}
        if claim['field'] == 'eligible':
            required = {'returns-v2-base'}
            if facts['product'] == 'battery' and facts['opened']:
                required.add('returns-v2-exception')
            if not required.issubset(citations):
                return {'accepted': False, 'reason': 'missing_required_evidence'}
            expected = facts['age_days'] <= 30 and (not facts['opened'] or facts['defective'])
            if type(claim['value']) is not bool or claim['value'] != expected:
                return {'accepted': False, 'reason': 'claim_contradicted'}
        elif claim['field'] == 'window_days':
            if 'returns-v2-base' not in citations or type(claim['value']) is not int or claim['value'] != 30:
                return {'accepted': False, 'reason': 'claim_contradicted'}
        else:
            return {'accepted': False, 'reason': 'unsupported_claim_field'}
    return {'accepted': True, 'reason': 'bounded_rules_supported', 'semantic_prose': 'not_scored'}


def candidate(value=False, citations=None):
    return {'claims': [{'field': 'eligible', 'value': value,
                        'citations': citations if citations is not None else ['returns-v2-base', 'returns-v2-exception']}]}


def demo():
    broken = assemble(include_exception=False)
    fixed = assemble()
    short = assemble(budget=100)
    denied = assemble(groups=())
    return {'origin': 'authored_rankings_claims_local_rules',
            'failure': {'trace': broken, 'candidate': candidate(True, ['returns-v2-base']),
                        'verdict': verify_claims(candidate(True, ['returns-v2-base']), broken)},
            'repair': {'trace': fixed, 'candidate': candidate(), 'verdict': verify_claims(candidate(), fixed)},
            'present_citation_wrong_claim': verify_claims(candidate(True), fixed),
            'budget_failure': {'trace': short, 'verdict': verify_claims(candidate(), short)},
            'permission_failure': {'trace': denied, 'verdict': verify_claims(candidate(), denied)},
            'boundary': 'No embedding inference, model generation, arbitrary prose entailment, or live ACL update is tested.'}


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2, sort_keys=True))

本地运行的预期输出

{
  "boundary": "No embedding inference, model generation, arbitrary prose entailment, or live ACL update is tested.",
  "budget_failure": {
    "trace": {
      "assembled_ids": [],
      "assembly_status": "budget_exceeded",
      "at": 150,
      "budget_chars": 100,
      "context": [],
      "eligible_ids": [
        "returns-v2-base",
        "returns-v2-exception"
      ],
      "expanded_ids": [
        "returns-v2-base",
        "returns-v2-exception"
      ],
      "fused_ids": [
        "returns-v2-base",
        "returns-v2-exception"
      ],
      "query": "opened battery return at 20 days",
      "rankings": [
        [
          "returns-v2-base",
          "returns-v2-exception"
        ],
        [
          "returns-v2-base",
          "returns-v2-exception"
        ]
      ],
      "required_chars": 163,
      "selected_ids": [
        "returns-v2-base"
      ],
      "tenant": "tenant-a"
    },
    "verdict": {
      "accepted": false,
      "reason": "no_assembled_evidence"
    }
  },
  "failure": {
    "candidate": {
      "claims": [
        {
          "citations": [
            "returns-v2-base"
          ],
          "field": "eligible",
          "value": true
        }
      ]
    },
    "trace": {
      "assembled_ids": [
        "returns-v2-base"
      ],
      "assembly_status": "assembled",
      "at": 150,
      "budget_chars": 300,
      "context": [
        {
          "id": "returns-v2-base",
          "text": "Current policy: unused products may be returned within 30 days. Product exceptions apply.",
          "version": 2
        }
      ],
      "eligible_ids": [
        "returns-v2-base",
        "returns-v2-exception"
      ],
      "expanded_ids": [
        "returns-v2-base"
      ],
      "fused_ids": [
        "returns-v2-base",
        "returns-v2-exception"
      ],
      "query": "opened battery return at 20 days",
      "rankings": [
        [
          "returns-v2-base",
          "returns-v2-exception"
        ],
        [
          "returns-v2-base",
          "returns-v2-exception"
        ]
      ],
      "required_chars": 89,
      "selected_ids": [
        "returns-v2-base"
      ],
      "tenant": "tenant-a"
    },
    "verdict": {
      "accepted": false,
      "reason": "missing_required_evidence"
    }
  },
  "origin": "authored_rankings_claims_local_rules",
  "permission_failure": {
    "trace": {
      "assembled_ids": [],
      "assembly_status": "no_evidence",
      "at": 150,
      "budget_chars": 300,
      "context": [],
      "eligible_ids": [],
      "expanded_ids": [],
      "fused_ids": [],
      "query": "opened battery return at 20 days",
      "rankings": [
        [],
        []
      ],
      "required_chars": 0,
      "selected_ids": [],
      "tenant": "tenant-a"
    },
    "verdict": {
      "accepted": false,
      "reason": "no_assembled_evidence"
    }
  },
  "present_citation_wrong_claim": {
    "accepted": false,
    "reason": "claim_contradicted"
  },
  "repair": {
    "candidate": {
      "claims": [
        {
          "citations": [
            "returns-v2-base",
            "returns-v2-exception"
          ],
          "field": "eligible",
          "value": false
        }
      ]
    },
    "trace": {
      "assembled_ids": [
        "returns-v2-base",
        "returns-v2-exception"
      ],
      "assembly_status": "assembled",
      "at": 150,
      "budget_chars": 300,
      "context": [
        {
          "id": "returns-v2-base",
          "text": "Current policy: unused products may be returned within 30 days. Product exceptions apply.",
          "version": 2
        },
        {
          "id": "returns-v2-exception",
          "text": "Opened batteries cannot be returned unless defective, even within 30 days.",
          "version": 2
        }
      ],
      "eligible_ids": [
        "returns-v2-base",
        "returns-v2-exception"
      ],
      "expanded_ids": [
        "returns-v2-base",
        "returns-v2-exception"
      ],
      "fused_ids": [
        "returns-v2-base",
        "returns-v2-exception"
      ],
      "query": "opened battery return at 20 days",
      "rankings": [
        [
          "returns-v2-base",
          "returns-v2-exception"
        ],
        [
          "returns-v2-base",
          "returns-v2-exception"
        ]
      ],
      "required_chars": 163,
      "selected_ids": [
        "returns-v2-base"
      ],
      "tenant": "tenant-a"
    },
    "verdict": {
      "accepted": true,
      "reason": "bounded_rules_supported",
      "semantic_prose": "not_scored"
    }
  }
}
  • 例外缺失返回 missing_required_evidence。
  • 完整证据和 eligibility=False 通过;True 返回 claim_contradicted。
  • 预算不足和权限拒绝均没有实际上下文证据。
查看运行环境、输出和校验记录 →

代码示例

版本权威优先不等于排名优先

两份有权政策有效区间重叠且结论不同,更高RRF位置不能决定制度优先级。报告来源/权威冲突,在可信优先规则或审阅解决前停止重要决策。

本层验收任务

设计历史政策回答:ACL 实时变化,预算小于必要证据包。比较两种检索/组装策略,定义部分回答、拒答规则与混版本回归案例。

逐条验收自评

正在读取此浏览器记录…

收起答案,检查理解

两个有权读取的政策冲突时,排名最高的来源获胜吗?

延伸原理与知识练习

遇到不熟悉的原理,先阅读实现、连续追问和迁移案例,再独立说明前提与边界。作答与笔记保存到原有账号记录。

本专题的全部关联解析与练习(4 道)

依据与验证范围

原理依据来自公开资料;数字、案例和任务是本站教学设计。离线实验验证本页注明的范围,学习效果仍需通过独立任务与反馈判断。