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

Knowledge management知识管理

Collect, validate, name, tier, and retire documents before any index sees them.在任何索引接触文档之前,先完成收集、校验、命名、分级和退役。

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

What是什么

Knowledge management is the pipeline and the rules that decide what enters the knowledge bank: where documents come from, how they are validated and filed, which are authoritative, and when a document is retired.知识管理是一套流程和规则,决定什么能进入知识库:文档从哪里来、如何校验和归档、哪些是权威来源、何时让一份文档退役。

Why为什么

Retrieval ranks whatever it is given. The reference build's own guide calls this work 90 percent librarianship and 10 percent technology. Folder taxonomy, file names, and pruning duplicates moved quality more than any algorithm change.检索只会对给它的内容排序。参考系统自己的指南把这项工作称为 90% 的图书管理加 10% 的技术。目录分类、文件命名和清理重复,对质量的提升超过任何算法改动。

How it works工作原理

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

Needs first前置模块

Nothing. You can start here.没有。可以从这里开始。

Unlocks解锁

  • RAG and knowledge graphRAG 与知识图谱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.检索只能返回入库的内容,并依靠入库时产生的信号排序:切块边界、路径、等级。整理阶段的错误会变成检索错误,任何排序手段都修不回来。
  • Evaluation评估Held-out material is sampled from the corpus. You cannot seal chunks that have not been ingested.留出材料是从语料中抽样的。没有入库的文本块无法封存。

In the reference build在参考系统中

Path路径Role作用
KNOWLEDGE_MANAGEMENT_GUIDE.mdThe three-tier plan: vector search, curated wiki, graph.三层规划:向量检索、人工整理的 wiki、图。
knowledge-bank/_inbox/Drop zone for new files.新文件的投放区。
knowledge-bank/source_authority.jsonPath rules for authority tiers.权威等级的路径规则。
apps/llm-wiki/llm_wiki.pyDrafts one page per concept for human review.为每个概念起草一页,交人工审核。

Process map流程图

From a downloaded file to something the index may read从下载的文件到索引可以读取的内容

  1. 1
    Inbox收件箱Every new file starts here. Nothing is indexed from the inbox.所有新文件从这里开始。收件箱里的内容不会被索引。
  2. 2
    Validate校验Leading bytes must match the extension. Empty files and HTML saved as text are rejected.文件头字节必须与扩展名匹配。空文件和被存成文本的 HTML 会被拒绝。
  3. 3
    File归档Move into the collection folder that matches its kind.移入与其类别对应的集合目录。
  4. 4
    Ledger row写入台账Hash, tier, kind, status. One row per file.哈希、等级、类别、状态。每个文件一行。
  5. 5
    Retire when superseded被取代时退役Status changes and a reason is recorded. The row stays.状态改变并记录原因。这一行保留。
  6. 6
    Hand to the index交给索引Only rows with status filed are indexed.只有状态为 filed 的行会被索引。

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. 1Fix the folder taxonomy and file names确定目录分类和文件命名
  2. 2Validate files by content按内容校验文件
  3. 3Write the authority rules编写权威等级规则
  4. 4Create the ledger建立台账
  5. 5Run intake: scan the bank and process the inbox执行入库:扫描知识库并处理收件箱
  6. 6Retire, do not delete退役,而不是删除
  7. 7Add collectors with a relevance filter加入带相关性过滤的采集器
  8. 8Add a curated tier for judgment为经验判断增加一个人工整理层
01Fix the folder taxonomy and file names确定目录分类和文件命名
Why this step is here为什么这一步排在这里Path is the first signal every later step uses: the tier rules match on it, and search results cite it. It cannot be added afterward without re-filing everything.路径是后续每一步都会用到的第一个信号:等级规则靠它匹配,检索结果引用它。事后再补就得把所有文件重新归档。
Uses用到Nothing from earlier steps.不依赖之前的任何步骤。

