0%

OpenClaw 技能开发指南:从 Function Calling 到专业工具封装

OpenClaw 技能开发指南:从 Function Calling 到专业工具封装

摘要:技能(Skills)是 OpenClaw AI Agent 的核心扩展机制,通过封装专业工具和能力,让 Agent 能够执行复杂任务。本文详细介绍 OpenClaw 技能开发的全流程:从 SKILL.md 设计规范、工具函数实现、测试验证,到发布共享。包含天气查询、文件转换、图表生成等真实案例,以及性能优化、错误处理、安全加固的最佳实践。

关键词:OpenClaw、技能开发、Function Calling、工具封装、AI Agent、最佳实践


一、背景与价值

1.1 为什么需要技能系统?

LLM 的局限性

1
2
3
4
5
6
7
纯 LLM 能力边界:
- ✅ 文本生成、翻译、总结
- ✅ 代码编写、解释
- ❌ 无法访问外部 API
- ❌ 无法执行系统命令
- ❌ 无法读取/写入文件
- ❌ 无法控制浏览器

技能系统扩展能力

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
graph TB
subgraph "LLM Core"
LLM[大语言模型<br/>文本理解/生成]
end

subgraph "Skill Layer"
S1[天气查询技能]
S2[文件转换技能]
S3[图表生成技能]
S4[浏览器控制技能]
S5[消息发送技能]
end

subgraph "External Tools"
E1[天气 API]
E2[文件系统]
E3[draw.io]
E4[Playwright]
E5[飞书/微信]
end

User[用户请求] --> LLM
LLM -->|Function Call| S1
LLM -->|Function Call| S2
LLM -->|Function Call| S3
LLM -->|Function Call| S4
LLM -->|Function Call| S5

S1 --> E1
S2 --> E2
S3 --> E3
S4 --> E4
S5 --> E5

1.2 技能系统架构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
OpenClaw 技能架构:
┌─────────────────────────────────────────────────────┐
│ User Request │
│ "帮我查一下深圳明天的天气" │
└────────────────────┬────────────────────────────────┘


┌─────────────────────────────────────────────────────┐
│ LLM Processing │
│ 1. 理解意图:天气查询 │
│ 2. 匹配技能:weather │
│ 3. 提取参数:location=深圳,date=明天 │
│ 4. 生成 Function Call │
└────────────────────┬────────────────────────────────┘


┌─────────────────────────────────────────────────────┐
│ Skill Execution │
│ 1. 加载技能文档:skills/weather/SKILL.md │
│ 2. 执行工具函数:get_weather(location, date) │
│ 3. 调用外部 API:wttr.in/深圳 │
│ 4. 格式化结果 │
└────────────────────┬────────────────────────────────┘


┌─────────────────────────────────────────────────────┐
│ Response Generation │
│ "深圳明天天气:晴,18-25°C,东南风 2 级" │
└─────────────────────────────────────────────────────┘

1.3 技能分类

分类 描述 示例 数量
系统技能 OpenClaw 内置 read/write/exec/browser 15+
扩展技能 社区贡献 weather/diagram-maker/ppt-maker 20+
自定义技能 用户私有 公司内部 API/专有工具 N

二、技能设计规范

2.1 SKILL.md 结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 技能名称

## 描述
一句话说明技能用途

## 使用场景
- 场景 1:当用户...
- 场景 2:当需要...

## 工具函数
```python
def function_name(param1: str, param2: int) -> str:
"""函数说明"""
# 实现代码

使用示例

1
2
3
用户:查询深圳天气
Agent:[调用 weather 技能]
结果:深圳今天晴,18-25°C

依赖

  • 依赖 1
  • 依赖 2

注意事项

  • 注意点 1
  • 注意点 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

### 2.2 完整案例:天气技能

```markdown
# weather

## 描述
查询天气和预报,支持全球城市,无需 API Key

## 使用场景
- 用户询问天气、温度、预报
- 需要出行前查看天气状况
- 对比多个城市天气

**不适用场景**:
- ❌ 历史天气数据(仅支持当前 + 预报)
- ❌ 严重天气警报(需专业气象服务)
- ❌ 详细气象分析(需专业工具)

## 工具函数

