原文标题:Skill authoring best practices 原文地址:https://console.anthropic.com/docs/en/agents-and-tools/agent-skills/best-practices 文档归属:Claude 平台官方文档(Agent Skills 系列) 翻译日期:2026-11-13 说明:本译文仅供学习参考,技术规范以英文原文为准;代码、命令、字段名与标识符均保留原文。

本指南介绍如何编写有效的 Skills,使 Claude 能够成功发现并使用它们。优秀的 Skills 应当简洁、结构清晰,并经过真实使用场景的检验。下文给出可落地的编写决策,帮助你写出能被 Claude 高效发现和使用的技能。

关于 Skills 工作原理的概念背景,参见《Skills 概览》。


第一部分 核心原则(Core principles)

1. 简洁是关键(Concise is key)

上下文窗口是一项公共资源。你的 Skill 要与 Claude 需要了解的其他所有内容共享这个窗口,包括:

  • 系统提示词;
  • 对话历史;
  • 其他 Skills 的元数据;
  • 用户的实际请求。

并非 Skill 中的每个 token 都会立即产生成本:启动时,只有所有技能的元数据(name 与 description)会被预加载;只有当 Skill 变得相关时,Claude 才会读取 SKILL.md;附加文件也只在需要时读取。但 SKILL.md 保持简洁仍然重要——一旦 Claude 加载了它,其中的每个 token 都要与对话历史及其他上下文竞争空间。

默认假设:Claude 已经足够聪明(Default assumption: Claude is already very smart)

只补充 Claude 尚不具备的上下文信息。对每一条信息都追问:

  • 「Claude 真的需要这段解释吗?」
  • 「这一点我可以默认 Claude 知道吗?」
  • 「这一段内容值回它消耗的 token 成本了吗?」

正例:简洁版(约 50 token)

## Extract PDF text
Use pdfplumber for text extraction:

```python
import pdfplumber

with pdfplumber.open("file.pdf") as pdf:
    text = pdf.pages[0].extract_text()
```

反例:过于冗长(约 150 token)

## Extract PDF text
PDF (Portable Document Format) files are a common file format that contains
text, images, and other content. To extract text from a PDF, you'll need to
use a library. There are many libraries available for PDF processing, but
pdfplumber is recommended because it's easy to use and handles most cases well.
First, you'll need to install it using pip. Then you can use the code below...

简洁版本默认 Claude 已经知道什么是 PDF、什么是代码库。

2. 设置恰当的自由度(Set appropriate degrees of freedom)

将指令的具体程度与任务的脆弱性、可变性相匹配。

高自由度(文本型指令)——适用场景:

  • 存在多种有效做法;
  • 决策依赖上下文;
  • 主要依靠经验法则(heuristics)推进。

示例:

## Code review process
1. Analyze the code structure and organization
2. Check for potential bugs or edge cases
3. Suggest improvements for readability and maintainability
4. Verify adherence to project conventions

中自由度(伪代码或带参数的脚本)——适用场景:

  • 存在一种推荐模式;
  • 允许一定程度的变体;
  • 配置项会影响行为。

示例:

## Generate report

def generate_report(data, format="markdown", include_charts=True):
    # Process data
    # Generate output in specified format
    # Optionally include visualizations

低自由度(特定脚本,参数很少或没有)——适用场景:

  • 操作脆弱、容易出错;
  • 一致性至关重要;
  • 必须遵循特定顺序。

示例:

## Database migration

Run exactly this script:

python scripts/migrate.py --verify --backup

不得修改命令或附加其他参数。

类比理解: 把 Claude 想象成一个在路径上探路的机器人:

  • 两侧是悬崖的窄桥:只有一条安全的前进路线,此时应提供明确的护栏和精确指令(低自由度)。例:必须按固定顺序执行的数据库迁移。
  • 没有危险的开阔场地:多条路径都能到达终点,此时给出总体方向,相信 Claude 能找到最佳路线(高自由度)。例:代码评审,具体做法由上下文决定。

3. 在所有计划使用的模型上测试(Test with all models you plan to use)

Skills 是模型能力的补充,其效果依赖底层模型。请在所有计划使用的模型上测试你的 Skill。

按模型划分的测试关注点:

  • Claude Haiku(快速、经济):Skill 是否提供了足够的指引?
  • Claude Sonnet(均衡):指令是否清晰、高效?
  • Claude Opus(强推理):Skill 是否避免了过度解释?

在 Opus 上表现完美的技能,对 Haiku 可能需要补充更多细节。如果计划跨多个模型使用技能,应追求一套对所有模型都适用良好的指令。


第二部分 技能结构(Skill structure)

YAML frontmatter