Do this操作

  1. Create one folder per collection. A collection is a body of documents that should never mix with another in an answer.每个集合建一个目录。集合是一批文档,在同一个回答里不应与其他集合混用。
  2. Inside it, create one folder per kind of authority: `policy/`, `guides/`, `memos/`.在集合内,按权威类别各建一个目录:`policy/`、`guides/`、`memos/`。
  3. Name files for what they are and when they apply. Avoid `final_v2`.文件名要说明内容和适用时间。不要用 `final_v2` 这类名字。
text
bank/
  policy/   travel-policy.md            the rule itself        tier 1
  guides/   traveler-quick-guide.md     explains the rule      tier 2
  memos/    2026-lodging-memo.md        commentary             tier 3
inbox/      everything new lands here first
You are done when完成标志For any file you can tell its authority from its path alone.仅凭路径,你就能判断任何文件的权威程度。
Produces产出A folder layout whose paths carry meaning.一个路径本身带有含义的目录结构。
Feeds供给
02Validate files by content按内容校验文件
Why this step is here为什么这一步排在这里It comes before filing because a bad file that reaches the bank will be chunked, embedded, and returned with confidence. On the reference build 15 files named .pdf were HTML error pages that passed a size check.它排在归档之前,因为坏文件一旦进入知识库,就会被切块、向量化,并被自信地返回。参考系统里有 15 个 .pdf 文件其实是 HTML 错误页,它们通过了文件大小检查。
Uses用到Nothing from earlier steps.不依赖之前的任何步骤。

Do this操作

  1. For binary types, compare the leading bytes with the expected signature.对二进制类型,比较文件头字节与预期的签名。
  2. For text types, reject files that start with an HTML tag.对文本类型,拒绝以 HTML 标签开头的文件。
  3. Return the reason as a string. It goes into the ledger.把拒绝原因以字符串返回,它会写进台账。
labs/m03_knowledge/ledger.py · validate
MAGIC = {".pdf": b"%PDF-", ".zip": b"PK\x03\x04", ".docx": b"PK\x03\x04"}
TEXT_TYPES = {".md", ".txt"}


def validate(path: Path) -> Optional[str]:
    """Return None when the file is what its name claims, else the reason it is not."""
    ext = path.suffix.lower()
    head = path.read_bytes()[:512]
    if not head.strip():
        return "empty file"
    if ext in MAGIC:
        return None if head.startswith(MAGIC[ext]) else f"not a real {ext} file (wrong leading bytes)"
    if ext in TEXT_TYPES:
        low = head.lstrip().lower()
        return "an HTML page saved as text" if low.startswith((b"<!doctype html", b"<html")) else None
    return f"unsupported type {ext}"
You are done when完成标志A file that is an HTML page with a .pdf name is rejected with a reason.一个名为 .pdf 但实际是 HTML 页面的文件被拒绝,并给出原因。
Produces产出`validate()`: None when good, a reason when not.`validate()`:正常返回 None,异常返回原因。
03Write the authority rules编写权威等级规则
Why this step is here为什么这一步排在这里Tiers depend on the taxonomy and are needed by the ledger, so they sit between the two. Retrieval later uses the tier as a small ranking bonus and to choose between duplicate passages.等级依赖目录分类,又是台账需要的字段,所以排在两者之间。之后检索会用等级做小幅排序加分,并在重复段落中做选择。

Do this操作

  1. Write rules as path patterns, first match wins.把规则写成路径模式,先匹配到的生效。
  2. Give anything unmatched the lowest tier. Unknown sources must not outrank known ones.未匹配到的一律给最低等级。来源不明的文档不能排在已知来源前面。
labs/m03_knowledge/ledger.py · tiers
DEFAULT_RULES = [            # first match wins; lower tier = more authoritative
    {"pattern": "policy/*", "tier": 1, "kind": "rule"},
    {"pattern": "guides/*", "tier": 2, "kind": "guide"},
    {"pattern": "memos/*",  "tier": 3, "kind": "commentary"},
]