### get_weather(location: str, days: int = 3) -> str
```python
"""
查询天气

Args:
location: 城市名称(中文/英文)
days: 预报天数(1-3)

Returns:
格式化天气信息
"""
import requests

def get_weather(location: str, days: int = 3):
url = f"https://wttr.in/{location}?format=j1"
response = requests.get(url)
response.raise_for_status()

data = response.json()

# 解析当前天气
current = data['current_condition'][0]
temp_c = current['temp_C']
weather_desc = current['weatherDesc'][0]['value']
humidity = current['humidity']
wind = f"{current['windspeedKmph']} km/h {current['winddir16Point']}"

# 解析预报
forecast = []
for i in range(min(days, 3)):
day = data['weather'][i]
forecast.append({
'date': day['date'],
'max_temp': day['maxtempC'],
'min_temp': day['mintempC'],
'desc': day['avgDesc'][0]['value']
})

# 格式化输出
result = f"🌤️ {location} 天气\n\n"
result += f"当前:{weather_desc} {temp_c}°C\n"
result += f"湿度:{humidity}%\n"
result += f"风力:{wind}\n\n"

if forecast:
result += "📅 预报:\n"
for day in forecast:
result += f"{day['date']}: {day['desc']} {day['min_temp']}~{day['max_temp']}°C\n"

return result

使用示例

1
2
3
4
5
6
7
8
9
10
11
12
用户:深圳明天天气怎么样?
Agent:[调用 get_weather('深圳', days=2)]
结果:
🌤️ 深圳 天气

当前:晴 22°C
湿度:65%
风力:12 km/h 东南

📅 预报:
2026-03-06: 晴 18~25°C
2026-03-07: 多云 19~24°C

依赖

  • requests 库
  • wttr.in API(免费,无需 Key)

注意事项

  • 城市名称支持中文,但英文更准确
  • 最多查询 3 天预报
  • API 限流:每分钟 60 次请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

### 2.3 技能注册

```python
# skills/registry.py

class SkillRegistry:
"""技能注册表"""

def __init__(self):
self.skills = {}

def register(self, name: str, skill_path: str):
"""注册技能"""

# 1. 读取 SKILL.md
skill_doc = Path(skill_path).read_text()

# 2. 解析元数据
metadata = self._parse_metadata(skill_doc)

# 3. 加载工具函数
functions = self._load_functions(skill_path)

# 4. 注册到技能表
self.skills[name] = Skill(
name=name,
description=metadata['description'],
usage_scenarios=metadata['usage_scenarios'],
functions=functions,
dependencies=metadata['dependencies']
)

def get_skill(self, name: str) -> Optional[Skill]:
"""获取技能"""
return self.skills.get(name)

def list_skills(self) -> List[Skill]:
"""列出所有技能"""
return list(self.skills.values())

三、技能开发流程

3.1 需求分析

3.1.1 确定技能边界

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
## 技能定义模板

**技能名称**:{name}

**一句话描述**
这个技能帮助 {目标用户} 在 {场景} 下完成 {任务}

**核心功能**
1. {功能 1}
2. {功能 2}
3. {功能 3}

**非功能**(明确不做的事情):
1. {不做 1}
2. {不做 2}

**成功标准**
- 响应时间 < {X} 秒
- 准确率 > {X}%
- 用户满意度 > {X}%

3.1.2 案例:XMind 生成技能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
## 技能定义:image-to-xmind

**一句话描述**
这个技能帮助内容创作者将图片/文字内容快速转换为 XMind 思维导图

**核心功能**
1. 解析输入内容(图片 OCR / 文字大纲)
2. 生成 XMind 文件结构
3. 应用样式模板(颜色/图标/布局)
4. 输出可编辑的 .xmind 文件

**非功能**
1. 不支持复杂图表(流程图/时序图)
2. 不支持多人协作编辑
3. 不支持 XMind 云同步

**成功标准**
- 生成时间 < 30 秒
- XMind 可正常打开
- 样式完整显示

3.2 实现步骤

3.2.1 创建技能目录

1
2
3
4
5
6
7
8
9
10
# 技能目录结构
skills/image-to-xmind/
├── SKILL.md # 技能文档(必需)
├── generate_xmind.py # 主实现文件
├── templates/ # 模板文件
│ ├── content.xml # XMind 内容模板
│ └── styles.xml # XMind 样式模板
├── tests/ # 测试文件
│ └── test_xmind.py
└── README.md # 使用说明

3.2.2 编写核心逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# skills/image-to-xmind/generate_xmind.py

import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path

class XMindGenerator:
"""XMind 文件生成器"""

