Agent Build智能体搭建 Tutor教程
Map地图 / Module模块 5 / labs/m05_*

RAG and knowledge graphRAG 与知识图谱

Find the right passage, prove it, and add graph edges where similarity misses.找到正确的段落并证明它,在相似度检索漏掉的地方用图的边补上。

What it is and why it exists它是什么,为什么需要它

What是什么

Retrieval-augmented generation puts retrieved text in front of the model at answer time. This module builds hybrid retrieval (vector plus keyword), rank fusion, an authority nudge, duplicate collapsing, and two kinds of graph expansion.检索增强生成(RAG)在回答时把检索到的文本放到模型面前。本模块搭建混合检索(向量加关键词)、排名融合、权威度微调、重复合并,以及两种图扩展。

Why为什么

The knowledge in a RAG system is in the store, and the model weights stay unchanged. An answer is grounded only if a tool returned the passage in that conversation. Retrieval quality sets the ceiling on answer quality and has to be measured apart from the chat model.RAG 系统的知识存在数据库里,模型权重并没有变。只有当工具在本次对话中返回了相应段落,回答才算有依据。检索质量决定了回答质量的上限,必须与聊天模型分开测量。

How it works工作原理

Where it sits in the build order它在搭建顺序中的位置

Needs first前置模块

  • Inference engineering推理工程Search needs an embedding call at index time and at query time. The vector width is fixed by that model, so the model choice comes first.索引和查询时都需要调用 embedding。向量维度由该模型决定,所以要先选定模型。Build out of order不按顺序搭建 Stand in with:可用以下替代: The hashing embedder in labs/common/llm.py. Plumbing works and results reflect shared words only.labs/common/llm.py 里的哈希 embedding。管道能跑通,但结果只反映词汇重合。
  • Knowledge management知识管理Retrieval returns what was ingested and ranks by signals made at ingestion: chunk boundaries, paths, tiers. Curation mistakes become retrieval mistakes that no ranking fix removes.检索只能返回入库的内容,并依靠入库时产生的信号排序:切块边界、路径、等级。整理阶段的错误会变成检索错误,任何排序手段都修不回来。Build out of order不按顺序搭建 Stand in with:可用以下替代: Three or four hand-written text files in one folder, all at the same tier.一个目录里放三四个手写的文本文件,等级都相同。
  • State and storage状态与存储Chunks, vectors, and edges need tables that survive a nightly writer and concurrent readers.文本块、向量和边需要存在表里,并且要经得住夜间写入和并发读取。Build out of order不按顺序搭建 Stand in with:可用以下替代: An in-memory list with brute-force cosine similarity.一个内存列表,加暴力计算的余弦相似度。

Unlocks解锁

  • Tools and MCP工具与 MCPThe first tool wraps search. Its result shape and diagnostic come from the retrieval module.第一个工具封装的就是检索。它的结果结构和诊断信息来自检索模块。
  • Evaluation评估The retrieval eval calls search and scores what it returns. Gold items name chunk ids, so the index has to exist.检索评估调用 search 并对返回结果评分。标准条目里写的是 chunk id,所以索引必须已经存在。
  • Self-evolving agents自进化智能体When the loop studies documents, it reads indexed chunks and must skip the held-out ones.循环学习文档时读取的是已索引的文本块,并且必须跳过留出的那些。

In the reference build在参考系统中

Path路径Role作用
apps/agent-server/kb_extract.pyTurn a source file into clean, structure-aware chunks.把源文件变成干净、保留结构的文本块。
apps/agent-server/tools/knowledge_base.pyThe search tool: hybrid SQL, fusion, authority weight, dedup, graph expansion, trace.检索工具:混合 SQL、融合、权威加权、去重、图扩展、追踪日志。
apps/agent-server/nightly/defines.pyBuilds definition edges from set definitional forms.从固定的定义句式中建立“定义”边。
apps/agent-server/nightly/citations.pyBuilds citation edges between passages.建立段落之间的“引用”边。
apps/agent-server/tools/passage_dedup.pyOne result for a paragraph that exists in several files.同一段落存在于多个文件时只返回一条。

Process map流程图

One search, from question to returned passages一次检索:从问题到返回的段落

  1. 1
    Question and collection问题与集合Collections are separate indexes on purpose.各集合的索引是有意分开的。
  2. 2
    Embed the query把问题向量化With the same model that embedded the chunks.使用与文本块相同的 embedding 模型。
  3. 3
    Dense top N向量检索 Top NNearest vectors. Finds paraphrases.最近邻向量。能找到换了说法的内容。
  4. 4
    Lexical top N关键词检索 Top NFull-text match by BM25. Finds exact terms, codes, and section numbers.按 BM25 的全文匹配。能找到精确术语、编号和章节号。
  5. 5
    Fuse by rank按名次融合Score is the sum of 1/(60 + rank) across the two lists.得分是两个列表中 1/(60 + 名次) 之和。
  6. 6
    Authority and dedup权威度与去重A bonus worth about one rank. One copy of a repeated paragraph.相当于约一个名次的加分。重复段落只留一份。
  7. 7
    Graph expansion图扩展Add defining and cited passages when the question calls for them.当问题需要时,补上定义段落和被引用的段落。
  8. 8
    Return with sources连同来源一起返回Text, source, section, and a diagnostic when nothing matched.文本、来源、章节;没有匹配时返回诊断信息。

