蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行文本切分、检索融合和证据验证

PYTHONCPython 3.12,langchain-text-splitters 1.1.3,SQLite FTS5;固定本地资料和本地引用验证rag_pipeline.py
rag_pipeline.py178 行
"""Offline RAG teaching chain with real text splitting, BM25 and citation validation."""
from collections import deque
from dataclasses import dataclass
from importlib.metadata import version
from math import sqrt
import re
import sqlite3

from langchain_text_splitters import RecursiveCharacterTextSplitter

from lab_tools import run_exercise


@dataclass(frozen=True)
class Passage:
    id: str
    text: str
    role: str = "public"


PASSAGES = (
    Passage("A10","ramp railing checklist; inspect bolts"),
    Passage("B17","ramp B17 wet deck; close south gate"),
    Passage("C03","staff B17 incident number","staff"),
    Passage("D02","battery D02; replace the sensor battery"),
)


def terms(text):
    return re.findall(r"[A-Za-z0-9]+",text.lower())


def dense(question, passages, limit):
    vocabulary=("ramp","battery","sensor","gate")
    def encode(text):
        tokens=terms(text)
        return [int(word in tokens) for word in vocabulary]
    query=encode(question)
    candidates=[]
    for record in passages:
        item=encode(record.text)
        product=sum(a*b for a,b in zip(item,query,strict=True))
        if product:
            score=product/sqrt(sum(query)*sum(item))
            candidates.append((record.id,score))
    return [key for key,_ in sorted(candidates,key=lambda item:(-item[1],item[0]))[:limit]]


def lexical(db, question, role, limit):
    if not terms(question):
        return []
    query=" OR ".join('"' + term + '"' for term in terms(question))
    return [row[0] for row in db.execute(
        "SELECT id FROM passages WHERE passages MATCH ? AND role=? ORDER BY bm25(passages), id LIMIT ?",
        (query,role,limit))]


def fuse(*lists):
    ranks={}
    for sequence in lists:
        for position, key in enumerate(sequence,1):
            ranks[key]=ranks.get(key,0)+1/(60+position)
    return sorted(ranks,key=lambda key:(-ranks[key],key))


def rerank(question, keys, by_id):
    required={term for term in terms(question) if any(ch.isdigit() for ch in term)}
    return sorted(keys,key=lambda key:(-len(required.intersection(terms(by_id[key].text))),key))


def validate_evidence(hits, citations, by_id):
    if not citations or any(key not in hits or not quote or quote not in by_id[key].text for key,quote in citations):
        raise ValueError("unverified quote or citation")
    return " / ".join(f"{quote} [{key}]" for key,quote in citations)


def parent_context(child, parents, role, budget):
    parent=parents.get(child.metadata["parent_id"])
    if parent is None or parent.role != role or len(parent.text) > budget:
        return None
    offset=child.metadata["start_index"]
    if parent.text[offset:offset+len(child.page_content)] != child.page_content:
        return None
    return parent.text


def graph_path(edges,start,target):
    queue=deque([(start,)])
    seen={start}
    while queue:
        path=queue.popleft()
        if path[-1]==target:
            return list(path)
        for child in edges.get(path[-1],()):
            if child not in seen:
                seen.add(child)
                queue.append((*path,child))
    return None


def retrieval_metrics(retrieved,relevant):
    if not relevant:
        return None
    hit=len(set(retrieved)&set(relevant))
    return [hit/len(retrieved) if retrieved else 0.0,hit/len(relevant)]