def __init__(self, template_dir: str = 'templates'):
self.template_dir = Path(template_dir)
self.content_template = self._load_template('content.xml')
self.styles_template = self._load_template('styles.xml')

def generate(self, content: dict, output_path: str) -> str:
"""
生成 XMind 文件

Args:
content: 思维导图内容(嵌套字典)
output_path: 输出文件路径

Returns:
生成的文件路径
"""
import tempfile

# 1. 创建临时目录
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir = Path(tmpdir)

# 2. 生成 content.xml
content_xml = self._generate_content(content)
(tmpdir / 'content.xml').write_text(content_xml)

# 3. 生成 styles.xml
styles_xml = self._generate_styles(content)
(tmpdir / 'styles.xml').write_text(styles_xml)

# 4. 生成 manifest.xml
manifest = self._generate_manifest()
(tmpdir / 'META-INF' / 'manifest.xml').write_text(manifest)

# 5. 打包为 ZIP(XMind 本质是 ZIP)
output = Path(output_path)
with zipfile.ZipFile(output, 'w', zipfile.ZIP_STORED) as zf:
for file in tmpdir.rglob('*'):
arcname = file.relative_to(tmpdir)
zf.write(file, arcname)

return str(output)

def _generate_content(self, content: dict) -> str:
"""生成 content.xml"""

# 使用模板替换
root_topic = self._build_topic_xml(content)

return self.content_template.replace(
'{{ROOT_TOPIC}}',
ET.tostring(root_topic, encoding='unicode')
)

def _build_topic_xml(self, node: dict) -> ET.Element:
"""构建主题 XML"""

topic = ET.Element('topic')
topic.set('id', node.get('id', 'root'))

# 标题
title = ET.SubElement(topic, 'title')
title.text = node['title']

# 样式
if 'color' in node:
props = ET.SubElement(topic, 'topic-properties')
props.set('svg:fill', node['color'])

# 子主题
if 'children' in node:
children = ET.SubElement(topic, 'children')
for child in node['children']:
child_topic = self._build_topic_xml(child)
children.append(child_topic)

return topic

3.2.3 专家脚本模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# skills/image-to-xmind/generate_xmind-expert.py
# 专家脚本:经过多次迭代优化的最佳实践

"""
XMind 生成专家脚本

使用方式:
1. 修改 content_xml 中的节点内容
2. 修改 styles_xml 中的颜色值(可选)
3. 运行:python3 generate_xmind-expert.py

验证清单:
- [ ] XMind 可正常打开
- [ ] 颜色显示正确
- [ ] 层级结构正确
- [ ] 无乱码/格式错误
"""

import zipfile
from pathlib import Path

# 内容模板(关键:根元素必须是 map,命名空间必须正确)
CONTENT_XML = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<map xmlns="urn:x-mind:map:1.0" xmlns:svg="urn:x-mind:svg:1.0">
<topic id="root">
<title>中心主题</title>
<topic-properties svg:fill="#FFD700"/>
<children>
<topic id="topic-1">
<title>分支主题 1</title>
<topic-properties svg:fill="#FF6B6B"/>
</topic>
<topic id="topic-2">
<title>分支主题 2</title>
<topic-properties svg:fill="#4ECDC4"/>
</topic>
</children>
</topic>
</map>
"""

# 样式模板(关键:必须包含 topic-properties 定义)
STYLES_XML = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<styles xmlns="urn:x-mind:map:1.0" xmlns:svg="urn:x-mind:svg:1.0">
<topic-properties svg:fill="#FFD700"/>
</styles>
"""

# Manifest(关键:不要带 manifest: 前缀)
MANIFEST_XML = """<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0">
<manifest:file-entry manifest:media-type="application/vnd.xmind.workbook" manifest:full-path="/"/>
<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="content.xml"/>
<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="styles.xml"/>
</manifest:manifest>
"""

def generate_xmind(output_path: str = 'output.xmind'):
"""生成 XMind 文件"""

output = Path(output_path)

with zipfile.ZipFile(output, 'w', zipfile.ZIP_STORED) as zf:
zf.writestr('content.xml', CONTENT_XML)
zf.writestr('styles.xml', STYLES_XML)
zf.writestr('META-INF/manifest.xml', MANIFEST_XML)

print(f"✅ XMind 已生成:{output}")
return output

if __name__ == '__main__':
generate_xmind()

3.3 测试验证

3.3.1 单元测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# skills/image-to-xmind/tests/test_xmind.py