Build steps搭建步骤

Follow them in order the first time. Each step names what it uses from earlier steps and what it leaves for later ones. Code is read from the lab files, and output is what the lab printed when it was run.第一次请按顺序做。每一步都写明它用到前面步骤的什么成果,又为后面的步骤留下什么。代码直接读取自 lab 文件,输出是 lab 实际运行时打印的内容。

  1. 1Chunk with a context line切块时带上上下文行
  2. 2Embed and load, driven by the ledger由台账驱动,向量化并入库
  3. 3Dense search向量检索
  4. 4Lexical search关键词检索
  5. 5Fuse the two lists by rank按名次融合两个列表
  6. 6Add the authority nudge and collapse duplicates加入权威度微调并合并重复
  7. 7Build graph edges at index time在索引阶段建立图的边
  8. 8Expand results along the edges沿着边扩展检索结果
  9. 9Explain empty results and write a trace解释空结果,并记录追踪信息
  10. 10Production form: Postgres with pgvector生产形态:Postgres 加 pgvector
01Chunk with a context line切块时带上上下文行
Why this step is here为什么这一步排在这里Chunking decides what a hit can contain, and the embedding is of the chunk text. It is first because changing it later means re-embedding everything.切块决定一次命中能包含什么,而向量是对块文本计算的。它排第一,因为以后再改就得全部重新向量化。

Do this操作

  1. Split on headings first, then by size with overlap.先按标题切分,再按长度切分并保留重叠。
  2. Store a context string per chunk: document title and section heading.为每个块保存一个上下文字符串:文档标题和章节标题。
  3. Index the context with the text so a chunk can match on its section name.把上下文和正文一起建索引,这样块可以通过章节名被匹配到。
labs/m05_rag/index.py · chunk
def chunk_markdown(text: str, size: int = 500, overlap: int = 80) -> list:
    """Split on headings first, then by size. Returns [(context, text)].

    The context is "<document title> > <section heading>". It is stored beside the
    chunk and indexed for keyword search, so a chunk can match on its section name.
    """
    title = ""
    section = ""
    blocks = []                 # (context, paragraph)
    for para in re.split(r"\n\s*\n", text):
        para = para.strip()
        if not para:
            continue
        if para.startswith("# "):
            title = para[2:].strip()
            continue
        if para.startswith("## "):
            section = para[3:].strip()
            continue
        blocks.append((" > ".join(x for x in (title, section) if x), para))
    chunks = []
    for context, para in blocks:
        step = size - overlap
        for i in range(0, max(len(para) - overlap, 1), step):
            chunks.append((context, para[i:i + size]))
    return chunks
You are done when完成标志A chunk from Section 3 carries the context `<title> > Section 3. Lodging`.来自第 3 节的块带有上下文 `<标题> > Section 3. Lodging`。
Produces产出`chunk_markdown()`: a list of (context, text).`chunk_markdown()`:返回 (上下文, 正文) 列表。
02Embed and load, driven by the ledger由台账驱动,向量化并入库
Why this step is here为什么这一步排在这里Loading joins three earlier modules: the ledger says which files, the embedder turns text into vectors, the schema says where rows go.入库把前面三个模块连在一起:台账决定处理哪些文件,embedding 把文本变成向量,表结构决定数据写到哪里。

Do this操作

  1. Index only ledger rows with status filed. Skip retired and rejected.只索引台账中状态为 filed 的记录。跳过 retired 和 rejected。
  2. Write each chunk to the chunk table and to the full-text table.把每个块同时写入文本块表和全文索引表。
  3. Copy the tier from the ledger onto every chunk.把台账里的等级复制到每个块上。
  4. Mark the ledger row indexed.把台账记录标记为 indexed。
labs/m05_rag/index.py · load
def index_collection(db: sqlite3.Connection, ledger: Ledger, collection: str, bank: Path) -> dict:
    """Index every 'filed' text file in the ledger. Retired and rejected files are skipped."""
    done = {"files": 0, "chunks": 0}
    for source, tier, kind, status, note in ledger.rows(collection):
        if status != "filed" or not source.endswith((".md", ".txt")):
            continue
        db.execute("DELETE FROM kb_fts WHERE chunk_id IN (SELECT chunk_id FROM kb_chunks WHERE source=?)", (source,))
        db.execute("DELETE FROM kb_chunks WHERE source=?", (source,))
        for n, (context, text) in enumerate(chunk_markdown((bank / source).read_text())):
            chunk_id = f"{source}::{n}"
            vec = llm.embed(context + " " + text)
            db.execute("INSERT INTO kb_chunks (chunk_id, collection, source, chunk_index, text, context, embedding, tier) "
                       "VALUES (?,?,?,?,?,?,?,?)",
                       (chunk_id, collection, source, n, text, context, json.dumps(vec), tier))
            db.execute("INSERT INTO kb_fts (chunk_id, collection, body) VALUES (?,?,?)",
                       (chunk_id, collection, context + " " + text))
            done["chunks"] += 1
        ledger.db.execute("UPDATE files SET status='indexed' WHERE collection=? AND source=?", (collection, source))
        done["files"] += 1
    ledger.db.commit()
    db.commit()
    return done
