Skills Design Patterns and Best Practices
Skill design patterns distilled from extensive practice can help you make sound decisions quickly when facing new requirements.
This article summarizes the 7 most commonly used design patterns and their applicable scenarios.
Pattern 1: Single-Responsibility Skill
Each Skill does one thing and does it well.
The more focused the functionality, the more precise the description, the higher the trigger accuracy, and the easier the maintenance.
| Approach | Example |
|---|---|
| Correct: single responsibility | pdf-to-text (only responsible for extracting text) |
| Incorrect: mixed responsibilities | pdf-tools (reading, converting, merging, watermarking... all together) |
If you find that a Skill's description needs to be very long to explain what it does not do, it usually means it takes on too many responsibilities and should be split.
Pattern 2: Defensive Input Checking
Perform all input validation centrally at the entry point of the Skill script, then proceed to business logic only after it passes.
Example
File path: scripts/defensive_entry.py
Pattern: Defensive Input Checking - centralized validation at the entry point, pass through after validation
import
sys
import
os
import
json
def
validate
(
args
)
list
:
"""Centrally validate all inputs, return a list of errors (an empty list means all passed)"""
errors
=
[
]
if
not
args.
file
:
errors.
append
(
"Missing parameter --file"
)
elif
not
os
.
path
.
exists
(
args.
file
)
:
errors.
append
(
f
"File does not exist: {args.file}"
)
elif
os
.
path
.
getsize
(
args.
file
)
==
0
:
errors.
append
(
"File content is empty"
)
if
args.
limit
<
1
:
errors.
append
(
"--limit must be greater than 0"
)
return
errors
def
run
(
args
)
:
"""Business logic entry point, called only after validation passes"""
Perform actual processing...
return
{
"status"
:
"success"
,
"file"
: args.
file
}
if
name
==
"main"
:
import
argparse
parser
=
argparse.
ArgumentParser
(
)
parser
.
add_argument
(
"--file"
,
required
=
False
,
default
=
""
)
parser
.
add_argument
(
"--limit"
,
type
=
int
,
default
=
100
)
args
=
parser
.
parse_args
(
)
1. Centralized validation
errors
=
validate
(
args
)
if
errors:
result
=
{
"status"
:
"input_error"
,
"errors"
: errors
}
(
json.
dumps
(
result
,
ensure_ascii
=
False
)
)
sys
.
exit
(
1
)
2. Execute business logic after validation passes
result
=
run
(
args
)
(
json.
dumps
(
result
,
ensure_ascii
=
False
)
)
Pattern 3: Progressive Output
For Skills that take more than 5 seconds, output progress in stages rather than leaving the user facing silent waiting.
## Execution flow (Progressive output example)
### 步骤一:读取文件
After running the reading script, immediately notify the user:
> 已读取文件:runoob_data.csv(1,024 行,8 列)正在进行数据清洗...
### Step 2: Data Cleaning
After cleaning, inform the user:
> 数据清洗完成:删除重复行 3 条,空值填充 12 处。正在生成报告...
### Step 3: Generate Report
After the report is generated, display the download link and describe the content:
> 报告已生成,包含统计摘要和数据质量评估。
Pattern 4: Idempotent Operations
A Skill's execution result should be idempotent: given the same input, the output should be consistent no matter how many times it is executed.
Non-idempotent operations (such as appending content on every execution) cause confusion when users retry.
Example
File path: scripts/idempotent_output.py
import
os
from
datetime
import
datetime
OUTPUT_DIR
=
"/mnt/user-data/outputs"
def
get_output_path
(
base_name:
str
,
suffix:
str
=
".xlsx"
)
str
:
"""
Generate deterministic output paths
Idempotent approach: each execution overwrites the file with the same name (rather than appending or generating new files)
Ensure that the same input always corresponds to the same output file
"""
Approach A: fixed filename (same input always overwrites)
return
os
.
path
.
join
(
OUTPUT_DIR
,
f
"{base_name}_report{suffix}"
)
Approach B (timestamp): generate a new file each time (non-idempotent, but preserves history)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
return os.path.join(OUTPUT_DIR, f"{base_name}_{ts}{suffix}")
Pattern 5: Clear Completion Signal
After a Skill finishes executing, it should give a clear completion signal so the user knows the task is over and no further waiting is needed.
## Output specifications after task completion
Whether successful or failed, the last step must output a clear status line:
On success:
> 任务完成:报告已生成,共处理 1,024 行数据,耗时约 3 秒。
On failure:
> 任务中断:在"数据清洗"步骤遇到错误(原因:文件编码不是 UTF-8)。
> 建议:将文件另存为 UTF-8 格式后重新上传。
Pattern 6: Version Compatibility Declaration
Declare compatible model versions in the frontmatter of SKILL.md to prevent unexpected behavior in unsupported environments.
---
name: data-analyzer
version: 1.2.0
description: 分析 CSV/Excel 数据,生成统计报告。
compatibility:
claude_models:
- claude-sonnet-4-20250514 # 经过验证的模型版本
- claude-opus-4 # 同样支持
python: ">=3.8"
platforms:
- linux # Claude 计算机使用环境
---
Pattern 7: Fail Fast
Once an unrecoverable error is found, stop immediately and report it clearly, rather than continuing with the error and producing meaningless output.
Example
File path: scripts/fail_fast.py
import
sys
import
json
def
assert_condition
(
condition:
bool
,
message:
str
,
hint:
str
=
""
)
:
"""If conditions are not met, output an error immediately and exit (Fail Fast mode)"""
if
not
condition:
result
=
{
"status"
:
"error"
,
"message"
: message
,
"hint"
: hint
}
(
json.
dumps
(
result
,
ensure_ascii
=
False
)
)
sys
.
exit
(
1
)
Perform all pre-checks centrally at the beginning of the script
import
os
file_path
=
sys
.
argv
[
1
]
if
len
(
sys
.
argv
)
1
else
""
assert_condition
(
bool
(
file_path
)
,
"Missing file path parameter"
,
"Usage: python script.py
)
assert_condition
(
os
.
path
.
exists
(
file_path
)
,
f
"File does not exist: {file_path}"
,
"Please check if the path is correct, or re-upload the file"
)
assert_condition
(
file_path.
endswith
(
".csv"
)
,
"File format not supported, expected .csv"
,
f
"Actual file: {file_path}"
)
All checks passed, execute actual logic
(
json.
dumps
(
{
"status"
:
"ok"
,
"file"
: file_path
}
)
)
Pattern Quick Reference
| Mode | Core principles | Problem Solved |
|---|---|---|
| Single Responsibility | One Skill does one thing | Inaccurate triggering, difficult to maintain |
| Defensive input checking | Centralized validation at the entry point | Errors reported only halfway through execution |
| Progressive output | Report progress in stages | User does not know whether it is running |
| Idempotent operations | Same input, same output | Retries produce chaotic results |
| Clear completion signal | Give a terminal notification upon completion | User does not know whether the task is complete |
| Version compatibility declaration | Declare supported runtime environments | Abnormal behavior when environments do not match |
| Fail Fast | Stop immediately upon encountering an error | Continuing with errors produces invalid output |