Template Skill 完整参考
本文档提供 Skill 模板的详细参考和自定义指南。建议先阅读 📋 概览 和 Skill Creator。
模板文件详解
SKILL.md 最小模板
---
name: template-skill
description: Replace with description of the skill and when Claude should use it.
---
# Insert instructions below
各部分说明
YAML 前置元数据
---
name: template-skill # 必需:skill 唯一标识符
description: Replace with... # 必需:触发器和使用说明
---
name 字段规范:
- 小写字母
- 单词间用连字符 (
-) 分隔 - 无空格、无下划线
- 描述性名称
示例:
✅ pdf-editor
✅ bigquery-analytics
✅ brand-guidelines
❌ PDF_Editor
❌ pdfEditor
❌ pdf editor
description 字段规范:
- 说明 Skill 的功能
- 列出所有触发场景
- 包含关键词
- 明确边界(如果需要)
结构:
[做什么]. [何时使用]: (1) [场景1], (2) [场景2], (3) [场景3].
[可选: 不做什么].
完整模板示例
示例 1:工具集成型 Skill
---
name: pdf-toolkit
description: >
Comprehensive PDF manipulation toolkit using PyPDF2.
Use when working with PDF files for:
(1) Rotating pages,
(2) Merging multiple PDFs,
(3) Extracting pages,
(4) Analyzing metadata.
Does NOT handle OCR, form filling, or digital signatures.
---
# PDF Toolkit
## Overview
This skill provides scripts and guidance for common PDF operations.
## Quick Start
### Rotate PDF
```bash
python scripts/rotate_pdf.py input.pdf output.pdf --angle 90
Merge PDFs
python scripts/merge_pdfs.py file1.pdf file2.pdf merged.pdf
Extract Pages
python scripts/extract_pages.py input.pdf output.pdf --pages 1-5,8,10
Scripts
All scripts are in scripts/ directory:
rotate_pdf.py- Rotate pages by 90/180/270 degreesmerge_pdfs.py- Combine multiple PDFsextract_pages.py- Extract specific pagesanalyze_pdf.py- Get PDF metadata
Advanced Features
For advanced operations, see:
Troubleshooting
Error: Encrypted PDF
Some PDFs are password-protected. Decrypt first or provide password:
python scripts/rotate_pdf.py input.pdf output.pdf --angle 90 --password SECRET
Error: Missing PyPDF2
Install dependency:
pip install PyPDF2
---
### 示例 2:领域知识型 Skill
```markdown
---
name: bigquery-sales
description: >
Query and analyze sales data in BigQuery including opportunities,
pipeline metrics, and conversion rates. Use when analyzing sales
performance, forecasting, or generating sales reports.
---
# BigQuery Sales Analytics
## Quick Reference
### Table Schema
Main tables:
- `sales.opportunities` - Sales opportunities and deals
- `sales.pipeline` - Pipeline stages and transitions
- `sales.conversions` - Conversion events and rates
Detailed schema: [SCHEMA.md](references/SCHEMA.md)
## Common Queries
### Today's Closed Deals
```sql
SELECT
opportunity_id,
deal_value,
closed_by
FROM sales.opportunities
WHERE
status = 'closed_won'
AND DATE(closed_date) = CURRENT_DATE()
Pipeline Value by Stage
SELECT
stage,
COUNT(*) as opportunity_count,
SUM(deal_value) as total_value
FROM sales.pipeline
WHERE status = 'active'
GROUP BY stage
ORDER BY total_value DESC
Conversion Rate This Month
SELECT
COUNT(CASE WHEN status = 'closed_won' THEN 1 END) / COUNT(*) as conversion_rate
FROM sales.opportunities
WHERE DATE(created_at) >= DATE_TRUNC(CURRENT_DATE(), MONTH)
Metrics Definitions
For detailed metric calculations and business logic: METRICS.md
Best Practices
- Always filter by date to improve query performance
- Use
DATE_TRUNCfor month/quarter aggregations - Join opportunities with pipeline for stage history
---
### 示例 3:工作流程型 Skill
```markdown
---
name: data-pipeline
description: >
Execute ETL data pipeline with extract, clean, transform, validate,
and load stages. Use when processing raw data into analytics-ready format.
---
# Data Pipeline
## Pipeline Stages
The pipeline consists of 5 sequential stages:
1. **Extract** - Fetch data from sources
2. **Clean** - Remove duplicates and handle nulls
3. **Transform** - Apply business logic
4. **Validate** - Check data quality
5. **Load** - Write to destination
## Running the Pipeline
### Full Pipeline
```bash
python scripts/run_pipeline.py --config pipeline.yaml
Individual Stages
# Run specific stage
python scripts/run_pipeline.py --stage extract
python scripts/run_pipeline.py --stage clean
python scripts/run_pipeline.py --stage transform
Configuration
Edit pipeline.yaml:
source:
type: postgres
connection: postgres://host/db
transform:
rules:
- remove_duplicates
- fill_nulls
- normalize_dates
destination:
type: bigquery
project: my-project
dataset: analytics
Checkpoint Recovery
Pipeline creates checkpoints at each stage:
.pipeline/
├── extract.done
├── clean.done
├── transform.done
├── validate.done
└── load.done
To resume from failure:
python scripts/run_pipeline.py --resume
Monitoring
View logs:
tail -f logs/pipeline.log
Check status:
python scripts/pipeline_status.py
---
## 目录结构模板
### 基础结构
my-skill/ └── SKILL.md
**何时使用**:
- 纯文本指令
- 无需脚本或资源
- 简单工作流程
**示例**:撰写内部沟通、设计指南
---
### 标准结构
my-skill/ ├── SKILL.md ├── scripts/ │ ├── script1.py │ └── script2.sh ├── references/ │ ├── api-docs.md │ └── examples.md └── assets/ ├── template.html └── logo.png
**何时使用**:
- 需要可执行脚本
- 需要参考文档
- 需要模板或资产
**示例**:PDF 编辑、前端构建、品牌应用
---
### 复杂结构
my-skill/ ├── SKILL.md (导航层) ├── scripts/ │ ├── common/ │ │ ├── utils.py │ │ └── config.py │ ├── aws_deploy.py │ ├── gcp_deploy.py │ └── azure_deploy.py ├── references/ │ ├── aws.md │ ├── gcp.md │ ├── azure.md │ ├── common-patterns.md │ └── troubleshooting.md └── assets/ ├── aws/ │ └── cloudformation.yaml ├── gcp/ │ └── deployment.yaml └── azure/ └── arm-template.json
**何时使用**:
- 支持多个变体/框架
- 复杂的目录结构
- 共享资源 + 变体特定资源
**示例**:云部署、多框架前端构建
---
## 资源文件模板
### scripts/ 模板
#### Python 脚本模板
```python
#!/usr/bin/env python3
"""
[脚本功能简短描述]
Usage:
script_name.py <arg1> <arg2> [options]
Examples:
script_name.py input.txt output.txt
script_name.py input.txt output.txt --verbose
"""
import argparse
import sys
import os
def main():
"""主函数"""
parser = argparse.ArgumentParser(
description='[详细描述]',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''
Examples:
%(prog)s input.txt output.txt
%(prog)s input.txt output.txt -v
'''
)
# 必需参数
parser.add_argument('input', help='输入文件路径')
parser.add_argument('output', help='输出文件路径')
# 可选参数
parser.add_argument('-v', '--verbose', action='store_true',
help='显示详细输出')
parser.add_argument('--format', choices=['json', 'csv', 'xml'],
default='json', help='输出格式')
args = parser.parse_args()
# 验证输入
if not os.path.exists(args.input):
print(f"✗ 错误: 文件不存在: {args.input}", file=sys.stderr)
sys.exit(1)
# 执行主逻辑
try:
process(args.input, args.output, args.format, args.verbose)
print(f"✓ 成功: 已保存到 {args.output}")
except Exception as e:
print(f"✗ 错误: {str(e)}", file=sys.stderr)
sys.exit(1)
def process(input_path, output_path, format, verbose):
"""核心处理逻辑"""
if verbose:
print(f"处理 {input_path}...")
# TODO: 实现处理逻辑
if verbose:
print("处理完成")
if __name__ == '__main__':
main()
Bash 脚本模板
#!/usr/bin/env bash
#
# [脚本功能描述]
#
# Usage: script_name.sh <arg1> <arg2>
# Example: script_name.sh input.txt output.txt
set -euo pipefail # 严格模式
# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color
# 使用说明
usage() {
cat << EOF
Usage: $(basename "$0") <input> <output>
Arguments:
input 输入文件
output 输出文件
Options:
-h, --help 显示帮助信息
-v, --verbose 详细输出
Example:
$(basename "$0") input.txt output.txt
EOF
exit 1
}
# 错误处理
error() {
echo -e "${RED}✗ 错误: $1${NC}" >&2
exit 1
}
success() {
echo -e "${GREEN}✓ $1${NC}"
}
# 参数解析
VERBOSE=false
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
usage
;;
-v|--verbose)
VERBOSE=true
shift
;;
*)
break
;;
esac
done
# 验证参数
[[ $# -lt 2 ]] && usage
INPUT="$1"
OUTPUT="$2"
# 验证输入文件
[[ ! -f "$INPUT" ]] && error "文件不存在: $INPUT"
# 主逻辑
$VERBOSE && echo "处理 $INPUT..."
# TODO: 实现处理逻辑
success "已保存到 $OUTPUT"
references/ 模板
API 参考模板
# API Reference
## 目录
- [认证](#认证)
- [核心 API](#核心-api)
- [错误处理](#错误处理)
- [速率限制](#速率限制)
---
## 认证
所有 API 请求需要认证令牌:
```python
import requests
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
response = requests.get('https://api.example.com/v1/users', headers=headers)
核心 API
GET /users
获取用户列表。
端点: GET /v1/users
参数:
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
limit | int | 否 | 返回数量 (默认: 10, 最大: 100) |
offset | int | 否 | 偏移量 (默认: 0) |
filter | string | 否 | 筛选条件 (例: "active") |
响应:
{
"users": [
{
"id": "user_123",
"name": "Alice",
"email": "alice@example.com",
"status": "active"
}
],
"total": 42,
"has_more": true
}
示例:
params = {'limit': 20, 'filter': 'active'}
response = requests.get(
'https://api.example.com/v1/users',
headers=headers,
params=params
)
users = response.json()['users']
POST /users
创建新用户。
端点: POST /v1/users
请求体:
{
"name": "Bob",
"email": "bob@example.com",
"role": "member"
}
响应: 201 Created
{
"id": "user_456",
"name": "Bob",
"email": "bob@example.com",
"role": "member",
"created_at": "2025-01-15T10:30:00Z"
}
错误处理
所有错误返回标准格式:
{
"error": {
"type": "invalid_request_error",
"message": "Email already exists",
"code": "email_duplicate"
}
}
常见错误码:
| HTTP 状态 | 错误类型 | 说明 |
|---|---|---|
| 400 | invalid_request_error | 请求参数无效 |
| 401 | authentication_error | 认证失败 |
| 403 | permission_error | 权限不足 |
| 404 | not_found_error | 资源不存在 |
| 429 | rate_limit_error | 超过速率限制 |
| 500 | api_error | 服务器内部错误 |
速率限制
- 标准账户: 100 请求/分钟
- 专业账户: 1000 请求/分钟
响应头包含限制信息:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 87
X-RateLimit-Reset: 1642248600
---
## 常见场景模板
### 场景 1:简单工具 Skill
**特点**:
- 单一功能
- 无复杂依赖
- 直接操作
**模板**:
simple-tool-skill/ ├── SKILL.md └── scripts/ └── tool.py
**SKILL.md**:
```markdown
---
name: simple-tool
description: [工具功能]. Use when [场景].
---
# Simple Tool
## Usage
```bash
python scripts/tool.py <input> <output>
Examples
[示例1] [示例2]
---
### 场景 2:多步骤工作流 Skill
**特点**:
- 顺序执行
- 状态管理
- 错误恢复
**模板**:
workflow-skill/ ├── SKILL.md ├── scripts/ │ ├── step1.py │ ├── step2.py │ └── run_pipeline.py └── references/ └── workflow-guide.md
**SKILL.md**:
```markdown
---
name: workflow
description: [工作流程描述]. Use for [场景].
---
# Workflow
## Stages
1. Stage 1 - [说明]
2. Stage 2 - [说明]
3. Stage 3 - [说明]
## Running
Full workflow:
```bash
python scripts/run_pipeline.py
Individual stages:
python scripts/step1.py
python scripts/step2.py
Recovery
[检查点和恢复说明]
---
## 验证和打包
### 打包前检查
```bash
# 1. 验证 YAML 语法
python -c "import yaml; yaml.safe_load(open('my-skill/SKILL.md').read().split('---')[1])"
# 2. 检查文件存在
ls my-skill/SKILL.md
ls my-skill/scripts/*.py
ls my-skill/references/*.md
# 3. 测试脚本
python my-skill/scripts/main_script.py --help
# 4. 打包
scripts/package_skill.py my-skill/
验证清单
- [ ] SKILL.md 存在且格式正确
- [ ] YAML 前置元数据完整
- [ ] name 符合命名规范
- [ ] description 包含触发信息
- [ ] 引用的文件都存在
- [ ] 脚本可执行且已测试
- [ ] 无示例文件残留
- [ ] 文档清晰简洁
返回:📋 概览 | Skill Creator | 技能列表