run
python3 -m labs.m05_rag.demo
Recorded output / 记录的输出 · m05.demo
indexed: {'index': {'files': 4, 'chunks': 20}, 'edges': {'defines': 4, 'cites': 4}}
You are done when完成标志The chunk count matches the output and no chunk comes from the retired file.文本块数量与输出一致,且没有任何块来自已退役的文件。
Produces产出An indexed collection: rows with text, context, vector, tier.一个已索引的集合:每行包含正文、上下文、向量、等级。
03Dense search向量检索
Why this step is here为什么这一步排在这里Each side of hybrid search is built and inspected alone before fusion, so you can see what each one finds and misses.混合检索的两路要先各自搭好、单独检查,再做融合,这样才能看清每一路能找到什么、会漏掉什么。

Do this操作

  1. Embed the query. Score every chunk by cosine similarity. Return the top N ids.把问题向量化,对每个块计算余弦相似度,返回前 N 个 id。
  2. The lab scans every row. In production an approximate index replaces the scan.lab 是全表扫描。生产环境用近似索引代替。
labs/m05_rag/search.py · dense
def dense(db: sqlite3.Connection, collection: str, query: str, n: int) -> list:
    """Nearest chunks by cosine similarity. Brute force here; an ANN index in production."""
    q = llm.embed(query)
    scored = []
    for chunk_id, emb in db.execute("SELECT chunk_id, embedding FROM kb_chunks WHERE collection=? AND NOT retired",
                                    (collection,)):
        scored.append((llm.cosine(q, json.loads(emb)), chunk_id))
    scored.sort(reverse=True)
    return [c for s, c in scored[:n] if s > 0]
You are done when完成标志A paraphrased question returns the right chunk near the top.换了说法的问题,正确的块排在靠前位置。
Produces产出A ranked list of chunk ids from meaning.一个基于语义的块 id 排序列表。
04Lexical search关键词检索
Why this step is here为什么这一步排在这里Built next to dense search for comparison. It finds exact tokens that vectors blur: policy numbers, section numbers, rare terms.紧挨着向量检索搭建,便于对比。它能找到向量会模糊掉的精确词:规定编号、章节号、罕见术语。

Do this操作

  1. Turn the query into terms joined by OR.把问题拆成用 OR 连接的词项。
  2. Rank by BM25 and return the top N ids.按 BM25 排序,返回前 N 个 id。
labs/m05_rag/search.py · lexical
def lexical(db: sqlite3.Connection, collection: str, query: str, n: int) -> list:
    """Keyword match ranked by BM25. Finds exact tokens such as 'NW-FIN-012' or 'Section 5'."""
    terms = [t for t in re.findall(r"[A-Za-z0-9\-]+", query) if len(t) > 1]
    if not terms:
        return []
    match = " OR ".join('"' + t.replace('"', "") + '"' for t in terms)
    rows = db.execute("SELECT chunk_id FROM kb_fts WHERE kb_fts MATCH ? AND collection=? ORDER BY bm25(kb_fts) LIMIT ?",
                      (match, collection, n)).fetchall()
    return [r[0] for r in rows]
Recorded output / 记录的输出 · m05.demo
2 exact token: 'NW-HR-031' (lexical finds one document, l=1; the other has l=None)
   policy/remote-work-policy.md::0      tier 1  d=1 l=1
   policy/travel-policy.md::0           tier 1  d=2 l=None
You are done when完成标志A query that is only a policy number returns the document with that number at lexical rank 1.只输入规定编号的查询,带该编号的文档在关键词检索中排第 1。
Produces产出A ranked list of chunk ids from exact words.一个基于精确词的块 id 排序列表。
05Fuse the two lists by rank按名次融合两个列表
Why this step is here为什么这一步排在这里Fusion needs both lists. It uses positions and never scores, because cosine similarity and BM25 are on unrelated scales.融合需要两个列表都就绪。它只用名次、不用分数,因为余弦相似度和 BM25 的量纲毫不相干。

Do this操作

  1. Give every chunk 1/(k + rank) per list and sum. k is 60 by convention.每个块在每个列表中得到 1/(k + 名次),然后求和。k 按惯例取 60。
  2. Work out one number: near the top, one rank step is worth 1/61 minus 1/62, about 0.00026. You need it in the next step.算出一个数:在榜首附近,一个名次差值为 1/61 减 1/62,约 0.00026。下一步要用到。
