跳到正文
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. 生成与核对

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

入门 · 理解原理

为什么相关资料与引用不能证明答案

本层目标:通过一条例外区分相关、有权读取、适用和充分的证据。

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

同时保留主规则与例外

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

一块已拆封、非缺陷电池在 20 天退货。当前规则允许未使用商品在 30 天内退货,相邻例外禁止已拆封电池退货,除非有缺陷。只引用“30 天”,会让答案看似有依据,却遗漏能够反转决策的条件。

证据有不同义务:相关性把候选资料带到问题附近;授权约束当前租户与读者能访问什么;适用性包含政策版本与有效时间;充分性要求实际上下文涵盖规则与所有重要例外;引用成员关系只证明某 ID 进入上下文,支撑则要核对声明及条件。

语料包含过期 v1、当前 v2 主规则及例外、未来 v3 和另一租户规则。高排名不能覆盖适用边界。先用可信权限范围与有效时间限制候选,再把限制保留到父块扩展和组装。安全过滤模式。

答案可以说有依据的退货窗口,把没有依据的运费标为 unknown。缺失事实决定写动作时,要拒绝该动作并补检索或澄清,比猜数字或一有缺口就拒绝整题更准确。

固定案例输入与三个声明

可信范围为tenant-a、retail组,有效时间at=150。案例事实为product=battery、opened=True、defective=False、age_days=20。returns-v2-base说明未使用商品可在30天退货且产品例外适用;returns-v2-exception说明已拆封电池不能退,除非有缺陷,即使仍在30天内。二者有效区间均为[100,300)。过期v1、未来v3及tenant-b材料不适用于这次有权案例。

任务固定使用这三个声明:

  1. 一般退货窗口是30天。来源为returns-v2-base,它支持窗口,不保证每类商品都有资格。
  2. 这块拆封非缺陷电池在20天时有退货资格。需要两条v2规则及案例事实;例外使这个声明为false。
  3. 退款已经执行。需要业务权威回执;两条政策均不提供,因此本案例是unknown。

变化案例只把defective改为True。按照本实验明确限定的v2资格规则,20天的缺陷电池可以eligible=True;资格成立仍不证明退款已提交。运费是另一项缺失事实,不是这里固定的第三个任务声明。

运行实验,观察反例

编写的语料、排名、案例事实和候选声明;实际过滤/组装/规则检查。没有 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。
  • 预算不足和权限拒绝均没有实际上下文证据。
查看运行环境、输出和校验记录 →

代码示例

时间改变会排除仍然相关的资料

保持电池事实但at改为300,v2区间已结束,文本再相关也不适用于当前政策声明。历史at150可在明确as-of基础使用它,但仍受当前读权限约束。

本层验收任务

对正文固定三项声明——一般窗口、本电池资格、退款已执行——制作证据映射,分别标相关性、权限、有效时间与支撑;再只改defective=True,解释资格变化而不声称已退款。

逐条验收自评

正在读取此浏览器记录…

收起答案,检查理解

已拆封非缺陷电池的 eligibility=True 声明附有正确引用 ID,答案有依据吗?

延伸原理与知识练习

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

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

依据与验证范围

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