def authority(source: str, rules: Optional[list] = None) -> dict:
    for r in rules or DEFAULT_RULES:
        if fnmatch.fnmatch(source, r["pattern"]):
            return {"tier": r["tier"], "kind": r["kind"]}
    return {"tier": 3, "kind": "unclassified"}
You are done when完成标志`authority('policy/x.md')` is tier 1 and `authority('downloads/x.md')` is tier 3.`authority('policy/x.md')` 是 1 级,`authority('downloads/x.md')` 是 3 级。
Produces产出`authority()`: path to tier and kind.`authority()`:由路径得到等级和类别。
04Create the ledger建立台账
Why this step is here为什么这一步排在这里The ledger is the single record of what exists. Indexing, retirement, and audits all read it, so it has to exist before any of them.台账是“有哪些文档”的唯一记录。索引、退役和审计都读它,所以必须先于它们存在。
Uses用到

Do this操作

  1. One row per file, keyed by collection and path.每个文件一行,以集合和路径为主键。
  2. Store the SHA-256 of the content. `record()` returns `unchanged` when the hash matches.保存内容的 SHA-256。哈希一致时 `record()` 返回 `unchanged`。
  3. Store status as one of: filed, indexed, retired, rejected.状态取值为:filed、indexed、retired、rejected。
labs/m03_knowledge/ledger.py · ledger
class Ledger:
    """One row per file: what it is, where it is, and what state it is in."""

    def __init__(self, db_path: Path):
        self.db = sqlite3.connect(str(db_path))
        self.db.execute("""CREATE TABLE IF NOT EXISTS files (
            collection TEXT NOT NULL, source TEXT NOT NULL, sha256 TEXT NOT NULL,
            tier INTEGER NOT NULL, kind TEXT NOT NULL,
            status TEXT NOT NULL DEFAULT 'filed',      -- filed | indexed | retired | rejected
            note TEXT, PRIMARY KEY (collection, source))""")
        self.db.commit()

    def record(self, collection: str, source: str, sha: str, status: str = "filed", note: str = "") -> str:
        old = self.db.execute("SELECT sha256, status FROM files WHERE collection=? AND source=?",
                              (collection, source)).fetchone()
        if old and old[0] == sha and old[1] != "rejected":
            return "unchanged"
        a = authority(source)
        self.db.execute("INSERT OR REPLACE INTO files VALUES (?,?,?,?,?,?,?)",
                        (collection, source, sha, a["tier"], a["kind"], status, note))
        self.db.commit()
        return "updated" if old else "new"

    def retire(self, collection: str, source: str, reason: str) -> None:
        self.db.execute("UPDATE files SET status='retired', note=? WHERE collection=? AND source=?",
                        (reason, collection, source))
        self.db.commit()

    def rows(self, collection: str, status: Optional[str] = None) -> list:
        q = "SELECT source, tier, kind, status, note FROM files WHERE collection=?"
        args = [collection]
        if status:
            q += " AND status=?"
            args.append(status)
        return self.db.execute(q + " ORDER BY tier, source", args).fetchall()
You are done when完成标志Scanning the same folder twice reports every file as unchanged the second time.对同一目录扫描两次,第二次所有文件都显示未变化。
Produces产出`Ledger`: the list the indexer reads.`Ledger`:索引程序读取的清单。
05Run intake: scan the bank and process the inbox执行入库:扫描知识库并处理收件箱
Why this step is here为什么这一步排在这里This is the first step that uses all three earlier pieces together. It is also the routine you will repeat every week.这是第一个同时用到前面三个部件的步骤,也是你以后每周要重复的例行操作。

Do this操作

  1. Run the demo. It scans the sample bank twice, then processes three inbox files.运行 demo。它先扫描样例知识库两次,再处理收件箱里的三个文件。
  2. Read the inbox lines: one file is rejected, two are filed.看收件箱那几行:一个文件被拒绝,两个被归档。
  3. Read the ledger: every file has a tier, a kind, and a status.看台账:每个文件都有等级、类别和状态。
