作者视角:资深架构师
目标读者:希望掌握 Agent Skills 的开发者、技术负责人
文档定位:入门级教程,但包含架构设计的深度思考
在传统的 AI 应用开发中,我们通常通过以下方式扩展 AI 的能力:
这些方式虽然有效,但存在明显的问题:
Agent Skills 正是为了解决这些问题而诞生的。它是一套标准化的能力封装规范,将领域知识、工作流程和工具脚本打包成可复用的"技能包"。
Agent Skills 是:
一种模块化、自包含的能力包,通过提供专业化的知识、工作流程和工具,扩展 AI 的能力。它就像特定领域或任务的"入职培训指南",将 Claude 从通用智能体转变为具备专业知识的专家智能体。
为了更好地理解 Agent Skills,让我们对比一下它与传统方式的区别:
| 特性 | Agent Skills | System Prompt | Tool Calling |
|---|---|---|---|
| 触发方式 | 模型自动识别(基于语义匹配) | 始终加载 | 模型主动调用 |
| 加载时机 | 按需加载(渐进式) | 对话开始时加载 | 执行时调用 |
| 组织方式 | 标准化目录结构 | 文本块 | 函数/API |
| 可复用性 | 高(跨项目、跨团队) | 低(项目特定) | 中(需要集成) |
| 维护成本 | 低(独立维护) | 高(分散在各处) | 中(需要版本管理) |
想象一下:
例如,一个 maven-search 技能不仅告诉 AI 如何搜索 Maven 依赖,还提供了:
假设你是一个 Java 开发者,经常需要:
pom.xml 的依赖代码传统方式:
每次都需要:
这个过程需要 3-5 分钟,而且容易出错。
使用 Agent Skills:
只需要对 AI 说:"帮我查找 Spring Boot 的最新版本",AI 会自动:
maven-search 技能整个过程只需 5 秒钟,而且结果准确可靠。
Agent Skills 带来的核心价值包括:
Agent Skills 的核心创新在于渐进式披露(Progressive Disclosure)机制。它通过三层加载,在"强大能力"和"低延迟/节省 Token"之间取得平衡:
┌─────────────────────────────────────────┐
│ Level 1: 元数据(Metadata) │
│ - 始终加载(~100 tokens) │
│ - 用于技能路由和触发判断 │
└─────────────────────────────────────────┘
↓
┌─────────────────────────────────────────┐
│ Level 2: 核心指令(SKILL.md) │
│ - 技能触发后加载(<5k tokens) │
│ - 包含工作流程和操作指南 │
└─────────────────────────────────────────┘
↓
┌─────────────────────────────────────────┐
│ Level 3: 配套资源(Bundled Resources) │
│ - 按需加载(scripts/references/assets) │
│ - 提供工具和详细文档 │
└─────────────────────────────────────────┘
作用:技能的路由决策层
内容:YAML Frontmatter 中的 name 和 description
特点:
示例:
---
name: maven-search
description: |
Provides comprehensive guidance for searching and retrieving Maven
components from Maven Central Repository. Use when the user needs
to find, verify, or retrieve Maven dependencies, check component
versions, analyze dependency trees, or work with Maven coordinates.
---
关键点:
description 是唯一的触发机制作用:技能的行动纲领
内容:详细的工作流程、决策矩阵、操作步骤
特点:
示例结构:
# Maven Search Skill
## When to use this skill
**ALWAYS use this skill when the user mentions:**
- Searching for Maven dependencies
- Finding Maven coordinates
- Checking component versions
## How to use this skill
1. Identify the search type from user's request
2. Load the appropriate example from `examples/` directory
3. Execute the workflow using scripts
4. Present results in a clear format
## Best Practices
- Always validate coordinates
- Specify version explicitly
- Provide clear output
作用:提供工具和详细文档
内容:
scripts/:可执行脚本(Python/Bash 等)references/:参考文档(API 文档、规范等)assets/:静态资源(模板、图标等)特点:
示例:
maven-search/
├── SKILL.md
├── scripts/
│ └── search_maven.py # 搜索脚本
├── references/
│ └── maven-coordinates.md # Maven 坐标规范
└── assets/
└── pom-template.xml # POM 模板
一个符合规范的 Agent Skill 目录结构如下:
skill-name/
├── SKILL.md # 必需:技能定义和说明
├── LICENSE.txt # 必需:许可证文件
├── examples/ # 可选:使用示例
│ ├── example-1.md
│ └── example-2.md
├── api/ # 可选:API 参考文档
│ └── api-reference.md
├── reference/ # 可选:领域知识库
│ ├── standards.md
│ └── best-practices.md
├── templates/ # 可选:输出模板
│ └── template-1.md
├── scripts/ # 可选:可执行脚本
│ └── script.py
└── assets/ # 可选:资源文件(不加载到上下文)
└── logo.png
SKILL.md 是技能的核心文件,包含两部分:
---
name: skill-name # 必需:技能名称(kebab-case)
description: | # 必需:技能描述(触发机制)
Comprehensive description of what this skill does and when to use it.
Use when the user needs to...
license: Complete terms in LICENSE.txt # 可选:许可证说明
---
关键要点:
description 是唯一的触发机制# Skill Title
## When to use this skill
**ALWAYS use this skill when the user mentions:**
- [明确的触发场景 1]
- [明确的触发场景 2]
## How to use this skill
1. **Identify the task type** from user's request
2. **Load the appropriate example** from `examples/` directory
3. **Follow the specific instructions** in that example
4. **Execute the workflow** using scripts or tools
5. **Present the results** in a clear format
## Best Practices
[最佳实践和注意事项]
## Keywords
**English keywords:**
[关键词列表]
**Chinese keywords:**
[中文关键词列表]
用途:执行确定性任务或重复性代码
何时包含:
示例:
#!/usr/bin/env python3
"""Maven Central Repository 搜索脚本"""
import requests
import json
import sys
def search_maven(query, limit=10):
"""搜索 Maven Central Repository"""
url = "https://search.maven.org/solrsearch/select"
params = {"q": query, "rows": limit, "wt": "json"}
response = requests.get(url, params=params)
return response.json()
if __name__ == "__main__":
query = sys.argv[1]
results = search_maven(query)
print(json.dumps(results, indent=2))
用途:提供领域知识和详细文档
何时包含:
示例:
# Maven 坐标参考
## 坐标格式
Maven 坐标由三部分组成:
- `groupId`:组织标识
- `artifactId`:项目标识
- `version`:版本号
## 版本规范
- **发布版本**:遵循语义化版本(SemVer)
- **快照版本**:以 `-SNAPSHOT` 结尾
用途:提供输出模板和静态资源
何时包含:
特点:
假设你经常需要让 AI 审查代码,希望它遵循特定的审查标准。让我们创建一个 code-review 技能。
mkdir -p code-review/{examples,reference,scripts}
cd code-review
---
name: code-review
description: |
Provides comprehensive code review guidance following industry best practices.
Use when the user asks for code review, code quality check, or code improvement
suggestions. This skill covers security, performance, maintainability, and
best practices for various programming languages.
license: Complete terms in LICENSE.txt
---
# Code Review Skill
## When to use this skill
**ALWAYS use this skill when the user mentions:**
- Code review
- Code quality check
- Code improvement
- Code refactoring suggestions
- Security vulnerabilities
- Performance issues
- Code style violations
**Trigger phrases include:**
- "审查这段代码" (review this code)
- "检查代码质量" (check code quality)
- "代码有什么问题" (what's wrong with this code)
- "如何改进这段代码" (how to improve this code)
## How to use this skill
**CRITICAL: This skill should be triggered when the user provides code and asks for review or improvement.**
1. **Identify the programming language** from the code
2. **Load the appropriate review checklist** from `reference/` directory
3. **Analyze the code** against the checklist:
- Security vulnerabilities
- Performance issues
- Code style and maintainability
- Best practices
4. **Provide structured feedback**:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (nice to have)
5. **Provide code examples** for improvements when applicable
## Review Checklist
Refer to `reference/review-checklist.md` for detailed checklists by language.
## Best Practices
1. **Be constructive**: Focus on improvement, not criticism
2. **Prioritize issues**: Critical > Warning > Suggestion
3. **Provide examples**: Show how to fix issues
4. **Consider context**: Understand the code's purpose before reviewing
## Keywords
**English keywords:**
code review, code quality, code inspection, code analysis, refactoring, security audit, performance review, code style, best practices, code smell, technical debt
**Chinese keywords:**
代码审查, 代码质量, 代码检查, 代码分析, 重构, 安全审计, 性能审查, 代码风格, 最佳实践, 代码异味, 技术债务
reference/review-checklist.md:
# Code Review Checklist
## Security
- [ ] Input validation
- [ ] SQL injection prevention
- [ ] XSS prevention
- [ ] Authentication and authorization
- [ ] Sensitive data exposure
- [ ] Dependency vulnerabilities
## Performance
- [ ] Algorithm efficiency
- [ ] Database query optimization
- [ ] Caching strategies
- [ ] Resource cleanup
- [ ] Memory leaks
## Maintainability
- [ ] Code readability
- [ ] Function complexity
- [ ] Code duplication
- [ ] Naming conventions
- [ ] Documentation
examples/java-review.md:
# Java Code Review Example
## Input
java public String getUserData(int userId) {
String sql = "SELECT * FROM users WHERE id = " + userId;
return db.execute(sql);
}
## Review Points
1. **Security**: SQL injection vulnerability
2. **Best Practice**: Use prepared statements
3. **Return Type**: Should return User object, not String
## Improved Code
java public User getUserData(int userId) {
String sql = "SELECT * FROM users WHERE id = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setInt(1, userId);
ResultSet rs = stmt.executeQuery();
// Map result to User object
return userMapper.map(rs);
}
LICENSE.txt:
Apache License 2.0
[完整的许可证文本]
~/.claude/skills/)code-review 技能description 是技能的唯一触发机制,必须精心设计:
好的示例:
description: |
Provides comprehensive guidance for searching and retrieving Maven
components from Maven Central Repository. Use when the user needs
to find, verify, or retrieve Maven dependencies, check component
versions, analyze dependency trees, or work with Maven coordinates.
不好的示例:
description: Maven search tool # 太简单,缺乏触发条件
设计原则:
原则:Claude 已经很聪明,只添加它不知道的信息
做法:
reference/ 或 examples/ 中示例:
# 好的写法
Extract text with pdfplumber. See [FORMS.md](reference/FORMS.md) for form filling.
# 不好的写法
This skill uses pdfplumber library which is a Python library for extracting
text from PDF files. It supports various features including form filling,
text extraction, and more. For form filling, you need to...
原则:不要创建"万能技能",遵循单一职责原则
好的设计:
git-standard-commit:标准化 Git 提交jira-issue-updater:更新 Jira 工单maven-search:搜索 Maven 依赖不好的设计:
developer-toolkit:包含所有开发工具(太大、难以触发)原则:LLM 擅长推理,但不擅长精确计算
做法:
示例:
# 使用脚本计算,而不是让 AI 计算
def calculate_compound_interest(principal, rate, years):
return principal * (1 + rate) ** years
原则:按需加载,节省 Token
做法:
reference/examples/assets/个人级技能:
~/.claude/skills/项目级技能:
.claude/skills/(项目根目录)可能原因:
description 不够明确解决方案:
description,添加更多触发关键词可能原因:
description 太宽泛解决方案:
description 更具体description解决方案:
reference/ 目录示例:
# 核心工作流程
1. Identify task type
2. Load appropriate reference: See [API.md](reference/API.md)
3. Execute workflow
方法:
可以,但需要注意:
示例:
import os
import requests
def call_api(endpoint, params):
api_key = os.getenv('API_KEY') # 从环境变量读取
headers = {'Authorization': f'Bearer {api_key}'}
response = requests.get(endpoint, params=params, headers=headers)
return response.json()
官方文档:
示例技能:
mermaid、maven-search 等技能最佳实践:
skill-creator 技能的详细指南Agent Skills 不仅仅是一种功能扩展方式,更是一种从"指令驱动"向"能力工程"演进的范式转变。它通过标准化的能力封装,让 AI 能够:
作为架构师,掌握 Agent Skills 是构建企业级 AI 应用的必经之路。通过精心设计的技能,我们可以:
现在,开始创建你的第一个 Agent Skill 吧!
文档版本:1.0.0
最后更新:2024-12-19
维护者:Full-Stack-Skills Team
相关资源: