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工作原理
- Documents are split into chunks. Each chunk gets a vector and a full-text entry.文档被切成文本块。每个块生成一个向量和一条全文索引。
- A query runs twice: nearest vectors (dense) and keyword match (lexical). Reciprocal rank fusion merges the two ranked lists by position.一次查询跑两路:最近邻向量(dense)和关键词匹配(lexical)。倒数排名融合(RRF)按名次合并两个列表。
- A tier bonus sized to one rank step lets a primary source win a near tie. Identical passages collapse to one, and the most authoritative copy is shown.一个相当于一个名次差的等级加分,让权威来源在接近平手时胜出。相同段落合并为一条,并展示最权威的那份。
- Graph edges add passages similarity cannot reach: the passage that defines a term, and the section a hit refers to.图的边补上相似度够不到的段落:定义某个术语的段落,以及命中段落所引用的章节。
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.py | Turn a source file into clean, structure-aware chunks.把源文件变成干净、保留结构的文本块。 |
| apps/agent-server/tools/knowledge_base.py | The search tool: hybrid SQL, fusion, authority weight, dedup, graph expansion, trace.检索工具:混合 SQL、融合、权威加权、去重、图扩展、追踪日志。 |
| apps/agent-server/nightly/defines.py | Builds definition edges from set definitional forms.从固定的定义句式中建立“定义”边。 |
| apps/agent-server/nightly/citations.py | Builds citation edges between passages.建立段落之间的“引用”边。 |
| apps/agent-server/tools/passage_dedup.py | One result for a paragraph that exists in several files.同一段落存在于多个文件时只返回一条。 |
Process map流程图
One search, from question to returned passages一次检索:从问题到返回的段落
- 1Question and collection问题与集合Collections are separate indexes on purpose.各集合的索引是有意分开的。
- 2Embed the query把问题向量化With the same model that embedded the chunks.使用与文本块相同的 embedding 模型。
- 3Dense top N向量检索 Top NNearest vectors. Finds paraphrases.最近邻向量。能找到换了说法的内容。
- 4Lexical top N关键词检索 Top NFull-text match by BM25. Finds exact terms, codes, and section numbers.按 BM25 的全文匹配。能找到精确术语、编号和章节号。
- 5Fuse by rank按名次融合Score is the sum of 1/(60 + rank) across the two lists.得分是两个列表中 1/(60 + 名次) 之和。
- 6Authority and dedup权威度与去重A bonus worth about one rank. One copy of a repeated paragraph.相当于约一个名次的加分。重复段落只留一份。
- 7Graph expansion图扩展Add defining and cited passages when the question calls for them.当问题需要时,补上定义段落和被引用的段落。
- 8Return 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 实际运行时打印的内容。
- 1Chunk with a context line切块时带上上下文行
- 2Embed and load, driven by the ledger由台账驱动,向量化并入库
- 3Dense search向量检索
- 4Lexical search关键词检索
- 5Fuse the two lists by rank按名次融合两个列表
- 6Add the authority nudge and collapse duplicates加入权威度微调并合并重复
- 7Build graph edges at index time在索引阶段建立图的边
- 8Expand results along the edges沿着边扩展检索结果
- 9Explain empty results and write a trace解释空结果,并记录追踪信息
- 10Production form: Postgres with pgvector生产形态:Postgres 加 pgvector
01Chunk with a context line切块时带上上下文行
- validated files in a known layout已校验、目录结构明确的文件 ← Knowledge management知识管理 5: Run intake: scan the bank and process the inbox执行入库:扫描知识库并处理收件箱
Do this操作
- Split on headings first, then by size with overlap.先按标题切分,再按长度切分并保留重叠。
- Store a context string per chunk: document title and section heading.为每个块保存一个上下文字符串:文档标题和章节标题。
- Index the context with the text so a chunk can match on its section name.把上下文和正文一起建索引,这样块可以通过章节名被匹配到。
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- RAG and knowledge graphRAG 与知识图谱 2: Embed and load, driven by the ledger由台账驱动,向量化并入库 (chunks to embed待向量化的文本块)
02Embed and load, driven by the ledger由台账驱动,向量化并入库
- chunks to embed待向量化的文本块 ← RAG and knowledge graphRAG 与知识图谱 1: Chunk with a context line切块时带上上下文行
- which files to index and their tier要索引哪些文件及其等级 ← Knowledge management知识管理 4: Create the ledger建立台账
- kb_chunks and kb_fts tableskb_chunks 和 kb_fts 表 ← State and storage状态与存储 3: Create the schema, grouped by owner按归属分组建表
- embed()embed() ← Inference engineering推理工程 5: Write one client function and use it everywhere写一个客户端函数,全系统共用
Do this操作
- Index only ledger rows with status filed. Skip retired and rejected.只索引台账中状态为 filed 的记录。跳过 retired 和 rejected。
- Write each chunk to the chunk table and to the full-text table.把每个块同时写入文本块表和全文索引表。
- Copy the tier from the ledger onto every chunk.把台账里的等级复制到每个块上。
- Mark the ledger row indexed.把台账记录标记为 indexed。
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 donepython3 -m labs.m05_rag.demoindexed: {'index': {'files': 4, 'chunks': 20}, 'edges': {'defines': 4, 'cites': 4}}- RAG and knowledge graphRAG 与知识图谱 3: Dense search向量检索 (stored vectors已存储的向量)
- RAG and knowledge graphRAG 与知识图谱 4: Lexical search关键词检索 (the full-text table全文索引表)
- RAG and knowledge graphRAG 与知识图谱 7: Build graph edges at index time在索引阶段建立图的边 (chunk text and context块的正文和上下文)
- Evaluation评估 2: Build a retrieval gold set构建检索标准集 (chunk ids to point at要指向的 chunk id)
03Dense search向量检索
- stored vectors已存储的向量 ← RAG and knowledge graphRAG 与知识图谱 2: Embed and load, driven by the ledger由台账驱动,向量化并入库
Do this操作
- Embed the query. Score every chunk by cosine similarity. Return the top N ids.把问题向量化,对每个块计算余弦相似度,返回前 N 个 id。
- The lab scans every row. In production an approximate index replaces the scan.lab 是全表扫描。生产环境用近似索引代替。
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]- RAG and knowledge graphRAG 与知识图谱 5: Fuse the two lists by rank按名次融合两个列表 (the dense list向量检索列表)
04Lexical search关键词检索
- the full-text table全文索引表 ← RAG and knowledge graphRAG 与知识图谱 2: Embed and load, driven by the ledger由台账驱动,向量化并入库
Do this操作
- Turn the query into terms joined by OR.把问题拆成用 OR 连接的词项。
- Rank by BM25 and return the top N ids.按 BM25 排序,返回前 N 个 id。
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]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- RAG and knowledge graphRAG 与知识图谱 5: Fuse the two lists by rank按名次融合两个列表 (the lexical list关键词检索列表)
05Fuse the two lists by rank按名次融合两个列表
- the dense list向量检索列表 ← RAG and knowledge graphRAG 与知识图谱 3: Dense search向量检索
- the lexical list关键词检索列表 ← RAG and knowledge graphRAG 与知识图谱 4: Lexical search关键词检索
Do this操作
- Give every chunk 1/(k + rank) per list and sum. k is 60 by convention.每个块在每个列表中得到 1/(k + 名次),然后求和。k 按惯例取 60。
- 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。下一步要用到。
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 score1 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- RAG and knowledge graphRAG 与知识图谱 6: Add the authority nudge and collapse duplicates加入权威度微调并合并重复 (fused scores, and the size of one rank step融合得分,以及一个名次差的大小)
- RAG and knowledge graphRAG 与知识图谱 10: Production form: Postgres with pgvector生产形态:Postgres 加 pgvector (the fusion logic, now in SQL融合逻辑,现在用 SQL 实现)
07Build graph edges at index time在索引阶段建立图的边
- chunk text and context块的正文和上下文 ← RAG and knowledge graphRAG 与知识图谱 2: Embed and load, driven by the ledger由台账驱动,向量化并入库
- the kb_edges tablekb_edges 表 ← State and storage状态与存储 3: Create the schema, grouped by owner按归属分组建表
Do this操作
- Definition edges: find sentences of the form "The term X means" and store X pointing at that chunk.定义边:找出“The term X means”这类句式,把 X 指向该块。
- Section edges: store which chunks belong to each numbered section.章节边:记录每个编号章节下有哪些块。
- Citation edges: when a chunk says "see Section N", store a pointer to that section, in the document it names.引用边:当某个块写着“see Section N”时,保存一个指向该章节的指针,并定位到它所提到的文档。
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}- RAG and knowledge graphRAG 与知识图谱 8: Expand results along the edges沿着边扩展检索结果 (the edges to follow要沿着走的边)
08Expand results along the edges沿着边扩展检索结果
- the hit list to expand from用于扩展的命中列表 ← RAG and knowledge graphRAG 与知识图谱 6: Add the authority nudge and collapse duplicates加入权威度微调并合并重复
- the edges to follow要沿着走的边 ← RAG and knowledge graphRAG 与知识图谱 7: Build graph edges at index time在索引阶段建立图的边
Do this操作
- If the question asks what a term means, add the chunk that defines any term found in the question.如果问题是在问某个术语的含义,就补上定义该术语的块。
- For the top hits, follow citation edges and add the cited section.对排名靠前的命中,沿引用边补上被引用的章节。
- Mark each added passage with how it got there.给每个补进来的段落标明它是怎么来的。
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]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]- RAG and knowledge graphRAG 与知识图谱 9: Explain empty results and write a trace解释空结果,并记录追踪信息 (the complete search path完整的检索路径)
09Explain empty results and write a trace解释空结果,并记录追踪信息
- the complete search path完整的检索路径 ← RAG and knowledge graphRAG 与知识图谱 8: Expand results along the edges沿着边扩展检索结果
Do this操作
- When nothing is returned, add a diagnostic that names the cause.没有结果时,附上说明原因的诊断信息。
- Return counts for each stage: dense, lexical, fused, expanded.返回每个阶段的数量:dense、lexical、fused、expanded。
6 empty: wrong collection
diagnostic: collection 'HR' has no chunks; known collections: ['POLICY']- Tools and MCP工具与 MCP 3: Write the tools, with diagnostics for empty results编写工具,并为空结果提供诊断 (search() and its result shapesearch() 及其结果结构)
10Production form: Postgres with pgvector生产形态:Postgres 加 pgvector
- a Postgres database with the vector extension带向量扩展的 Postgres 数据库 ← State and storage状态与存储 8: Move to Postgres when the workload asks for it当负载需要时迁移到 Postgres
- the fusion logic, now in SQL融合逻辑,现在用 SQL 实现 ← RAG and knowledge graphRAG 与知识图谱 5: Fuse the two lists by rank按名次融合两个列表
Do this操作
- Bulk load rows first, then build the HNSW index once. Building it row by row during a large load is hours slower.先批量导入数据,再一次性建立 HNSW 索引。在大批量导入过程中逐行建索引要慢好几个小时。
- Write the hybrid query with the query vector as a parameter in each ORDER BY.写混合检索查询时,在每个 ORDER BY 里直接把查询向量作为参数。
- 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 演示了这三种写法。
- Run EXPLAIN with sequential scans turned off and confirm the plan names the HNSW index.关闭顺序扫描后运行 EXPLAIN,确认执行计划里出现了 HNSW 索引。
- Score the gold set through both engines before you switch traffic.切换流量之前,用两个引擎分别跑一遍金标准集。
# 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)。
PG_RUN_AS=<ordinary user, only when running as root> python3 -m labs.m05_rag.pg3 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/15How it works with the other parts它如何与其他部分协作
- Tools and MCP工具与 MCPSearch is wrapped as a tool. Its diagnostic is what the tool returns when empty.检索被封装成工具。结果为空时,工具返回的就是它的诊断信息。
- Guardrails and verification护栏与验证The guard compares the answer with what retrieval returned in this request.护栏会把回答与本次请求中检索返回的内容进行比对。
- Evaluation评估A sealed gold set scores retrieval alone. Every flag in this module is an eval variant.封存的标准集单独给检索打分。本模块的每个开关都是一个评估变体。
- Self-evolving agents自进化智能体The learner reads chunks and writes claims that point back to them. Held-out chunks are excluded.学习任务读取文本块,写下指回这些块的论断。留出的块不在其阅读范围内。
What went wrong in the real build真实搭建中踩过的坑
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.把向量索引当作派生数据,随时能从可信的数据行重建。
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。索引存在不代表它被用上了。
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.隔离要靠数据结构实现。提示词里的指令不是边界。
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本模块如何对应 |
|---|---|
| Databricks | AI 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 watsonx | watsonx.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 智能体可挂载基于它的知识库。各阶段保持不变:校验、切块、向量化、混合查询、重排。 |
| Codex | Codex does not provide a retrieval store. Run this stack as a service and expose search as an MCP tool.Codex 不提供检索存储。把这套系统作为服务运行,并把检索以 MCP 工具的形式暴露出去。 |
| Cursor | Cursor 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 SDK | Expose 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 machine | The 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?为什么用混合检索,而不是只用向量?
Why does fusion use ranks and not scores?为什么融合用名次而不用分数?
How large should the authority bonus be, and how do you know?权威加分应该多大?你怎么确定?
Why are graph edges added after hybrid search works?为什么图的边要在混合检索跑通之后再加?
Trace the data from a file in the inbox to a passage in an answer. Name each step.追踪数据从收件箱里的文件到回答中的段落。说出每一步。
Terms术语
| RRFRRF(倒数排名融合) | Reciprocal rank fusion. Score is the sum over lists of 1/(k + rank).得分是各列表中 1/(k + 名次) 之和。 |
| BM25BM25 | A keyword ranking function based on term frequency and rarity.基于词频和稀有度的关键词排序函数。 |
| HNSWHNSW | A 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.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。
- Corroboration needs two independent texts: copies of one passage count once; duplicate the regulation copy retired from the learner queue
- recall_claims returns the source passage beside each claim and tells the model the passage is the authority
- Claim fidelity eval: a sample of served claims is checked against the cited passage by the 35B model; weekly, with a report line
- Knowledge graph: 'defines' edges from set definitional forms, used in retrieval for definitional questions; gold set and nightly eval
- Answers that used tools stream line by line as they clear the guard; new chunks get their Qwen3 embedding after ingest
- Reranker: cap and release the MLX buffer cache (process had grown to 71 GB)
- Tests: isolate conversations.db and the retrieval trace
- Skills: '_none' margin for embedding routing; default chosen by the eval
- FINANCE: name the actual authority, don't just summarize — and show it in practice, not just recite the rule
- CLAUDE.md — build-host Mac Studio
- Full-stack audit — 2026-09-07
- Whole-System Audit and Revised Update Plan
- Eval set v2 — built 2026-08-19
- K12: name the standard, match the grade, teach it like a tutor — not a textbook
- guards on the retrieval changes of 2026-09-30. Run: venv/bin/python3 test_retrieval.py (no database, no network) 1. SQL v2 renders for nomic (768) and Qwen3 (1024) with no stray fields, and passes the query vector as a parameter (the 5.4 s bug was a CTE) 2.
- does search_knowledge_base find the right passage? (2026-09-30) The weekly quiz measures whether a 9B model answers better with learned atoms. Nothing measured retrieval itself, so a chunker, embedding or ranking change could make search worse and no number would move.
- the search_knowledge_base tool. This is the single highest-leverage piece of Phase 7 step 2 (v2 guide §4).
- the same paragraph from two copies of a document is one result. The the regulation is in the bank three times: the per-volume PDFs, Download-the regulation-PDF and Full-the regulation-Policy-PDF. Appropriations acts and committee reports repeat each other.
- the "defines" edge of the knowledge graph. venv/bin/python3 nightly/defines.py --index # scan new chunks (incremental) venv/bin/python3 nightly/defines.py --stats venv/bin/python3 nightly/defines.py --build-gold # once; sealed The citation layer links a passage to what it CITES.
- which term does a passage DEFINE, and which term does a question ask about. The citation layer answers "which passages cite 31 U.S.C. 1341". This is the other typed edge a budget analyst needs: "which passage says what an 'unliquidated obligation' IS".
- Standalone reranker server for build-host agent-server's rerank_route.py. Added 2026-08-03.
- searchable index of past conversations (2026-10-01). The audit scored memory 2 of 5: conversations.db keeps every exchange for 90 days and nothing can search it, so "what did we decide about X last week" has no answer.