Skill 编写最佳实践
学习如何编写 Claude 能够发现并成功使用的有效 Skills。
好的 Skills 简洁、结构良好,并经过实际使用测试。本指南提供实用的编写决策,帮助您编写 Claude 能够有效发现和使用的 Skills。
有关 Skills 工作原理的概念背景,请参阅 Skills 概览。
核心原则
简洁是关键
上下文窗口是公共资源。您的 Skill 与 Claude 需要了解的所有其他内容共享上下文窗口,包括:
- 系统提示
- 对话历史
- 其他 Skills 的元数据
- 您的实际请求
并非 Skill 中的每个 token 都有直接成本。在启动时,只有所有 Skills 的元数据(名称和描述)被预加载。Claude 仅在 Skill 变得相关时才读取 SKILL.md,仅在需要时读取额外文件。然而,在 SKILL.md 中保持简洁仍然很重要:一旦 Claude 加载它,每个 token 都与对话历史和其他上下文竞争。
默认假设: Claude 已经非常聪明
只添加 Claude 没有的上下文。质疑每条信息:
- "Claude 真的需要这个解释吗?"
- "我能假设 Claude 知道这个吗?"
- "这个段落值得它的 token 成本吗?"
好示例:简洁(约 50 tokens):
## 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 tokens):
## 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 以及库如何工作。
设置适当的自由度
根据任务的脆弱性和可变性匹配特异性级别。
高自由度(基于文本的指令):
适用于:
- 多种方法都有效
- 决策取决于上下文
- 启发式方法指导
示例:
## 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
Use this template and customize as needed:
```python
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:
```bash
python scripts/migrate.py --verify --backup
```
Do not modify the command or add additional flags.
类比: 将 Claude 想象为探索路径的机器人:
- 两侧都是悬崖的窄桥: 只有一条安全的前进之路。提供特定的护栏和精确的指令(低自由度)。示例:必须按精确顺序运行的数据库迁移。
- 没有危险的开阔田野: 多条路径通向成功。给出大方向,相信 Claude 找到最佳路线(高自由度)。示例:上下文决定最佳方法的代码审查。
使用所有计划使用的模型进行测试
Skills 作为模型的补充,因此有效性取决于底层模型。在您计划使用的所有模型上测试您的 Skill。
按模型的测试注意事项:
- Claude Haiku(快速、经济):Skill 是否提供了足够的指导?
- Claude Sonnet(平衡):Skill 是否清晰高效?
- Claude Opus(强大推理):Skill 是否避免了过度解释?
对 Opus 完美工作的可能需要更多细节给 Haiku。如果您计划在多个模型上使用您的 Skill,目标是编写对所有模型都效果良好的指令。
Skill 结构
YAML 前置信息: SKILL.md 前置信息需要两个字段:
name:
- 最多 64 个字符
- 只能包含小写字母、数字和连字符
- 不能包含 XML 标签
- 不能包含保留字:"anthropic"、"claude"
description:
- 必须非空
- 最多 1024 个字符
- 不能包含 XML 标签
- 应描述 Skill 的功能以及何时使用
完整的 Skill 结构详情请参阅 Skills 概览。
命名约定
使用一致的命名模式使 Skills 更易于引用和讨论。考虑使用动名词形式(动词 + -ing)作为 Skill 名称,因为这清楚地描述了 Skill 提供的活动或能力。
记住 name 字段只能使用小写字母、数字和连字符。
好的命名示例(动名词形式):
processing-pdfsanalyzing-spreadsheetsmanaging-databasestesting-codewriting-documentation
可接受的替代方案:
- 名词短语:
pdf-processing、spreadsheet-analysis - 面向动作:
process-pdfs、analyze-spreadsheets
避免:
- 模糊名称:
helper、utils、tools - 过于通用:
documents、data、files - 保留字:
anthropic-helper、claude-tools - Skill 集合内不一致的模式
一致的命名使以下操作更容易:
- 在文档和对话中引用 Skills
- 一目了然地了解 Skill 的功能
- 组织和搜索多个 Skills
- 维护专业、连贯的 skill 库
编写有效的描述
description 字段实现 Skill 发现,应包含 Skill 的功能和使用时机。
始终使用第三人称。描述被注入系统提示,不一致的视角会导致发现问题。
- 好: "Processes Excel files and generates reports"
- 避免: "I can help you process Excel files"
- 避免: "You can use this to process Excel files"
具体并包含关键词。包含 Skill 的功能和使用时机的特定触发/上下文。
每个 Skill 恰好有一个 description 字段。描述对 skill 选择至关重要:Claude 使用它从可能 100+ 个可用 Skills 中选择正确的 Skill。您的描述必须提供足够的细节让 Claude 知道何时选择此 Skill,而 SKILL.md 的其余部分提供实现细节。
有效示例:
PDF 处理 skill:
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 分析 skill:
description: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when analyzing Excel files, spreadsheets, tabular data, or .xlsx files.
Git 提交助手 skill:
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
渐进式披露模式
SKILL.md 作为概览,根据需要将 Claude 指向详细材料,就像入职指南中的目录。有关渐进式披露工作原理的解释,请参阅概览中的 Skills 工作原理。
实用指导:
- 保持 SKILL.md 正文在 500 行以内以获得最佳性能
- 接近此限制时将内容拆分为单独文件
- 使用以下模式有效组织指令、代码和资源
视觉概览:从简单到复杂
基本 Skill 从仅包含元数据和指令的 SKILL.md 文件开始:

随着 Skill 的增长,您可以捆绑额外内容,Claude 仅在需要时加载:

完整的 Skill 目录结构可能如下:
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:领域特定组织
对于具有多个领域的 Skills,按领域组织内容以避免加载不相关的上下文。当用户询问销售指标时,Claude 只需要读取销售相关的模式,而不是财务或营销数据。这保持 token 使用量低且上下文集中。
bigquery-skill/
├── SKILL.md(概览和导航)
└── reference/
├── finance.md(收入、计费指标)
├── sales.md(机会、管道)
├── product.md(API 使用、功能)
└── marketing.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:条件详情
显示基本内容,链接到高级内容:
# 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。
避免深层嵌套引用
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)
用目录结构化较长的参考文件
对于超过 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 然后可以读取完整文件或根据需要跳转到特定部分。
有关此基于文件系统的架构如何实现渐进式披露的详情,请参阅下面高级部分中的运行时环境。
工作流和反馈循环
使用工作流处理复杂任务
将复杂操作分解为清晰的顺序步骤。对于特别复杂的工作流,提供一个清单,Claude 可以复制到其响应中并在进行时勾选。
示例 1:研究综合工作流(用于无代码的 Skills):
## 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 表单填写工作流(用于有代码的 Skills):
## 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)
```
清晰的步骤防止 Claude 跳过关键验证。清单帮助 Claude 和您跟踪多步骤工作流的进度。
实现反馈循环
常见模式: 运行验证器 → 修复错误 → 重复
此模式大大提高输出质量。
示例 1:风格指南合规(用于无代码的 Skills):
## 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
示例 2:文档编辑过程(用于有代码的 Skills):
## 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
验证循环尽早捕获错误。
内容指南
避免时间敏感信息
不要包含会过时的信息:
坏示例:时间敏感(会变得不正确):
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>
旧模式部分提供历史上下文而不杂乱主要内容。
使用一致的术语
选择一个术语并在整个 Skill 中使用:
好 - 一致:
- 始终使用 "API endpoint"
- 始终使用 "field"
- 始终使用 "extract"
坏 - 不一致:
- 混用 "API endpoint"、"URL"、"API route"、"path"
- 混用 "field"、"box"、"element"、"control"
- 混用 "extract"、"pull"、"get"、"retrieve"
一致性帮助 Claude 理解和遵循指令。
常见模式
模板模式
为输出格式提供模板。根据需求匹配严格程度。
对于严格要求(如 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.
示例模式
对于输出质量取决于看到示例的 Skills,像常规提示一样提供输入/输出对:
## 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
```
Follow this style: type(scope): brief description, then detailed explanation.
示例帮助 Claude 比仅描述更清楚地理解所需的风格和详细程度。
条件工作流模式
引导 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 根据手头的任务读取适当的文件。
评估和迭代
首先构建评估
在编写大量文档之前创建评估。 这确保您的 Skill 解决实际问题而不是记录想象中的问题。
评估驱动开发:
- 识别差距: 在没有 Skill 的情况下让 Claude 运行代表性任务。记录特定失败或缺失的上下文
- 创建评估: 构建三个测试这些差距的场景
- 建立基线: 在没有 Skill 的情况下测量 Claude 的性能
- 编写最小指令: 创建刚好足够的内容来解决差距并通过评估
- 迭代: 执行评估,与基线比较,并改进
此方法确保您解决实际问题而不是预测可能永远不会出现的需求。
评估结构:
{
"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"
]
}
此示例展示了带有简单测试标准的数据驱动评估。目前没有内置方法来运行这些评估。用户可以创建自己的评估系统。评估是衡量 Skill 有效性的权威来源。
与 Claude 一起迭代开发 Skills
最有效的 Skill 开发过程涉及 Claude 本身。与一个 Claude 实例("Claude A")合作创建由其他实例("Claude B")使用的 Skill。Claude A 帮助您设计和改进指令,而 Claude B 在实际任务中测试它们。这之所以有效,是因为 Claude 模型既理解如何编写有效的智能体指令,也理解智能体需要什么信息。
创建新 Skill:
-
在没有 Skill 的情况下完成任务: 使用正常提示与 Claude A 一起解决一个问题。在工作过程中,您自然会提供上下文、解释偏好并分享程序性知识。注意您重复提供哪些信息。
-
识别可复用模式: 完成任务后,识别您提供的哪些上下文对未来类似任务有用。
-
让 Claude A 创建 Skill: "创建一个 Skill 来捕获我们刚使用的这个 BigQuery 分析模式。包括表模式、命名约定和关于过滤测试账户的规则。"
TipClaude 模型原生理解 Skill 格式和结构。您不需要特殊的系统提示或"编写 skills"的 skill 来让 Claude 帮助创建 Skills。只需让 Claude 创建 Skill,它就会生成具有适当前置信息和正文内容的结构正确的 SKILL.md 内容。
-
检查简洁性: 检查 Claude A 是否添加了不必要的解释。问:"删除关于胜率意味着什么的解释 - Claude 已经知道了。"
-
改进信息架构: 让 Claude A 更有效地组织内容。例如:"组织这个使表模式在单独的参考文件中。我们以后可能会添加更多表。"
-
在类似任务上测试: 使用 Claude B(加载了 Skill 的新实例)在相关用例上使用该 Skill。观察 Claude B 是否找到正确的信息、正确应用规则并成功处理任务。
-
基于观察迭代: 如果 Claude B 遇到困难或遗漏了什么,带着具体问题回到 Claude A:"当 Claude 使用这个 Skill 时,它忘记按 Q4 的日期过滤。我们应该添加关于日期过滤模式的部分吗?"
迭代现有 Skills:
改进 Skills 时,同样的分层模式继续。您交替进行:
- 与 Claude A 合作(帮助改进 Skill 的专家)
- 用 Claude B 测试(使用 Skill 执行实际工作的智能体)
- 观察 Claude B 的行为并将洞察带回 Claude A
-
在实际工作流中使用 Skill: 给 Claude B(加载了 Skill)实际任务,而不是测试场景
-
观察 Claude B 的行为: 注意它在哪里遇到困难、成功或做出意外选择
-
返回 Claude A 进行改进: 分享当前的 SKILL.md 并描述您观察到的内容
-
审查 Claude A 的建议: Claude A 可能建议重组以使规则更突出,使用更强的语言如"MUST filter"而不是"always filter",或重构工作流部分
-
应用和测试变更: 使用 Claude A 的改进更新 Skill,然后在类似请求上用 Claude B 再次测试
-
基于使用重复: 继续这个观察-改进-测试循环。每次迭代基于实际智能体行为改进 Skill,而不是假设。
收集团队反馈:
- 与团队成员分享 Skills 并观察他们的使用
- 问:Skill 是否在预期时激活?指令清晰吗?缺少什么?
- 纳入反馈以解决您自己使用模式中的盲点
为什么这种方法有效: Claude A 理解智能体需求,您提供领域专业知识,Claude B 通过实际使用揭示差距,迭代改进基于观察到的行为而不是假设来改进 Skills。
观察 Claude 如何导航 Skills
在迭代 Skills 时,注意 Claude 实际上如何在实践中使用它们。观察:
- 意外的探索路径: Claude 是否以您未预期的顺序读取文件?这可能表明您的结构不如您想象的直观
- 遗漏的连接: Claude 是否未能跟随对重要文件的引用?您的链接可能需要更明确或更突出
- 过度依赖某些部分: 如果 Claude 反复读取同一文件,考虑该内容是否应该在主 SKILL.md 中
- 被忽略的内容: 如果 Claude 从不访问捆绑文件,它可能是不必要的或在主指令中信号不足
基于这些观察而不是假设进行迭代。Skill 元数据中的 name 和 description 特别关键。Claude 在决定是否响应当前任务触发 Skill 时使用这些。确保它们清楚地描述 Skill 的功能和使用时机。
应避免的反模式
避免 Windows 风格路径
始终在文件路径中使用正斜杠,即使在 Windows 上:
- ✓ 好:
scripts/helper.py、reference/guide.md - ✗ 避免:
scripts\helper.py、reference\guide.md
Unix 风格路径在所有平台上有效,而 Windows 风格路径在 Unix 系统上会导致错误。
避免提供太多选项
除非必要,否则不要呈现多种方法:
**坏示例:太多选择**(令人困惑):
"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
以下部分侧重于包含可执行脚本的 Skills。如果您的 Skill 仅使用 markdown 指令,请跳至有效 Skills 清单。
解决问题,不要推卸
为 Skills 编写脚本时,处理错误条件而不是推卸给 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()
配置参数也应有理由和文档,避免"巫毒常量"(Ousterhout 定律)。如果您不知道正确的值,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?
提供实用脚本
即使 Claude 可以编写脚本,预制脚本也有优势:
实用脚本的好处:
- 比生成的代码更可靠
- 节省 tokens(无需在上下文中包含代码)
- 节省时间(无需代码生成)
- 确保跨使用的一致性

上图展示了可执行脚本如何与指令文件协同工作。指令文件(forms.md)引用脚本,Claude 可以执行它而无需将其内容加载到上下文中。
重要区别: 在指令中明确 Claude 应该:
- 执行脚本(最常见):"Run
analyze_form.pyto extract fields" - 作为参考读取(用于复杂逻辑):"See
analyze_form.pyfor 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
```
使用视觉分析
当输入可以渲染为图像时,让 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 的视觉能力帮助理解布局和结构。
创建可验证的中间输出
当 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 修复问题。
打包依赖
Skills 在具有平台特定限制的代码执行环境中运行:
- claude.ai: 可以从 npm 和 PyPI 安装包,并从 GitHub 仓库拉取
- Claude API: 无网络访问,无运行时包安装
在 SKILL.md 中列出所需包,并在代码执行工具文档中验证它们可用。
运行时环境
Skills 在具有文件系统访问、bash 命令和代码执行能力的代码执行环境中运行。有关此架构的概念解释,请参阅概览中的 Skills 架构。
这对您的编写有何影响:
Claude 如何访问 Skills:
- 元数据预加载: 启动时,所有 Skills YAML 前置信息中的名称和描述加载到系统提示
- 文件按需读取: Claude 使用 bash Read 工具在需要时从文件系统访问 SKILL.md 和其他文件
- 脚本高效执行: 实用脚本可以通过 bash 执行,无需将完整内容加载到上下文。只有脚本的输出消耗 tokens
- 大文件无上下文损耗: 参考文件、数据或文档在实际读取前不消耗上下文 tokens
- 文件路径很重要: Claude 像文件系统一样导航您的 skill 目录。使用正斜杠(
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.pyto extract fields"(执行) - "See
analyze_form.pyfor the extraction algorithm"(作为参考读取)
- "Run
- 测试文件访问模式: 通过实际请求验证 Claude 可以导航您的目录结构
示例:
bigquery-skill/
├── SKILL.md(概览,指向参考文件)
└── reference/
├── finance.md(收入指标)
├── sales.md(管道数据)
└── product.md(使用分析)
当用户询问收入时,Claude 读取 SKILL.md,看到对 reference/finance.md 的引用,并调用 bash 仅读取该文件。sales.md 和 product.md 文件留在文件系统上,在需要前消耗零上下文 tokens。这种基于文件系统的模型是实现渐进式披露的关键。Claude 可以导航并选择性地加载每个任务所需的内容。
有关技术架构的完整详情,请参阅 Skills 概览中的 Skills 工作原理。
MCP 工具引用
如果您的 Skill 使用 MCP(模型上下文协议)工具,始终使用完全限定的工具名称以避免"tool not found"错误。
格式: 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 服务器可用时。
避免假设工具已安装
不要假设包可用:
**坏示例:假设已安装**:
"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")
```"
技术说明
YAML 前置信息要求
SKILL.md 前置信息需要 name 和 description 字段,具有特定验证规则:
name:最多 64 个字符,仅限小写字母/数字/连字符,无 XML 标签,无保留字description:最多 1024 个字符,非空,无 XML 标签
完整结构详情请参阅 Skills 概览。
Token 预算
保持 SKILL.md 正文在 500 行以内以获得最佳性能。如果内容超过此限制,使用前面描述的渐进式披露模式拆分为单独文件。架构详情请参阅 Skills 概览。
有效 Skills 清单
分享 Skill 之前,验证:
核心质量
- 描述具体且包含关键词
- 描述包含 Skill 的功能和使用时机
- SKILL.md 正文在 500 行以内
- 额外细节在单独文件中(如果需要)
- 无时间敏感信息(或在"旧模式"部分)
- 全文术语一致
- 示例具体而非抽象
- 文件引用一级深度
- 渐进式披露使用适当
- 工作流有清晰步骤
代码和脚本
- 脚本解决问题而非推卸给 Claude
- 错误处理显式且有帮助
- 无"巫毒常量"(所有值有理由)
- 所需包在指令中列出并验证可用
- 脚本有清晰文档
- 无 Windows 风格路径(全部正斜杠)
- 关键操作有验证/验证步骤
- 质量关键任务包含反馈循环
测试
- 至少创建三个评估
- 在 Haiku、Sonnet 和 Opus 上测试
- 在实际使用场景中测试
- 纳入团队反馈(如适用)