SKILL.md 的 frontmatter 要求两个字段:

  • name:
    • 最多 64 个字符;
    • 只能包含小写字母、数字与连字符;
    • 不能包含 XML 标签;
    • 不能包含保留字:anthropic、claude。
  • description:
    • 不能为空;
    • 最多 1024 个字符;
    • 不能包含 XML 标签;
    • 应说明 Skill 做什么、何时使用。

完整结构细节参见《Skills 概览》。

2.1 命名规范(Naming conventions)

使用一致的命名模式,便于引用和讨论。技能名可考虑使用动名词形式(动词 + -ing),以清晰描述该技能提供的活动或能力。注意:name 字段只能使用小写字母、数字与连字符。

良好命名示例(动名词形式):

  • processing-pdfs
  • analyzing-spreadsheets
  • managing-databases
  • testing-code
  • writing-documentation

可接受的替代形式:

  • 名词短语:pdf-processing、spreadsheet-analysis
  • 动作导向:process-pdfs、analyze-spreadsheets

应避免:

  • 模糊名称:helper、utils、tools
  • 过于宽泛:documents、data、files
  • 保留字:anthropic-helper、claude-tools
  • 技能集合内命名模式不一致

一致的命名让以下事项更容易:在文档和对话中引用技能;一眼理解技能用途;组织和检索多个技能;维护专业、统一的技能库。

2.2 撰写有效的 description(Writing effective descriptions)

description 字段决定技能能否被发现,必须同时包含技能做什么与何时使用它。

  • 始终使用第三人称。description 会被注入系统提示词,人称不一致会导致发现问题。
    • 正确:“Processes Excel files and generates reports”
    • 避免:“I can help you process Excel files”
    • 避免:“You can use this to process Excel files”
  • 要具体,并包含关键词。同时写明技能能力与适用的触发条件/上下文。

每个 Skill 只有一个 description 字段,它对技能选择至关重要:Claude 要从可能多达 100+ 个可用技能中选出正确的那一个。你的 description 必须提供足够细节,让 Claude 知道何时选用本技能;而 SKILL.md 的其余部分负责提供实现细节。

有效示例:

PDF Processing 技能:

description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.

Excel Analysis 技能:

description: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when analyzing Excel files, spreadsheets, tabular data, or .xlsx files.

Git Commit Helper 技能:

description: Generate descriptive commit messages by analyzing git diffs. Use when the user asks for help writing commit messages or reviewing staged changes.

应避免这类模糊描述:

description: Helps with documents
description: Processes data
description: Does stuff with files

2.3 渐进式披露模式(Progressive disclosure patterns)

SKILL.md 相当于一份概览,像入职指南中的目录一样,在需要时引导 Claude 查阅详细材料。渐进式披露的原理见概览文档中的「Skills 工作原理」。

实操指引:

  • 为获得最佳性能,SKILL.md 主体控制在 500 行以内;
  • 接近该上限时,将内容拆分到独立文件;
  • 使用下文模式有效组织指令、代码与资源。

可视化概览:从简单到复杂

一个基础技能只含一个 SKILL.md 文件,包含元数据与指令。随着技能增长,可以打包附加内容,仅在需要时由 Claude 加载。完整目录结构可能如下:

pdf/
├── SKILL.md              # 主指令(触发时加载)
├── FORMS.md              # 表单填写指南(按需加载)
├── reference.md          # API 参考(按需加载)
├── examples.md           # 使用示例(按需加载)
└── scripts/
    ├── analyze_form.py   # 实用脚本(被执行,而非被加载)
    ├── fill_form.py      # 表单填写脚本
    └── validate.py        # 校验脚本

模式 1:高层指南 + 引用

---
name: pdf-processing
description: Extracts text and tables from PDF files, fills forms, and merges documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
---

# PDF Processing

## Quick start
Extract text with pdfplumber:

```python
import pdfplumber

with pdfplumber.open("file.pdf") as pdf:
    text = pdf.pages[0].extract_text()
```

## Advanced features
**Form filling**: See [FORMS.md](FORMS.md) for complete guide
**API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
**Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns

Claude 仅在需要时才加载 FORMS.md、REFERENCE.md 或 EXAMPLES.md。

模式 2:按领域组织(Domain-specific organization)

对于包含多个领域的技能,按领域组织内容,避免加载无关上下文。当用户询问销售指标时,Claude 只需要读取销售相关的数据结构,而无需读取财务或市场数据,从而保持 token 用量低、上下文聚焦。

bigquery-skill/
├── SKILL.md (overview and navigation)
└── reference/
    ├── finance.md (revenue, billing metrics)
    ├── sales.md (opportunities, pipeline)
    ├── product.md (API usage, features)
    └── marketing.md (campaigns, attribution)

SKILL.md:

