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

Skills技能(Skills)

Instruction files loaded on demand, so routing knowledge costs nothing until it is needed.按需加载的指令文件,路由知识在用到之前不占任何开销。

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

What是什么

A skill is a Markdown file with a one-line description and a body of instructions for one class of task. A router matches a request to at most one skill, and the harness injects its body into the prompt.技能是一个 Markdown 文件,包含一行描述和针对某一类任务的指令正文。路由器把请求匹配到至多一个技能,由 Harness 把正文注入提示词。

Why为什么

A base prompt that holds every rule is paid for on every turn and gets ignored. Skills keep the base short and load detail only when relevant. They also carry routing: which tool answers which kind of question.把所有规则都塞进基础提示词,每一轮都要付费,而且会被模型忽略。技能让基础部分保持简短,只在相关时加载细节。它还承载路由知识:哪类问题该用哪个工具。

How it works工作原理

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

Needs first前置模块

  • Harness engineeringHarness 工程A skill is text injected during prompt composition. Without that step there is nowhere to load it.技能是在组装提示词时注入的文本。没有那一步,它就无处加载。Build out of order不按顺序搭建 Stand in with:可用以下替代: Paste the skill body into the system prompt by hand.手动把技能正文粘贴进系统提示词。

Unlocks解锁

  • Multi-agent patterns多智能体模式Roles are defined by scoped instructions. A worker's base prompt is a skill that is always on.角色由限定范围的指令来定义。子智能体的基础提示词相当于一个始终生效的技能。

In the reference build在参考系统中

Path路径Role作用
apps/agent-server/skills/loader.pyParse, match, and return skills.解析、匹配并返回技能。
apps/agent-server/skills/routing.jsonRouting exemplars per skill.每个技能的路由示例。
apps/agent-server/skills/*.mdThe skills.技能文件。
.claude/skills/Links to the same files for the coding agent.供编程智能体使用的、指向同一批文件的链接。

Process map流程图

How a request gets its skill一个请求如何获得它的技能

  1. 1
    User text用户文本The latest user message.最新的一条用户消息。
  2. 2
    Embed向量化Once per request.每个请求一次。
  3. 3
    Compare with examples与示例比较Best similarity per skill, and for `_none`.每个技能取最高相似度,`_none` 同样计算。
  4. 4
    Margin test幅度检验The best skill must beat `_none` by a margin, or nothing loads.最高分的技能必须超过 `_none` 一定幅度,否则不加载任何技能。
  5. 5
    Inject注入The body is appended to the system prompt under a heading.正文附加到系统提示词的一个标题之下。

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. 1Write one skill from a real failure从一次真实的失败出发写一个技能
  2. 2Load skill files加载技能文件
  3. 3Write routing examples, including a list for no skill编写路由示例,包括“不需要技能”的列表
  4. 4Match a request to at most one skill把请求匹配到至多一个技能
  5. 5Plug the router into the harness把路由器接入 Harness
  6. 6Share the same files with a coding agent让编程智能体共用同一批文件
  7. 7Score routing with examples the router never saw用路由器没见过的例子给路由打分
01Write one skill from a real failure从一次真实的失败出发写一个技能
Why this step is here为什么这一步排在这里A skill encodes a correction. Start from a request the agent handled badly in the harness logs, so every line has a reason.技能是把一次纠正固化下来。从 Harness 日志里智能体处理得不好的请求入手,这样每一行都有来由。
Uses用到

Do this操作

  1. Open the request log. Find a class of question that went wrong.打开请求日志,找出一类处理出错的问题。
  2. Write the frontmatter: one line describing which requests this skill is for.写 frontmatter:一行文字描述这个技能适用于哪些请求。
  3. Write the body as short imperative lines: which tool, in what order, what never to say.正文用简短的祈使句:用哪个工具、按什么顺序、哪些话绝不能说。
labs/m08_skills/skills/expense-investigation.md
---
description: Questions about what was actually spent, by whom, where or when, from expense records
---
Call query_expenses before stating any amount. Name the filters you used in the answer.
A follow-up question means another query. Do not reuse totals from an earlier turn.
When the result is empty, read the diagnostic, relax the filter it names, and try once more.
Never explain why spending could not exist. Say what you searched and that you found nothing.
You are done when完成标志Each line of the body traces to something that went wrong once.正文的每一行都能追溯到曾经出过的某个问题。
Produces产出A skill file: description plus body.一个技能文件:描述加正文。
Feeds供给
02Load skill files加载技能文件
Why this step is here为什么这一步排在这里Parsing comes before matching. Keep it trivial so a skill stays a file anyone can edit.先解析,再匹配。解析要足够简单,让技能始终只是一个人人都能编辑的文件。

Do this操作

  1. Read every Markdown file in the folder.读取目录下的每个 Markdown 文件。
  2. Split frontmatter from body. Keep name, description, body.把 frontmatter 和正文分开。保留名称、描述、正文。
labs/m08_skills/loader.py · load
def load_skills(folder: Path = HERE / "skills") -> dict:
    """Parse every *.md: a frontmatter block with `description:`, then the body."""
    skills = {}
    for p in sorted(folder.glob("*.md")):
        m = re.match(r"^---\n(.*?)\n---\n(.*)$", p.read_text(), re.S)
        if not m:
            continue
        desc = re.search(r"^description:\s*(.+)$", m.group(1), re.M)
        skills[p.stem] = {"name": p.stem, "description": desc.group(1).strip() if desc else "", "body": m.group(2).strip()}
    return skills
run
python3 -m labs.m08_skills.demo
Recorded output / 记录的输出 · m08.demo
1 loaded: {'expense-investigation': 'Questions about what was actually spent, by whom...', 'policy-citation': 'Questions about what a policy rule, limit, defin...'}
You are done when完成标志Both skills load with their descriptions.两个技能都连同描述一起加载成功。
Produces产出`load_skills()`: a dict of skills by name.`load_skills()`:按名称索引的技能字典。
03Write routing examples, including a list for no skill编写路由示例,包括“不需要技能”的列表
Why this step is here为什么这一步排在这里Examples are written before the matcher because the matcher is only as good as they are. The `_none` list is what stops small talk from loading the least-bad skill.先写示例再写匹配器,因为匹配器的效果完全取决于示例。`_none` 列表的作用是防止闲聊时加载“最不差”的那个技能。
Uses用到

Do this操作

  1. For each skill, write five real requests it should handle.为每个技能写五条它应该处理的真实请求。
  2. Under `_none`, write requests that need no skill: greetings, thanks, off-topic.在 `_none` 下写不需要技能的请求:问候、感谢、跑题内容。
  3. Keep this file apart from any eval set. Add a line whenever a real request is misrouted.这个文件要和评估集分开保存。每当有真实请求被路由错,就加一行。
labs/m08_skills/routing.json
{
  "_note": "Requests each skill should handle. Kept apart from evals so the eval stays honest. Add a line when a real request is routed wrong.",
  "policy-citation": [
    "What is the nightly lodging cap?",
    "How many days do I have to file an expense report?",
    "What does per diem mean?",
    "Is alcohol reimbursable?",
    "When do I need approval before booking a trip?"
  ],
  "expense-investigation": [
    "How much did we spend on meals in Chicago?",
    "What did B. Chen spend on lodging in June?",
    "Total air travel for cost center CC-100",
    "Did anyone exceed the cap in Boston?",
    "List lodging expenses for 2026-04"
  ],
  "_none": [
    "hello",
    "what can you do?",
    "thanks, that helps",
    "write a haiku about airports"
  ]
}
You are done when完成标志No example line also appears in an eval file.任何示例行都没有同时出现在评估文件里。
Produces产出`routing.json`: examples per skill and for `_none`.`routing.json`:每个技能和 `_none` 的示例。
04Match a request to at most one skill把请求匹配到至多一个技能
Why this step is here为什么这一步排在这里Matching needs skills and examples. It returns one skill or nothing, because stacking skills dilutes each and raises prompt cost.匹配需要技能和示例都就绪。它只返回一个技能或空,因为叠加多个技能会相互稀释,还会增加提示词开销。

Do this操作

  1. Embed every example once at start.启动时把所有示例向量化一次。
  2. For a request, take the best similarity per skill and for `_none`.对一个请求,分别取每个技能和 `_none` 的最高相似度。
  3. Return the best skill only if it beats `_none` by the margin and clears a floor.只有当最高分的技能超过 `_none` 一定幅度、并且高于最低门槛时才返回它。
labs/m08_skills/loader.py · match
class Router:
    def __init__(self, skills: Optional[dict] = None, routing_path: Path = HERE / "routing.json"):
        self.skills = skills if skills is not None else load_skills()
        routing = json.loads(routing_path.read_text())
        self.exemplars = {name: [llm.embed(x) for x in lines]            # embedded once, at start
                          for name, lines in routing.items() if not name.startswith("_note")}

    def scores(self, text: str) -> dict:
        v = llm.embed(text)
        return {name: max((llm.cosine(v, e) for e in vecs), default=0.0) for name, vecs in self.exemplars.items()}

    def match(self, text: str) -> Optional[dict]:
        """The skill whose examples look most like this request, or None.

        '_none' holds requests that need no skill. It competes like any skill, so
        small talk routes to nothing instead of to the least-bad instruction file.
        """
        s = self.scores(text)
        none = s.pop("_none", 0.0)
        if not s:
            return None
        best = max(s, key=s.get)
        if s[best] < none + MARGIN or s[best] < 0.2 or best not in self.skills:
            return None
        return self.skills[best]
Recorded output / 记录的输出 · m08.demo
2 What is the cap on a hotel room per night?     -> policy-citation        {'policy-citation': 0.51, 'expense-investigation': 0.31, '_none': 0.22}
2 How much did Rivera spend on air travel?       -> expense-investigation  {'policy-citation': 0.14, 'expense-investigation': 0.62, '_none': 0.22}
2 hi there                                       -> no skill               {'policy-citation': 0.0, 'expense-investigation': 0.0, '_none': 0.5}
2 Can you total lodging for Boston in 2026-06?   -> expense-investigation  {'policy-citation': 0.17, 'expense-investigation': 0.51, '_none': 0.44}
You are done when完成标志The greeting routes to no skill. The spending question routes to the expense skill.问候语没有匹配到任何技能。关于支出的问题匹配到报销技能。
Produces产出`Router.match()`: text to one skill or None.`Router.match()`:输入文本,返回一个技能或 None。
05Plug the router into the harness把路由器接入 Harness
Why this step is here为什么这一步排在这里This is the join. The harness already has the plug point, so this step is one argument.这是两个模块的连接点。Harness 已经留好了接入点,所以这一步只是传一个参数。

Do this操作

  1. Pass `router.match` as the `skills` argument when you create the agent.创建智能体时,把 `router.match` 作为 `skills` 参数传入。
  2. Compare prompt length with and without a matched skill.对比匹配到技能和没匹配到时的提示词长度。
  3. Check the request log now records the skill name.确认请求日志现在记录了技能名。
python
from labs.m08_skills.loader import Router

router = Router()
agent = Agent(registry, skills=router.match)     # the only change to the harness call
Recorded output / 记录的输出 · m08.demo
3 prompt with skill: expense-investigation | 591 chars | last line: Never explain why spending could not exist. Say what you searched and that you found nothing.
4 prompt without   : None | 199 chars
5 run: policy-citation -> Lodging is reimbursed at actual cost up to 220 dollars per night. A stay above t ...
You are done when完成标志A matched request has a longer prompt ending in the skill's last line. An unmatched one has the base prompt only.匹配到技能的请求,提示词更长,并以技能的最后一行结尾。没匹配到的只有基础提示词。
Produces产出An agent whose instructions depend on the request.指令随请求而变的智能体。
06Share the same files with a coding agent让编程智能体共用同一批文件Not executed in the labslab 中未执行
Why this step is here为什么这一步排在这里Once skills are plain files they can serve more than one harness. Do it after the router works so you know the files are sound.技能既然是普通文件,就能服务多个 Harness。等路由器跑通、确认文件没问题之后再做这一步。

Do this操作

  1. Create a folder per skill in the coding agent's skills directory.在编程智能体的 skills 目录下,为每个技能建一个文件夹。
  2. Link the file as that folder's SKILL.md.把技能文件链接为该文件夹下的 SKILL.md。
  3. Remember that an edit now changes both agents.记住:现在改一次文件,两个智能体都会受影响。
bash
mkdir -p .claude/skills/expense-investigation
ln -s "$PWD/labs/m08_skills/skills/expense-investigation.md" .claude/skills/expense-investigation/SKILL.md

Some agents require a `name:` line in the frontmatter as well. Check the current format for the agent you use.有些智能体还要求 frontmatter 里有 `name:` 一行。请查看你所用智能体当前的格式要求。

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完成标志The coding agent lists the skill.编程智能体列出了这个技能。
Produces产出One source of instructions for two surfaces.两个入口共用的同一份指令来源。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
07Score routing with examples the router never saw用路由器没见过的例子给路由打分
Why this step is here为什么这一步排在这里It is last because it needs the router, and it belongs with the evaluation module's sealed sets. Routing is a separate layer, so it gets its own number.它排在最后,因为需要路由器已就绪,而且要和评估模块的封存集放在一起。路由是独立的一层,所以要有自己的指标。

Do this操作

  1. Write a gold file of requests with the skill each should get, including `none`.写一个标准文件,列出请求及其应得的技能,包括 `none`。
  2. Seal it with the other eval files.把它和其他评估文件一起封存。
  3. Report accuracy and list every misrouted request.报告准确率,并列出每一条被路由错的请求。
  4. Fix a miss by adding a new exemplar in different words to routing.json. Never copy the gold request itself, or the eval stops measuring routing.修正误判的办法是在 routing.json 里用不同的说法加一条新示例。绝不要把金标准里的请求原样抄过去,否则评估就不再衡量路由了。
labs/m08_skills/route_eval.py · route-eval
def seal_gold(dest_dir: Path) -> Path:
    dest = dest_dir / "routing_gold.json"
    shutil.copy2(HERE / "routing_gold.json", dest)
    os.chmod(dest, 0o444)
    (dest_dir / "SEAL.json").write_text(json.dumps({"routing_gold.json": hashlib.sha256(dest.read_bytes()).hexdigest()}))
    return dest


def check_seal(dest_dir: Path) -> None:
    want = json.loads((dest_dir / "SEAL.json").read_text())["routing_gold.json"]
    if hashlib.sha256((dest_dir / "routing_gold.json").read_bytes()).hexdigest() != want:
        raise RuntimeError("SEAL BROKEN: routing gold changed after sealing")


def evaluate(router: Router, dest_dir: Path) -> dict:
    check_seal(dest_dir)
    items = json.loads((dest_dir / "routing_gold.json").read_text())["items"]
    exemplars = json.loads((HERE / "routing.json").read_text())
    leaked = [i["q"] for i in items if any(i["q"] in v for k, v in exemplars.items() if not k.startswith("_note"))]
    if leaked:
        raise RuntimeError(f"gold items copied into routing.json: {leaked}")
    misses = []
    for i in items:
        got = (router.match(i["q"]) or {}).get("name", "none")
        if got != i["skill"]:
            misses.append((i["q"], i["skill"], got))
    return {"n": len(items), "accuracy": round(1 - len(misses) / len(items), 3), "misrouted": misses}
run
python3 -m labs.m08_skills.route_eval
Recorded output / 记录的输出 · m08.eval
1 routing accuracy on 12 unseen requests: 0.667
  misrouted: 'What is the maximum I can claim for a hotel night?'  wanted policy-citation, got none
  misrouted: 'Explain what an incidental expense is.'  wanted policy-citation, got none
  misrouted: 'Which trips went over the hotel cap?'  wanted expense-investigation, got policy-citation
  misrouted: 'good morning'  wanted none, got expense-investigation
2 exemplars and gold kept apart: no gold item found in routing.json
You are done when完成标志On 12 unseen requests the lab router scores 0.667 and names its 4 misses. That is the starting number to improve, with gold and exemplars kept apart.在 12 条没见过的请求上,lab 路由器得分 0.667,并列出了 4 条误判。这是要改进的起点,金标准和示例始终分开。
Produces产出A routing accuracy number that moves when exemplars change.一个会随示例变化而变化的路由准确率。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。

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

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

2026-09

Keyword overlap picked the wrong skill关键词重合选错了技能

What happened发生了什么
Matching on words shared with the description routed requests by vocabulary and missed paraphrases.靠与描述的词汇重合来匹配,结果是按用词路由,换个说法就匹配不上。
Fix修复
Route by natural-language examples, with descriptions as a fallback.改为按自然语言示例路由,描述只作为兜底。
Lesson教训
Route on what people ask, in their words.按人们实际提问的方式、用他们的原话来做路由。
2026-09

Every request loaded some skill每个请求都加载了某个技能

What happened发生了什么
With no examples of requests that need nothing, the closest skill always won.由于没有“什么都不需要”的示例,总是由最接近的技能胜出。
Fix修复
A `_none` list and a margin the winner must clear.增加 `_none` 列表,并要求胜出者必须超过一定幅度。
Lesson教训
A classifier needs examples of the empty class.分类器需要“空类别”的示例。

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

Platform平台How this module maps本模块如何对应
DatabricksNo native skill format. Store skill files in a volume and load them in your agent code, or register prompts in the prompt registry.没有原生的技能格式。把技能文件存在 volume 里,由智能体代码加载;或者在 prompt registry 里登记提示词。
IBM watsonxAgent instructions and per-agent guidelines play this role. Narrow collaborator agents are the platform's way to scope instructions.智能体的 instructions 和各自的 guidelines 起到这个作用。平台用职责单一的协作智能体来限定指令范围。
CodexSkills are supported as folders with a SKILL.md. The lab skill bodies move over with small edits.支持技能,形式是带 SKILL.md 的文件夹。lab 的技能正文稍作修改即可迁移。
CursorRules files scoped by path or description, plus skills. The description line does the same matching job.有按路径或描述限定范围的规则文件,也有技能。描述那一行承担同样的匹配作用。
Claude Code / Agent SDKNative. A folder per skill with a SKILL.md whose description decides when it loads.原生支持。每个技能一个文件夹,内含 SKILL.md,由其中的描述决定何时加载。
Another machineMarkdown files and a short loader. Fully portable.Markdown 文件加一个简短的加载器。完全可移植。

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

Explain it back讲给自己听

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

Why at most one skill per request?为什么每个请求最多一个技能?
A strong answer参考答案A skill is a narrow instruction set. Stacking several dilutes each and raises prompt cost on every turn.技能是一组专门的指令。叠加多个会相互稀释,并且每一轮的提示词开销都会增加。
What is the difference between a skill and a tool?技能和工具有什么区别?
A strong answer参考答案A tool does something and returns data. A skill tells the model how to approach a class of task, including which tools to use and in what order.工具执行某个操作并返回数据。技能告诉模型如何处理某一类任务,包括用哪些工具、按什么顺序。
Why keep routing examples and routing gold in separate files?为什么路由示例和路由标准集要放在不同文件?
A strong answer参考答案The router matches against the examples. If gold items are in that file, the eval measures lookup of known strings and stops measuring routing.路由器是对着示例做匹配的。如果标准集的条目也在里面,评估测的就变成了“查找已知字符串”,而不再是路由能力。
What does the `_none` list do?`_none` 列表起什么作用?
A strong answer参考答案It competes like a skill. A greeting is closer to `_none` than to any skill, so nothing loads. Without it the nearest skill always wins.它像技能一样参与竞争。问候语离 `_none` 比离任何技能都近,于是不加载任何技能。没有它,最接近的技能总会胜出。

Terms术语

FrontmatterFrontmatterThe block between `---` lines at the top of a file that holds metadata.文件顶部两行 `---` 之间存放元数据的部分。
Exemplar示例A real request stored as an example of what a skill should handle.作为“该技能应处理的请求”样例而保存的真实请求。
Margin幅度How much the best skill must beat `_none` by.得分最高的技能必须超过 `_none` 多少。

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