labs/m05_rag/search.py · rrf
def rrf(lists: list, k: int = RRF_K) -> dict:
    """Reciprocal rank fusion. Uses positions only, so the two score scales never meet."""
    score = {}
    for ranked in lists:
        for rank, chunk_id in enumerate(ranked, start=1):
            score[chunk_id] = score.get(chunk_id, 0.0) + 1.0 / (k + rank)
    return score
Recorded output / 记录的输出 · m05.demo
1 paraphrase: 'how much can I spend on food each day'
   policy/travel-policy.md::4           tier 1  d=2 l=5
   guides/traveler-quick-guide.md::2    tier 2  d=5 l=1
   guides/traveler-quick-guide.md::1    tier 2  d=3 l=6
   memos/2026-lodging-memo.md::1        tier 3  d=4 l=4
You are done when完成标志In the output each result shows its dense rank and lexical rank. A chunk strong in both ranks first.输出中每条结果都显示它在向量检索和关键词检索中的名次。两边都靠前的块排在最前。
Produces产出One fused score per chunk.每个块一个融合得分。
Feeds供给
06Add the authority nudge and collapse duplicates加入权威度微调并合并重复
Why this step is here为什么这一步排在这里Both act on the fused list. They fix two failures you only see once search works: a summary outranking the rule, and one paragraph filling the results.两者都作用于融合后的列表。它们解决的是检索跑通之后才会暴露的两个问题:摘要排在规定原文前面,以及同一段话占满结果。
Uses用到

Do this操作

  1. Add a bonus per tier step. Size it to about one rank step. The lab first used a value 15 times larger, and tier 2 chunks could no longer reach the top however relevant they were.每高一个等级加一点分,大小约等于一个名次差。lab 最初用了大 15 倍的值,结果 2 级的块无论多相关都排不到前面。
  2. Group results with identical text. Keep the best position and show the copy with the lowest tier.把正文相同的结果归为一组。保留最好的名次,并展示等级最高(数字最小)的那份。
  3. Put every feature behind an environment flag so an eval can turn it off.给每项功能都加一个环境变量开关,让评估时可以关掉它。
labs/m05_rag/search.py · search
def search(db: sqlite3.Connection, collection: str, query: str, top_k: int = 5) -> dict:
    d = dense(db, collection, query, CANDIDATES)
    l = lexical(db, collection, query, CANDIDATES) if flag("RAG_HYBRID") else []
    fused = rrf([d, l])
    rows = []
    for chunk_id, score in fused.items():
        row = _row(db, chunk_id)
        if not row:
            continue
        if flag("RAG_AUTHORITY"):
            score += AUTHORITY_WEIGHT * (3 - row["tier"])          # tier 1 gets the largest nudge
        rows.append({**row, "score": round(score, 5),
                     "dense_rank": d.index(chunk_id) + 1 if chunk_id in d else None,
                     "lexical_rank": l.index(chunk_id) + 1 if chunk_id in l else None})
    rows.sort(key=lambda r: (-r["score"], r["tier"], r["chunk_id"]))
    if flag("RAG_DEDUP"):
        best = {}                                                    # text -> most authoritative copy
        for r in rows:
            key = " ".join(r["text"].lower().split())
            if key not in best or r["tier"] < best[key]["tier"]:
                best[key] = r
        seen, unique = set(), []
        for r in rows:                                               # keep the best position,
            key = " ".join(r["text"].lower().split())                # show the best source
            if key not in seen:
                seen.add(key)
                unique.append({**best[key], "score": r["score"]})
        rows = unique
    hits = rows[:top_k]
    extra = expand(db, query, hits) if flag("RAG_GRAPH") else []
    out = {"query": query, "collection": collection, "results": hits + extra,
           "trace": {"dense": len(d), "lexical": len(l), "fused": len(fused), "expanded": len(extra)}}
    if not hits:
        known = [r[0] for r in db.execute("SELECT DISTINCT collection FROM kb_chunks")]
        out["diagnostic"] = (f"collection '{collection}' has no chunks; known collections: {known}"
                             if collection not in known else
                             "no chunk shares a word or a vector direction with the query; try different terms")
    return out
Recorded output / 记录的输出 · m05.demo
3 the same paragraph is in two files. dedup off:
   policy/travel-policy.md::4           tier 1  d=1 l=2
   guides/traveler-quick-guide.md::3    tier 2  d=2 l=1
  dedup on: one copy, and the tier 1 file is the one kept
   policy/travel-policy.md::4           tier 1  d=1 l=2
   policy/travel-policy.md::6           tier 1  d=5 l=4
You are done when完成标志With dedup off the same paragraph appears twice. With it on, one copy remains and it is the tier 1 file.关闭去重时同一段落出现两次。开启后只剩一份,而且来自 1 级文件。
Produces产出`search()`: ranked, deduplicated, tier-aware results.`search()`:已排序、已去重、考虑等级的结果。
Feeds供给
07Build graph edges at index time在索引阶段建立图的边
Why this step is here为什么这一步排在这里Edges are built after loading because they are derived from chunk text. They come after baseline search because you need failing questions to know which edges are worth building.边要在入库之后建,因为它们是从块的正文中提取的。又排在基础检索之后,因为你需要先有答不好的问题,才知道哪些边值得建。