# BigQuery Data Analysis

## Available datasets
**Finance**: Revenue, ARR, billing → See [reference/finance.md](reference/finance.md)
**Sales**: Opportunities, pipeline, accounts → See [reference/sales.md](reference/sales.md)
**Product**: API usage, features, adoption → See [reference/product.md](reference/product.md)
**Marketing**: Campaigns, attribution, email → See [reference/marketing.md](reference/marketing.md)

## Quick search
Find specific metrics using grep:

```bash
grep -i "revenue" reference/finance.md
grep -i "pipeline" reference/sales.md
grep -i "api usage" reference/product.md
```

模式 3:条件化细节(Conditional details)

先呈现基础内容,再链接到高级内容:

# DOCX Processing

## Creating documents
Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).

## Editing documents
For simple edits, modify the XML directly.

**For tracked changes**: See [REDLINING.md](REDLINING.md)
**For OOXML details**: See [OOXML.md](OOXML.md)

Claude 只在需要这些功能时才读取 REDLINING.md 或 OOXML.md。

2.4 避免深层嵌套引用(Avoid deeply nested references)

当文件被其他被引用文件再次引用时,Claude 可能只读取部分内容。遇到嵌套引用时,Claude 可能使用 head -100 之类的命令预览内容,而不是通读全文件,导致信息不完整。

引用层级保持距 SKILL.md 一层深。所有参考文件都应直接从 SKILL.md 链接,确保需要时 Claude 能读到完整文件。

反例:层级过深

# SKILL.md
See [advanced.md](advanced.md)...

# advanced.md
See [details.md](details.md)...

# details.md
Here's the actual information...

正例:只有一层

# SKILL.md
**Basic usage**: [instructions in SKILL.md]
**Advanced features**: See [advanced.md](advanced.md)
**API reference**: See [reference.md](reference.md)
**Examples**: See [examples.md](examples.md)

2.5 较长参考文件需加目录(Structure longer reference files with table of contents)

超过 100 行的参考文件,应在顶部加入目录。这样即使 Claude 以部分读取方式预览,也能看到可用信息的完整范围。

示例:

# API Reference

## Contents
- Authentication and setup
- Core methods (create, read, update, delete)
- Advanced features (batch operations, webhooks)
- Error handling patterns
- Code examples

## Authentication and setup
...

## Core methods
...

随后 Claude 可以通读全文,或按需跳转到特定章节。


第三部分 工作流与反馈回路(Workflows and feedback loops)

3.1 复杂任务使用工作流(Use workflows for complex tasks)

把复杂操作拆解为清晰的顺序步骤。对于特别复杂的工作流,可提供一份清单,让 Claude 复制到自己的回复中,并在推进过程中逐项勾选。

示例 1:研究综合工作流(不含代码的技能)

## Research synthesis workflow
Copy this checklist and track your progress:

```
Research Progress:
- [ ] Step 1: Read all source documents
- [ ] Step 2: Identify key themes
- [ ] Step 3: Cross-reference claims
- [ ] Step 4: Create structured summary
- [ ] Step 5: Verify citations
```

**Step 1: Read all source documents**
Review each document in the `sources/` directory. Note the main arguments and supporting evidence.

**Step 2: Identify key themes**
Look for patterns across sources. What themes appear repeatedly? Where do sources agree or disagree?

**Step 3: Cross-reference claims**
For each major claim, verify it appears in the source material. Note which source supports each point.

**Step 4: Create structured summary**
Organize findings by theme. Include:
- Main claim
- Supporting evidence from sources
- Conflicting viewpoints (if any)

**Step 5: Verify citations**
Check that every claim references the correct source document. If citations are incomplete, return to Step 3.

本示例展示工作流如何应用于无需代码的分析类任务。清单模式适用于任何复杂的多步骤流程。

示例 2:PDF 表单填写工作流(含代码的技能)

## PDF form filling workflow
Copy this checklist and check off items as you complete them:

```
Task Progress:
- [ ] Step 1: Analyze the form (run analyze_form.py)
- [ ] Step 2: Create field mapping (edit fields.json)
- [ ] Step 3: Validate mapping (run validate_fields.py)
- [ ] Step 4: Fill the form (run fill_form.py)
- [ ] Step 5: Verify output (run verify_output.py)
```

**Step 1: Analyze the form**
Run: `python scripts/analyze_form.py input.pdf`
This extracts form fields and their locations, saving to `fields.json`.

**Step 2: Create field mapping**
Edit `fields.json` to add values for each field.

**Step 3: Validate mapping**
Run: `python scripts/validate_fields.py fields.json`
Fix any validation errors before continuing.

**Step 4: Fill the form**
Run: `python scripts/fill_form.py input.pdf fields.json output.pdf`

