创建自定义 Skills
本指南将教您如何创建自己的自定义技能,扩展 Claude 的能力以满足特定需求。
为什么要创建自定义技能?
创建自定义技能适用于:
- ✅ 重复性工作 - 经常执行相同的工作流程
- ✅ 专业领域 - 需要特定领域知识或公司知识
- ✅ 工具集成 - 与特定 API 或工具的标准化交互
- ✅ 复杂流程 - 多步骤流程需要一致性
- ✅ 资源打包 - 需要脚本、模板或参考文档
快速开始
最简单的技能
创建一个技能只需要一个 SKILL.md 文件:
---
name: my-first-skill
description: A simple skill that does something useful. Use when Claude needs to do X, Y, or Z.
---
# My First Skill
## What This Skill Does
This skill helps with [specific task].
## How to Use
1. First step
2. Second step
3. Third step
## Example
\`\`\`
Example code or output
\`\`\`
就这么简单!
使用模板快速创建
方法 1: 复制 template-skill
# 复制模板
cp -r skills/template-skill skills/my-new-skill
# 编辑 SKILL.md
vim skills/my-new-skill/SKILL.md
方法 2: 使用 init_skill.py(推荐)
# 下载或克隆 anthropics/skills 仓库
git clone https://github.com/anthropics/skills.git
# 运行初始化脚本
cd skills
scripts/init_skill.py my-new-skill --path ./custom-skills
# 生成的结构:
custom-skills/my-new-skill/
├── SKILL.md # 技能定义
├── scripts/ # 可选:脚本目录
├── references/ # 可选:参考文档
└── assets/ # 可选:资产文件
技能创建流程(6 步)
完整的技能创建流程请参考 skill-creator 文档,这里是简化版本:
第 1 步: 理解需求
明确您的技能要解决什么问题。
问自己:
- 这个技能会被用来做什么?
- 用户会如何描述他们的需求?
- 需要哪些输入和输出?
示例:
需求: "我需要一个技能来自动生成 Git 提交消息"
具体场景:
- 用户: "帮我写个提交消息,我添加了用户认证功能"
- 用户: "生成提交消息: 修复了日期显示的 bug"
第 2 步: 规划资源
确定需要哪些可重用资源:
| 资源类型 | 何时需要 | 示例 |
|---|---|---|
| scripts/ | 需要重复运行相同代码 | PDF 旋转脚本 |
| references/ | 需要参考文档或架构 | API 文档、数据库架构 |
| assets/ | 需要模板或资产文件 | 品牌 logo、HTML 模板 |
第 3 步: 初始化技能
# 使用 init_skill.py 创建基础结构
scripts/init_skill.py my-skill --path ./skills
第 4 步: 编写 SKILL.md
Frontmatter(必需)
---
name: commit-message-generator
description: |
Generate conventional commit messages following best practices.
Use when Claude needs to create git commit messages that follow
the conventional commits specification.
---
关键点:
name: 小写,连字符分隔description: 详细说明功能和触发时机
正文内容
# Commit Message Generator
## Format
Use the conventional commits format:
\`\`\`
<type>(<scope>): <subject>
<body>
<footer>
\`\`\`
## Types
- **feat**: New feature
- **fix**: Bug fix
- **docs**: Documentation changes
- **style**: Code style changes (formatting)
- **refactor**: Code refactoring
- **test**: Adding tests
- **chore**: Maintenance tasks
## Examples
### Feature Addition
\`\`\`
feat(auth): add JWT authentication
Implement login endpoint with JWT token generation
and validation middleware.
Closes #123
\`\`\`
### Bug Fix
\`\`\`
fix(reports): correct date formatting in timezone conversion
Use UTC timestamps consistently across report generation
Fixes #456
\`\`\`
## Guidelines
1. Keep subject line under 50 characters
2. Capitalize the subject line
3. Don't end subject line with a period
4. Use imperative mood ("add" not "added")
5. Wrap body at 72 characters
6. Use body to explain what and why, not how
第 5 步: 添加资源(可选)
添加脚本
# scripts/validate_commit.py
#!/usr/bin/env python3
import re
import sys
def validate_commit_message(message):
pattern = r'^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .{1,50}$'
first_line = message.split('\n')[0]
return bool(re.match(pattern, first_line))
if __name__ == '__main__':
message = sys.argv[1]
if validate_commit_message(message):
print("✅ Valid commit message")
sys.exit(0)
else:
print("❌ Invalid commit message format")
sys.exit(1)
添加参考文档
# references/conventional-commits.md
# Conventional Commits Specification
[详细的规范说明]
添加资产
# assets/commit-template.txt
<type>(<scope>): <subject>
<body>
<footer>
第 6 步: 打包和验证
# 验证技能
scripts/quick_validate.py skills/my-skill
# 打包技能
scripts/package_skill.py skills/my-skill
# 生成 my-skill.skill 文件
技能设计原则
1. 简洁是关键
上下文窗口是公共资源 - 与系统提示、对话历史共享。
✅ 好的做法:
## PDF Rotation
Run `scripts/rotate_pdf.py input.pdf output.pdf --angle 90`
❌ 避免冗长:
## PDF Rotation
PDF rotation is the process of changing the orientation of pages
in a PDF document. This can be useful when scanned documents are
in the wrong orientation. Our script provides a simple way to
accomplish this task by accepting an input file, output file,
and rotation angle as parameters...
2. 使用示例而非解释
✅ 提供示例:
## Email Format
\`\`\`
Subject: [Project] Weekly Update - Jan 15
Progress:
- Completed user authentication
- Fixed 3 critical bugs
Plans:
- Start payment integration
- Review security audit
Problems:
- Need design feedback on dashboard
\`\`\`
❌ 冗长解释:
## Email Format
Emails should follow our internal format which includes
a subject line that starts with the project name in brackets,
followed by the update type and date. The body should have
three sections: Progress, Plans, and Problems. Progress
lists completed items, Plans lists upcoming work...
3. 设置适当的自由度
根据任务的脆弱性和可变性选择合适的约束级别:
| 自由度 | 适用场景 | 形式 |
|---|---|---|
| 高 | 多种方法都可行,需要上下文判断 | 文本指令和示例 |
| 中 | 有首选模式,但允许变化 | 伪代码或带参数的脚本 |
| 低 | 操作脆弱,必须精确执行 | 具体脚本,少量参数 |
4. 渐进式披露
将内容分层组织,避免一次性加载所有内容:
SKILL.md (核心指令,<500 行)
↓
references/advanced.md (高级用法)
references/api-docs.md (API 参考)
references/examples.md (更多示例)
在 SKILL.md 中引用:
## Basic Usage
[基本说明]
## Advanced Features
For advanced usage, see [advanced.md](references/advanced.md)
For complete API reference, see [api-docs.md](references/api-docs.md)
实战示例
示例 1: SQL 查询助手
---
name: sql-query-helper
description: |
Help write and optimize SQL queries for the company database.
Use when Claude needs to query the production database or
help with SQL query optimization.
---
# SQL Query Helper
## Database Schema
Our main tables:
- `users` (id, email, created_at, status)
- `orders` (id, user_id, amount, created_at, status)
- `products` (id, name, price, category)
Full schema: [schema.md](references/schema.md)
## Query Guidelines
1. Always use parameterized queries
2. Include LIMIT clauses for safety
3. Use indexes on WHERE clauses
4. Test queries in staging first
## Common Queries
### Active Users
\`\`\`sql
SELECT id, email, last_login
FROM users
WHERE status = 'active'
ORDER BY last_login DESC
LIMIT 100;
\`\`\`
### Revenue by Month
\`\`\`sql
SELECT
DATE_TRUNC('month', created_at) as month,
SUM(amount) as revenue
FROM orders
WHERE status = 'completed'
GROUP BY month
ORDER BY month DESC;
\`\`\`
## Optimization Tips
- See [optimization.md](references/optimization.md) for indexing strategies
- Use EXPLAIN ANALYZE to check query plans
示例 2: 品牌资产管理
---
name: company-brand-assets
description: |
Apply company brand guidelines including colors, fonts, and logos
to documents and designs. Use when creating branded materials.
---
# Company Brand Assets
## Brand Colors
Primary: `#1E40AF` (Blue)
Secondary: `#10B981` (Green)
Accent: `#F59E0B` (Orange)
See [colors.md](references/colors.md) for full palette
## Logos
Available in `assets/logos/`:
- `logo-full.svg` - Full logo with text
- `logo-icon.svg` - Icon only
- `logo-white.svg` - White version for dark backgrounds
## Typography
- Headlines: Montserrat Bold
- Body: Inter Regular
- Code: JetBrains Mono
Font files in `assets/fonts/`
## Usage Examples
### PowerPoint Slides
\`\`\`python
from pptx import Presentation
prs = Presentation('assets/templates/brand-template.pptx')
# Template already has brand colors and fonts
\`\`\`
### Web Pages
\`\`\`css
:root {
--brand-primary: #1E40AF;
--brand-secondary: #10B981;
--brand-accent: #F59E0B;
}
\`\`\`
最佳实践清单
✅ 应该做的
- 测试脚本 - 确保所有脚本实际运行
- 提供示例 - 展示而非讲述
- 保持简洁 - 挑战每段文字的价值
- 清晰的 description - 这是触发机制
- 版本控制 - 使用 Git 管理技能
❌ 不应该做的
- 不要创建额外文档 - 无需 README.md、CHANGELOG.md
- 不要重复信息 - 选择 SKILL.md 或 references,不要两处都有
- 不要深度嵌套 - 引用文件保持一级深度
- 不要假设基础知识需要解释 - Claude 已经很聪明
打包和分发
验证技能
# 快速验证
scripts/quick_validate.py skills/my-skill
# 检查项:
# - YAML frontmatter 格式
# - 必需字段存在
# - 文件引用有效
# - 命名规范符合
打包技能
# 打包为 .skill 文件
scripts/package_skill.py skills/my-skill
# 输出: my-skill.skill (实际是 zip 文件)
上传到 Claude
Claude.ai
- 访问 Settings → Skills
- 点击 "Upload Skill"
- 选择 .skill 文件
Claude API
import anthropic
client = anthropic.Anthropic()
with open("my-skill.skill", "rb") as f:
skill = client.skills.create(
name="my-skill",
file=f
)
进阶主题
工作流模式
顺序工作流:
1. Analyze input
2. Process data
3. Generate output
4. Validate results
条件工作流:
1. Determine document type:
**Creating new?** → Follow creation workflow
**Editing existing?** → Follow editing workflow
详见 skill-creator 的 references/workflows.md
输出模式
模板模式(严格输出):
ALWAYS use this exact format:
[template]
示例模式(灵活输出):
Follow these examples:
[示例 1]
[示例 2]
详见 skill-creator 的 references/output-patterns.md
获取帮助
深入学习
- skill-creator 完整文档 - 详细的创建指南
- template-skill - 快速模板
- 示例技能 - 浏览 所有技能 作为参考
官方资源
下一步
- 创建第一个技能 - 使用 template-skill 或 init_skill.py
- 测试和迭代 - 在实际场景中使用
- 分享和改进 - 基于反馈优化
准备好了吗? 开始创建您的第一个自定义技能!