Learn how to write effective Skills that Claude can discover and use successfully. 学习如何编写 Claude 可以成功发现和使用的有效技能。
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. 优秀的技能应简洁、结构良好,并经过实际使用测试。本指南提供实用的编写决策,帮助你编写 Claude 可以发现并有效使用的技能。
Core principles 核心原则
Concise is key 简洁至上
The context window is a public good. Your Skill shares the context window with everything else Claude needs to know, including: 上下文窗口是一种公共资源。你的技能与 Claude 需要了解的所有其他信息共享上下文窗口
- The system prompt 系统提示词
- Conversation history 对话历史
- Other Skills' metadata 其他技能的元数据
- Your actual request 你的实际请求
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. 技能并非每个token都有即时成本。在启动时,只有所有技能的元数据(名称和描述)被预加载。Claude 只在技能变得相关时读取 SKILL.md,并且只在需要时读取附加文件。然而,在 SKILL.md 中保持简洁仍然很重要:一旦 Claude 加载它,每个token都会与对话历史和其他上下文竞争。
Default assumption: Claude is already very smart 假设:Claude 已经非常智能
Only add context Claude doesn't already have. Challenge each piece of information:只添加 Claude 尚未拥有的上下文。对每一条信息进行严格控制
- "Does Claude really need this explanation?" 真的需要这个解释吗
- "Can I assume Claude knows this?" 我可以假设 Claude 知道这个吗
- "Does this paragraph justify its token cost?"这段话是否值得它的token成本
Good example: Concise (approximately 50 tokens):简洁示例,大约 50 个tokens
## Extract PDF text 提取 PDF 文本
Use pdfplumber for text extraction: 使用 pdfplumber 进行文本提取:
```python
import pdfplumber
with pdfplumber.open("file.pdf") as pdf:
text = pdf.pages[0].extract_text()
```
Bad example: Too verbose (approximately 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 we
recommend pdfplumber 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...
PDF(便携式文档格式)文件是一种常见的文件格式,包含文本、图像和其他内容。要从 PDF 中提取文本,你需要使用一个库。有许多用于 PDF 处理的库,但我们推荐 pdfplumber, 因为它易于使用并且能够很好地处理大多数情况。首先,你需要使用 pip 安装它。然后你可以使用以下代码...
The concise version assumes Claude knows what PDFs are and how libraries work. 简洁版假设 Claude 知道 PDF 是什么以及库如何运作。
Set appropriate degrees of freedom 设置适当的自由度
Match the level of specificity to the task's fragility and variability. 根据任务的脆弱性和可变性来匹配具体程度。
High freedom (text-based instructions): 高自由度(主要是基于文本的指令):
Use when:使用场景
- Multiple approaches are valid 多种方法都有效
- Decisions depend on context 决策取决于上下文
- Heuristics guide the approach 启发式方法指导方法
Example:示例
## Code review process 代码审查流程
1. Analyze the code structure and organization 分析代码结构和组织
2. Check for potential bugs or edge cases 检查潜在的 bug 或边缘情况
3. Suggest improvements for readability and maintainability 提出可读性和可维护性的改进建议
4. Verify adherence to project conventions 验证是否遵循项目规范
Medium freedom (pseudocode or scripts with parameters): 中等自由度(带伪代码或带参数的脚本):
Use when:使用场景
- A preferred pattern exists存在首选模式
- Some variation is acceptable 可接受某些变化
- Configuration affects behavior配置影响行为
Example示例:
## 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 可选地包含可视化
```
Low freedom (specific scripts, few or no parameters): 低自由度(特定脚本,参数很少或没有):
Use when:使用场景
- Operations are fragile and error-prone 操作易碎且易出错
- Consistency is critical 一致性至关重要
- A specific sequence must be followed 必须遵循特定顺序
Example示例:
## Database migration 数据库迁移
Run exactly this script: 严格运行这个脚本:
```bash
python scripts/migrate.py --verify --backup
```
Do not modify the command or add additional flags.不要修改命令或添加其他标志
Analogy类比: Think of Claude as a robot exploring a path:将 Claude 想象成一个探索路径的机器人
-
Narrow bridge with cliffs on both sides: There's only one safe way forward. Provide specific guardrails and exact instructions (low freedom). Example: database migrations that must run in exact sequence. 两侧悬崖的窄桥:只有一条安全的行进路线。提供具体的护栏和精确的指令(低自由度)。例如:必须按确切顺序执行的数据库迁移。
-
Open field with no hazards: Many paths lead to success. Give general direction and trust Claude to find the best route (high freedom). Example: code reviews where context determines the best approach. 无危险的开阔地带:许多路径都能通向成功。给出总体方向并信任 Claude 找到最佳路线(高自由度)。例如:代码审查中,上下文决定最佳方法。
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. 对 Opus 来说完美的工作方式可能需要为 Haiku 提供更多细节。如果你计划在多个模型中使用你的技能,目标是制定适用于所有模型的指令。
Skill structure 技能结构
<Note> YAML Frontmatter: The SKILL.md frontmatter requires two fields需要两个字段:
name:
- Maximum 64 characters
- Must contain only lowercase letters, numbers, and hyphens 小写字母、数字和连字符
- Cannot contain XML tags
- Cannot contain reserved words: "anthropic", "claude"不能包含保留词
description:
- Must be non-empty 不能为空
- Maximum 1024 characters 最多 1024 个字符
- Cannot contain XML tags
- Should describe what the Skill does and when to use it 应描述技能的作用以及何时使用它
</Note>
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. 使用一致的命名模式,以便更容易地引用和讨论技能。我们建议使用动名词形式(动词 + -ing)作为技能名称,因为这样可以清楚地描述技能提供的活动或功能。
Good naming examples (gerund form):良好的命名示例(动名词形式)
processing-pdfsanalyzing-spreadsheetsmanaging-databasestesting-codewriting-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过于笼统 - Reserved words:
anthropic-helper,claude-tools保留字 - 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 维护专业、统一的技能库
Writing effective descriptions 撰写有效的描述
The description field enables Skill discovery and should include both what the Skill does and when to use it.
description字段用于技能发现,应包含技能的功能以及使用时机。
<Warning> Always write in third person. The description is injected into the system prompt, and inconsistent point-of-view can cause discovery problems. 始终使用第三人称。描述会被注入系统提示中,不一致的视角可能导致探索问题。
- Good: "Processes Excel files and generates reports" 良好示例:处理 Excel 文件并生成报告
- Avoid: "I can help you process Excel files" 避免:我可以帮助你处理 Excel 文件
- Avoid: "You can use this to process Excel files" 避免:你可以使用这个来处理 Excel 文件 </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. 每个技能只有一个描述字段。描述对于技能选择至关重要,Claude 用它从 100 多个可用技能中选择正确的技能。你的描述必须提供足够的信息,让 Claude 知道何时选择这个技能,而 SKILL.md 的其余部分则提供实现细节。
Effective examples: 有效的示例:
PDF Processing skill: PDF 处理技能
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.
从 PDF 文件中提取文本和表格,填写表单,合并文档。在处理 PDF 文件或用户提到 PDF、表单或文档提取时使用。
Excel Analysis skill: Excel 分析技能
description: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when analyzing Excel files, spreadsheets, tabular data, or .xlsx files.
分析 Excel 电子表格,创建数据汇总表,生成图表。用于分析 Excel 文件、电子表格、表格数据或.xlsx 文件。
Git Commit Helper skill: Git 提交助手技能
description: Generate descriptive commit messages by analyzing git diffs. Use when the user asks for help writing commit messages or reviewing staged changes.
通过分析 git 差异生成描述性提交信息。用于用户请求帮助编写提交信息或审查已暂存更改时。
Avoid vague descriptions like these: 避免使用模糊的描述,例如:
description: Helps with documents 帮助处理文档
description: Processes data 处理数据
description: Does stuff with files 对文件进行操作
Progressive 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. SKILL.md 作为概览,引导 Claude 根据需要指向详细材料,类似于入门指南中的目录。
Practical guidance实用指南:
- Keep SKILL.md body under 500 lines for optimal performance 保持 SKILL.md 正文在 500 行以内以获得最佳性能
- Split content into separate files when approaching this limit 接近此限制时将内容拆分到单独文件中
- Use the patterns below to organize instructions, code, and resources effectively 使用下面章节介绍的模式有效组织指令、代码和资源
Visual overview: From simple to complex 视觉概览:从简单到复杂
A basic Skill starts with just a SKILL.md file containing metadata and instructions: 一个基本技能从一个仅包含元数据和指令的 SKILL.md 文件开始:
简单 SKILL.md 文件示例:
As your Skill grows, you can bundle additional content that Claude loads only when needed: 随着技能的增长,你可以捆绑额外的内容,Claude 仅在需要时加载这些内容:
捆绑参考文件如 reference.md 和 forms.md的技能示例:
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) API 参考(按需加载)
├── 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验证脚本
Pattern 1: High-level guide with references 模式 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 文件中提取文本和表格,填写表单,并合并文档。在处理 PDF 文件或用户提到 PDF、表单或文档提取时使用。
---
# PDF Processing PDF 处理(名字)
## 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 请参阅FORMS.md获取完整指南
**API reference**: See [REFERENCE.md](REFERENCE.md) for all methods API 参考:请参阅REFERENCE.md获取所有方法
**Examples示例**: See [EXAMPLES.md](EXAMPLES.md) for common patterns 获取常见模式
Claude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed. 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. 对于具有多个领域知识的技能,按域组织内容以避免加载不相关的上下文。当用户询问销售指标时,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收入、ARR、计费 → See [reference/finance.md](reference/finance.md)
**Sale销售s**: Opportunities, pipeline, accounts 机会、管道、账户 → See [reference/sales.md](reference/sales.md)
**Product产品**: API usage, features, adoption API 使用、功能、采用→ 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:使用 grep 查找特定指标:
```bash
grep -i "revenue" reference/finance.md
grep -i "pipeline" reference/sales.md
grep -i "api usage" reference/product.md
```
Pattern 3: Conditional details 模式 3:条件详情
Show basic content, link to advanced content: 显示基本内容,链接到高级内容:
# DOCX Processing DOCX 处理
## Creating documents 创建文档
Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).使用 docx-js 创建新文档。
## Editing documents 编辑文档
For simple edits, modify the XML directly.对于简单的编辑,直接修改 XML。
**For tracked changes对于跟踪更改**: See [REDLINING.md](REDLINING.md)
**For OOXML details细节**: See [OOXML.md](OOXML.md)
Claude reads REDLINING.md or OOXML.md only when the user needs those features. 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 head -100 to preview content rather than reading entire files, resulting in incomplete information.
Claude 在从其他引用文件中引用文件时可能会部分读取文件。当遇到嵌套引用时,Claude 可能会使用head -100等命令来预览内容,而不是读取整个文件,从而导致信息不完整。
Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md to ensure Claude reads complete files when needed. 从 SKILL.md 保持一级引用。所有引用文件应直接从 SKILL.md 链接,以确保 Claude 在需要时读取完整的文件。
Bad example: Too deep:不良示例:过深
# SKILL.md
See [advanced.md](advanced.md)...
# advanced.md
See [details.md](details.md)...
# details.md
Here's the actual information...
Good example: One level deep:好的示例:一级深
# 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)
Structure 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. 对于超过 100 行的参考文件,请在顶部包含目录。这确保了即使使用部分读取预览时,Claude 也能看到完整的信息范围。
Example:
# API Reference
## Contents 目录
- Authentication and setup 认证和设置
- Core methods (create, read, update, delete) 核心方法(创建、读取、更新、删除)
- Advanced features (batch operations, webhooks) 高级功能(批量操作、webhooks)
- Error handling patterns 错误处理模式
- Code examples 代码示例
## Authentication and setup
...
## Core methods
...
Claude can then read the complete file or jump to specific sections as needed. Claude 然后可以读取完整文件或根据需要跳转到特定章节。
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. 将复杂的操作分解为清晰、按顺序的步骤。对于特别复杂的工作流,提供一个清单,Claude 可以将其复制到其响应中,并在进行过程中进行勾选。
Example 1: Research synthesis workflow (for Skills without code): 研究综合工作流(适用于无代码的技能):
## 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.
审查`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.
检查每个论点是否引用了正确的源文档。如果引用不完整,返回步骤 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):PDF 表单填写工作流**(适用于带代码的技能)
## 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.pdf`
This extracts form fields and their locations, saving to `fields.json`.
这会提取表单字段及其位置,并保存到 `fields.json`。
**Step 2: Create field mapping**
Edit `fields.json` to add values for each field.
编辑 `fields.json` 文件以添加每个字段的值。
**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.
如果验证失败,返回步骤 2
Clear steps prevent Claude from skipping critical validation. The checklist helps both Claude and you track progress through multi-step workflows. 清晰的步骤防止 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): 风格指南合规性(适用于无代码的技能)
## Content review process 内容审查流程
1. Draft your content following the guidelines in STYLE_GUIDE.md 按照 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 最终确定并保存文档
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. 这展示了使用参考文档而非脚本进行的验证循环模式。"验证者"是 STYLE_GUIDE.md,Claude 通过阅读和比较来执行检查。
Example 2: Document editing process (for Skills with code): 文档编辑流程(适用于带代码的技能)
## Document editing process 文档编辑流程
1. Make your edits to `word/document.xml` 对 `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 修复 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 测试输出文档
The validation loop catches errors early. 验证循环可及早捕获错误。
Content guidelines 内容指南
Avoid time-sensitive information 避免包含时效性信息
Don't include information that will become outdated: 不要包含会过时的信息:
Bad example: Time-sensitive (will become wrong): 坏例子:有时间限制(会变得错误)
If you're doing this before August 2025, use the old API. 如果你是在 2025 年 8 月之前做的,使用旧的 API
After August 2025, use the new API. 2025 年 8 月之后,使用新的 API
Good example (use "old patterns" section): 好例子(使用"旧模式"部分)
## Current method 当前方法
Use the v2 API endpoint: `api.example.com/v2/messages`
使用 v2 API 端点
## Old patterns 旧模式
<details>
<summary>Legacy v1 API (deprecated 2025-08) 旧版 v1 API(2025-08 停用)</summary>
The v1 API used: `api.example.com/v1/messages`
使用的 v1 API 为
This endpoint is no longer supported.此端点不再支持
</details>
The old patterns section provides historical context without cluttering the main content. 旧模式部分提供历史背景,而不会使主要内容显得杂乱。
Use consistent terminology 使用一致的术语
Choose one term and use it throughout the Skill: 在整个技能中选择一个术语并始终使用:
Good - Consistent: 良好 - 一致
- Always "API endpoint" 始终使用“API 端点”
- 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. 一致性有助于 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): 对于严格的要求(比如 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 发现 1 及支持数据
- Finding 2 with supporting data
- Finding 3 with supporting data
## Recommendations 建议
1. Specific actionable recommendation 具体的可操作建议
2. Specific actionable recommendation
```
For flexible guidance (when adaptation is useful): 用于灵活指导(当自适应有用时):
## 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.根据具体的分析类型调整各部分
Examples pattern 示例模式
For Skills where output quality depends on seeing examples, provide input/output pairs just like in regular prompting: 对于输出质量依赖于查看示例的技能,请像常规提示那样提供输入/输出对:
## Commit message format 提交信息格式
Generate commit messages following these examples:
根据以下示例生成提交信息:
**Example 1:**
Input: Added user authentication with JWT tokens 使用 JWT tokens添加用户认证输出
Output:
```
feat(auth): implement JWT-based authentication 实现 JWT 基于的认证
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 在报告生成中始终使用 UTC 时间戳
```
**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. 遵循此风格:类型(范围):简要描述,然后是详细说明
Examples help Claude understand the desired style and level of detail more clearly than descriptions alone. 示例比描述更能帮助 Claude 更清晰地理解所需的风格和详细程度。
Conditional workflow pattern 条件工作流模式
Guide Claude through decision points: 引导 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 完成时重新打包
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.
如果工作流庞大或复杂,包含许多步骤,可以考虑将它们放入单独的文件,并告诉 Claude 根据具体任务读取相应的文件。
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 识别差距:在无skill的情况下运行 Claude 在代表性任务上。记录具体的失败或缺失的上下文
- Create evaluations: Build three scenarios that test these gaps 创建评估:构建三个测试这些差距的场景
- Establish baseline: Measure Claude's performance without the Skill 建立基线:测量无技能时的 Claude 性能
- 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:评估结构
{
"skills": ["pdf-processing"],
"query": "Extract all text from this PDF file and save it to output.txt", //从这个 PDF 文件中提取所有文本并保存到 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"
]
}
使用适当的 PDF 处理库或命令行工具成功读取 PDF 文件 从文档的所有页面中提取文本内容,不遗漏任何页面 将提取的文本保存到名为 output.txt 的文件中,格式清晰易读
This example demonstrates a data-driven evaluation with a simple testing rubric. We do not currently provide a built-in way to run these evaluations. Users can create their own evaluation system. Evaluations are your source of truth for measuring Skill effectiveness.
上面例子展示了一个数据驱动的评估,并附带了一个简单的测试标准。目前我们没有提供内置的方式来运行这些评估。用户可以创建自己的评估系统。评估是衡量技能有效性的依据。
Develop Skills iteratively with Claude 使用 Claude 迭代开发技能
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. 最有效的技能开发过程涉及 Claude 本身。与 Claude 的一个实例("Claude A")合作创建一个技能,该技能将由其他实例("Claude B")使用。Claude A 帮助你设计和完善指令,而 Claude B 在真实任务中测试这些指令。这之所以有效,是因为 Claude 模型既理解如何编写有效的代理指令,也明白代理需要哪些信息。
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. 无技能完成任务:使用正常提示与 Claude A 一起解决问题。在解决问题的过程中,你会自然地提供背景信息、解释偏好,并分享程序性知识。注意你反复提供的信息。
-
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. 示例:如果你完成了一个 BigQuery 分析,你可能会提供表名、字段定义、过滤规则(例如"始终排除测试账户")和常见的查询模式。
-
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." 让 Claude A 创建一个技能:"创建一个技能,捕获我们刚刚使用的 BigQuery 分析模式。包括表架构、命名约定以及过滤测试账户的规则。"
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.
Claude 模型原生理解技能的格式和结构。你不需要特殊的系统提示或"编写技能"技能来让 Claude 帮助你创建技能。只需让 Claude 创建一个技能,它就会生成结构良好的 SKILL.md 内容,包含适当的 frontmatter 和正文内容。
-
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." 检查简洁性:确认 Claude A 没有添加不必要的解释。询问:"移除关于胜率的解释——Claude 已经知道这意味着什么。"
-
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." 改进信息架构:让 Claude A 更有效地组织内容。例如:"将表格模式放在单独的参考文件中组织。我们可能以后会添加更多表格。"
-
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. 在相似任务上测试:使用 Claude B(一个加载了技能的新实例)在相关用例上使用该技能。观察 Claude B 是否找到正确信息、正确应用规则以及成功完成任务。
-
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?" 根据观察进行迭代:如果 Claude B 遇到困难或遗漏了某些内容,请带着具体问题返回 Claude A:"当 Claude 使用这个技能时,它忘记按 Q4 日期筛选了。我们应该增加一个关于日期筛选模式的章节吗?"
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 观察 Claude B 的行为:并将见解反馈给 Claude A
-
Use the Skill in real workflows: Give Claude B (with the Skill loaded) actual tasks, not test scenarios 在真实工作流程中使用技能:给加载了技能的 Claude B 分配实际任务,而不是测试场景
-
Observe Claude B's behavior: Note where it struggles, succeeds, or makes unexpected choices 观察 Claude B 的行为:记录它在哪些地方遇到困难、成功或做出意外选择
Example 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." 观察示例:"当我向 Claude B 请求区域销售报告时,它写出了查询但忘记过滤测试账户,尽管技能中提到了这一规则。"
-
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?" 返回 Claude A 进行改进: 分享当前的 SKILL.md 并描述你的观察。询问:"我注意到 Claude B 在请求区域报告时忘记过滤测试账户。技能中提到了过滤,但也许不够突出?"
-
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. 审查 Claude A 的建议: Claude A 可能会建议重新组织以使规则更突出,使用更强的语言如"必须过滤"而不是"总是过滤",或重新构建工作流部分。
-
Apply and test changes: Update the Skill with Claude A's refinements, then test again with Claude B on similar requests 应用并测试更改: 使用 Claude A 的改进更新技能,然后用 Claude B 对类似请求再次进行测试
-
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. 这种方法为何有效:Claude A 理解代理需求,你提供领域专业知识,Claude B 通过实际使用揭示差距,而迭代优化是基于观察到的行为而非假设来改进技能。
Observe how Claude navigates Skills 观察 Claude 如何导航技能
As you iterate on Skills, pay attention to how Claude actually uses them in practice. Watch for: 在迭代技能时,注意 Claude 在实际应用中如何使用它们。留意以下情况:
- 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 意外的探索路径:Claude 是否按你未预料到的顺序读取文件?这可能表明你的结构不如你想象的直观
- Missed connections: Does Claude fail to follow references to important files? Your links might need to be more explicit or prominent 遗漏的连接:Claude 是否未能遵循对重要文件的关键引用?你的链接可能需要更明确或突出
- Overreliance on certain sections: If Claude repeatedly reads the same file, consider whether that content should be in the main SKILL.md instead 对某些部分的过度依赖:如果 Claude 反复读取同一文件,请考虑该内容是否应放在主 SKILL.md 中
- Ignored content: If Claude never accesses a bundled file, it might be unnecessary or poorly signaled in the main instructions 被忽略的内容:如果 Claude 从未访问过捆绑的文件,它可能是不必要的或主指令中标记不当
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. 根据这些观察结果进行迭代,而不是基于假设。你的技能元数据中的“名称”和“描述”尤其关键。Claude 决定是否在当前任务中触发技能时使用这些信息。确保它们清楚地描述了技能的作用以及何时应使用它。
Anti-patterns to avoid 需避免的反模式
Avoid Windows-style paths 避免使用 Windows 风格的路径
Always use forward slashes in file paths, even on Windows: 在文件路径中始终使用正斜杠,即使在 Windows 上:
- ✓ Good:
scripts/helper.py,reference/guide.md - ✗ Avoid:
scripts\helper.py,reference\guide.md
Unix-style paths work across all platforms, while Windows-style paths cause errors on Unix systems. Unix 风格的路径在所有平台上都有效,而 Windows 风格的路径在 Unix 系统上会导致错误。
Avoid offering too many options 避免提供过多选项
Don't present multiple approaches unless necessary: 除非必要,否则不要呈现多种方法:
**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." 对于需要 OCR 的扫描 PDF 文件,使用 pdf2image 与 pytesseract
Advanced: Skills with executable code 高级:可执行代码的技能
The sections below focus on Skills that include executable scripts. 以下部分专注于包含可执行脚本的技能。
Solve, don't punt 解决问题,不要逃避
When writing scripts for Skills, handle error conditions rather than punting to Claude. 在为技能编写脚本时,应处理错误情况,而不是将问题推给 Claude。
Good example: Handle errors explicitly: 好的示例:明确处理错误
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: 坏的示例:推给 Claude
def process_file(path):
# Just fail and let Claude figure it out 直接失败并让 Claude 处理
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? 配置参数也应该进行说明和记录,以避免出现“巫术常量”(Ousterhout 定律)。如果你不知道正确的值,Claude 又将如何确定它?
Good example: Self-documenting:好的示例:自解释性
# HTTP requests typically complete within 30 seconds HTTP 请求通常在 30 秒内完成
# 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
Bad example: Magic numbers: 不好的示例:魔术数字
TIMEOUT = 47 # Why 47?
RETRIES = 5 # Why 5?
Provide utility scripts 提供实用脚本
Even if Claude could write a script, pre-made scripts offer advantages: 即使 Claude 能够编写脚本,现成的脚本也具有优势:
Benefits of utility scripts: 实用脚本的好处
- More reliable than generated code 比生成的代码更可靠
- Save tokens (no need to include code in context) 节省tokens(无需在上下文中包含代码)
- Save time (no code generation required) 节省时间(无需生成代码)
- Ensure consistency across uses 确保不同使用场景的一致性
下面展示了一个将可执行脚本与指令文件捆绑在一起的skill
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. 上图展示了可执行脚本如何与指令文件协同工作。指令文件(forms.md)引用了脚本,Claude 可以执行它而无需将其内容加载到上下文中。
Important distinction: Make clear in your instructions whether Claude should: 重要区别:在你的指令中明确说明 Claude 应该
- Execute the script (most common): "Run
analyze_form.pyto extract fields" 执行脚本(最常见) 运行analyze_form.py以提取字段 - Read it as reference (for complex logic): "See
analyze_form.pyfor the field extraction algorithm" 将其作为参考(用于复杂逻辑)有关字段提取算法,请参阅analyze_form.py
For most utility scripts, execution is preferred because it's more reliable and efficient. 对于大多数实用脚本,执行是首选的,因为它更可靠和高效。
Example:
## Utility scripts 实用脚本
**analyze_form.py**: Extract all form fields from PDF 从 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 返回: "OK" 或列出冲突
```
**fill_form.py**: Apply field values to PDF 将字段值应用于 PDF
```bash
python scripts/fill_form.py input.pdf fields.json output.pdf
```
Use visual analysis 使用视觉分析
When inputs can be rendered as images, have Claude analyze them: 当输入可以渲染为图像时,让 Claude 进行分析:
## Form layout analysis 表单布局分析
1. Convert PDF to images: 将 PDF 转换为图像
```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 Claude 可以直观地看到字段位置和类型
Claude's vision capabilities help understand layouts and structures. 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. 当 Claude 执行复杂、开放式的任务时,它可能会犯错误。"计划-验证-执行"模式让 Claude 首先以结构化格式创建计划,然后在执行前用脚本验证该计划来尽早捕获错误。
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. 示例:想象一下让 Claude 根据电子表格更新 PDF 中的 50 个表单字段。如果没有验证,Claude 可能会引用不存在的字段、创建冲突的值、遗漏必需的字段或错误地应用更新。
Solution: Use the workflow pattern shown above (PDF form filling), but add an intermediate changes.json file that gets validated before applying changes. The workflow becomes: analyze → create plan file → validate plan → execute → verify.
解决方案:使用上述所示的工作流模式(PDF 表单填写),但增加一个中间的changes.json文件,在应用更改前进行验证。工作流变为:分析 → 创建计划文件 → 验证计划 → 执行 → 验证。
**Why 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 可逆规划:Claude 可以在不触碰原始文件的情况下迭代计划
- 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. 实施技巧:使验证脚本输出详细内容,包含具体错误信息,如"未找到字段 'signature_date'。可用字段: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 可以从 npm 和 PyPI 安装包,并从 GitHub 存储库拉取
- 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.md 中列出所需的包,并验证它们在代码执行工具文档中可用。
Runtime environment 运行环境
Skills run in a code execution environment with filesystem access, bash commands, and code execution capabilities. 技能在一个具有文件系统访问、bash 命令和代码执行能力的代码执行环境中运行。
How this affects your authoring: 这对你的创作有何影响:
How Claude accesses Skills: Claude 如何访问技能:
- Metadata pre-loaded: At startup, the name and description from all Skills' YAML frontmatter are loaded into the system prompt 元数据预加载:启动时,所有技能的 YAML 前导块的名称和描述被加载到系统提示中
- Files read on-demand: Claude uses bash Read tools to access SKILL.md and other files from the filesystem when needed 按需读取文件:Claude 使用 bash 读取工具在需要时从文件系统中访问 SKILL.md 和其他文件
- Scripts executed efficiently: Utility scripts can be executed via bash without loading their full contents into context. Only the script's output consumes tokens 脚本高效执行:实用脚本可以通过 bash 执行,而无需将它们全部内容加载到上下文中。只有脚本的输出会消耗 token
- No context penalty for large files: Reference files, data, or documentation don't consume context tokens until actually read 大文件不产生上下文惩罚:参考文件、数据或文档只有在实际读取时才会消耗上下文 token
- File paths matter: Claude navigates your skill directory like a filesystem. Use forward slashes (
reference/guide.md), not backslashes 文件路径很重要:Claude 像文件系统一样导航你的技能目录。使用正斜杠(reference/guide.md),而不是反斜杠 - Name files descriptively: Use names that indicate content:
form_validation_rules.md, notdoc2.md文件名要描述性:使用能表明内容的名称 - Organize for discovery: Structure directories by domain or feature 为了便于发现而组织::按领域或功能结构化目录
- Good:
reference/finance.md,reference/sales.md - Bad:
docs/file1.md,docs/file2.md
- Good:
- Bundle comprehensive resources: Include complete API docs, extensive examples, large datasets; no context penalty until accessed 捆绑综合资源:包含完整的 API 文档、丰富的示例、大型数据集;只有在访问时才产生上下文惩罚
- Prefer scripts for deterministic operations: Write
validate_form.pyrather than asking Claude to generate validation code 对于确定性操作优先使用脚本:而不是让 Claude 生成验证代码 - Make execution intent clear: 明确执行意图
- "Run
analyze_form.pyto extract fields" (execute) - "See
analyze_form.pyfor 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 测试文件访问模式:通过实际请求验证 Claude 能否导航你的目录结构
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 reference/finance.md, 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.
当用户询问收入时,Claude 读取 SKILL.md,看到对reference/finance.md的引用,并调用 bash 仅读取该文件。sales.md 和 product.md 文件仍保留在文件系统中,直到需要时才消耗零上下文令牌。这种基于文件系统的模型使得渐进式披露成为可能。Claude 可以导航并选择性地加载每个任务所需的确切内容。
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. 如果你的技能使用 MCP(模型上下文协议)工具,请始终使用完全限定工具名称以避免"工具未找到"错误。
Format: ServerName:tool_name 服务器名:工具名
Example:
Use the BigQuery:bigquery_schema tool to retrieve table schemas. 使用 BigQuery:bigquery_schema 工具来检索表结构
Use the GitHub:create_issue tool to create issues. 使用 GitHub:create_issue 工具来创建问题
Where:
BigQueryandGitHubare MCP server names MCP 服务器名bigquery_schemaandcreate_issueare the tool names within those servers 是这些服务器中的工具名
Without the server prefix, Claude may fail to locate the tool, especially when multiple MCP servers are available. 如果没有服务器前缀,Claude 可能无法找到工具,尤其是在有多个 MCP 服务器可用时。
Avoid assuming tools are installed 避免假设工具已安装
Don't assume packages are available: 不要假设包可用:
**Bad example: Assumes installation**: 坏示例:假设已安装
"Use the pdf library to process the file." 使用 pdf 库处理文件
**Good example: Explicit about dependencies**: 好示例:明确说明依赖关系
"Install required package: `pip install pypdf` 安装所需包
Then use it:
```python
from pypdf import PdfReader
reader = PdfReader("file.pdf")
```"
Technical notes 技术说明
Token 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. 将 SKILL.md 正文保持在 500 行以内以获得最佳性能。如果你的内容超过此限制,请使用前面描述的渐进式披露模式将其拆分为单独的文件。
Checklist for effective Skills 有效技能的检查清单
Before sharing a Skill, verify: 在分享一个技能之前,请验证:
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 SKILL.md 正文少于 500 行
- 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 工作流程步骤清晰
Code and scripts 代码和脚本
- Scripts solve problems rather than punt to Claude 脚本解决问题而非将问题推给 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) 无 Windows 风格路径(全部使用正斜杠)
- Validation/verification steps for critical operations 对关键操作进行验证/确认步骤
- Feedback loops included for quality-critical tasks 对质量关键任务包含反馈循环
Testing 测试
- At least three evaluations created 至少创建三个评估
- Tested with Haiku, Sonnet, and Opus 使用 Haiku、Sonnet 和 Opus 进行测试
- Tested with real usage scenarios 使用实际使用场景进行测试
- Team feedback incorporated (if applicable) 结合团队反馈(如果适用)
小结:可以写1,2,3,4步骤
技能效果跟使用的模型有关
description 最多 1024 个字符,description字段用于技能发现,应包含技能的功能以及使用时机。
name 使用 动名词形式
SKILL.md 类似于入门指南中的目录
可以通过reference/finance.md,reference/sales.md 存放多个文档,并在主skill.md里面通过链接方式指定
对于嵌套的引用文件,Claude 可能会使用head -100等命令来预览引用的链接内容。最好直接从skill.md里面引用
对于超过 100 行的参考文件,请在顶部包含目录。会根据需要跳转到特定章节
使用工作流处理复杂任务
提示了2个示例,一个适用于无代码的技能,另一个适用于带代码的技能
提供了一个实施反馈循环的示例:运行验证器 → 修复错误 → 重复
提供了3种常见模式,
Claude A 帮助你设计和完善指令,而 Claude B 在真实任务中测试这些指令:创建一个技能,捕获我们刚刚使用的 BigQuery 分析模式。包括表架构、命名约定以及过滤测试账户的规则。
即使 Claude 能够编写脚本,现成的脚本也具有优势
技能在一个具有文件系统访问、bash 命令和代码执行能力的代码执行环境中运行。
如果你的技能使用 MCP(模型上下文协议)工具,请始终使用完全限定工具名称以避免"工具未找到"错误