**Step 5: Verify output**
Run: `python scripts/verify_output.py output.pdf`
If verification fails, return to Step 2.

清晰的步骤可防止 Claude 跳过关键校验环节。清单帮助 Claude 和你双方在多步骤工作流中跟踪进度。

3.2 实现反馈回路(Implement feedback loops)

常见模式:运行校验器 → 修复错误 → 重复。该模式能显著提升输出质量。

示例 1:风格规范符合性(不含代码的技能)

## Content review process
1. Draft your content following the guidelines in STYLE_GUIDE.md
2. Review against the checklist:
   - Check terminology consistency
   - Verify examples follow the standard format
   - Confirm all required sections are present
3. If issues found:
   - Note each issue with specific section reference
   - Revise the content
   - Review the checklist again
4. Only proceed when all requirements are met
5. Finalize and save the document

这是使用参考文档而非脚本的校验回路模式:「校验器」就是 STYLE_GUIDE.md,Claude 通过阅读并比对完成检查。

示例 2:文档编辑流程(含代码的技能)

## Document editing process
1. Make your edits to `word/document.xml`
2. **Validate immediately**: `python ooxml/scripts/validate.py unpacked_dir/`
3. If validation fails:
   - Review the error message carefully
   - Fix the issues in the XML
   - Run validation again
4. **Only proceed when validation passes**
5. Rebuild: `python ooxml/scripts/pack.py unpacked_dir/ output.docx`
6. Test the output document

校验回路能尽早发现错误。


第四部分 内容准则(Content guidelines)

4.1 避免时效性信息(Avoid time-sensitive information)

不要写入会过时的信息。

反例:时效性内容(终将出错)

If you're doing this before August 2025, use the old API.
After August 2025, use the new API.

正例(放入「旧模式」章节)

## Current method
Use the v2 API endpoint: `api.example.com/v2/messages`

## Old patterns
<details>
<summary>Legacy v1 API (deprecated 2025-08)</summary>
The v1 API used: `api.example.com/v1/messages`
This endpoint is no longer supported.
</details>

旧模式章节提供历史背景,而不干扰主体内容。

4.2 使用一致术语(Use consistent terminology)

选定一个术语并在整个技能中统一使用:

正例:术语一致

  • 始终用 “API endpoint”
  • 始终用 “field”
  • 始终用 “extract”

反例:术语混乱

  • 混用 “API endpoint”、“URL”、“API route”、“path”
  • 混用 “field”、“box”、“element”、“control”
  • 混用 “extract”、“pull”、“get”、“retrieve”

一致性有助于 Claude 理解并遵循指令。


第五部分 常见模式(Common patterns)

5.1 模板模式(Template pattern)

为输出格式提供模板。严格程度按需匹配。

严格要求场景(如 API 响应或数据格式):

## Report structure
ALWAYS use this exact template structure:

```markdown
# [Analysis Title]

## Executive summary
[One-paragraph overview of key findings]

## Key findings
- Finding 1 with supporting data
- Finding 2 with supporting data
- Finding 3 with supporting data

## Recommendations
1. Specific actionable recommendation
2. Specific actionable recommendation
```

灵活指引场景(允许按需适配):

## Report structure
Here is a sensible default format, but use your best judgment based on the analysis:

```markdown
# [Analysis Title]

## Executive summary
[Overview]

## Key findings
[Adapt sections based on what you discover]

## Recommendations
[Tailor to the specific context]
```

Adjust sections as needed for the specific analysis type.

5.2 示例模式(Examples pattern)

对于输出质量依赖于「看过示例」的技能,像常规提示词那样提供输入/输出对:

## Commit message format
Generate commit messages following these examples:

**Example 1:**
Input: Added user authentication with JWT tokens
Output:
```
feat(auth): implement JWT-based authentication
Add login endpoint and token validation middleware
```

**Example 2:**
Input: Fixed bug where dates displayed incorrectly in reports
Output:
```
fix(reports): correct date formatting in timezone conversion
Use UTC timestamps consistently across report generation
```

**Example 3:**
Input: Updated dependencies and refactored error handling
Output:
```
chore: update dependencies and refactor error handling
- Upgrade lodash to 4.17.21
- Standardize error response format across endpoints
```

Follow this style: type(scope): brief description, then detailed explanation.

与单纯的文字描述相比,示例能让 Claude 更清晰地理解期望的风格与详略程度。

5.3 条件工作流模式(Conditional workflow pattern)

引导 Claude 经过决策节点:

## Document modification workflow
1. Determine the modification type:
   **Creating new content?** → Follow "Creation workflow" below
   **Editing existing content?** → Follow "Editing workflow" below

2. Creation workflow:
   - Use docx-js library
   - Build document from scratch
   - Export to .docx format