def exercise(checks, _):
    expect=checks.expect
    expect("rag_splitter_version","package metadata","Read installed splitter version","1.1.3",version("langchain-text-splitters"))
    splitter=RecursiveCharacterTextSplitter(chunk_size=8,chunk_overlap=0,separators=["\n\n","。",""],length_function=len)
    guide="潮位手册。\n\n航标检查。\n\n离线值守。"
    expect("rag_recursive_zh",guide,"Split on ordered paragraph and sentence separators",
        ["潮位手册。","航标检查。","离线值守。"],splitter.split_text(guide))
    splitter=RecursiveCharacterTextSplitter(chunk_size=4,chunk_overlap=2,separators=[""],add_start_index=True)
    docs=splitter.create_documents(["ABCDEFGHIJ"],metadatas=[{"parent_id":"manual"}])
    expect("rag_overlap_offsets","ABCDEFGHIJ","Read text, overlap, exact offsets and stable parent ID",
        [["ABCD",0,"manual"],["CDEF",2,"manual"],["EFGH",4,"manual"],["GHIJ",6,"manual"]],
        [[doc.page_content,doc.metadata["start_index"],doc.metadata["parent_id"]] for doc in docs])
    expect("rag_empty_split","","Split an empty document",[],splitter.split_text(""))
    parent=Passage("manual","ABCDEFGHIJ")
    expect("rag_parent_context",{"child":"CDEF","parent":"manual","offset":2},
        "Expand to the parent only when its identity, source offset, scope and budget pass",
        ["ABCDEFGHIJ",None,None],
        [parent_context(docs[1],{"manual":parent},"public",10),
         parent_context(docs[1],{"manual":parent},"staff",10),
         parent_context(docs[1],{"manual":parent},"public",8)])

    db=sqlite3.connect(":memory:")
    try:
        db.execute("CREATE VIRTUAL TABLE passages USING fts5(id UNINDEXED, text, role UNINDEXED)")
        db.executemany("INSERT INTO passages VALUES (?,?,?)",[(row.id,row.text,row.role) for row in PASSAGES])
        public={row.id:row for row in PASSAGES if row.role=="public"}
        question="ramp B17"
        dense_one=dense(question,public.values(),1)
        words=lexical(db,question,"public",2)
        expect("rag_dense_loses_identifier",question,"Search one toy dense candidate before lexical search",["A10"],dense_one)
        expect("rag_bm25",question,"Use SQLite FTS5 BM25 within public rows",["B17","A10"],words)
        expect("rag_access_scope","B17","Search a code shared by public and staff entries using both scopes",
            [["B17"],["C03"]],[lexical(db,"B17","public",3),lexical(db,"B17","staff",3)])
        expect("rag_rewrite","deck B17","Apply a fixed query rewrite to a known term variant",["B17","A10"],
            lexical(db,"ramp B17","public",2))
        candidates=fuse(dense_one,words)
        ordered=rerank(question,candidates,public)
        expect("rag_fuse_and_rerank",{"dense":dense_one,"bm25":words},"Fuse ranks and use an explicit pair score",
            [["A10","B17"],["B17","A10"]],[candidates,ordered])
        expect("rag_rerank_tie",["B17","A10"],"Resolve equal scores by stable document ID",
            ["A10","B17"],rerank("ramp",["B17","A10"],public))
        expect("rag_evidence","close south gate","Verify a literal quote inside a retrieved allowed record",
            "close south gate [B17]",validate_evidence(ordered,[("B17","close south gate")],public))
        for name, hits, citations in (
            ("ungrounded",ordered,[("B17","open south gate")]),
            ("unretrieved",ordered,[("D02","replace the sensor battery")]),
            ("empty",[],[]),
        ):
            try:
                validate_evidence(hits,citations,public)
            except ValueError:
                actual="insufficient"
            else:
                actual="passed"
            expect("rag_refuse_"+name,citations,"Refuse a missing or ungrounded citation","insufficient",actual)
        expect("rag_precision_recall",["B17","A10"],"Compare exact ID precision and recall against a labeled set",
            [0.5,1.0],retrieval_metrics(["B17","A10"],["B17"]))
        expect("rag_no_hits","unlisted","Allow an empty retrieval and report zero recall for a nonempty reference",
            [[],[0.0,0.0]],[lexical(db,"unlisted","public",4),retrieval_metrics([],["B17"])])
    finally:
        db.close()

    edges={"pier":("ramp",),"ramp":("pier","sensor"),"sensor":("safety-log",)}
    expect("rag_graph_path",["pier","safety-log"],"Traverse a local cycle safely and preserve source relationship order",
        ["pier","ramp","sensor","safety-log"],graph_path(edges,"pier","safety-log"))
    expect("rag_graph_miss","unlinked","Stop traversal when the target has no path",None,graph_path(edges,"pier","unlinked"))


if __name__=="__main__":
    run_exercise(exercise)
本例需在 CPython 3.12,langchain-text-splitters 1.1.3,SQLite FTS5;固定本地资料和本地引用验证 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12,langchain-text-splitters 1.1.3,SQLite FTS5;固定本地资料和本地引用验证

入口文件:projects/ai-agent-rag/rag_pipeline.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 rag_pipeline.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12,langchain-text-splitters 1.1.3,SQLite FTS5;固定本地资料和本地引用验证。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3105.zip

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习