Do this操作

  1. Definition edges: find sentences of the form "The term X means" and store X pointing at that chunk.定义边:找出“The term X means”这类句式,把 X 指向该块。
  2. Section edges: store which chunks belong to each numbered section.章节边:记录每个编号章节下有哪些块。
  3. Citation edges: when a chunk says "see Section N", store a pointer to that section, in the document it names.引用边:当某个块写着“see Section N”时,保存一个指向该章节的指针,并定位到它所提到的文档。
labs/m05_rag/index.py · edges
DEFINES = re.compile(r"\b(?:The term|An?|The)\s+([a-z][a-z \-]{2,40}?)\s+means\b", re.I)
CITES = re.compile(r"\bSection\s+(\d+)\b")
POLICY_NO = re.compile(r"\b(NW-[A-Z]+-\d+)\b")


def build_edges(db: sqlite3.Connection, collection: str) -> dict:
    """Two typed edges that similarity search cannot supply.

    defines   term            -> the chunk that defines it   ("X means ...")
    cites     "<doc>#<n>"     -> every chunk in section n of that document
              "<chunk_id>"    -> the "<doc>#<n>" keys it refers to are resolved at query time
    """
    db.execute("DELETE FROM kb_edges")
    rows = db.execute("SELECT chunk_id, source, text, context FROM kb_chunks WHERE collection=? AND NOT retired",
                      (collection,)).fetchall()
    policy_doc = {}                                   # "NW-FIN-012" -> source file
    for chunk_id, source, text, context in rows:
        for no in POLICY_NO.findall(text):
            if text.lstrip().startswith("Policy number"):
                policy_doc[no] = source
    n_def = n_cite = 0
    for chunk_id, source, text, context in rows:
        for term in DEFINES.findall(text):
            db.execute("INSERT OR IGNORE INTO kb_edges VALUES (?,?,?)", (term.strip().lower(), chunk_id, "defines"))
            n_def += 1
        m = re.search(r"Section (\d+)\.", context or "")
        if m:                                         # this chunk belongs to a numbered section
            db.execute("INSERT OR IGNORE INTO kb_edges VALUES (?,?,?)", (f"{source}#{m.group(1)}", chunk_id, "section"))
        nos = POLICY_NO.findall(text)
        target_doc = policy_doc.get(nos[0], source) if nos else source
        for sec in CITES.findall(text):
            if m and sec == m.group(1) and target_doc == source:
                continue                              # a section naming itself is not a citation
            db.execute("INSERT OR IGNORE INTO kb_edges VALUES (?,?,?)", (chunk_id, f"{target_doc}#{sec}", "cites"))
            n_cite += 1
    db.commit()
    return {"defines": n_def, "cites": n_cite}
You are done when完成标志The edge table holds a defines row for `per diem` and a cites row from Section 3 to Section 5.边表里有一条 `per diem` 的定义边,以及一条从第 3 节指向第 5 节的引用边。
Produces产出Typed edges: defines, section, cites.带类型的边:defines、section、cites。
08Expand results along the edges沿着边扩展检索结果
Why this step is here为什么这一步排在这里Expansion starts from a hit list, so it follows search. It is bounded, because every added passage costs context.扩展从命中列表出发,所以排在检索之后。它必须有上限,因为每多一个段落都要占用上下文。

Do this操作

  1. If the question asks what a term means, add the chunk that defines any term found in the question.如果问题是在问某个术语的含义,就补上定义该术语的块。
  2. For the top hits, follow citation edges and add the cited section.对排名靠前的命中,沿引用边补上被引用的章节。
  3. Mark each added passage with how it got there.给每个补进来的段落标明它是怎么来的。
labs/m05_rag/search.py · expand
def expand(db: sqlite3.Connection, query: str, hits: list, limit: int = 3) -> list:
    """Add passages that graph edges point to.

    defines  if the question asks what a term means, fetch the chunk that defines it
    cites    if a top hit says 'see Section N', fetch that section
    """
    added = []
    have = {h["chunk_id"] for h in hits}
    if re.search(r"\b(what is|what does|define|definition|mean)\b", query, re.I):
        for term, chunk_id in db.execute("SELECT from_key, to_chunk FROM kb_edges WHERE relation='defines'"):
            if term in query.lower() and chunk_id not in have:
                row = _row(db, chunk_id)
                if row:
                    added.append({**row, "via": f"defines:{term}"})
                    have.add(chunk_id)
    for h in hits[:3]:
        for (section_key,) in db.execute("SELECT to_chunk FROM kb_edges WHERE relation='cites' AND from_key=?",
                                         (h["chunk_id"],)):
            for (chunk_id,) in db.execute("SELECT to_chunk FROM kb_edges WHERE relation='section' AND from_key=?",
                                          (section_key,)):
                if chunk_id not in have and len(added) < limit:
                    row = _row(db, chunk_id)
                    if row:
                        added.append({**row, "via": f"cited-by:{h['chunk_id']}"})
                        have.add(chunk_id)
    return added[:limit]