3. Editing workflow:
   - Unpack existing document
   - Modify XML directly
   - Validate after each change
   - Repack when complete

如果工作流变得庞大复杂、步骤众多,考虑将其推入独立文件,并告知 Claude 根据当前任务读取相应文件。


第六部分 评估与迭代(Evaluation and iteration)

6.1 先构建评估(Build evaluations first)

在编写大量文档之前先建立评估。这能确保技能解决的是真实问题,而不是记录想象中的问题。

评估驱动开发(Evaluation-driven development):

  1. 识别缺口:在不使用技能的情况下,让 Claude 处理代表性任务,记录具体失败之处或缺失的上下文。
  2. 创建评估:构建三个测试这些缺口的场景。
  3. 建立基线:测量无技能时 Claude 的表现。
  4. 编写最小指令:只写足以补齐缺口、通过评估的内容。
  5. 迭代:运行评估、与基线对比、持续改进。

该方法确保你解决的是实际问题,而非预判可能永远不会出现的需求。

评估结构示例:

{
  "skills": ["pdf-processing"],
  "query": "Extract all text from this PDF file and save it to output.txt",
  "files": ["test-files/document.pdf"],
  "expected_behavior": [
    "Successfully reads the PDF file using an appropriate PDF processing library or command-line tool",
    "Extracts text content from all pages in the document without missing any pages",
    "Saves the extracted text to a file named output.txt in a clear, readable format"
  ]
}

本示例展示了一套带简单评分标准的数据驱动评估。目前尚无内置方式运行这些评估,使用者可自行搭建评估体系。评估是衡量技能有效性的事实依据。

6.2 与 Claude 协作迭代开发(Develop Skills iteratively with Claude)

最有效的技能开发过程本身就有 Claude 参与。与一个 Claude 实例(「Claude A」)协作创建技能,再由其他实例(「Claude B」)使用该技能。Claude A 帮你设计和打磨指令,Claude B 在真实任务中检验它们。这一方式可行,是因为 Claude 模型既懂得如何编写有效的智能体指令,也清楚智能体需要哪些信息。

创建新技能:

  1. 不用技能先完成任务:用普通提示词与 Claude A 一起解决问题。过程中你自然会补充上下文、说明偏好、分享程序性知识;留意你反复提供了哪些信息。
  2. 识别可复用模式:任务完成后,挑出那些对未来类似任务有用的上下文。
    • 示例:完成一次 BigQuery 分析后,你可能提供过表名、字段定义、过滤规则(如「始终排除测试账户」)以及常见查询模式。
  3. 请 Claude A 创建技能:「Create a Skill that captures this BigQuery analysis pattern we just used. Include the table schemas, naming conventions, and the rule about filtering test accounts.」
  4. Claude 模型原生理解技能格式与结构,无需特殊系统提示词或一个「写作技能的技能」;直接请它创建,即可生成结构规范、含适当 frontmatter 与主体内容的 SKILL.md。
  5. 检查简洁性:确认 Claude A 没有添加不必要的解释。可要求:「Remove the explanation about what win rate means - Claude already knows that.」
  6. 改进信息架构:请 Claude A 更有效地组织内容。例如:「Organize this so the table schema is in a separate reference file. We might add more tables later.」
  7. 在类似任务上测试:用 Claude B(加载了该技能的全新实例)在相关用例上试用,观察它能否找到正确信息、正确应用规则并顺利完成任务。
  8. 基于观察迭代:如果 Claude B 卡住或遗漏了内容,带着具体情况回到 Claude A:「When Claude used this Skill, it forgot to filter by date for Q4. Should we add a section about date filtering patterns?」

迭代现有技能: 改进技能时沿用同样的分层模式,在以下角色间交替:

  • 与 Claude A(协助打磨技能的专家)协作;
  • 用 Claude B(使用技能完成真实工作的智能体)测试;
  • 观察 Claude B 的行为,把发现带回给 Claude A。

在真实工作流中使用技能: 给 Claude B(加载技能)布置真实任务,而非测试场景;观察它在哪里卡住、在哪里成功、在哪里做出意料之外的选择。

  • 观察示例:「When I asked Claude B for a regional sales report, it wrote the query but forgot to filter out test accounts, even though the Skill mentions this rule.」
  • 回到 Claude A 改进:附上当前 SKILL.md 并描述观察结果:「I noticed Claude B forgot to filter test accounts when I asked for a regional report. The Skill mentions filtering, but maybe it’s not prominent enough?」
  • 审阅 Claude A 的建议:它可能建议重新组织、让规则更醒目,改用更强的措辞(如用 “MUST filter” 替代 “always filter”),或重构工作流章节。
  • 应用并测试:按 Claude A 的打磨更新技能,再用 Claude B 在类似请求上复测。
  • 按使用情况重复:遇到新场景时继续「观察—打磨—测试」循环。每一轮迭代都基于真实智能体行为,而非假设。