labs/m03_knowledge/ledger.py · intake
def scan_bank(ledger: Ledger, collection: str, bank: Path) -> dict:
    """Record every file already in the bank. Safe to run again: unchanged files are skipped."""
    counts = {"new": 0, "updated": 0, "unchanged": 0, "rejected": 0}
    for p in sorted(bank.rglob("*")):
        if not p.is_file():
            continue
        source = p.relative_to(bank).as_posix()
        problem = validate(p)
        if problem:
            ledger.record(collection, source, sha256(p), "rejected", problem)
            counts["rejected"] += 1
        else:
            counts[ledger.record(collection, source, sha256(p))] += 1
    return counts


def process_inbox(ledger: Ledger, collection: str, inbox: Path, bank: Path, routing: dict) -> list:
    """Validate each inbox file. Good files move into the bank folder named by `routing`
    (file name -> subfolder). Bad files stay put and are recorded as rejected."""
    report = []
    for p in sorted(inbox.iterdir()):
        problem = validate(p)
        if problem:
            ledger.record(collection, "_inbox/" + p.name, sha256(p), "rejected", problem)
            report.append((p.name, "REJECTED", problem))
            continue
        dest = bank / routing.get(p.name, "memos") / p.name
        dest.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(p, dest)
        state = ledger.record(collection, dest.relative_to(bank).as_posix(), sha256(dest))
        report.append((p.name, "FILED", f"{dest.relative_to(bank).as_posix()} ({state})"))
    return report
run
python3 -m labs.m03_knowledge.demo
Recorded output / 记录的输出 · m03.demo
first scan : {'new': 3, 'updated': 0, 'unchanged': 0, 'rejected': 0}
second scan: {'new': 0, 'updated': 0, 'unchanged': 3, 'rejected': 0} (nothing re-read as new)
inbox:
  air-travel-annex.pdf       REJECTED  not a real .pdf file (wrong leading bytes)
  remote-work-policy.md      FILED     policy/remote-work-policy.md (new)
  vendor-rates.pdf           FILED     guides/vendor-rates.pdf (new)
ledger:
  tier 1 rule        filed     policy/remote-work-policy.md
  tier 1 rule        filed     policy/travel-policy.md
  tier 2 guide       filed     guides/traveler-quick-guide.md
  tier 2 guide       retired   guides/vendor-rates.pdf  <- placeholder file, superseded
  tier 3 unclassified rejected  _inbox/air-travel-annex.pdf  <- not a real .pdf file (wrong leading bytes)
  tier 3 commentary  filed     memos/2026-lodging-memo.md
You are done when完成标志The fake PDF is rejected for wrong leading bytes and the second scan reports 3 unchanged.假 PDF 因文件头不符被拒绝;第二次扫描显示 3 个未变化。
Produces产出A bank folder and a ledger that agree with each other.内容一致的知识库目录和台账。
Feeds供给
06Retire, do not delete退役,而不是删除
Why this step is here为什么这一步排在这里Retirement needs ledger rows to act on. Keeping the row lets the system explain why a passage vanished and recognize the same file if it is downloaded again.退役需要台账里已有记录。保留这一行,系统就能解释某段内容为什么消失,并在同一文件被再次下载时认出它。

Do this操作

  1. Call `retire()` with a reason when a file is superseded, duplicated, or off topic.文件被取代、重复或跑题时,调用 `retire()` 并写明原因。
  2. Leave the file on disk or move it to an archive folder. The ledger status is what the index obeys.文件可以留在磁盘上,或移到归档目录。索引只认台账里的状态。