import unittest
from pathlib import Path
from generate_xmind import XMindGenerator

class TestXMindGenerator(unittest.TestCase):

def setUp(self):
self.generator = XMindGenerator()
self.test_output = '/tmp/test.xmind'

def test_generate_basic(self):
"""测试基础生成"""

content = {
'id': 'root',
'title': '测试主题',
'children': [
{'id': 'c1', 'title': '子主题 1'},
{'id': 'c2', 'title': '子主题 2'}
]
}

output = self.generator.generate(content, self.test_output)

# 验证文件存在
self.assertTrue(Path(output).exists())

# 验证可以打开
with zipfile.ZipFile(output, 'r') as zf:
self.assertIn('content.xml', zf.namelist())
self.assertIn('styles.xml', zf.namelist())

def test_generate_with_styles(self):
"""测试带样式生成"""

content = {
'id': 'root',
'title': '彩色主题',
'color': '#FF0000',
'children': [
{'id': 'c1', 'title': '红色子主题', 'color': '#FF0000'},
{'id': 'c2', 'title': '蓝色子主题', 'color': '#0000FF'}
]
}

output = self.generator.generate(content, self.test_output)

# 验证样式
with zipfile.ZipFile(output, 'r') as zf:
styles = zf.read('styles.xml').decode()
self.assertIn('#FF0000', styles)
self.assertIn('#0000FF', styles)

def test_open_in_xmind(self):
"""测试在 XMind 中打开(集成测试)"""

# 需要安装 XMind 命令行工具
import subprocess

content = {'id': 'root', 'title': '集成测试'}
output = self.generator.generate(content, self.test_output)

result = subprocess.run(
['xmind', 'open', output],
capture_output=True
)

self.assertEqual(result.returncode, 0)

if __name__ == '__main__':
unittest.main()

3.3.2 验证清单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
## XMind 技能验证清单

### 基础验证
- [ ] 文件可以生成(无报错)
- [ ] 文件大小合理(< 1MB)
- [ ] ZIP 格式正确(可用 unzip 打开)