Recorded output / 记录的输出 · m05.demo
4 definition edge: 'what does approving official mean when a hotel costs more than the cap'
   policy/travel-policy.md::5           tier 1  d=1 l=5
   memos/2026-lodging-memo.md::0        tier 3  d=2 l=1
   policy/travel-policy.md::2           tier 1  [defines:approving official]
   policy/travel-policy.md::7           tier 1  [cited-by:policy/travel-policy.md::5]
5 citation edge: 'can I stay in a hotel above the lodging cap' (Section 3 says: see Section 5)
   policy/travel-policy.md::5           tier 1  d=2 l=3
   policy/travel-policy.md::7           tier 1  [cited-by:policy/travel-policy.md::5]
You are done when完成标志Result 4 adds the definition of `approving official`. Result 5 adds Section 5 because Section 3 cites it.结果 4 补上了 `approving official` 的定义。结果 5 补上了第 5 节,因为第 3 节引用了它。
Produces产出Results that include passages reached by structure.包含按结构关系找到的段落的结果。
09Explain empty results and write a trace解释空结果,并记录追踪信息
Why this step is here为什么这一步排在这里This finishes the search function. The agent will call it as a tool next, and an empty result with no explanation is where fabrication starts.这一步让检索函数完整。接下来智能体会把它当工具调用,而没有解释的空结果正是编造的起点。

Do this操作

  1. When nothing is returned, add a diagnostic that names the cause.没有结果时,附上说明原因的诊断信息。
  2. Return counts for each stage: dense, lexical, fused, expanded.返回每个阶段的数量:dense、lexical、fused、expanded。
Recorded output / 记录的输出 · m05.demo
6 empty: wrong collection
   diagnostic: collection 'HR' has no chunks; known collections: ['POLICY']
You are done when完成标志Searching a collection that does not exist returns a diagnostic listing the collections that do.检索一个不存在的集合时,返回的诊断信息会列出实际存在的集合。
Produces产出A search result shape with results, trace, and diagnostic. The tools module wraps it.包含 results、trace 和 diagnostic 的检索结果结构。工具模块会对它做封装。
10Production form: Postgres with pgvector生产形态:Postgres 加 pgvector
Why this step is here为什么这一步排在这里Same stages, different engine. It is last because the lab version is enough to build and evaluate everything after it.阶段相同,引擎不同。它排在最后,因为 lab 版本足够搭建和评估后面的所有内容。
Uses用到

Do this操作

  1. Bulk load rows first, then build the HNSW index once. Building it row by row during a large load is hours slower.先批量导入数据,再一次性建立 HNSW 索引。在大批量导入过程中逐行建索引要慢好几个小时。
  2. Write the hybrid query with the query vector as a parameter in each ORDER BY.写混合检索查询时,在每个 ORDER BY 里直接把查询向量作为参数。
  3. Do not read the vector from a CTE that two branches use. Postgres inlines a CTE that is read once and materializes one that is read twice, and a materialized value cannot drive the index. The lab shows all three forms.不要让两个分支从同一个 CTE 里读取向量。只被读取一次的 CTE 会被 Postgres 内联,被读取两次的会被物化,而物化后的值无法驱动索引。lab 演示了这三种写法。
  4. Run EXPLAIN with sequential scans turned off and confirm the plan names the HNSW index.关闭顺序扫描后运行 EXPLAIN,确认执行计划里出现了 HNSW 索引。
  5. Score the gold set through both engines before you switch traffic.切换流量之前,用两个引擎分别跑一遍金标准集。
labs/m05_rag/pg.py · hybrid
# OR over the question's lexemes, like the lab's keyword search. websearch_to_tsquery would AND them.
TSQ_OR = ("coalesce((SELECT string_agg(quote_literal(l), ' | ') FROM "
          "unnest(tsvector_to_array(to_tsvector('english', %(text)s))) l), '')::tsquery")
HYBRID = f"""
WITH q AS (SELECT {TSQ_OR} AS t),
dense AS (
  SELECT chunk_id, row_number() OVER (ORDER BY d) AS r
  FROM (SELECT chunk_id, embedding <=> %(vec)s::vector AS d FROM kb.chunks
        WHERE NOT retired AND collection = %(coll)s
        ORDER BY embedding <=> %(vec)s::vector LIMIT %(n)s) c),
lexical AS (
  SELECT chunk_id, row_number() OVER (ORDER BY rank DESC) AS r
  FROM (SELECT chunk_id, ts_rank_cd(to_tsvector('english', coalesce(context,'') || ' ' || text), q.t) AS rank
        FROM kb.chunks, q
        WHERE NOT retired AND collection = %(coll)s
          AND to_tsvector('english', coalesce(context,'') || ' ' || text) @@ q.t
        ORDER BY rank DESC LIMIT %(n)s) l),
fused AS (
  SELECT chunk_id, sum(1.0 / (60 + r)) AS rrf
  FROM (SELECT chunk_id, r FROM dense UNION ALL SELECT chunk_id, r FROM lexical) u GROUP BY chunk_id)
SELECT c.chunk_id, f.rrf FROM fused f JOIN kb.chunks c USING (chunk_id)
ORDER BY f.rrf DESC, c.chunk_id LIMIT %(k)s
"""