python
ledger.retire("POLICY", "guides/vendor-rates.pdf", "placeholder file, superseded")
You are done when完成标志The retired file appears in the ledger with its reason and is absent from the next index run.退役文件在台账里带着原因出现,并且不会出现在下一次索引中。
Produces产出A status the indexer and the learner both respect.一个索引程序和学习任务都会遵守的状态。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
07Add collectors with a relevance filter加入带相关性过滤的采集器Not executed in the labslab 中未执行
Why this step is here为什么这一步排在这里Automation comes after the manual path works, because a collector only feeds the inbox. Without a filter it fills the bank with off-topic documents that then compete in retrieval.自动化要等手工流程跑通之后再做,因为采集器只是往收件箱送文件。没有过滤的话,它会把跑题的文档塞满知识库,然后在检索中抢位置。
Uses用到

Do this操作

  1. For each feed, write the terms that make an item relevant.为每个信息源写下判断条目是否相关的关键词。
  2. Match broad terms on the title only. Match specific names on title and summary.宽泛的词只匹配标题。具体的名称可以匹配标题和摘要。
  3. Download matches into the inbox. Intake does the rest.把匹配到的条目下载到收件箱。其余交给入库流程。
python
def relevant(item: dict, broad: set, specific: set) -> bool:
    title = item["title"].lower()
    text = title + " " + item.get("summary", "").lower()
    return any(w in title for w in broad) or any(w in text for w in specific)

This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。

Checked on the reference machine在参考机器上的检查结果Not checked on a machine yet. On your own machine run the command below. It only reads, and it writes the result here when you add --write.还没有在机器上检查过。在你自己的机器上运行下面的命令。它只做读取操作;加上 --write 后会把结果写到这里。
run
python3 labs/machine/check.py --write
You are done when完成标志A week of collected items contains nothing you would retire on sight.一周采集到的条目里,没有你一眼就想退役的内容。
Produces产出A scheduled source of new files, already filtered.一个定时运行、已经过滤的新文件来源。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
08Add a curated tier for judgment为经验判断增加一个人工整理层Not executed in the labslab 中未执行
Why this step is here为什么这一步排在这里It is last because it is built from the bank. Source documents state rules. They do not contain your judgment about how the rules apply, and that is often what a question needs.它排在最后,因为它是从知识库里提炼出来的。原始文档陈述规则,但不包含你对规则如何适用的判断,而问题往往需要的正是这个。

Do this操作

  1. For any concept you have explained twice, have a model draft a one-page note from the sources.凡是你解释过两次的概念,就让模型根据原始文档起草一页说明。
  2. Review it yourself. Only reviewed pages move into the bank, in their own folder and tier.由你亲自审核。只有审核过的页面才进入知识库,放在单独的目录和等级下。
  3. Date each page with when it was last verified.在每一页上注明最近一次核实的日期。

This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。

Checked on the reference machine在参考机器上的检查结果Not checked on a machine yet. On your own machine run the command below. It only reads, and it writes the result here when you add --write.还没有在机器上检查过。在你自己的机器上运行下面的命令。它只做读取操作;加上 --write 后会把结果写到这里。
run
python3 labs/machine/check.py --write
You are done when完成标志Every curated page names its sources and has a verified date.每一页整理内容都注明了来源和核实日期。
Produces产出Reviewed concept pages that retrieval can return ahead of raw text.经过审核的概念页,检索时可以排在原文之前返回。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。

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

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

2026-07

HTML error pages saved as PDFsHTML 错误页被存成了 PDF

What happened发生了什么
A size check let 15 files through that were error pages with a .pdf extension.文件大小检查放过了 15 个扩展名为 .pdf 的错误页面。
Fix修复
Check leading bytes for every binary type.对每种二进制类型都检查文件头字节。
Lesson教训
Validate what a file is, never what it is called.校验文件的真实内容,而不是它的名字。
2026-08

A 56 GB table corpus in a document folder文档目录里放了 56 GB 的表格数据

What happened发生了什么
Spending records sat in the document bank as CSV files. The ingester skipped them, so none of it was searchable, and chunking it would have produced nonsense.支出记录以 CSV 形式放在文档库里。入库程序跳过了它们,所以完全无法检索;如果硬去切块,只会产生无意义的内容。
Fix修复
Load tabular data into a query engine and expose query tools.把表格数据加载进查询引擎,并提供查询工具。
Lesson教训
Documents are retrieved. Records are queried. Decide which one you have.文档靠检索,记录靠查询。先判断你手里的是哪一种。
2026-10