收集团队反馈: 把技能分享给同事并观察使用情况;询问:技能是否在预期时机被触发?指令是否清晰?还缺什么?将反馈纳入,弥补你个人使用模式中的盲区。

该方法为何有效: Claude A 理解智能体需求,你提供领域专长,Claude B 通过真实使用暴露缺口,迭代改进则基于观察而非假设。

6.3 观察 Claude 如何浏览技能(Observe how Claude navigates Skills)

迭代技能时,留意 Claude 在实际中如何使用它们。关注:

  • 意料之外的探索路径:Claude 是否按你未曾预料的顺序读取文件?这可能说明你的结构并不像你以为的那样直观。
  • 遗漏的关联:Claude 是否未能遵循指向重要文件的引用?你的链接可能需要更明确、更醒目。
  • 过度依赖某些章节:如果 Claude 反复读取同一个文件,考虑该内容是否应移入主 SKILL.md。
  • 被忽略的内容:如果某个打包文件从未被访问,它可能是不必要的,或在主指令中信号不足。

基于这些观察迭代,而不是凭假设。技能元数据中的 name 与 description 尤为关键:Claude 依据它们判断是否在当前任务下触发技能。务必让它们清晰说明技能做什么、何时使用。


第七部分 应避免的反模式(Anti-patterns to avoid)

7.1 避免 Windows 风格路径(Avoid Windows-style paths)

文件路径始终使用正斜杠,即使在 Windows 上:

  • 正确:scripts/helper.py、reference/guide.md
  • 避免:scripts\helper.py、reference\guide.md

Unix 风格路径跨平台通用,而 Windows 风格路径会在 Unix 系统上报错。

7.2 避免提供过多选项(Avoid offering too many options)

除非确有必要,不要罗列多种做法。

反例:选项过多(令人困惑)

You can use pypdf, or pdfplumber, or PyMuPDF, or pdf2image, or...

正例:给出默认方案(保留逃生通道)

Use pdfplumber for text extraction:

```python
import pdfplumber
```

For scanned PDFs requiring OCR, use pdf2image with pytesseract instead.

第八部分 进阶:含可执行代码的技能(Skills with executable code)

以下章节聚焦包含可执行脚本的技能。如果你的技能只使用 Markdown 指令,可直接跳到「有效技能检查清单」。

8.1 解决问题,不要甩给 Claude(Solve, don’t punt)

为技能编写脚本时,应处理错误情况,而不是把问题推给 Claude。

正例:显式处理错误

def process_file(path):
    """Process a file, creating it if it doesn't exist."""
    try:
        with open(path) as f:
            return f.read()
    except FileNotFoundError:
        # Create file with default content instead of failing
        print(f"File {path} not found, creating default")
        with open(path, "w") as f:
            f.write("")
        return ""
    except PermissionError:
        # Provide alternative instead of failing
        print(f"Cannot access {path}, using default")
        return ""

反例:甩给 Claude

def process_file(path):
    # Just fail and let Claude figure it out
    return open(path).read()

配置参数也应给出依据并写入文档,避免「巫毒常数(voodoo constants,奥斯特豪特定律)」。如果你不知道合适取值,Claude 又如何确定?

正例:自解释

# HTTP requests typically complete within 30 seconds
# Longer timeout accounts for slow connections
REQUEST_TIMEOUT = 30

# Three retries balances reliability vs speed
# Most intermittent failures resolve by the second retry
MAX_RETRIES = 3

反例:魔法数字

TIMEOUT = 47  # Why 47?
RETRIES = 5  # Why 5?

8.2 提供实用脚本(Provide utility scripts)

即使 Claude 自己也能写出脚本,预置脚本仍有以下优势:比临时生成的代码更可靠;节省 token(无需把代码放进上下文);节省时间(无需代码生成);保证多次使用间的一致性。

指令文件(如 forms.md)引用脚本,Claude 可以执行它,而无需把脚本内容加载进上下文。

关键区分:在指令中明确说明 Claude 应当:

  • 执行脚本(最常见):“Run analyze_form.py to extract fields”
  • 作为参考阅读(用于复杂逻辑):“See analyze_form.py for the field extraction algorithm”

对于多数实用脚本,优先选择执行方式,因为更可靠、高效。

示例:

## Utility scripts

**analyze_form.py**: Extract all form fields from PDF

```bash
python scripts/analyze_form.py input.pdf > fields.json
```

Output format:

