apply-anthropic-skill-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAnthropic's official skill authoring best practices
Anthropic官方Skill创作最佳实践
Apply Anthropic's official skill authoring best practices to your skill.
Good Skills are concise, well-structured, and tested with real usage. This guide provides practical authoring decisions to help you write Skills that Claude can discover and use effectively.
将Anthropic官方的Skill创作最佳实践应用到你的Skill中。
优秀的Skill简洁、结构清晰,并经过实际使用测试。本指南提供实用的创作决策建议,帮助你编写Claude能够发现并有效使用的Skill。
Core principles
核心原则
Skill Metadata
Skill元数据
Not every token in your Skill has an immediate cost. At startup, only the metadata (name and description) from all Skills is pre-loaded. Claude reads SKILL.md only when the Skill becomes relevant, and reads additional files only as needed. However, being concise in SKILL.md still matters: once Claude loads it, every token competes with conversation history and other context.
并非Skill中的每个token都会立即产生成本。启动时,仅预加载所有Skill的元数据(名称和描述)。只有当Skill相关时,Claude才会读取SKILL.md,并且仅在需要时才会读取其他文件。不过,SKILL.md的简洁性仍然很重要:一旦Claude加载它,每个token都会与对话历史和其他上下文竞争资源。
Test with all models you plan to use
在所有计划使用的模型上进行测试
Skills act as additions to models, so effectiveness depends on the underlying model. Test your Skill with all the models you plan to use it with.
Testing considerations by model:
- Claude Haiku (fast, economical): Does the Skill provide enough guidance?
- Claude Sonnet (balanced): Is the Skill clear and efficient?
- Claude Opus (powerful reasoning): Does the Skill avoid over-explaining?
What works perfectly for Opus might need more detail for Haiku. If you plan to use your Skill across multiple models, aim for instructions that work well with all of them.
Skill是对模型的补充,因此其有效性取决于底层模型。请在所有计划使用该Skill的模型上进行测试。
按模型划分的测试注意事项:
- Claude Haiku(快速、经济):Skill是否提供了足够的指导?
- Claude Sonnet(平衡型):Skill是否清晰高效?
- Claude Opus(强大推理能力):Skill是否避免过度解释?
在Opus上完美运行的内容,可能需要为Haiku补充更多细节。如果你计划在多个模型上使用Skill,目标是编写对所有模型都适用的指令。
Skill structure
Skill结构
<Note>
**YAML Frontmatter**: The SKILL.md frontmatter supports two fields:
-
- Human-readable name of the Skill (64 characters maximum)
name -
- One-line description of what the Skill does and when to use it (1024 characters maximum)
descriptionFor complete Skill structure details, see the Skills overview.
<Note>
**YAML前置元数据**:SKILL.md的前置元数据支持两个字段:
-
- Skill的可读名称(最多64个字符)
name -
- 描述Skill功能及使用场景的单行文本(最多1024个字符)
description有关完整Skill结构的详细信息,请参阅Skills概述。
Naming conventions
命名规范
Use consistent naming patterns to make Skills easier to reference and discuss. We recommend using gerund form (verb + -ing) for Skill names, as this clearly describes the activity or capability the Skill provides.
Good naming examples (gerund form):
- "Processing PDFs"
- "Analyzing spreadsheets"
- "Managing databases"
- "Testing code"
- "Writing documentation"
Acceptable alternatives:
- Noun phrases: "PDF Processing", "Spreadsheet Analysis"
- Action-oriented: "Process PDFs", "Analyze Spreadsheets"
Avoid:
- Vague names: "Helper", "Utils", "Tools"
- Overly generic: "Documents", "Data", "Files"
- Inconsistent patterns within your skill collection
Consistent naming makes it easier to:
- Reference Skills in documentation and conversations
- Understand what a Skill does at a glance
- Organize and search through multiple Skills
- Maintain a professional, cohesive skill library
使用一致的命名模式,使Skill更易于引用和讨论。我们建议Skill名称使用动名词形式(动词+ing),因为这能清晰描述Skill提供的活动或能力。
优秀命名示例(动名词形式):
- "Processing PDFs"
- "Analyzing spreadsheets"
- "Managing databases"
- "Testing code"
- "Writing documentation"
可接受的替代形式:
- 名词短语:"PDF Processing", "Spreadsheet Analysis"
- 动作导向:"Process PDFs", "Analyze Spreadsheets"
需避免:
- 模糊名称:"Helper", "Utils", "Tools"
- 过于通用:"Documents", "Data", "Files"
- Skill集合内命名模式不一致
一致的命名有助于:
- 在文档和对话中引用Skill
- 一眼了解Skill的功能
- 组织和搜索多个Skill
- 维护专业、统一的Skill库
Writing effective descriptions
编写有效的描述
The field enables Skill discovery and should include both what the Skill does and when to use it.
<Warning>
**Always write in third person**. The description is injected into the system prompt, and inconsistent point-of-view can cause discovery problems.
description- Good: "Processes Excel files and generates reports"
- Avoid: "I can help you process Excel files"
- Avoid: "You can use this to process Excel files" </Warning>
Be specific and include key terms. Include both what the Skill does and specific triggers/contexts for when to use it.
Each Skill has exactly one description field. The description is critical for skill selection: Claude uses it to choose the right Skill from potentially 100+ available Skills. Your description must provide enough detail for Claude to know when to select this Skill, while the rest of SKILL.md provides the implementation details.
Effective examples:
PDF Processing skill:
yaml
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 skill:
yaml
description: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when analyzing Excel files, spreadsheets, tabular data, or .xlsx files.Git Commit Helper skill:
yaml
description: Generate descriptive commit messages by analyzing git diffs. Use when the user asks for help writing commit messages or reviewing staged changes.Avoid vague descriptions like these:
yaml
description: Helps with documentsyaml
description: Processes datayaml
description: Does stuff with filesdescription- 正确示例:"Processes Excel files and generates reports"
- 避免:"I can help you process Excel files"
- 避免:"You can use this to process Excel files" </Warning>
具体明确并包含关键术语。同时包含Skill的功能和使用它的特定触发条件/场景。
每个Skill只有一个描述字段。描述对于Skill选择至关重要:Claude会用它从可能的100多个可用Skill中选择合适的Skill。你的描述必须提供足够的细节,让Claude知道何时选择该Skill,而SKILL.md的其余部分提供实现细节。
有效示例:
PDF处理Skill:
yaml
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:
yaml
description: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when analyzing Excel files, spreadsheets, tabular data, or .xlsx files.Git提交助手Skill:
yaml
description: Generate descriptive commit messages by analyzing git diffs. Use when the user asks for help writing commit messages or reviewing staged changes.避免如下模糊描述:
yaml
description: Helps with documentsyaml
description: Processes datayaml
description: Does stuff with filesProgressive disclosure patterns
渐进式披露模式
SKILL.md serves as an overview that points Claude to detailed materials as needed, like a table of contents in an onboarding guide. For an explanation of how progressive disclosure works, see How Skills work in the overview.
Practical guidance:
- Keep SKILL.md body under 500 lines for optimal performance
- Split content into separate files when approaching this limit
- Use the patterns below to organize instructions, code, and resources effectively
SKILL.md作为概述,在需要时引导Claude查看详细资料,就像入门指南中的目录一样。有关渐进式披露工作原理的说明,请参阅概述中的Skill工作机制。
实用指南:
- 为获得最佳性能,SKILL.md主体内容保持在500行以内
- 当接近此限制时,将内容拆分为单独文件
- 使用以下模式有效组织指令、代码和资源
Visual overview: From simple to complex
可视化概述:从简单到复杂
A basic Skill starts with just a SKILL.md file containing metadata and instructions:
<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=87782ff239b297d9a9e8e1b72ed72db9" alt="Simple SKILL.md file showing YAML frontmatter and markdown body" data-og-width="2048" width="2048" data-og-height="1153" height="1153" data-path="images/agent-skills-simple-file.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=c61cc33b6f5855809907f7fda94cd80e 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=90d2c0c1c76b36e8d485f49e0810dbfd 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=ad17d231ac7b0bea7e5b4d58fb4aeabb 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=f5d0a7a3c668435bb0aee9a3a8f8c329 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=0e927c1af9de5799cfe557d12249f6e6 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=46bbb1a51dd4c8202a470ac8c80a893d 2500w" />
As your Skill grows, you can bundle additional content that Claude loads only when needed:
<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=a5e0aa41e3d53985a7e3e43668a33ea3" alt="Bundling additional reference files like reference.md and forms.md." data-og-width="2048" width="2048" data-og-height="1327" height="1327" data-path="images/agent-skills-bundling-content.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=f8a0e73783e99b4a643d79eac86b70a2 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=dc510a2a9d3f14359416b706f067904a 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=82cd6286c966303f7dd914c28170e385 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=56f3be36c77e4fe4b523df209a6824c6 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=d22b5161b2075656417d56f41a74f3dd 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=3dd4bdd6850ffcc96c6c45fcb0acd6eb 2500w" />
The complete Skill directory structure might look like this:
pdf/
├── SKILL.md # Main instructions (loaded when triggered)
├── FORMS.md # Form-filling guide (loaded as needed)
├── reference.md # API reference (loaded as needed)
├── examples.md # Usage examples (loaded as needed)
└── scripts/
├── analyze_form.py # Utility script (executed, not loaded)
├── fill_form.py # Form filling script
└── validate.py # Validation script基础Skill仅包含一个SKILL.md文件,其中包含元数据和指令:
<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=87782ff239b297d9a9e8e1b72ed72db9" alt="Simple SKILL.md file showing YAML frontmatter and markdown body" data-og-width="2048" width="2048" data-og-height="1153" height="1153" data-path="images/agent-skills-simple-file.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=c61cc33b6f5855809907f7fda94cd80e 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=90d2c0c1c76b36e8d485f49e0810dbfd 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=ad17d231ac7b0bea7e5b4d58fb4aeabb 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=f5d0a7a3c668435bb0aee9a3a8f8c329 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=0e927c1af9de5799cfe557d12249f6e6 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=46bbb1a51dd4c8202a470ac8c80a893d 2500w" />
随着Skill的扩展,你可以捆绑额外内容,Claude仅在需要时加载这些内容:
<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=a5e0aa41e3d53985a7e3e43668a33ea3" alt="Bundling additional reference files like reference.md and forms.md." data-og-width="2048" width="2048" data-og-height="1327" height="1327" data-path="images/agent-skills-bundling-content.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=f8a0e73783e99b4a643d79eac86b70a2 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=dc510a2a9d3f14359416b706f067904a 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=82cd6286c966303f7dd914c28170e385 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=56f3be36c77e4fe4b523df209a6824c6 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=d22b5161b2075656417d56f41a74f3dd 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=3dd4bdd6850ffcc96c6c45fcb0acd6eb 2500w" />
完整的Skill目录结构可能如下所示:
pdf/
├── SKILL.md # 主指令(触发时加载)
├── FORMS.md # 表单填写指南(按需加载)
├── reference.md # API参考(按需加载)
├── examples.md # 使用示例(按需加载)
└── scripts/
├── analyze_form.py # 实用脚本(执行,不加载)
├── fill_form.py # 表单填写脚本
└── validate.py # 验证脚本Pattern 1: High-level guide with references
模式1:带参考链接的高级指南
markdown
---
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.
---markdown
---
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
PDF Processing
Quick start
快速入门
Extract text with pdfplumber:
python
import pdfplumber
with pdfplumber.open("file.pdf") as pdf:
text = pdf.pages[0].extract_text()使用pdfplumber提取文本:
python
import pdfplumber
with pdfplumber.open("file.pdf") as pdf:
text = pdf.pages[0].extract_text()Advanced features
高级功能
Form filling: See FORMS.md for complete guide
API reference: See REFERENCE.md for all methods
Examples: See EXAMPLES.md for common patterns
Claude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.表单填写:完整指南请参阅FORMS.md
API参考:所有方法请参阅REFERENCE.md
示例:常见模式请参阅EXAMPLES.md
Claude仅在需要时加载FORMS.md、REFERENCE.md或EXAMPLES.md。Pattern 2: Domain-specific organization
模式2:特定领域组织
For Skills with multiple domains, organize content by domain to avoid loading irrelevant context. When a user asks about sales metrics, Claude only needs to read sales-related schemas, not finance or marketing data. This keeps token usage low and context focused.
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)markdown
undefined对于包含多个领域的Skill,按领域组织内容,避免加载无关上下文。当用户询问销售指标时,Claude只需要读取与销售相关的模式,而不需要财务或营销数据。这样可以降低token使用量,保持上下文聚焦。
bigquery-skill/
├── SKILL.md (概述和导航)
└── reference/
├── finance.md (收入、计费指标)
├── sales.md (商机、销售管道)
├── product.md (API使用情况、功能)
└── marketing.md (营销活动、归因)markdown
undefinedBigQuery Data Analysis
BigQuery数据分析
Available datasets
可用数据集
Finance: Revenue, ARR, billing → See reference/finance.md
Sales: Opportunities, pipeline, accounts → See reference/sales.md
Product: API usage, features, adoption → See reference/product.md
Marketing: Campaigns, attribution, email → See reference/marketing.md
财务:收入、ARR、计费 → 请参阅reference/finance.md
销售:商机、销售管道、客户 → 请参阅reference/sales.md
产品:API使用情况、功能、采用率 → 请参阅reference/product.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.mdundefined使用grep查找特定指标:
bash
grep -i "revenue" reference/finance.md
grep -i "pipeline" reference/sales.md
grep -i "api usage" reference/product.mdundefinedPattern 3: Conditional details
模式3:条件式细节展示
Show basic content, link to advanced content:
markdown
undefined展示基础内容,链接到高级内容:
markdown
undefinedDOCX Processing
DOCX处理
Creating documents
创建文档
Use docx-js for new documents. See DOCX-JS.md.
使用docx-js创建新文档。请参阅DOCX-JS.md。
Editing documents
编辑文档
For simple edits, modify the XML directly.
For tracked changes: See REDLINING.md
For OOXML details: See OOXML.md
Claude reads REDLINING.md or OOXML.md only when the user needs those features.对于简单编辑,直接修改XML即可。
如需跟踪更改:请参阅REDLINING.md
如需OOXML详细信息:请参阅OOXML.md
Claude仅在用户需要这些功能时才会读取REDLINING.md或OOXML.md。Avoid deeply nested references
避免深度嵌套引用
Claude may partially read files when they're referenced from other referenced files. When encountering nested references, Claude might use commands like to preview content rather than reading entire files, resulting in incomplete information.
head -100Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md to ensure Claude reads complete files when needed.
Bad example: Too deep:
markdown
undefined当文件从其他引用文件中被引用时,Claude可能会部分读取这些文件。遇到嵌套引用时,Claude可能会使用等命令预览内容,而不是读取整个文件,导致信息不完整。
head -100保持引用从SKILL.md开始仅一层深度。所有参考文件应直接链接到SKILL.md,以确保Claude在需要时读取完整文件。
不良示例:层级过深:
markdown
undefinedSKILL.md
SKILL.md
See advanced.md...
请参阅advanced.md...
advanced.md
advanced.md
See details.md...
请参阅details.md...
details.md
details.md
Here's the actual information...
**Good example: One level deep**:
```markdown theme={null}这里是实际信息...
**良好示例:一层深度**:
```markdown theme={null}SKILL.md
SKILL.md
Basic usage: [instructions in SKILL.md]
Advanced features: See advanced.md
API reference: See reference.md
Examples: See examples.md
undefined基础用法:[SKILL.md中的指令]
高级功能:请参阅advanced.md
API参考:请参阅reference.md
示例:请参阅examples.md
undefinedStructure longer reference files with table of contents
为较长的参考文件添加目录
For reference files longer than 100 lines, include a table of contents at the top. This ensures Claude can see the full scope of available information even when previewing with partial reads.
Example:
markdown
undefined对于超过100行的参考文件,在顶部添加目录。这样即使Claude部分读取文件预览,也能看到可用信息的完整范围。
示例:
markdown
undefinedAPI Reference
API参考
Contents
目录
- Authentication and setup
- Core methods (create, read, update, delete)
- Advanced features (batch operations, webhooks)
- Error handling patterns
- Code examples
- 认证与设置
- 核心方法(创建、读取、更新、删除)
- 高级功能(批量操作、Webhooks)
- 错误处理模式
- 代码示例
Authentication and setup
认证与设置
...
...
Core methods
核心方法
...
Claude can then read the complete file or jump to specific sections as needed.
For details on how this filesystem-based architecture enables progressive disclosure, see the [Runtime environment](#runtime-environment) section in the Advanced section below....
Claude可以读取完整文件,或根据需要跳转到特定章节。
有关基于文件系统的架构如何实现渐进式披露的详细信息,请参阅下方高级部分中的[运行时环境](#runtime-environment)章节。Workflows and feedback loops
工作流与反馈循环
Use workflows for complex tasks
为复杂任务使用工作流
Break complex operations into clear, sequential steps. For particularly complex workflows, provide a checklist that Claude can copy into its response and check off as it progresses.
Example 1: Research synthesis workflow (for Skills without code):
markdown
undefined将复杂操作分解为清晰的连续步骤。对于特别复杂的工作流,提供一个清单,Claude可以将其复制到响应中,并在进展过程中勾选。
示例1:研究合成工作流(适用于无代码Skill):
markdown
undefinedResearch 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 citationsStep 1: Read all source documents
Review each document in the directory. Note the main arguments and supporting evidence.
sources/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.
This example shows how workflows apply to analysis tasks that don't require code. The checklist pattern works for any complex, multi-step process.
**Example 2: PDF form filling workflow** (for Skills with code):
````markdown theme={null}复制此清单并跟踪进度:
研究进度:
- [ ] 步骤1:阅读所有源文档
- [ ] 步骤2:识别关键主题
- [ ] 步骤3:交叉引用主张
- [ ] 步骤4:创建结构化摘要
- [ ] 步骤5:验证引用步骤1:阅读所有源文档
查看目录中的每个文档。记录主要论点和支持证据。
sources/步骤2:识别关键主题
寻找跨源文档的模式。哪些主题反复出现?源文档在哪些方面达成一致或存在分歧?
步骤3:交叉引用主张
对于每个主要主张,验证它是否出现在源材料中。记录哪个源支持每个观点。
步骤4:创建结构化摘要
按主题组织发现结果。包括:
- 主要主张
- 来自源文档的支持证据
- 冲突观点(如有)
步骤5:验证引用
检查每个主张是否引用了正确的源文档。如果引用不完整,返回步骤3。
此示例展示了工作流如何应用于不需要代码的分析任务。清单模式适用于任何复杂的多步骤流程。
**示例2:PDF表单填写工作流**(适用于带代码Skill):
````markdown theme={null}PDF form filling workflow
PDF表单填写工作流
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.pdfThis extracts form fields and their locations, saving to .
fields.jsonStep 2: Create field mapping
Edit to add values for each field.
fields.jsonStep 3: Validate mapping
Run:
python scripts/validate_fields.py fields.jsonFix any validation errors before continuing.
Step 4: Fill the form
Run:
python scripts/fill_form.py input.pdf fields.json output.pdfStep 5: Verify output
Run:
python scripts/verify_output.py output.pdfIf verification fails, return to Step 2.
Clear steps prevent Claude from skipping critical validation. The checklist helps both Claude and you track progress through multi-step workflows.复制此清单并在完成项目时勾选:
任务进度:
- [ ] 步骤1:分析表单(运行analyze_form.py)
- [ ] 步骤2:创建字段映射(编辑fields.json)
- [ ] 步骤3:验证映射(运行validate_fields.py)
- [ ] 步骤4:填写表单(运行fill_form.py)
- [ ] 步骤5:验证输出(运行verify_output.py)步骤1:分析表单
运行:
python scripts/analyze_form.py input.pdf这将提取表单字段及其位置,并保存到。
fields.json步骤2:创建字段映射
编辑为每个字段添加值。
fields.json步骤3:验证映射
运行:
python scripts/validate_fields.py fields.json在继续之前修复所有验证错误。
步骤4:填写表单
运行:
python scripts/fill_form.py input.pdf fields.json output.pdf步骤5:验证输出
运行:
python scripts/verify_output.py output.pdf如果验证失败,返回步骤2。
清晰的步骤可防止Claude跳过关键验证环节。清单有助于Claude和你跟踪多步骤工作流的进度。Implement feedback loops
实现反馈循环
Common pattern: Run validator → fix errors → repeat
This pattern greatly improves output quality.
Example 1: Style guide compliance (for Skills without code):
markdown
undefined常见模式:运行验证器→修复错误→重复
此模式可显著提高输出质量。
示例1:风格指南合规性(适用于无代码Skill):
markdown
undefinedContent review process
内容审核流程
- Draft your content following the guidelines in STYLE_GUIDE.md
- Review against the checklist:
- Check terminology consistency
- Verify examples follow the standard format
- Confirm all required sections are present
- If issues found:
- Note each issue with specific section reference
- Revise the content
- Review the checklist again
- Only proceed when all requirements are met
- Finalize and save the document
This shows the validation loop pattern using reference documents instead of scripts. The "validator" is STYLE\_GUIDE.md, and Claude performs the check by reading and comparing.
**Example 2: Document editing process** (for Skills with code):
```markdown theme={null}- 遵循STYLE_GUIDE.md中的指南起草内容
- 根据清单审核:
- 检查术语一致性
- 验证示例是否遵循标准格式
- 确认所有必填部分均已包含
- 如果发现问题:
- 记录每个问题并注明具体章节引用
- 修改内容
- 再次审核清单
- 仅在满足所有要求时继续
- 定稿并保存文档
这展示了使用参考文档而非脚本的验证循环模式。"验证器"是STYLE_GUIDE.md,Claude通过读取和比较来执行检查。
**示例2:文档编辑流程**(适用于带代码Skill):
```markdown theme={null}Document editing process
文档编辑流程
- Make your edits to
word/document.xml - Validate immediately:
python ooxml/scripts/validate.py unpacked_dir/ - If validation fails:
- Review the error message carefully
- Fix the issues in the XML
- Run validation again
- Only proceed when validation passes
- Rebuild:
python ooxml/scripts/pack.py unpacked_dir/ output.docx - Test the output document
The validation loop catches errors early.- 对进行编辑
word/document.xml - 立即验证:
python ooxml/scripts/validate.py unpacked_dir/ - 如果验证失败:
- 仔细查看错误消息
- 在XML中修复问题
- 再次运行验证
- 仅在验证通过时继续
- 重建:
python ooxml/scripts/pack.py unpacked_dir/ output.docx - 测试输出文档
验证循环可及早发现错误。Content guidelines
内容指南
Avoid time-sensitive information
避免时效性信息
Don't include information that will become outdated:
Bad example: Time-sensitive (will become wrong):
markdown
If you're doing this before August 2025, use the old API.
After August 2025, use the new API.Good example (use "old patterns" section):
markdown
undefined不要包含会过时的信息:
不良示例:时效性(会失效):
markdown
如果在2025年8月之前执行此操作,请使用旧API。
2025年8月之后,请使用新API。良好示例(使用"旧模式"章节):
markdown
undefinedCurrent method
当前方法
Use the v2 API endpoint:
api.example.com/v2/messages使用v2 API端点:
api.example.com/v2/messagesOld patterns
旧模式
<details>
<summary>Legacy v1 API (deprecated 2025-08)</summary>
The v1 API used:
api.example.com/v1/messagesThis endpoint is no longer supported.
</details>
```
The old patterns section provides historical context without cluttering the main content.
<details>
<summary>旧版v1 API(2025-08弃用)</summary>
v1 API使用:
api.example.com/v1/messages此端点不再受支持。
</details>
```
旧模式章节提供历史背景,同时不会使主要内容混乱。
Use consistent terminology
使用一致的术语
Choose one term and use it throughout the Skill:
Good - Consistent:
- Always "API endpoint"
- Always "field"
- Always "extract"
Bad - Inconsistent:
- Mix "API endpoint", "URL", "API route", "path"
- Mix "field", "box", "element", "control"
- Mix "extract", "pull", "get", "retrieve"
Consistency helps Claude understand and follow instructions.
选择一个术语并在整个Skill中使用:
良好示例 - 一致:
- 始终使用"API endpoint"
- 始终使用"field"
- 始终使用"extract"
不良示例 - 不一致:
- 混合使用"API endpoint", "URL", "API route", "path"
- 混合使用"field", "box", "element", "control"
- 混合使用"extract", "pull", "get", "retrieve"
一致性有助于Claude理解并遵循指令。
Common patterns
常见模式
Template pattern
模板模式
Provide templates for output format. Match the level of strictness to your needs.
For strict requirements (like API responses or data formats):
markdown
undefined提供输出格式模板。根据需求匹配严格程度。
对于严格要求(如API响应或数据格式):
markdown
undefinedReport structure
报告结构
ALWAYS use this exact template structure:
markdown
undefined始终使用此精确模板结构:
markdown
undefined[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
- 带支持数据的发现1
- 带支持数据的发现2
- 带支持数据的发现3
Recommendations
建议
- Specific actionable recommendation
- Specific actionable recommendation
undefinedFor flexible guidance (when adaptation is useful):
markdown
undefined- 具体可操作的建议
- 具体可操作的建议
undefined对于灵活指导(当需要适应性时):
markdown
undefinedReport structure
报告结构
Here is a sensible default format, but use your best judgment based on the analysis:
markdown
undefined以下是合理的默认格式,但请根据分析情况做出最佳判断:
markdown
undefined[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.[根据具体情况定制]
根据具体分析类型调整章节。Examples pattern
示例模式
For Skills where output quality depends on seeing examples, provide input/output pairs just like in regular prompting:
markdown
undefined对于输出质量依赖示例的Skill,提供输入/输出对,就像常规提示一样:
markdown
undefinedCommit 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 middlewareExample 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 generationExample 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 endpointsFollow this style: type(scope): brief description, then detailed explanation.
Examples help Claude understand the desired style and level of detail more clearly than descriptions alone.按照以下示例生成提交消息:
示例1:
输入:Added user authentication with JWT tokens
输出:
feat(auth): implement JWT-based authentication
Add login endpoint and token validation middleware示例2:
输入:Fixed bug where dates displayed incorrectly in reports
输出:
fix(reports): correct date formatting in timezone conversion
Use UTC timestamps consistently across report generation示例3:
输入:Updated dependencies and refactored error handling
输出:
chore: update dependencies and refactor error handling
- Upgrade lodash to 4.17.21
- Standardize error response format across endpoints遵循此风格:type(scope): 简要描述,然后详细解释。
示例比单独的描述更能帮助Claude理解所需的风格和详细程度。Conditional workflow pattern
条件工作流模式
Guide Claude through decision points:
markdown
undefined引导Claude完成决策点:
markdown
undefinedDocument modification workflow
文档修改工作流
-
Determine the modification type:Creating new content? → Follow "Creation workflow" below Editing existing content? → Follow "Editing workflow" below
-
Creation workflow:
- Use docx-js library
- Build document from scratch
- Export to .docx format
-
Editing workflow:
- Unpack existing document
- Modify XML directly
- Validate after each change
- Repack when complete
<Tip>
If workflows become large or complicated with many steps, consider pushing them into separate files and tell Claude to read the appropriate file based on the task at hand.
</Tip>-
确定修改类型:创建新内容? → 遵循下方"创建工作流" 编辑现有内容? → 遵循下方"编辑工作流"
-
创建工作流:
- 使用docx-js库
- 从头构建文档
- 导出为.docx格式
-
编辑工作流:
- 解压现有文档
- 直接修改XML
- 每次修改后验证
- 完成后重新打包
<Tip>
如果工作流变得庞大或复杂,包含许多步骤,考虑将其推入单独文件,并告知Claude根据任务读取相应文件。
</Tip>Evaluation and iteration
评估与迭代
Build evaluations first
先构建评估
Create evaluations BEFORE writing extensive documentation. This ensures your Skill solves real problems rather than documenting imagined ones.
Evaluation-driven development:
- Identify gaps: Run Claude on representative tasks without a Skill. Document specific failures or missing context
- Create evaluations: Build three scenarios that test these gaps
- Establish baseline: Measure Claude's performance without the Skill
- Write minimal instructions: Create just enough content to address the gaps and pass evaluations
- Iterate: Execute evaluations, compare against baseline, and refine
This approach ensures you're solving actual problems rather than anticipating requirements that may never materialize.
Evaluation structure:
json
{
"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解决实际问题,而不是记录想象中的问题。
评估驱动开发:
- 识别差距:在不使用Skill的情况下,让Claude处理代表性任务。记录具体的失败或缺失的上下文
- 创建评估:构建三个测试这些差距的场景
- 建立基准:测量Claude在不使用Skill时的性能
- 编写最小化指令:创建足够解决差距并通过评估的内容
- 迭代:执行评估,与基准比较,然后优化
此方法确保你解决实际问题,而不是预测可能永远不会出现的需求。
评估结构:
json
{
"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"
]
}Develop Skills iteratively with Claude
与Claude一起迭代开发Skill
The most effective Skill development process involves Claude itself. Work with one instance of Claude ("Claude A") to create a Skill that will be used by other instances ("Claude B"). Claude A helps you design and refine instructions, while Claude B tests them in real tasks. This works because Claude models understand both how to write effective agent instructions and what information agents need.
Creating a new Skill:
-
Complete a task without a Skill: Work through a problem with Claude A using normal prompting. As you work, you'll naturally provide context, explain preferences, and share procedural knowledge. Notice what information you repeatedly provide.
-
Identify the reusable pattern: After completing the task, identify what context you provided that would be useful for similar future tasks.Example: If you worked through a BigQuery analysis, you might have provided table names, field definitions, filtering rules (like "always exclude test accounts"), and common query patterns.
-
Ask Claude A to create a Skill: "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."<Tip> Claude models understand the Skill format and structure natively. You don't need special system prompts or a "writing skills" skill to get Claude to help create Skills. Simply ask Claude to create a Skill and it will generate properly structured SKILL.md content with appropriate frontmatter and body content. </Tip>
-
Review for conciseness: Check that Claude A hasn't added unnecessary explanations. Ask: "Remove the explanation about what win rate means - Claude already knows that."
-
Improve information architecture: Ask Claude A to organize the content more effectively. For example: "Organize this so the table schema is in a separate reference file. We might add more tables later."
-
Test on similar tasks: Use the Skill with Claude B (a fresh instance with the Skill loaded) on related use cases. Observe whether Claude B finds the right information, applies rules correctly, and handles the task successfully.
-
Iterate based on observation: If Claude B struggles or misses something, return to Claude A with specifics: "When Claude used this Skill, it forgot to filter by date for Q4. Should we add a section about date filtering patterns?"
Iterating on existing Skills:
The same hierarchical pattern continues when improving Skills. You alternate between:
- Working with Claude A (the expert who helps refine the Skill)
- Testing with Claude B (the agent using the Skill to perform real work)
- Observing Claude B's behavior and bringing insights back to Claude A
-
Use the Skill in real workflows: Give Claude B (with the Skill loaded) actual tasks, not test scenarios
-
Observe Claude B's behavior: Note where it struggles, succeeds, or makes unexpected choicesExample observation: "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."
-
Return to Claude A for improvements: Share the current SKILL.md and describe what you observed. Ask: "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?"
-
Review Claude A's suggestions: Claude A might suggest reorganizing to make rules more prominent, using stronger language like "MUST filter" instead of "always filter", or restructuring the workflow section.
-
Apply and test changes: Update the Skill with Claude A's refinements, then test again with Claude B on similar requests
-
Repeat based on usage: Continue this observe-refine-test cycle as you encounter new scenarios. Each iteration improves the Skill based on real agent behavior, not assumptions.
Gathering team feedback:
- Share Skills with teammates and observe their usage
- Ask: Does the Skill activate when expected? Are instructions clear? What's missing?
- Incorporate feedback to address blind spots in your own usage patterns
Why this approach works: Claude A understands agent needs, you provide domain expertise, Claude B reveals gaps through real usage, and iterative refinement improves Skills based on observed behavior rather than assumptions.
最有效的Skill开发过程涉及Claude本身。使用一个Claude实例("Claude A")创建将被其他实例("Claude B")使用的Skill。Claude A帮助你设计和优化指令,而Claude B在实际任务中测试这些指令。这之所以有效,是因为Claude模型既了解如何编写有效的Agent指令,也了解Agent需要哪些信息。
创建新Skill:
-
不使用Skill完成任务:使用常规提示与Claude A解决问题。在工作过程中,你会自然地提供上下文、解释偏好并分享过程知识。注意你反复提供的信息。
-
识别可重用模式:完成任务后,确定你提供的哪些上下文对类似的未来任务有用。示例:如果你完成了BigQuery分析,你可能提供了表名、字段定义、过滤规则(如"始终排除测试账户")和常见查询模式。
-
让Claude A创建Skill:"创建一个Skill,捕捉我们刚刚使用的BigQuery分析模式。包括表模式、命名约定以及关于过滤测试账户的规则。"<Tip> Claude模型原生理解Skill格式和结构。你不需要特殊的系统提示或"编写Skill"的Skill来让Claude帮助创建Skill。只需让Claude创建一个Skill,它就会生成结构正确的SKILL.md内容,包含适当的前置元数据和主体内容。 </Tip>
-
检查简洁性:检查Claude A是否添加了不必要的解释。询问:"删除关于win rate含义的解释——Claude已经知道了。"
-
改进信息架构:让Claude A更有效地组织内容。例如:"将表架构组织到单独的参考文件中。我们以后可能会添加更多表。"
-
在类似任务上测试:将Skill加载到Claude B(新实例)中,在相关用例上使用。观察Claude B是否找到正确信息、正确应用规则并成功处理任务。
-
基于观察迭代:如果Claude B遇到困难或遗漏了某些内容,将具体情况反馈给Claude A:"当Claude使用此Skill时,它忘记按第四季度的日期过滤。我们应该添加关于日期过滤模式的章节吗?"
迭代现有Skill:
改进Skill时,同样的分层模式继续适用。你需要在以下环节交替进行:
- 与Claude A协作(帮助优化Skill的专家)
- 与Claude B测试(使用Skill执行实际工作的Agent)
- 观察Claude B的行为并将见解反馈给Claude A
-
在实际工作流中使用Skill:让加载了Skill的Claude B处理实际任务,而不是测试场景
-
观察Claude B的行为:注意它在哪些地方遇到困难、取得成功或做出意外选择示例观察:"当我让Claude B生成区域销售报告时,它编写了查询,但忘记过滤测试账户,尽管Skill提到了这个规则。"
-
回到Claude A进行改进:分享当前的SKILL.md并描述你的观察结果。询问:"我注意到当我要求区域报告时,Claude B忘记过滤测试账户。Skill提到了过滤,但可能不够突出?"
-
审查Claude A的建议:Claude A可能建议重新组织内容,使规则更突出,使用更强的语言如"必须过滤"代替"始终过滤",或重构工作流章节。
-
应用并测试更改:使用Claude A的优化更新Skill,然后在类似请求上再次用Claude B测试
-
基于使用情况重复:在遇到新场景时继续此观察-优化-测试循环。每次迭代都基于实际Agent行为而非假设改进Skill。
收集团队反馈:
- 与团队成员分享Skill并观察他们的使用情况
- 询问:Skill是否在预期时激活?指令是否清晰?缺少什么?
- 整合反馈,解决你自己使用模式中的盲点
此方法为何有效:Claude A理解Agent需求,你提供领域专业知识,Claude B通过实际使用揭示差距,迭代优化基于观察到的行为而非假设改进Skill。
Observe how Claude navigates Skills
观察Claude如何使用Skill
As you iterate on Skills, pay attention to how Claude actually uses them in practice. Watch for:
- Unexpected exploration paths: Does Claude read files in an order you didn't anticipate? This might indicate your structure isn't as intuitive as you thought
- Missed connections: Does Claude fail to follow references to important files? Your links might need to be more explicit or prominent
- Overreliance on certain sections: If Claude repeatedly reads the same file, consider whether that content should be in the main SKILL.md instead
- Ignored content: If Claude never accesses a bundled file, it might be unnecessary or poorly signaled in the main instructions
Iterate based on these observations rather than assumptions. The 'name' and 'description' in your Skill's metadata are particularly critical. Claude uses these when deciding whether to trigger the Skill in response to the current task. Make sure they clearly describe what the Skill does and when it should be used.
在迭代Skill时,注意Claude在实践中实际如何使用它们。关注:
- 意外探索路径:Claude是否以你未预期的顺序读取文件?这可能表明你的结构不如你想象的直观
- 缺失的关联:Claude是否未能遵循指向重要文件的引用?你的链接可能需要更明确或突出
- 过度依赖某些章节:如果Claude反复读取同一个文件,考虑是否应将该内容放入主SKILL.md中
- 被忽略的内容:如果Claude从未访问过捆绑文件,它可能是不必要的,或者在主指令中信号不足
基于这些观察而非假设进行迭代。Skill元数据中的"name"和"description"尤为关键。Claude在决定是否响应当前任务触发Skill时会使用这些信息。确保它们清晰描述Skill的功能和使用场景。
Anti-patterns to avoid
需避免的反模式
Avoid Windows-style paths
避免Windows风格路径
Always use forward slashes in file paths, even on Windows:
- ✓ Good: ,
scripts/helper.pyreference/guide.md - ✗ Avoid: ,
scripts\helper.pyreference\guide.md
Unix-style paths work across all platforms, while Windows-style paths cause errors on Unix systems.
始终在文件路径中使用正斜杠,即使在Windows上:
- ✓ 正确:,
scripts/helper.pyreference/guide.md - ✗ 避免:,
scripts\helper.pyreference\guide.md
Unix风格路径在所有平台上都有效,而Windows风格路径在Unix系统上会导致错误。
Avoid offering too many options
避免提供过多选项
Don't present multiple approaches unless necessary:
markdown
**Bad example: Too many choices** (confusing):
"You can use pypdf, or pdfplumber, or PyMuPDF, or pdf2image, or..."
**Good example: Provide a default** (with escape hatch):
"Use pdfplumber for text extraction:
```python
import pdfplumber
```
For scanned PDFs requiring OCR, use pdf2image with pytesseract instead."除非必要,否则不要提供多种方法:
markdown
**不良示例:过多选择**(令人困惑):
"你可以使用pypdf,或pdfplumber,或PyMuPDF,或pdf2image,或..."
**良好示例:提供默认选项**(带有备选方案):
"使用pdfplumber进行文本提取:
```python
import pdfplumber
```
对于需要OCR的扫描PDF,改用pdf2image和pytesseract。"Advanced: Skills with executable code
高级:包含可执行代码的Skill
The sections below focus on Skills that include executable scripts. If your Skill uses only markdown instructions, skip to Checklist for effective Skills.
以下章节重点介绍包含可执行脚本的Skill。如果你的Skill仅使用markdown指令,请跳至有效Skill检查清单。
Solve, don't punt
解决问题,而非推诿
When writing scripts for Skills, handle error conditions rather than punting to Claude.
Good example: Handle errors explicitly:
python
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 ''Bad example: Punt to Claude:
python
def process_file(path):
# Just fail and let Claude figure it out
return open(path).read()Configuration parameters should also be justified and documented to avoid "voodoo constants" (Ousterhout's law). If you don't know the right value, how will Claude determine it?
Good example: Self-documenting:
python
undefined为Skill编写脚本时,处理错误条件,而不是推给Claude。
良好示例:显式处理错误:
python
def process_file(path):
"""处理文件,若不存在则创建。"""
try:
with open(path) as f:
return f.read()
except FileNotFoundError:
# 创建带默认内容的文件,而非失败
print(f"File {path} not found, creating default")
with open(path, 'w') as f:
f.write('')
return ''
except PermissionError:
# 提供替代方案,而非失败
print(f"Cannot access {path}, using default")
return ''不良示例:推给Claude:
python
def process_file(path):
# 直接失败,让Claude解决
return open(path).read()配置参数也应合理并记录,避免"神秘常量"(Ousterhout定律)。如果你不知道正确的值,Claude如何确定?
良好示例:自文档化:
python
undefinedHTTP requests typically complete within 30 seconds
HTTP请求通常在30秒内完成
Longer timeout accounts for slow connections
更长的超时时间考虑了慢速连接
REQUEST_TIMEOUT = 30
REQUEST_TIMEOUT = 30
Three retries balances reliability vs speed
三次重试平衡了可靠性与速度
Most intermittent failures resolve by the second retry
大多数间歇性故障在第二次重试时解决
MAX_RETRIES = 3
**Bad example: Magic numbers**:
```python theme={null}
TIMEOUT = 47 # Why 47?
RETRIES = 5 # Why 5?MAX_RETRIES = 3
**不良示例:魔法数字**:
```python theme={null}
TIMEOUT = 47 # 为什么是47?
RETRIES = 5 # 为什么是5?Provide utility scripts
提供实用脚本
Even if Claude could write a script, pre-made scripts offer advantages:
Benefits of utility scripts:
- More reliable than generated code
- Save tokens (no need to include code in context)
- Save time (no code generation required)
- Ensure consistency across uses
The diagram above shows how executable scripts work alongside instruction files. The instruction file (forms.md) references the script, and Claude can execute it without loading its contents into context.
Important distinction: Make clear in your instructions whether Claude should:
- Execute the script (most common): "Run to extract fields"
analyze_form.py - Read it as reference (for complex logic): "See for the field extraction algorithm"
analyze_form.py
For most utility scripts, execution is preferred because it's more reliable and efficient. See the Runtime environment section below for details on how script execution works.
Example:
markdown
undefined即使Claude可以编写脚本,预制脚本也有优势:
实用脚本的好处:
- 比生成的代码更可靠
- 节省token(无需在上下文中包含代码)
- 节省时间(无需生成代码)
- 确保跨使用场景的一致性
上图展示了可执行脚本如何与指令文件配合使用。指令文件(forms.md)引用脚本,Claude可以执行它而无需将其内容加载到上下文中。
重要区别:在指令中明确说明Claude应该:
- 执行脚本(最常见):"Run to extract fields"
analyze_form.py - 将其作为参考读取(用于复杂逻辑):"See for the field extraction algorithm"
analyze_form.py
对于大多数实用脚本,执行是首选,因为它更可靠、高效。有关脚本执行工作原理的详细信息,请参阅下方的运行时环境章节。
示例:
markdown
undefinedUtility scripts
实用脚本
analyze_form.py: Extract all form fields from PDF
bash
python scripts/analyze_form.py input.pdf > fields.jsonOutput 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.jsonanalyze_form.py:从PDF中提取所有表单字段
bash
python scripts/analyze_form.py input.pdf > fields.json输出格式:
json
{
"field_name": {"type": "text", "x": 100, "y": 200},
"signature": {"type": "sig", "x": 150, "y": 500}
}validate_boxes.py:检查重叠的边界框
bash
python scripts/validate_boxes.py fields.jsonReturns: "OK" or lists conflicts
返回:"OK"或列出冲突
**fill_form.py**: Apply field values to PDF
```bash
python scripts/fill_form.py input.pdf fields.json output.pdfundefined
**fill_form.py**:将字段值应用到PDF
```bash
python scripts/fill_form.py input.pdf fields.json output.pdfundefinedUse visual analysis
使用视觉分析
When inputs can be rendered as images, have Claude analyze them:
markdown
undefined当输入可以渲染为图像时,让Claude分析它们:
markdown
undefinedForm layout analysis
表单布局分析
-
Convert PDF to images:bash
python scripts/pdf_to_images.py form.pdf -
Analyze each page image to identify form fields
-
Claude can see field locations and types visually
<Note>
In this example, you'd need to write the `pdf_to_images.py` script.
</Note>
Claude's vision capabilities help understand layouts and structures.-
将PDF转换为图像:bash
python scripts/pdf_to_images.py form.pdf -
分析每个页面图像以识别表单字段
-
Claude可以直观地看到字段位置和类型
<Note>
在此示例中,你需要编写`pdf_to_images.py`脚本。
</Note>
Claude的视觉功能有助于理解布局和结构。Create verifiable intermediate outputs
创建可验证的中间输出
When Claude performs complex, open-ended tasks, it can make mistakes. The "plan-validate-execute" pattern catches errors early by having Claude first create a plan in a structured format, then validate that plan with a script before executing it.
Example: Imagine asking Claude to update 50 form fields in a PDF based on a spreadsheet. Without validation, Claude might reference non-existent fields, create conflicting values, miss required fields, or apply updates incorrectly.
Solution: Use the workflow pattern shown above (PDF form filling), but add an intermediate file that gets validated before applying changes. The workflow becomes: analyze → create plan file → validate plan → execute → verify.
changes.jsonWhy this pattern works:
- Catches errors early: Validation finds problems before changes are applied
- Machine-verifiable: Scripts provide objective verification
- Reversible planning: Claude can iterate on the plan without touching originals
- Clear debugging: Error messages point to specific problems
When to use: Batch operations, destructive changes, complex validation rules, high-stakes operations.
Implementation tip: Make validation scripts verbose with specific error messages like "Field 'signature_date' not found. Available fields: customer_name, order_total, signature_date_signed" to help Claude fix issues.
当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修复问题。
Package dependencies
打包依赖项
Skills run in the code execution environment with platform-specific limitations:
- claude.ai: Can install packages from npm and PyPI and pull from GitHub repositories
- Anthropic API: Has no network access and no runtime package installation
List required packages in your SKILL.md and verify they're available in the code execution tool documentation.
Skill在代码执行环境中运行,具有平台特定限制:
- claude.ai:可以从npm和PyPI安装包,并从GitHub仓库拉取代码
- Anthropic API:无网络访问权限,无法在运行时安装包
在SKILL.md中列出所需包,并在代码执行工具文档中验证它们是否可用。
Runtime environment
运行时环境
Skills run in a code execution environment with filesystem access, bash commands, and code execution capabilities. For the conceptual explanation of this architecture, see The Skills architecture in the overview.
How this affects your authoring:
How Claude accesses Skills:
- Metadata pre-loaded: At startup, the name and description from all Skills' YAML frontmatter are loaded into the system prompt
- Files read on-demand: Claude uses bash Read tools to access SKILL.md and other files from the filesystem when needed
- Scripts executed efficiently: Utility scripts can be executed via bash without loading their full contents into context. Only the script's output consumes tokens
- No context penalty for large files: Reference files, data, or documentation don't consume context tokens until actually read
- File paths matter: Claude navigates your skill directory like a filesystem. Use forward slashes (), not backslashes
reference/guide.md - Name files descriptively: Use names that indicate content: , not
form_validation_rules.mddoc2.md - Organize for discovery: Structure directories by domain or feature
- Good: ,
reference/finance.mdreference/sales.md - Bad: ,
docs/file1.mddocs/file2.md
- Good:
- Bundle comprehensive resources: Include complete API docs, extensive examples, large datasets; no context penalty until accessed
- Prefer scripts for deterministic operations: Write rather than asking Claude to generate validation code
validate_form.py - Make execution intent clear:
- "Run to extract fields" (execute)
analyze_form.py - "See for the extraction algorithm" (read as reference)
analyze_form.py
- "Run
- Test file access patterns: Verify Claude can navigate your directory structure by testing with real requests
Example:
bigquery-skill/
├── SKILL.md (overview, points to reference files)
└── reference/
├── finance.md (revenue metrics)
├── sales.md (pipeline data)
└── product.md (usage analytics)When the user asks about revenue, Claude reads SKILL.md, sees the reference to , and invokes bash to read just that file. The sales.md and product.md files remain on the filesystem, consuming zero context tokens until needed. This filesystem-based model is what enables progressive disclosure. Claude can navigate and selectively load exactly what each task requires.
reference/finance.mdFor complete details on the technical architecture, see How Skills work in the Skills overview.
Skill在具有文件系统访问、bash命令和代码执行能力的代码执行环境中运行。有关此架构的概念性说明,请参阅概述中的Skill架构。
这如何影响你的创作:
Claude如何访问Skill:
- 元数据预加载:启动时,所有Skill的YAML前置元数据中的名称和描述被加载到系统提示中
- 文件按需读取:Claude在需要时使用bash读取工具从文件系统访问SKILL.md和其他文件
- 脚本高效执行:实用脚本可以通过bash执行,无需将其完整内容加载到上下文中。只有脚本的输出消耗token
- 大文件无上下文惩罚:参考文件、数据或文档在实际读取前不会消耗上下文token
- 文件路径很重要:Claude像文件系统一样导航你的Skill目录。使用正斜杠(),不要使用反斜杠
reference/guide.md - 文件命名要描述性:使用能表明内容的名称:,而不是
form_validation_rules.mddoc2.md - 为发现而组织:按领域或功能组织目录
- 良好:,
reference/finance.mdreference/sales.md - 不良:,
docs/file1.mddocs/file2.md
- 良好:
- 捆绑全面资源:包含完整的API文档、大量示例、大型数据集;在访问前无上下文惩罚
- 确定性操作首选脚本:编写,而不是让Claude生成验证代码
validate_form.py - 明确执行意图:
- "Run to extract fields"(执行)
analyze_form.py - "See for the extraction algorithm"(作为参考读取)
analyze_form.py
- "Run
- 测试文件访问模式:通过实际请求测试,验证Claude可以导航你的目录结构
示例:
bigquery-skill/
├── SKILL.md (概述,指向参考文件)
└── reference/
├── finance.md (收入指标)
├── sales.md (销售管道数据)
└── product.md (使用分析)当用户询问收入时,Claude读取SKILL.md,看到对的引用,并调用bash仅读取该文件。sales.md和product.md文件保留在文件系统中,在需要前消耗零上下文token。这种基于文件系统的模型实现了渐进式披露。Claude可以导航并选择性加载每个任务所需的内容。
reference/finance.md有关技术架构的完整详细信息,请参阅Skill概述中的Skill工作机制。
MCP tool references
MCP工具引用
If your Skill uses MCP (Model Context Protocol) tools, always use fully qualified tool names to avoid "tool not found" errors.
Format:
ServerName:tool_nameExample:
markdown
Use the BigQuery:bigquery_schema tool to retrieve table schemas.
Use the GitHub:create_issue tool to create issues.Where:
- and
BigQueryare MCP server namesGitHub - and
bigquery_schemaare the tool names within those serverscreate_issue
Without the server prefix, Claude may fail to locate the tool, especially when multiple MCP servers are available.
如果你的Skill使用MCP(Model Context Protocol)工具,请始终使用完全限定的工具名称,避免"工具未找到"错误。
格式:
ServerName:tool_name示例:
markdown
使用BigQuery:bigquery_schema工具检索表模式。
使用GitHub:create_issue工具创建问题。其中:
- 和
BigQuery是MCP服务器名称GitHub - 和
bigquery_schema是这些服务器中的工具名称create_issue
如果没有服务器前缀,Claude可能无法找到工具,尤其是当多个MCP服务器可用时。
Avoid assuming tools are installed
不要假设工具已安装
Don't assume packages are available:
markdown
**Bad example: Assumes installation**:
"Use the pdf library to process the file."
**Good example: Explicit about dependencies**:
"Install required package: `pip install pypdf`
Then use it:
```python
from pypdf import PdfReader
reader = PdfReader("file.pdf")
```"不要假设包已可用:
markdown
**不良示例:假设已安装**:
"使用pdf库处理文件。"
**良好示例:明确依赖项**:
"安装所需包:`pip install pypdf`
然后使用:
```python
from pypdf import PdfReader
reader = PdfReader("file.pdf")
```"Technical notes
技术说明
YAML frontmatter requirements
YAML前置元数据要求
The SKILL.md frontmatter includes only (64 characters max) and (1024 characters max) fields. See the Skills overview for complete structure details.
namedescriptionSKILL.md的前置元数据仅包含(最多64个字符)和(最多1024个字符)字段。有关完整结构详细信息,请参阅Skill概述。
namedescriptionToken budgets
Token预算
Keep SKILL.md body under 500 lines for optimal performance. If your content exceeds this, split it into separate files using the progressive disclosure patterns described earlier. For architectural details, see the Skills overview.
为获得最佳性能,SKILL.md主体内容保持在500行以内。如果内容超过此限制,使用前面描述的渐进式披露模式将其拆分为单独文件。有关架构详细信息,请参阅Skill概述。
Checklist for effective Skills
有效Skill检查清单
Before sharing a Skill, verify:
在分享Skill之前,请验证:
Core quality
核心质量
- Description is specific and includes key terms
- Description includes both what the Skill does and when to use it
- SKILL.md body is under 500 lines
- Additional details are in separate files (if needed)
- No time-sensitive information (or in "old patterns" section)
- Consistent terminology throughout
- Examples are concrete, not abstract
- File references are one level deep
- Progressive disclosure used appropriately
- Workflows have clear steps
- 描述具体明确并包含关键术语
- 描述同时包含Skill功能和使用场景
- SKILL.md主体内容在500行以内
- 额外细节在单独文件中(如有需要)
- 无时效性信息(或在"旧模式"章节中)
- 整个Skill中术语一致
- 示例具体,而非抽象
- 文件引用仅一层深度
- 适当使用渐进式披露
- 工作流步骤清晰
Code and scripts
代码与脚本
- Scripts solve problems rather than punt to Claude
- Error handling is explicit and helpful
- No "voodoo constants" (all values justified)
- Required packages listed in instructions and verified as available
- Scripts have clear documentation
- No Windows-style paths (all forward slashes)
- Validation/verification steps for critical operations
- Feedback loops included for quality-critical tasks
- 脚本解决问题而非推给Claude
- 错误处理显式且有帮助
- 无"神秘常量"(所有值均有说明)
- 所需包在指令中列出并验证为可用
- 脚本有清晰的文档
- 无Windows风格路径(均为正斜杠)
- 关键操作有验证/确认步骤
- 对质量关键任务包含反馈循环
Testing
测试
- At least three evaluations created
- Tested with Haiku, Sonnet, and Opus
- Tested with real usage scenarios
- Team feedback incorporated (if applicable)
- 至少创建三个评估
- 在Haiku、Sonnet和Opus上测试
- 在实际使用场景中测试
- 纳入团队反馈(如适用)