### 内容验证
- [ ] content.xml 存在且格式正确
- [ ] styles.xml 存在且格式正确
- [ ] manifest.xml 存在且格式正确
- [ ] 根元素是 <map>(不是 <topic>
- [ ] 命名空间正确(urn:x-mind:map:1.0)

### 样式验证
- [ ] 颜色显示正确(在 XMind 中打开)
- [ ] 层级结构正确
- [ ] 无乱码

### 压缩验证
- [ ] ZIP 压缩方式是 Stored(不是 Deflated)
- [ ] 文件列表完整

### 实际测试
- [ ] XMind 桌面版可以打开
- [ ] XMind Web 版可以打开
- [ ] 可以编辑和保存

### 性能测试
- [ ] 生成时间 < 5 秒
- [ ] 内存占用 < 100MB

四、实战案例

4.1 案例 #1:文件转换技能

技能:markdown-converter

功能:将各种文档格式转换为 Markdown

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# skills/markdown-converter/SKILL.md

## 描述
将 PDF/Word/PPT/Excel/图片等转换为 Markdown,使用 markitdown 库

## 使用场景
- 用户需要处理非文本格式文档
- 提取 PDF/Word 中的文字内容
- 图片 OCR 识别
- 音频转录

## 工具函数

```python
def convert_to_markdown(file_path: str) -> str:
"""
转换文件为 Markdown

Args:
file_path: 文件路径

Returns:
Markdown 内容
"""
from markitdown import MarkItDown

md = MarkItDown()
result = md.convert(file_path)
return result.text_content

支持格式

格式 扩展名 支持度
PDF .pdf ✅ 完整
Word .docx ✅ 完整
PowerPoint .pptx ✅ 完整
Excel .xlsx, .xls ✅ 完整
HTML .html ✅ 完整
图片 .jpg, .png ✅ OCR
音频 .mp3, .wav ✅ 转录
ZIP .zip ✅ 解压

使用示例

1
2
3
4
5
6
7
用户:[上传文件:report.pdf] 帮我转成 Markdown
Agent:[调用 convert_to_markdown('report.pdf')]
结果:
# 报告标题

## 摘要
这里是报告内容...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

### 4.2 案例 #2:图表生成技能

#### 技能:diagram-maker

**功能**:使用 draw.io 创建专业图表

```python
# skills/diagram-maker/SKILL.md

## 描述
创建架构图、流程图、序列图等专业图表,支持 draw.io XML 和 Mermaid

## 使用场景
- 系统架构设计
- 业务流程图
- 数据流图
- UML 图

## 工具函数

```python
def create_diagram(
diagram_type: str,
content: dict,
output_format: str = 'png'
) -> str:
"""
创建图表

Args:
diagram_type: 图表类型(architecture/flowchart/sequence)
content: 图表内容描述
output_format: 输出格式(png/svg/pdf)

Returns:
输出文件路径
"""
# 1. 生成 draw.io XML
xml = self._generate_drawio_xml(diagram_type, content)

# 2. 保存为 .drawio 文件
drawio_path = self._save_drawio(xml)

# 3. 导出为目标格式
output_path = self._export(drawio_path, output_format)

return output_path

使用示例

1
2
3
4
5
6
用户:帮我画一个微服务架构图
Agent:[调用 create_diagram('architecture', {...})]
结果:
✅ 架构图已生成:/path/to/architecture.png

![微服务架构图](architecture.png)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

### 4.3 案例 #3:PPT 生成技能

#### 技能:ppt-maker

**功能**:专业 PPT 创建和编辑

```python
# skills/ppt-maker/SKILL.md

## 描述
创建专业 PPT 演示文稿,支持模板、内容格式化、专业排版

## 使用场景
- 工作汇报 PPT
- 产品演示 PPT
- 培训材料 PPT
- 学术论文 PPT

## 工具函数

```python
def create_ppt(
title: str,
slides: list,
template: str = 'default'
) -> str:
"""
创建 PPT

Args:
title: PPT 标题
slides: 幻灯片内容列表
template: 模板名称

Returns:
PPT 文件路径
"""
from pptx import Presentation

prs = Presentation(template)

# 标题页
slide = prs.slides.add_slide(prs.slide_layouts[0])
slide.shapes.title.text = title

# 内容页
for slide_content in slides:
slide = prs.slides.add_slide(prs.slide_layouts[1])
slide.shapes.title.text = slide_content['title']
slide.shapes.placeholders[1].text = slide_content['content']

# 保存
output_path = f'{title}.pptx'
prs.save(output_path)

return output_path

注意事项

⚠️ 质量限制

  • python-pptx 生成的 PPT 质量一般
  • 建议使用模板或 LibreOffice 提升质量
  • 复杂排版建议手动调整
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

### 4.4 案例 #4:MinIO 文件管理技能

#### 技能:minio-manager

**功能**:MinIO 云存储文件上传下载

```python
# skills/minio-manager/SKILL.md

## 描述
MinIO 文件上传下载管理,支持 S3 兼容 API

## 使用场景
- 上传文件到云存储
- 生成分享链接
- 下载文件
- 列出文件

## 配置

```json
{
"endpoint": "https://img.sharezone.cn",
"access_key": "minioadminjohn",
"secret_key": "Adbdedkkf@12321",
"buckets": {
"imageproxy/claw/": "公开图片(永久有效)",
"nanwang/": "文档资料(7 天分享链接)"
}
}

工具函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def upload_file(
file_path: str,
bucket: str = 'nanwang',
public: bool = False
) -> dict:
"""
上传文件

Args:
file_path: 文件路径
bucket: 桶名称
public: 是否公开

Returns:
{
'url': '分享链接',
'expires': '过期时间'
}
"""
import boto3

s3 = boto3.client(
's3',
endpoint_url=config['endpoint'],
aws_access_key_id=config['access_key'],
aws_secret_access_key=config['secret_key']
)

# 上传
file_name = Path(file_path).name
s3.upload_file(file_path, bucket, file_name)

# 生成分享链接
if public:
url = f"{config['endpoint']}/{bucket}/{file_name}"
expires = '永久'
else:
url = s3.generate_presigned_url(
'get_object',
Params={'Bucket': bucket, 'Key': file_name},
ExpiresIn=604800 # 7 天
)
expires = '7 天'

return {'url': url, 'expires': expires}

使用示例

1
2
3
4
5
6
7
8
用户:[上传文件:report.pdf]
Agent:[调用 upload_file('report.pdf', bucket='nanwang')]
结果:
✅ 文件已上传

📄 report.pdf
🔗 https://img.sharezone.cn/nanwang/report.pdf?X-Amz-...
⏰ 有效期:7 天
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

---

## 五、性能优化

### 5.1 缓存策略

```python
class SkillCache:
"""技能缓存层"""

def __init__(self, ttl: int = 3600):
self.cache = {}
self.ttl = ttl

def get(self, key: str) -> Optional[Any]:
"""获取缓存"""
if key in self.cache:
entry = self.cache[key]
if time.time() - entry['timestamp'] < self.ttl:
return entry['data']
else:
del self.cache[key]
return None

def set(self, key: str, data: Any):
"""设置缓存"""
self.cache[key] = {
'data': data,
'timestamp': time.time()
}

# 使用示例
@cache_result(ttl=300)
def get_weather(location: str) -> str:
"""天气查询(带 5 分钟缓存)"""
# ...

5.2 异步执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
async def execute_skill_async(skill_name: str, **kwargs):
"""异步执行技能"""

loop = asyncio.get_event_loop()

# 将阻塞操作放到线程池
result = await loop.run_in_executor(
None,
lambda: execute_skill(skill_name, **kwargs)
)

return result

# 使用示例
async def handle_user_request(message: Message):
"""处理用户请求"""

# 并行执行多个技能
tasks = [
execute_skill_async('weather', location='深圳'),
execute_skill_async('calendar', date='today'),
execute_skill_async('todos', user='john')
]

results = await asyncio.gather(*tasks)

# 合并结果
response = merge_results(results)
return response

5.3 批量处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def batch_process_files(files: List[str], batch_size: int = 10):
"""批量处理文件"""

results = []

for i in range(0, len(files), batch_size):
batch = files[i:i + batch_size]

# 并行处理批次
batch_results = parallel_map(
convert_to_markdown,
batch,
max_workers=4
)

results.extend(batch_results)

# 进度反馈
progress = (i + len(batch)) / len(files) * 100
log(f"进度:{progress:.1f}%")

return results

六、错误处理

6.1 异常分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class SkillError(Exception):
"""技能错误基类"""
pass

class SkillNotFoundError(SkillError):
"""技能未找到"""
pass

class SkillExecutionError(SkillError):
"""技能执行失败"""
pass

class SkillTimeoutError(SkillError):
"""技能执行超时"""
pass

class SkillValidationError(SkillError):
"""参数验证失败"""
pass

6.2 错误处理模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def execute_with_retry(
skill_name: str,
max_retries: int = 3,
timeout: int = 30
):
"""带重试的执行"""

for attempt in range(max_retries):
try:
# 设置超时
with timeout_context(timeout):
result = execute_skill(skill_name)
return result

except SkillTimeoutError as e:
if attempt == max_retries - 1:
raise
log(f"超时,重试 {attempt + 1}/{max_retries}")
time.sleep(2 ** attempt)

except SkillExecutionError as e:
# 执行错误不重试,直接返回友好错误
return format_error_for_user(e)

except Exception as e:
# 未知错误,记录日志
log.error(f"未知错误:{e}", exc_info=True)
if attempt == max_retries - 1:
raise
time.sleep(1)

raise SkillExecutionError("多次重试后仍失败")

6.3 用户友好错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def format_error_for_user(error: Exception) -> str:
"""格式化错误为用户友好消息"""

error_templates = {
SkillNotFoundError: "❌ 技能 '{skill}' 不存在,请检查技能名称",
SkillTimeoutError: "⏱️ 操作超时,请稍后重试或联系管理员",
SkillValidationError: "⚠️ 参数错误:{message}",
SkillExecutionError: "🔧 执行失败:{message}\n\n建议:{suggestion}",
}

template = error_templates.get(type(error), "❌ 发生错误:{message}")

return template.format(
skill=getattr(error, 'skill_name', 'unknown'),
message=str(error),
suggestion=get_suggestion(error)
)

七、安全加固

7.1 权限控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class SkillPermissions:
"""技能权限控制"""

def __init__(self):
self.permissions = {
'read': ['user', 'admin'],
'write': ['admin'],
'exec': ['user', 'admin'],
'delete': ['admin']
}

def check_permission(self, user_role: str, action: str) -> bool:
"""检查权限"""
allowed_roles = self.permissions.get(action, [])
return user_role in allowed_roles

# 使用示例
@require_permission('write')
def write_file(path: str, content: str):
"""写入文件(需要写权限)"""
# ...

7.2 输入验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def validate_input(params: dict, schema: dict) -> ValidationResult:
"""验证输入参数"""

errors = []

for field, rules in schema.items():
value = params.get(field)

# 必需字段检查
if rules.get('required') and value is None:
errors.append(f"字段 '{field}' 是必需的")
continue

# 类型检查
if value is not None and not isinstance(value, rules['type']):
errors.append(f"字段 '{field}' 类型错误,期望 {rules['type'].__name__}")
continue

# 范围检查
if 'min' in rules and value < rules['min']:
errors.append(f"字段 '{field}' 值过小,最小值 {rules['min']}")

if 'max' in rules and value > rules['max']:
errors.append(f"字段 '{field}' 值过大,最大值 {rules['max']}")

return ValidationResult(
valid=len(errors) == 0,
errors=errors
)

7.3 敏感信息保护

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def sanitize_output(output: str) -> str:
"""清理输出中的敏感信息"""

# 移除 API Key
output = re.sub(r'api[_-]?key[=:]\s*\S+', '[REDACTED]', output, flags=re.I)

# 移除密码
output = re.sub(r'password[=:]\s*\S+', '[REDACTED]', output, flags=re.I)

# 移除 Token
output = re.sub(r'token[=:]\s*\S+', '[REDACTED]', output, flags=re.I)

# 移除私钥
output = re.sub(r'-----BEGIN.*?-----.*?-----END.*?-----', '[REDACTED]', output, flags=re.DOTALL)

return output

八、最佳实践

8.1 设计原则

原则 说明 示例
单一职责 一个技能只做一件事 weather 只查天气
明确边界 清楚定义做什么/不做什么 不支持历史天气
错误友好 错误信息清晰可操作 “参数 X 缺失,请提供 Y”
性能优先 响应时间 < 3 秒 使用缓存/异步
安全默认 默认最小权限 需要显式授权

8.2 文档规范

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
## 好的 SKILL.md

- ✅ 一句话清晰描述用途
- ✅ 明确使用场景和不适用场景
- ✅ 完整的函数签名和参数说明
- ✅ 至少 2 个使用示例
- ✅ 依赖和注意事项
- ✅ 常见问题解答

## 避免的问题

- ❌ 描述模糊不清
- ❌ 没有使用示例
- ❌ 参数说明不完整
- ❌ 没有错误处理说明
- ❌ 缺少依赖说明

8.3 测试策略

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 测试金字塔

# 1. 单元测试(70%)
def test_weather_api_call():
"""测试 API 调用"""
# ...

# 2. 集成测试(20%)
def test_weather_end_to_end():
"""测试端到端流程"""
# ...

# 3. 性能测试(10%)
def test_weather_latency():
"""测试响应延迟"""
# ...

九、踩坑记录

9.1 问题 #1:XMind 颜色不显示

现象

生成的 XMind 文件可以打开,但颜色不显示。

根因

  1. ZIP 压缩方式错误(用了 Deflated 而非 Stored)
  2. 样式属性格式错误(用 fill-color 而非 topic-properties svg:fill)

解决方案

1
2
3
4
5
# 错误 ❌
zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED)