```json
{
  "field_name": {"type": "text", "x": 100, "y": 200},
  "signature": {"type": "sig", "x": 150, "y": 500}
}
```

**validate_boxes.py**: Check for overlapping bounding boxes

```bash
python scripts/validate_boxes.py fields.json
# Returns: "OK" or lists conflicts
```

**fill_form.py**: Apply field values to PDF

```bash
python scripts/fill_form.py input.pdf fields.json output.pdf
```

8.3 使用视觉分析(Use visual analysis)

当输入可以渲染为图片时,让 Claude 对图片进行分析:

## Form layout analysis
1. Convert PDF to images:

```bash
python scripts/pdf_to_images.py form.pdf
```

2. Analyze each page image to identify form fields
3. Claude can see field locations and types visually

本示例中需要自行编写 pdf_to_images.py。Claude 的视觉能力有助于理解版式与结构。

8.4 创建可验证的中间产物(Create verifiable intermediate outputs)

Claude 执行复杂、开放式任务时可能出错。「计划—校验—执行」模式让 Claude 先以结构化格式生成计划,再用脚本校验计划,最后才执行,从而尽早捕捉错误。

示例:设想要求 Claude 根据电子表格更新 PDF 中的 50 个表单字段。缺少校验时,Claude 可能引用不存在的字段、创建冲突取值、遗漏必填字段,或错误地应用更新。

解决方案:沿用上述工作流模式(PDF 表单填写),但增加一个中间的 changes.json 文件,在应用变更前先对其校验。工作流变为:分析 → 创建计划文件 → 校验计划 → 执行 → 验证。

该模式为何有效:

  • 尽早捕捉错误:校验在变更落地前发现问题;
  • 可机器验证:脚本提供客观核验;
  • 可回退的计划:Claude 可在不触碰原始文件的情况下迭代计划;
  • 便于调试:错误信息指向具体问题。

适用场景:批量操作、破坏性变更、复杂校验规则、高风险操作。

实现提示:校验脚本应输出详尽、具体的错误信息,例如 “Field ‘signature_date’ not found. Available fields: customer_name, order_total, signature_date_signed”,帮助 Claude 定位问题。

8.5 包依赖(Package dependencies)

技能在代码执行环境中运行,受各平台特定限制:

  • claude.ai:可从 npm、PyPI 安装包,并可拉取 GitHub 仓库。
  • Claude API:无网络访问,运行时不可安装软件包。

在 SKILL.md 中列出所需软件包,并在代码执行工具文档中核实它们确实可用。


第九部分 运行时环境(Runtime environment)

技能运行在具备文件系统访问、bash 命令与代码执行能力的代码执行环境中。该架构的概念解释见概览文档的「Skills 架构」。

这对编写工作的影响:

Claude 如何访问技能:

  • 元数据预加载:启动时,所有技能 YAML frontmatter 中的 name 与 description 被载入系统提示词;
  • 文件按需读取:需要时,Claude 使用 bash Read 工具从文件系统访问 SKILL.md 及其他文件;
  • 脚本高效执行:实用脚本可通过 bash 执行,无需将全部内容加载进上下文,只有脚本输出消耗 token;
  • 大文件无上下文负担:参考文件、数据或文档在被实际读取前不消耗上下文 token;
  • 文件路径很重要:Claude 像浏览文件系统一样浏览技能目录,使用正斜杠(reference/guide.md),不要用反斜杠;
  • 文件名要有描述性:使用能表明内容的名称,如 form_validation_rules.md,而非 doc2.md;
  • 按便于发现的方式组织:按领域或功能组织目录。
    • 正确:reference/finance.md、reference/sales.md
    • 错误:docs/file1.md、docs/file2.md
  • 打包完备资源:可包含完整 API 文档、大量示例、大型数据集;未被访问前无上下文负担;
  • 确定性操作优先用脚本:编写 validate_form.py,而不是要求 Claude 临时生成校验代码;
  • 明确执行意图:
    • 「Run analyze_form.py to extract fields」(执行)
    • 「See analyze_form.py for the extraction algorithm」(作为参考阅读)
  • 测试文件访问模式:用真实请求验证 Claude 能否在你的目录结构中导航。

示例:

bigquery-skill/
├── SKILL.md (overview, points to reference files)
└── reference/
    ├── finance.md (revenue metrics)
    ├── sales.md (pipeline data)
    └── product.md (usage analytics)

当用户询问收入时,Claude 读取 SKILL.md,看到对 reference/finance.md 的引用,再通过 bash 只读取这一个文件;sales.md 与 product.md 留在文件系统中,在需要之前消耗零上下文 token。正是这种文件系统模型支撑了渐进式披露:Claude 能够导航并选择性加载每个任务恰好需要的内容。

MCP 工具引用(MCP tool references)

