技能建议
从 Nous Research 的 Hermes 目录的 182 个技能中,为一次 agent 回合最多挑选一个技能:第一个 TypeSafe 请求给每个技能排序,并回答该回合究竟需不需要技能;第二个请求认真读一遍排名前三的技能,可以把它们全部否决。胜出者的名字会写进 agent 系统提示词的一行,而它加载错误技能的比例、以及在没有任何技能合适时仍然加载的比例,都下降了一半以上。
agent 挑选技能的方式是把它们全部截断后加载进系统消息,这会抬升成本、降低技能选择的表现,并在本次会话余下的时间里引发上下文腐化。我们的应对方式是每个回合使用两个 TypeSafe 请求,一个给技能排序,一个验证所选项,从而把错误的技能加载减少一半以上。
技能名单庞大的 agent 几乎是在毫无信息的情况下做出选择。名单以索引的形式来到它面前:每个技能一行,描述被截断,以免全文挤占对话。此处使用的 agent 框架 Hermes 默认把它截到 60 个字符。例如在这样的宽度下,编辑 .pptx 文件的技能读起来和创作这类文件的技能几乎一模一样。让它做一份融资路演文档,它可能加载错误的那一个。在某次完全没有技能合适的回合里,它仍然可能照样加载一个,因为一串名字会诱人去猜。
本实践手册不去动那些描述,而是改用渐进式披露:先便宜地读完全部 182 个技能,再详细读其中三个。在「加载哪个技能(如果真有的话)」这个决定之前,先放入两个 TypeSafe 请求。第一个请求把名单里的每个技能与用户这一回合做排序,并回答该回合到底需不需要技能。第二个请求只重读排名前三的技能,此时每个技能都带着自己的完整描述和 instructions 的开头,并且可以全部否决。
胜出者的名字会成为该回合 agent 系统提示词中额外的一行:
<skill_relevance>
Relevant to the current request: pptx-author. Ignore this if it does not fit what the user
actually asked for.
</skill_relevance>
agent 保留自己完整的索引和判断,那一行只是告诉它先看哪一条。名单本身从不改变,因此对它的任何前缀缓存都依然有效。针对 claude-haiku-4-5-20251001 的 488 个请求,使用 Hermes 名单中的技能:
| 加载了错误的技能 | 没有任何技能合适时仍然加载 | |
|---|---|---|
| 只有名单、独自运行的 agent | 16.8% | 9.8% |
| 带有 TypeSafe 建议的 agent | 7.3% | 4.0% |
| 被直接告知正确答案的 agent | 2.5% | 1.2% |
第三行说明犯错的下限并非为零,因为即使被直接给了正确的技能,agent 也不总会加载它,而任何选择方法无论多好都越不过这一点。
你最终会得到一个最多返回一个技能名的 suggest() 函数、一个把它包装起来放进系统提示词的 suggestion_block(),以及生成上表的测试框架,随时可以指向你自己的名单。
设置
- 安装 TypeSafe 客户端、Anthropic 客户端,以及共享的实践手册辅助工具。
- 设置 TypeSafe API key,以及一个用于被测 agent 的 Anthropic 密钥。
pip install anthropic matplotlib ipython "typesafe-sdk>=0.5.7" cooksafe --extra-index-url https://pypi.typesafe.ai/
export TYPESAFE_API_KEY=your-key-here
export ANTHROPIC_API_KEY=your-key-here
注意: 下面的代码块是同一个脚本,按顺序排列。若要跟着操作,请按所示的顺序把它们放进一个文件。
缓存结果
JsonCache 保存每次调用的结果,并以它的输入为键,因此重新运行时会重放下面这些数字,而不去调用任何一个 API。删除 json_cache.json 即可真实运行。已发布的运行使用的是 jev-1.12 和 claude-haiku-4-5-20251001,渲染于 2026-07-31。
import json
import os
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from time import perf_counter
import anthropic
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
from cooksafe import JsonCache, make_playground_link
from IPython.display import Markdown, display
from typesafe_sdk import Choice, Noul, TypeSafeClient
matplotlib.use("Agg") # headless render
TYPESAFE_MODEL = "jev-1.12"
AGENT_MODEL = (
"claude-haiku-4-5-20251001" # the agent under test, pinned so scores are stable
)
SHORTLIST = 3 # candidates carried from the first request into the second
EXCERPT_CHARS = (
700 # SKILL.md characters each candidate brings; the roster file stores 1600
)
GATE_THRESHOLD = (
0.30 # mean of the three request nouls, below which nothing is suggested
)
FITS_THRESHOLD = (
0.30 # a shortlist whose best "does this fit" noul is under this is dropped
)
WORKERS = 8 # small pool: enough to keep a live run to minutes, gentle on rate limits
assert EXCERPT_CHARS <= 1600, (
"the shipped roster file stores 1600 body characters per skill"
)
client = TypeSafeClient(
api_key=os.environ.get(
"TYPESAFE_API_KEY", "cache-only"
), # keyless kernels replay the cache
base_url=os.environ.get("TYPESAFE_ENDPOINT"),
timeout=120.0,
)
agent = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY", "cache-only"))
json_cache = JsonCache(Path("json_cache.json"))
步骤 1:加载名单
hermes_roster.json 在某个固定提交上保存了 NousResearch/hermes-agent(MIT)的 182 个技能。每条记录保存一个技能的名称与分类、索引中呈现的那段描述、完整描述,以及它 SKILL.md 的开头部分。
下面的索引,以及提示词中位于它上方的那段说明,都从 Hermes 原样照搬而来。
ROSTER = json.loads(Path("hermes_roster.json").read_text(encoding="utf-8"))
BY_NAME = {skill["name"]: skill for skill in ROSTER}
# Verbatim from hermes-agent agent/prompt_builder.py:build_skills_system_prompt.
PREAMBLE = (
"## Skills (mandatory)\n"
"Before replying, scan the skills below. If a skill matches or is even partially relevant "
"to your task, you MUST load it with skill_view(name) and follow its instructions. "
"Err on the side of loading — it is always better to have context you don't need "
"than to miss critical steps, pitfalls, or established workflows. "
"Skills contain specialized knowledge — API endpoints, tool-specific commands, "
"and proven workflows that outperform general-purpose approaches. Load the skill "
"even if you think you could handle the task with basic tools like web_search or terminal. "
"Skills also encode the user's preferred approach, conventions, and quality standards "
"for tasks like code review, planning, and testing — load them even for tasks you "
"already know how to do, because the skill defines how it should be done here.\n"
"Whenever the user asks you to configure, set up, install, enable, disable, modify, "
"or troubleshoot Hermes Agent itself — its CLI, config, models, providers, tools, "
"skills, voice, gateway, plugins, or any feature — load the `hermes-agent` skill "
"first. It has the actual commands (e.g. `hermes config set …`, `hermes tools`, "
"`hermes setup`) so you don't have to guess or invent workarounds.\n"
"If a skill has issues, fix it with skill_manage(action='patch').\n"
"After difficult/iterative tasks, offer to save as a skill. "
"If a skill you loaded was missing steps, had wrong commands, or needed "
"pitfalls you discovered, update it before finishing.\n"
"\n"
)
FOOTER = "\n\nOnly proceed without loading a skill if genuinely none are relevant to the task."
IDENTITY = (
"You are Hermes, a capable AI assistant with access to tools and a library "
"of skills. You help the user with coding, research, and everyday tasks.\n\n"
)
def render_index() -> str:
"""The body of <available_skills>: skills grouped by category, both sorted by name."""
by_category = defaultdict(list)
for skill in ROSTER:
by_category[skill["category"]].append(skill)
lines = []
for category in sorted(by_category):
lines.append(f" {category}:")
for skill in sorted(by_category[category], key=lambda s: s["name"]):
lines.append(f" - {skill['name']}: {skill['description']}")
return "\n".join(lines)
CATALOG_PROMPT = (
IDENTITY
+ PREAMBLE
+ "<available_skills>\n"
+ render_index()
+ "\n</available_skills>"
+ FOOTER
)
widths = [len(skill["description"]) for skill in ROSTER]
print(f"{len(ROSTER)} skills in {len({s['category'] for s in ROSTER})} categories")
print(f"roster prompt: {len(CATALOG_PROMPT):,} characters")
print(
f"index description: {sum(widths) / len(widths):.0f} characters on average, "
f"{max(widths)} at most"
)
print("\none category, as the agent reads it:")
index_lines = render_index().splitlines()
start = index_lines.index(" apple:")
end = next(
i
for i in range(start + 1, len(index_lines))
if not index_lines[i].startswith(" ")
)
print("\n".join(index_lines[start:end]))
182 skills in 33 categories
roster prompt: 16,089 characters
index description: 54 characters on average, 60 at most
one category, as the agent reads it:
apple:
- apple-notes: Manage Apple Notes via memo CLI: create, search, edit.
- apple-reminders: Apple Reminders via remindctl: add, list, complete.
- findmy: Track Apple devices/AirTags via FindMy.app on macOS.
- imessage: Send and receive iMessages/SMS via the imsg CLI on macOS.
步骤 2:先评估 agent 自己
requests.json 保存了 488 个单回合请求,其中 315 个恰好被一个技能覆盖,另外 173 个没有任何技能覆盖。
被覆盖的那些请求由 Claude Sonnet 5 依据每个技能自己的 SKILL.md 写出,因此标签可信,而且这些请求比用户真实发来的更简单。
那 173 个未被覆盖的请求全都是为了惩罚猜测而写的:85 个日常请求,42 个没有任何技能能服务的技术问题(解释一下什么是 monad),以及 46 个索取名单里没有对应技能的具体事情,比如在一份只覆盖 X、别无其他的名单上要求把这个发到 Mastodon。
评分只读取 agent 的第一次响应。两个数字都是错误率,所以每个都是越低越好:
- 错误加载:在被覆盖的请求里,第一次
skill_view调用不是覆盖该请求的那个技能所占的比例。一个完全没有加载任何技能的回合也算一次失误。 - 多余加载:在未被覆盖的请求里,agent 有调用
skill_view所占的比例。
REQUESTS = json.loads(Path("requests.json").read_text(encoding="utf-8"))
POSITIVES = [p for p in REQUESTS if p["gold"]]
NEGATIVES = [p for p in REQUESTS if not p["gold"]]
print(
f"{len(REQUESTS)} requests: {len(POSITIVES)} covered by a skill "
f"({len({p['gold'] for p in POSITIVES})} distinct skills), {len(NEGATIVES)} covered by none"
)
print(f"\ncovered [{POSITIVES[0]['gold']}] {POSITIVES[0]['text']}")
print(f"uncovered {NEGATIVES[0]['text']}")
488 requests: 315 covered by a skill (171 distinct skills), 173 covered by none
covered [1password] I've got a config.yaml with `{{ op://app-prod/db/password }}` placeholders in it — can you set up my project to pull the real values in at runtime instead of hardcoding them?
uncovered Add these three cards to our Trello backlog.
建议被放进系统提示词里它自己的区块,位于名单之后而不是名单之内,这样名单文本在每个回合都完全一致,以维持前缀缓存。
agent 有一套最小的工具集,其中包括用自由文本名称加载技能的 skill_view。名称必须与技能完全一致才算一次正确的加载。
# Verbatim from hermes-agent tools/skills_tool.py:SKILL_VIEW_SCHEMA.
SKILL_VIEW_DESCRIPTION = (
"Skills allow for loading information about specific tasks and workflows, as "
"well as scripts and templates. Load a skill's full content or access its "
"linked files (references, templates, scripts). First call returns SKILL.md "
"content plus a 'linked_files' dict showing available references/templates/"
"scripts. To access those, call again with file_path parameter."
)
TOOLS = [
{
"name": "skill_view",
"description": SKILL_VIEW_DESCRIPTION,
"input_schema": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "The skill name."}
},
"required": ["name"],
},
},
{
"name": "terminal",
"description": "Run a shell command on the user's machine and return its output.",
"input_schema": {
"type": "object",
"properties": {"command": {"type": "string"}},
"required": ["command"],
},
},
{
"name": "read_file",
"description": "Read a file from the user's filesystem.",
"input_schema": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
},
},
{
"name": "web_search",
"description": "Search the web and return result snippets.",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"],
},
},
]
@json_cache
def run_turn(model: str, arm: str, request: str, suggestion: str) -> dict:
"""One measured turn. ``arm`` is in the key so each arm samples independently."""
system = [
{"type": "text", "text": CATALOG_PROMPT, "cache_control": {"type": "ephemeral"}}
]
if suggestion:
system.append({"type": "text", "text": suggestion}) # after the breakpoint
response = agent.messages.create(
model=model,
max_tokens=1024,
system=system,
tools=TOOLS,
messages=[{"role": "user", "content": request}],
)
usage = response.usage
return {
"loaded": [
str(block.input.get("name", ""))
for block in response.content
if block.type == "tool_use" and block.name == "skill_view"
],
"input_tokens": usage.input_tokens or 0,
"output_tokens": usage.output_tokens or 0,
}
def summarise(turns: dict[str, dict]) -> dict[str, float]:
"""Two failure rates: wrong loads on covered requests, needless ones on uncovered."""
hits = [turns[p["text"]]["loaded"][:1] == [p["gold"]] for p in POSITIVES]
over = [bool(turns[p["text"]]["loaded"]) for p in NEGATIVES]
return {
# both metrics are errors, so the two columns read the same direction
"wrong_load": 1 - sum(hits) / len(hits),
"needless_load": sum(over) / len(over),
}
def run_arm(arm: str, suggestions: dict[str, str]) -> dict[str, dict]:
"""One measured turn per request, in a small pool. 488 calls."""
texts = [request["text"] for request in REQUESTS]
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
turns = pool.map(
lambda t: run_turn(AGENT_MODEL, arm, t, suggestions.get(t, "")), texts
)
return dict(zip(texts, turns))
agent 先只带着自己的名单运行一次,也就是它今天的工作方式。它的两个错误率就是本实践手册其余部分用来对照的基线。
baseline = run_arm("baseline", {})
base_scores = summarise(baseline)
print(
f"wrong loads {base_scores['wrong_load']:.1%} ({len(POSITIVES)} covered requests)"
)
print(
f"needless loads {base_scores['needless_load']:.1%} ({len(NEGATIVES)} uncovered requests)"
)
# where the wrong loads land: a neighbour of the right skill, or somewhere unrelated?
misses = [
(p["gold"], baseline[p["text"]]["loaded"][0])
for p in POSITIVES
if baseline[p["text"]]["loaded"] and baseline[p["text"]]["loaded"][0] != p["gold"]
]
same_category = sum(
1
for gold, got in misses
if got in BY_NAME and BY_NAME[got]["category"] == BY_NAME[gold]["category"]
)
print(
f"\nof {len(misses)} wrong first picks, {same_category} came from the right skill's own "
f"category"
)
wrong loads 16.8% (315 covered requests)
needless loads 9.8% (173 uncovered requests)
of 36 wrong first picks, 10 came from the right skill's own category
错误加载落在正确技能所属分类里的次数,远多于随机情形下应有的比例,所以难点在于把几个长得很像的技能区分开。agent 大致上已经在往对的地方找了。
步骤 3:给整份名单排序
一个请求承载两类问题:
which是一个覆盖全部 182 个技能名的Choice问题,以索引中的描述作为每个选项的 criteria(与 agent 自己拿到的文本相同)。它的概率就是排序结果。- 三个关于该请求的
Noul问题,列在下面,每一个都以不同方式追问:它想要的是采取行动,而不是得到一段解释。prose_suffices的方向正好相反。它们的平均值决定到底要不要给出建议,低于 0.30 就什么都不建议。
两者在同一个请求里发出,所以排序和检查只花一次往返。
把这三问写成在问「是否需要采取行动」。一个关于主题内容的问题无法把解释一下什么是 monad 与一个需要技能的请求分开,因为两者都属于软件。
一个 Choice 问题能从容装下这个规模的名单。再大上几倍,就得把它切成若干块分别排序,然后对胜出者再跑一遍这个同样的候选清单步骤。
CHOICE_INSTRUCTIONS = (
"Which of these skills, if any, is the right one to load to help with the "
"user's latest request?"
)
GATE_QUESTIONS = {
"acts_on_user_system": (
"Is the assistant being asked to act on the user's files, accounts, devices, "
"or online services, rather than only to explain or advise?"
),
"would_follow_documented_procedure": (
"Would a careful expert answering this consult a specific documented procedure "
"or set of commands, rather than answering from general understanding?"
),
"prose_suffices": (
"Could a knowledgeable generalist fully satisfy this request in prose, with "
"no tools, no documentation, and no access to the user's files or accounts?"
),
}
INVERTED = {"prose_suffices"} # a yes here points away from needing a skill
def build_state(request: str) -> dict:
return {"request": request, "recent_context": ""}
@json_cache
def rank_wide(request: str) -> dict:
"""Request 1: rank all 182 skills, and score the request for whether a skill applies."""
questions = {
"which": Choice(
instructions=CHOICE_INSTRUCTIONS,
criteria={skill["name"]: skill["description"] for skill in ROSTER},
)
}
for key, text in GATE_QUESTIONS.items():
questions[f"gate::{key}"] = Noul(instructions=text)
started = perf_counter()
response = client.system_one(
state=build_state(request), questions=questions, model=TYPESAFE_MODEL
)
ranked = sorted(
response.answers["which"].probabilities.items(), key=lambda kv: -kv[1]
)
values = {
key.removeprefix("gate::"): answer.noul
for key, answer in response.answers.items()
if key.startswith("gate::")
}
oriented = [(1.0 - v) if k in INVERTED else v for k, v in values.items()]
return {
"ranked": ranked[
:12
], # more than any shortlist needs, and keeps the cache small
"gate": sum(oriented) / len(oriented),
"values": values,
"seconds": round(perf_counter() - started, 2),
"input_tokens": response.usage.input_tokens or 0,
"output_tokens": response.usage.output_tokens or 0,
}
DEMO = [
"Can you save this recipe as a new note in my 'Recipes' folder in Notes.app so it syncs"
" to my phone? Just write it up in whatever editor pops up.",
"Can you put together a pitch deck skeleton (cover, situation overview, comps, precedent"
" transactions, DCF, LBO) as a .pptx, using our firm-template.pptx for branding and"
" footnoting each valuation number back to the cell it came from in the model?",
"Post this announcement to my Mastodon account.",
]
for request in DEMO:
wide = rank_wide(request)
verdict = "suggest" if wide["gate"] >= GATE_THRESHOLD else "stay quiet"
print(f'"{request[:78]}"')
print(f" needs a skill {wide['gate']:.2f} -> {verdict} ({wide['seconds']}s)")
for name, probability in wide["ranked"][:SHORTLIST]:
print(f" {probability:.3f} {name:<38}{BY_NAME[name]['description']}")
print()
"Can you save this recipe as a new note in my 'Recipes' folder in Notes.app so "
needs a skill 0.75 -> suggest (0.31s)
0.990 apple-notes Manage Apple Notes via memo CLI: create, search, edit.
0.010 computer-use Drive the user's desktop in the background — clicking, ty...
0.000 concept-diagrams Generate flat, minimal educational SVG visuals as HTML.
"Can you put together a pitch deck skeleton (cover, situation overview, comps, "
needs a skill 0.76 -> suggest (0.16s)
0.700 powerpoint Create, read, edit .pptx decks, slides, notes, templates.
0.300 pptx-author Build PowerPoint decks headless with python-pptx.
0.000 chroma Embedding database for RAG and semantic search.
"Post this announcement to my Mastodon account."
needs a skill 0.78 -> suggest (0.16s)
0.550 xurl X/Twitter via xurl CLI: raw post search, posting, DM, media.
0.140 computer-use Drive the user's desktop in the background — clicking, ty...
0.080 openhands Delegate coding to OpenHands CLI (model-agnostic, LiteLLM).
Notes.app 那个请求含义明确,它的首选就是对的。Mastodon 那个则不是排序能挽救的:三个问题都说需要技能,因为向一个账号发帖是一种行动,而名单里有向 X 发帖的技能、没有针对 Mastodon 的技能,最接近的那个无论如何都会胜出。
剩下的是那份演示文稿。两个领先者都是 .pptx 技能,而在 60 个字符的宽度下,宽排序的 Choice 问题把编辑技能排在了创作技能之前,而请求要的恰恰是创作一份演示文稿。
步骤 4:给前三名重新排序
三个选项留出了空间,可以放下完整描述加上每个技能自己 SKILL.md 的开头,于是第二个请求把同一个问题交给更好的证据:
which是一个针对候选清单的Choice问题,以那段更长的文本作为每个选项的 criteria。fits::{name}是每个候选一个Noul问题:这个技能是否做请求所要求的那件具体事情?每一个都单独作答,因此它们可能全都给出低分,而最高分低于 0.30 的候选清单会被整体丢弃。
RERANK_INSTRUCTIONS = (
"Exactly one of these skills is the right one to load for the user's latest "
"request. Which one? Read what each actually does, not just its name."
)
def rerank_criteria(names: tuple[str, ...], excerpt: int) -> dict[str, str]:
return {
name: f"{BY_NAME[name]['description_full']} — {BY_NAME[name]['body'][:excerpt]}"
for name in names
}
def rerank_questions(names: tuple[str, ...], excerpt: int) -> dict:
questions = {
"which": Choice(
instructions=RERANK_INSTRUCTIONS, criteria=rerank_criteria(names, excerpt)
)
}
for name in names:
questions[f"fits::{name}"] = Noul(
instructions=(
f"Does the skill '{name}' do the specific thing the user's request asks "
f"for? It is described as: {BY_NAME[name]['description_full']}"
)
)
return questions
@json_cache
def rerank(request: str, names: tuple[str, ...], excerpt: int) -> dict:
"""Request 2: the same Choice over a shortlist, plus one absolute noul per candidate."""
started = perf_counter()
response = client.system_one(
state=build_state(request),
questions=rerank_questions(names, excerpt),
model=TYPESAFE_MODEL,
)
return {
"winner": response.answers["which"].choice,
"fits": {
key.removeprefix("fits::"): answer.noul
for key, answer in response.answers.items()
if key.startswith("fits::")
},
"seconds": round(perf_counter() - started, 2),
"input_tokens": response.usage.input_tokens or 0,
"output_tokens": response.usage.output_tokens or 0,
}
for request in DEMO:
wide = rank_wide(request)
if wide["gate"] < GATE_THRESHOLD:
print(f'"{request[:78]}"\n scored too low, nothing suggested\n')
continue
shortlist = tuple(name for name, _ in wide["ranked"][:SHORTLIST])
result = rerank(request, shortlist, EXCERPT_CHARS)
best = max(result["fits"].values())
verdict = result["winner"] if best >= FITS_THRESHOLD else "nothing fits"
print(f'"{request[:78]}"')
print(f" was {shortlist[0]} -> {verdict} ({result['seconds']}s)")
for name in shortlist:
print(f" fits {result['fits'][name]:.2f} {name}")
print()
"Can you save this recipe as a new note in my 'Recipes' folder in Notes.app so "
was apple-notes -> apple-notes (0.12s)
fits 0.60 apple-notes
fits 0.54 computer-use
fits 0.01 concept-diagrams
"Can you put together a pitch deck skeleton (cover, situation overview, comps, "
was powerpoint -> pptx-author (0.09s)
fits 0.73 powerpoint
fits 0.38 pptx-author
fits 0.02 chroma
"Post this announcement to my Mastodon account."
was xurl -> xurl (0.09s)
fits 0.56 xurl
fits 0.38 computer-use
fits 0.05 openhands
两个 .pptx 技能在各自带上自己的文本之后就分开了:那份演示文稿请求翻到了创作技能。
在那里,fits noul 与 Choice 意见不一:noul 给编辑技能打的分更高,而 Choice 选的是创作技能。它们决定的是不同的事。Choice 决定哪一个技能,noul 决定要不要开口说这件事。
Mastodon 那个请求闯过了两道检查:它最好的 fits noul 高于 0.30,于是这份实践手册为一个关于 Mastodon 的请求建议了 X 技能。大多数同类请求都会被拦下。第二遍只能否决宽排序交给它的东西,而这里交给它的是三个擦边球。
下面这个函数就是整份实践手册的全部:两个请求加两个阈值,最多返回一个技能名。
要把它指向你自己的名单,替换 hermes_roster.json 即可。上面每个问题都只从该文件里读 name、description、description_full 和 body,此外没有任何地方知道 Hermes 的存在。
def suggest(request: str) -> tuple[str, ...]:
"""At most one skill name for a request, or () for "nothing here applies"."""
wide = rank_wide(request)
if wide["gate"] < GATE_THRESHOLD:
return ()
shortlist = tuple(name for name, _ in wide["ranked"][:SHORTLIST])
result = rerank(request, shortlist, EXCERPT_CHARS)
if max(result["fits"].values()) < FITS_THRESHOLD:
return ()
return (result["winner"],)
def suggestion_block(names: tuple[str, ...]) -> str:
"""What gets appended after the roster, in the suggestion.
This string is a measured input rather than prose: it goes to the agent, so it is part
of every graded turn's cache key. Editing a word here silently invalidates the shipped
results and costs a live re-run to restore them.
"""
body = (
f"Relevant to the current request: {', '.join(names)}. Ignore this if it does not "
"fit what the user actually asked for."
if names
else "No skill in the roster appears relevant to this request."
)
return f"\n\n<skill_relevance>\n{body}\n</skill_relevance>"
print(suggestion_block(suggest(DEMO[1])))
print(suggestion_block(suggest(DEMO[2])))
<skill_relevance>
Relevant to the current request: pptx-author. Ignore this if it does not fit what the user actually asked for.
</skill_relevance>
<skill_relevance>
Relevant to the current request: xurl. Ignore this if it does not fit what the user actually asked for.
</skill_relevance>
步骤 5:衡量建议的效果
488 个请求中的每一个都送到 agent 那里三次,每次是一个被测量的回合。几次运行的差别只在于告知了 agent 什么:
| 系统提示词里放入的内容 | |
|---|---|
| 只有 agent | 什么都不放 |
| 带有建议的 agent | suggest() 返回的内容 |
| 被直接告知答案的 agent | 覆盖该请求的技能名;没有时则是 "nothing applies" |
第三行无法达成;它是另外两行用来对照的天花板。
那条建议的措辞承担着两项工作。它说明这条建议可以被忽略,因为更用力地推销在错误的建议上同样能换来顺从,而一条错误的建议比没有建议更糟。而且即使某个回合没有什么可建议,也仍然会发一句话说明这一点;什么都不发,就会让名单自带的那句「宁可多加载」失去制衡。
texts = [request["text"] for request in REQUESTS]
with ThreadPoolExecutor(max_workers=WORKERS) as pool: # up to 488 x 2 TypeSafe requests
suggested = dict(zip(texts, pool.map(suggest, texts)))
WIDE = {text: rank_wide(text) for text in texts} # all cache hits now; reused below
arms = {
"baseline": {},
"TypeSafe": {
request["text"]: suggestion_block(suggested[request["text"]])
for request in REQUESTS
},
"oracle": {
request["text"]: suggestion_block((request["gold"],) if request["gold"] else ())
for request in REQUESTS
},
}
scores = {
arm: summarise(run_arm(arm, suggestions)) for arm, suggestions in arms.items()
}
print(f"{'run':<10}{'wrong loads':>13}{'needless loads':>16}")
for arm, row in scores.items():
print(f"{arm:<10}{row['wrong_load']:>13.1%}{row['needless_load']:>16.1%}")
def fewer(metric: str) -> str:
"""The plain ratio between the two arms' error rates."""
return f"{scores['baseline'][metric] / scores['TypeSafe'][metric]:.1f}x fewer"
print(
f"\nbaseline -> TypeSafe: {fewer('wrong_load')} wrong loads, "
f"{fewer('needless_load')} needless ones"
)
run wrong loads needless loads
baseline 16.8% 9.8%
TypeSafe 7.3% 4.0%
oracle 2.5% 1.2%
baseline -> TypeSafe: 2.3x fewer wrong loads, 2.4x fewer needless ones
moved = [
(
baseline[p["text"]]["loaded"][:1] == [p["gold"]],
run_turn(AGENT_MODEL, "TypeSafe", p["text"], arms["TypeSafe"][p["text"]])[
"loaded"
][:1]
== [p["gold"]],
)
for p in POSITIVES
]
print(
f"of {len(POSITIVES)} covered requests: {sum(not b and a for b, a in moved)} the suggestion "
f"fixed, {sum(b and not a for b, a in moved)} it broke"
)
of 315 covered requests: 37 the suggestion fixed, 7 it broke
这条建议修好的请求远多于它弄坏的,但它确实弄坏了一些 agent 原本自己做对的请求。一条自信的错误建议比完全没有建议更有说服力,这就是把它放在回合之前的代价。
SURFACE, INK, INK2, MUTED = "#fcfcfb", "#0b0b0b", "#52514e", "#898781"
GRID, AXIS, BLUE, ORANGE = "#e1e0d9", "#c3c2b7", "#2a78d6", "#eb6834"
ARM_COLOR = {"baseline": BLUE, "TypeSafe": ORANGE, "oracle": MUTED}
def style(ax):
ax.set_facecolor(SURFACE)
for side in ("top", "right"):
ax.spines[side].set_visible(False)
for side in ("left", "bottom"):
ax.spines[side].set_color(AXIS)
ax.tick_params(colors=MUTED, labelcolor=INK2, labelsize=9)
ax.set_axisbelow(True)
panels = [
("wrong_load", f"wrong loads\n{len(POSITIVES)} covered requests"),
("needless_load", f"needless loads\n{len(NEGATIVES)} uncovered requests"),
]
names = list(scores)
fig, axes = plt.subplots(1, 2, figsize=(8.4, 3.6), facecolor=SURFACE)
for ax, (metric, title) in zip(axes, panels):
style(ax)
ax.grid(axis="y", color=GRID, linewidth=0.8)
values = [scores[arm][metric] for arm in names]
bars = ax.bar(
names,
values,
0.58,
color=[ARM_COLOR[arm] for arm in names],
# the oracle is a ceiling, not a competitor: gray, and hatched so it never depends
# on colour alone
hatch=["", "", "///"],
edgecolor=SURFACE,
linewidth=1.2,
)
ax.bar_label(
bars,
labels=[f"{v:.1%}" for v in values],
padding=3,
color=INK2,
fontsize=9,
)
ax.set_title(title, loc="left", color=INK2, fontsize=9.5)
ax.set_ylim(0, max(values) * 1.28)
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))
ax.set_ylabel("% of those requests - lower is better", color=INK2, fontsize=9)
fig.suptitle(
f"Hermes' {len(ROSTER)}-skill roster, {len(REQUESTS)} requests, {AGENT_MODEL}",
x=0.02,
ha="left",
color=INK,
fontsize=11,
)
fig.tight_layout()
display(fig)
plt.close(fig)
结果说明了什么
- 错误加载从 16.8% 降到 7.3%,多余加载从 9.8% 降到 4.0%,这已经填上了「从被截断的索引里猜测」与「被直接告知答案」之间的大部分差距。
- 有些 agent 原本自己做对的请求,在附上建议之后反而错了。计数见上。
当你的某个 agent 带着一份庞大的名单时,就照搬这个形状:先对全部内容做一次便宜的排序,再近距离看两三个。两个步骤都可能空手而归。
在 playground 中打开
为步骤 4 里的演示文稿请求构建一个 playground 链接,用每个候选的完整描述和正文摘录作为它的 criteria。
demo_shortlist = tuple(name for name, _ in rank_wide(DEMO[1])["ranked"][:SHORTLIST])
playground_link = make_playground_link(
build_state(DEMO[1]),
rerank_questions(demo_shortlist, EXCERPT_CHARS),
models=[TYPESAFE_MODEL],
)
display(
Markdown(
f"🔗 [Open the shortlist + questions in the TypeSafe playground]({playground_link})"
)
)
在 TypeSafe playground 中打开候选清单与问题 →
接下来
同样的形状还会出现在别处:意图路由 用于路由到一个处理程序而不是技能,置信度 用于挑选那两个阈值,推测式扇出 用于把每个问题都放进一个请求里。