# 正确 ✅
zipfile.ZipFile(output, 'w', zipfile.ZIP_STORED)

9.2 问题 #2:技能执行超时

现象

大文件转换时经常超时。

解决方案

1
2
3
4
5
6
7
8
9
10
11
12
# 1. 增加超时时间
@timeout(300) # 5 分钟

# 2. 异步执行
async def convert_large_file():
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, convert, file)

# 3. 进度反馈
def convert_with_progress(file):
for chunk in process_chunks(file):
yield_progress(chunk)

9.3 问题 #3:技能冲突

现象

多个技能处理相同意图,导致 LLM 选择错误。

解决方案

1
2
3
4
5
6
7
## 技能描述优化

# 模糊描述 ❌
"处理文件"

# 清晰描述 ✅
"将 PDF/Word/PPT/Excel转换为Markdown格式"

十、参考资料

10.1 官方文档

10.2 示例技能

1
2
3
4
5
6
7
skills/
├── weather/
├── diagram-maker/
├── ppt-maker/
├── minio-manager/
├── markdown-converter/
└── image-to-xmind/

10.3 相关工具


作者:John
职位:高级技术架构师
日期:2026-03-06
版本:v1.0

本文基于 OpenClaw 技能开发真实经验编写,包含多个生产环境技能的完整实现。技能是 AI Agent 扩展能力的核心,值得深入设计和持续优化。