Skill 是什么?
Skill 是 OpenClaw 的扩展能力单元。每个 Skill 为 AI 模型提供一组工具(Tools),模型根据对话上下文自动决定是否调用。例如 Web Search Skill 让 AI 具备搜索能力,Calendar Skill 让 AI 能管理日程。
项目初始化
使用脚手架快速创建 Skill 项目:
clawhub create my-skill
cd my-skill
生成的目录结构:
my-skill/
├── package.json
├── src/
│ └── index.ts # 入口文件
├── manifest.json # Skill 元数据
└── README.md
manifest.json
元数据文件定义了 Skill 的基本信息:
{
"name": "my-skill",
"version": "1.0.0",
"displayName": "My Custom Skill",
"description": "A brief description of what this skill does",
"author": "your-name",
"category": "工具",
"config": {
"apiKey": {
"type": "string",
"required": true,
"description": "API 密钥"
},
"maxResults": {
"type": "number",
"default": 10,
"description": "最大返回数量"
}
}
}
config 字段定义了用户在 openclaw.json5 中需要填写的配置项。
编写 Skill 逻辑
打开 src/index.ts,核心是导出一组 Tool 定义:
import { defineTool, SkillContext } from "@openclaw/skill-sdk";
// 定义一个工具
const searchTool = defineTool({
name: "search_items",
description: "根据关键词搜索项目列表",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "搜索关键词"
},
limit: {
type: "number",
description: "返回数量上限"
}
},
required: ["query"]
},
async execute(params, ctx: SkillContext) {
const { query, limit = ctx.config.maxResults } = params;
const apiKey = ctx.config.apiKey;
const response = await fetch(`https://api.example.com/search?q=${query}&limit=${limit}`, {
headers: { Authorization: `Bearer ${apiKey}` }
});
const data = await response.json();
return {
content: data.results.map(item => ({
title: item.title,
url: item.url,
summary: item.summary
}))
};
}
});
// 可以定义多个工具
const detailTool = defineTool({
name: "get_item_detail",
description: "获取某个项目的详细信息",
parameters: {
type: "object",
properties: {
id: { type: "string", description: "项目 ID" }
},
required: ["id"]
},
async execute(params, ctx: SkillContext) {
const response = await fetch(`https://api.example.com/items/${params.id}`, {
headers: { Authorization: `Bearer ${ctx.config.apiKey}` }
});
return await response.json();
}
});
// 导出所有工具
export default [searchTool, detailTool];
本地调试
在本地测试 Skill:
# 安装依赖
npm install
# 启动开发模式
clawhub dev
# 或链接到本地 OpenClaw 实例
clawhub link
openclaw gateway
clawhub dev 会启动一个本地调试环境,你可以在终端中模拟 AI 调用你的工具。
配置 Schema 验证
Skill SDK 会自动根据 manifest.json 中的 config 定义验证用户配置。如果缺少必填项,网关启动时会报错:
[skill:my-skill] Config validation failed: "apiKey" is required
错误处理
在工具执行中抛出错误,OpenClaw 会将错误信息反馈给 AI 模型:
async execute(params, ctx) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`API 请求失败: ${response.status} ${response.statusText}`);
}
return await response.json();
}
AI 收到错误后可能会尝试修正参数并重试,或直接告知用户。
发布到 ClawHub
开发完成后,发布到技能市场:
# 登录 ClawHub
clawhub login
# 发布
clawhub publish
发布前确保:
manifest.json中的信息完整准确README.md包含使用说明和配置示例- 代码中不包含硬编码的密钥或敏感信息
- 至少包含基本的错误处理
最佳实践
- 工具命名清晰:AI 根据
name和description决定何时调用,描述要准确 - 参数描述详细:每个参数都写清楚
description,帮助 AI 正确传参 - 控制返回量:避免返回过大的数据,会消耗模型上下文窗口
- 幂等设计:AI 可能对同一工具重复调用,确保不会产生副作用
- 超时处理:外部 API 调用加上合理的超时时间