如果技能使用 MCP(Model Context Protocol)工具,始终使用全限定工具名,以避免「工具未找到」错误。

格式: ServerName:tool_name

示例:

  • Use the BigQuery:bigquery_schema tool to retrieve table schemas.
  • Use the GitHub:create_issue tool to create issues.

其中 BigQuery、GitHub 是 MCP 服务器名,bigquery_schema、create_issue 是这些服务器内的工具名。没有服务器前缀时,Claude 可能无法定位工具,尤其在同时存在多个 MCP 服务器的情况下。

不要假设工具已安装(Avoid assuming tools are installed)

不要假设软件包可用:

反例:假设已安装

"Use the pdf library to process the file."

正例:明确依赖

"Install required package: `pip install pypdf`
Then use it:

```python
from pypdf import PdfReader
reader = PdfReader("file.pdf")
```"

第十部分 技术说明(Technical notes)

YAML frontmatter 要求

SKILL.md frontmatter 的 name、description 字段遵循特定校验规则:

  • name:最多 64 个字符;仅小写字母/数字/连字符;无 XML 标签;无保留字。
  • description:最多 1024 个字符;非空;无 XML 标签。

完整结构细节见《Skills 概览》。

Token 预算(Token budgets)

为获得最佳性能,SKILL.md 主体控制在 500 行以内。内容超出时,使用前文所述的渐进式披露模式拆分到独立文件。架构细节见《Skills 概览》。


第十一部分 有效技能检查清单(Checklist for effective Skills)

分享技能前,请逐项核验:

核心质量

  • description 具体且包含关键词
  • description 同时说明技能做什么、何时使用
  • SKILL.md 主体在 500 行以内
  • 附加细节已放入独立文件(如需要)
  • 无时效性信息(或已放入「旧模式」章节)
  • 全文术语一致
  • 示例具体,而非抽象
  • 文件引用只有一层深度
  • 恰当使用渐进式披露
  • 工作流步骤清晰

代码与脚本

  • 脚本解决问题,而非甩给 Claude
  • 错误处理显式且有帮助
  • 无「巫毒常数」(所有取值均有依据)
  • 所需软件包已在指令中列出并核实可用
  • 脚本有清晰文档
  • 无 Windows 风格路径(全部使用正斜杠)
  • 关键操作设有校验/验证步骤
  • 对质量关键任务包含反馈回路

测试

  • 至少创建三个评估场景
  • 在 Haiku、Sonnet、Opus 上均完成测试
  • 经过真实使用场景测试
  • 已纳入团队反馈(如适用)

后续阅读(Next steps)

  • Get started with Agent Skills(Agent Skills 入门)
  • Create your first Skill(创建第一个技能)
  • Use Skills in Claude Code(在 Claude Code 中使用 Skills)
  • Create and manage Skills in Claude Code(在 Claude Code 中创建与管理技能)
  • Use Skills in the Agent SDK(在 Agent SDK 中使用 Skills)
  • Use Skills programmatically in TypeScript and Python(以 TypeScript / Python 编程方式使用 Skills)
  • Use Skills with the API(在 API 中使用 Skills)
  • Upload and use Skills programmatically(以编程方式上传和使用 Skills)

本文档章节索引

  • Core principles(核心原则)
  • Set appropriate degrees of freedom(设置恰当自由度)
  • Test with all models you plan to use(跨模型测试)
  • Skill structure(技能结构)
  • Naming conventions(命名规范)
  • Writing effective descriptions(撰写有效描述)
  • Progressive disclosure patterns(渐进式披露模式)
  • Avoid deeply nested references(避免深层嵌套引用)
  • Structure longer reference files with table of contents(长文件加目录)
  • Workflows and feedback loops(工作流与反馈回路)
  • Use workflows for complex tasks(复杂任务用工作流)
  • Implement feedback loops(实现反馈回路)
  • Content guidelines(内容准则)
  • Avoid time-sensitive information(避免时效性信息)
  • Use consistent terminology(一致术语)
  • Common patterns(常见模式)
  • Template pattern(模板模式)
  • Examples pattern(示例模式)
  • Conditional workflow pattern(条件工作流模式)
  • Evaluation and iteration(评估与迭代)
  • Observe how Claude navigates Skills(观察技能浏览方式)
  • Anti-patterns to avoid(应避免的反模式)
  • Avoid Windows-style paths(避免 Windows 风格路径)
  • Avoid offering too many options(避免选项过多)
  • Use visual analysis(视觉分析)
  • Create verifiable intermediate outputs(可验证中间产物)
  • Package dependencies(包依赖)
  • Runtime environment(运行时环境)
  • MCP tool references(MCP 工具引用)
  • Technical notes(技术说明)

站内相关文章