def pg_search(conn, query: str, k: int = 5, n: int = 20) -> list:
    p = {"text": query, "vec": vec(llm.embed(query)), "coll": "POLICY", "n": n, "k": k}
    return [r[0] for r in conn.execute(HYBRID, p).fetchall()]

The lab uses vector(256) because its fake embedder has 256 dimensions. With pgvector 0.7 or later, halfvec halves storage. The reference build uses halfvec(768).lab 用的是 vector(256),因为它的假嵌入器是 256 维。pgvector 0.7 及以上版本可以用 halfvec,存储减半。参考系统用的是 halfvec(768)。

run
PG_RUN_AS=<ordinary user, only when running as root> python3 -m labs.m05_rag.pg
Recorded output / 记录的输出 · m05.pg
3 loaded 20 chunks from the lab index, then built the HNSW and GIN indexes
4 EXPLAIN, vector as a parameter   : index scan
4 EXPLAIN, CTE read once           : index scan
4 EXPLAIN, CTE read twice          : no index (table scan)
5 gold set, fusion only, n=15: hit@5 lab engine 15/15, Postgres 15/15, same top result 12/15
You are done when完成标志EXPLAIN names the HNSW index for the parameter form, and the gold set scores the same through Postgres as through the lab engine.参数写法的 EXPLAIN 结果里出现 HNSW 索引,并且金标准集在 Postgres 上的得分与 lab 引擎相同。
Produces产出The same search contract over millions of rows.同样的检索接口,支撑百万级数据。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。

How it works with the other parts它如何与其他部分协作

What went wrong in the real build真实搭建中踩过的坑

2026-08

A corrupt vector segment stopped sync for four weeks一个损坏的向量分段让同步停了四周

What happened发生了什么
The single-process vector store had one unreadable segment. Search on the main collection failed and ingestion could not proceed.单进程向量库有一个分段无法读取。主集合的检索失败,入库也无法继续。
Fix修复
Move vectors into database tables with write-ahead logging and a rebuildable index.把向量存进带预写日志的数据库表,索引可以随时重建。
Lesson教训
Treat the vector index as derived data that can be rebuilt from rows you trust.把向量索引当作派生数据,随时能从可信的数据行重建。
2026-09

Every search scanned the whole table每次检索都在全表扫描

What happened发生了什么
The query vector sat in a CTE that both the dense and the keyword branch read. Postgres materializes a CTE that is read twice, so the vector stopped being a constant the HNSW index could use. Every search scanned 2.4 million rows and took 5.4 seconds.查询向量放在一个 CTE 里,稠密检索和关键词检索两个分支都读取它。被读取两次的 CTE 会被 Postgres 物化,向量于是不再是 HNSW 索引能用的常量。每次检索扫描 240 万行,耗时 5.4 秒。
Fix修复
Pass the vector as a query parameter in the ORDER BY clause.把向量作为查询参数直接写进 ORDER BY 子句。
Lesson教训
Run EXPLAIN on the retrieval query. An index that exists may still go unused.对检索查询运行 EXPLAIN。索引存在不代表它被用上了。
2026-07

One collection leaked into another一个集合的内容漏进了另一个集合

What happened发生了什么
Finance passages appeared in education-scoped chats because the knowledge attachment was set per model.财务类段落出现在教育范围的对话里,因为知识库是按模型挂载的。
Fix修复
Separate indexes per collection and a deterministic scope filter.每个集合单独建索引,并加上确定性的范围过滤。
Lesson教训
Isolation belongs in the data layout. A prompt instruction is not a boundary.隔离要靠数据结构实现。提示词里的指令不是边界。
found while building the labs搭建 lab 时发现

An authority bonus that overrode relevance盖过了相关性的权威加分

What happened发生了什么
The first lab version added 0.004 per tier. One rank step is worth 0.00026, so the bonus equaled about 15 ranks and tier decided everything.lab 的第一版每个等级加 0.004。而一个名次差只值 0.00026,所以这个加分相当于约 15 个名次,结果完全由等级决定。
Fix修复
Size the bonus to one rank step.把加分调到一个名次差的大小。
Lesson教训
Express every ranking weight in the units of the score it is added to.任何排序权重,都要用它所加到的那个分数的量纲来衡量。

The same idea on other platforms同样的思路在其他平台上