One regulation stored three times同一份规章被存了三遍

What happened发生了什么
The same document existed as per-volume files and two full copies. Search results filled with one paragraph repeated.同一份文档既有分卷文件,又有两份完整副本。检索结果里全是同一段话的重复。
Fix修复
Retire duplicate copies in the ledger and collapse identical passages at query time.在台账里退役重复副本,并在查询时合并相同段落。
Lesson教训
Duplicates are a curation problem first and a ranking problem second.重复首先是整理问题,其次才是排序问题。

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

Platform平台How this module maps本模块如何对应
DatabricksLand raw files in a Unity Catalog volume. Use a Lakeflow pipeline for validation and chunk tables. The ledger is a Delta table, and tier is a column.把原始文件放进 Unity Catalog volume。用 Lakeflow 流水线做校验并生成文本块表。台账是一张 Delta 表,等级是其中一列。
IBM watsonxStore documents in watsonx.data or object storage and register them as knowledge sources. Keep the ledger and tier rules as your own tables.把文档存到 watsonx.data 或对象存储,并注册为知识来源。台账和等级规则仍用你自己的表维护。
CodexNot provided. Keep the bank as a repo or bucket with the same ledger, and let agents reach it through a search tool.平台不提供。把知识库放在代码仓库或存储桶里,配同样的台账,让智能体通过检索工具访问。
CursorNot provided. Same approach: your pipeline, your ledger, exposed through a tool.平台不提供。做法相同:你自己的流程和台账,通过工具暴露出去。
Claude Code / Agent SDKNot provided by the coding agent. Project knowledge features hold small document sets. A large bank still needs this pipeline.编程智能体不提供这一层。项目知识功能只适合少量文档,大型知识库仍需要这套流程。
Another machineFolders, a hash ledger, and a rules file work on any filesystem. The lab uses only the standard library.目录、哈希台账和规则文件在任何文件系统上都能用。lab 只用了标准库。

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

Explain it back讲给自己听

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

Why keep retired files in the ledger?为什么要把退役文件留在台账里?
A strong answer参考答案So the system can explain why a passage no longer appears, and so a re-download of the same file is recognized and skipped.这样系统能解释某段内容为什么不再出现,而且同一文件被再次下载时能被认出并跳过。
A folder holds 56 GB of CSV files. Should it be chunked and embedded?一个目录里有 56 GB 的 CSV 文件。应该切块并向量化吗?
A strong answer参考答案No. Tabular records are an analysis corpus. Load them into a query engine and expose query tools. Chunking rows into passages produces confident nonsense.不应该。表格记录是用来分析的数据。应该加载进查询引擎并提供查询工具。把数据行切成段落只会产生看似可信的胡话。
Why do tier rules come before the ledger and after the taxonomy?为什么等级规则排在目录分类之后、台账之前?
A strong answer参考答案Rules match on folder names, so the folders must exist. The ledger stores a tier per row, so the rule must exist when the row is written.规则靠目录名匹配,所以目录必须先有。台账每一行都要存等级,所以写入时规则必须已经存在。
What can you build with this module alone, before any model exists?在没有任何模型的情况下,仅凭这个模块能做成什么?
A strong answer参考答案All of it. Nothing here calls a model. That is why it is a starting point on the map.全部。这里没有任何一步调用模型。这也是它在地图上是起点的原因。

Terms术语

Collection集合A body of documents indexed and searched as one unit, kept apart from other collections.作为一个整体被索引和检索的一批文档,与其他集合相互隔离。
Ledger台账The table with one row per file: hash, tier, status.每个文件一行的表:哈希、等级、状态。
Authority tier权威等级A trust level assigned by path rule. Tier 1 is the rule itself.按路径规则分配的可信度等级。1 级是规定本身。

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就本模块向导师提问