Platform平台How this module maps本模块如何对应
DatabricksAI Search (formerly Vector Search) with a Delta Sync index replaces the chunk table and ANN index, and it supports full-text and hybrid queries. Chunks live in a Delta table governed by Unity Catalog. Graph edges are Delta tables you join. Lakebase gives you Postgres if you want to keep the SQL as written.带 Delta Sync 索引的 AI Search(原 Vector Search)取代文本块表和近似索引,并支持全文和混合查询。文本块存在受 Unity Catalog 管理的 Delta 表里。图的边是你自己关联的 Delta 表。想原样保留 SQL 的话可以用 Lakebase(Postgres)。
IBM watsonxwatsonx.data provides the lakehouse and a vector engine (Milvus). Orchestrate agents attach knowledge bases backed by it. You keep the same stages: validate, chunk, embed, hybrid query, rerank.watsonx.data 提供湖仓和向量引擎(Milvus)。Orchestrate 智能体可挂载基于它的知识库。各阶段保持不变:校验、切块、向量化、混合查询、重排。
CodexCodex does not provide a retrieval store. Run this stack as a service and expose search as an MCP tool.Codex 不提供检索存储。把这套系统作为服务运行,并把检索以 MCP 工具的形式暴露出去。
CursorCursor indexes your code for its own use. Domain retrieval is yours to host. Register your search service as an MCP server in the project config.Cursor 会为自身用途索引你的代码。业务领域的检索需要你自己托管。在项目配置里把检索服务注册为 MCP 服务。
Claude Code / Agent SDKExpose the search tool through an MCP server. The reference build does this so a coding agent and the chat agent share one retrieval implementation.通过 MCP 服务暴露检索工具。参考系统就是这么做的,让编程智能体和聊天智能体共用同一套检索实现。
Another machineThe lab runs anywhere Python runs. Postgres with pgvector runs anywhere Docker runs. Only the embedding endpoint URL changes.lab 在任何有 Python 的地方都能跑。Postgres 加 pgvector 在任何有 Docker 的地方都能跑。只需要改 embedding 端点的 URL。

Step-by-step guides per platform各平台的分步指南

Explain it back讲给自己听

Answer aloud first. Then open the answer and compare.先自己说一遍答案,再展开对照。

Why hybrid search and not vectors alone?为什么用混合检索,而不是只用向量?
A strong answer参考答案Vectors match meaning and miss exact tokens such as section numbers and codes. Keyword search does the reverse. They fail on different questions, so fusing both covers more than either.向量匹配语义,但会漏掉章节号、编号这类精确词。关键词检索正好相反。两者在不同的问题上失效,融合后的覆盖面比任何一方都大。
Why does fusion use ranks and not scores?为什么融合用名次而不用分数?
A strong answer参考答案Cosine similarity and BM25 are on unrelated scales. Ranks are comparable across any two lists, so fusion needs no calibration.余弦相似度和 BM25 的量纲毫不相干。名次在任意两个列表之间都可比,所以融合不需要校准。
How large should the authority bonus be, and how do you know?权威加分应该多大?你怎么确定?
A strong answer参考答案About one rank step of the fused score, which near the top is 1/61 minus 1/62. Larger and tier overrides relevance. You confirm by running the retrieval eval with the flag on and off.大约是融合得分的一个名次差,在榜首附近是 1/61 减 1/62。再大,等级就会盖过相关性。通过开关该功能分别运行检索评估来确认。
Why are graph edges added after hybrid search works?为什么图的边要在混合检索跑通之后再加?
A strong answer参考答案Edges expand from a hit list, so they need one. You also need failing questions to know which edges to build. In the lab's own eval the graph flag changed no score on a 15-question set, which is a result worth knowing before investing more.边是从命中列表扩展出去的,所以先得有命中列表。你还需要答不好的问题,才知道该建哪些边。在 lab 自带的评估中,图扩展的开关在 15 道题上没有改变任何分数,这是在继续投入之前值得知道的结果。
Trace the data from a file in the inbox to a passage in an answer. Name each step.追踪数据从收件箱里的文件到回答中的段落。说出每一步。
A strong answer参考答案Validate, file, ledger row with tier, chunk with context, embed, load into chunk and full-text tables, build edges, then at query time dense plus lexical, fuse, tier bonus, dedup, expand, return with source.校验、归档、写入带等级的台账、带上下文切块、向量化、写入文本块表和全文表、建边;查询时:向量加关键词检索、融合、等级加分、去重、扩展、连同来源返回。

Terms术语

RRFRRF(倒数排名融合)Reciprocal rank fusion. Score is the sum over lists of 1/(k + rank).得分是各列表中 1/(k + 名次) 之和。
BM25BM25A keyword ranking function based on term frequency and rarity.基于词频和稀有度的关键词排序函数。
HNSWHNSWA graph index for approximate nearest-neighbor search over vectors.用于向量近似最近邻检索的图索引。
Edge边A stored link from a term or passage to another passage, with a type.从术语或段落指向另一个段落的、带类型的链接。

From the live build来自实时构建

Recent changes and files the sync job filed under this module. These lines are in English as written in the build.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。

Ask the tutor about this module就本模块向导师提问