OpenClaw 技能开发:构建可复用的智能体工具

OpenClaw 真正的威力不在于平台本身——而在于您所构建的技能。技能是智能体可以调用的可复用工具,能够扩展内置功能之外的能力,并解决特定领域的问题。
可以把 OpenClaw 想象成 iPhone:手机本身很有用,但真正让它强大的是各种应用。技能就是您的应用。
什么是 OpenClaw 技能?
电脑上的软件代码——示意图
技能是一个独立的模块,包含:
- 定义:技能的功能以及所需的输入
- 处理程序:执行任务的代码
- 验证:有效输入的规则
- 错误处理:如何应对失败
- 文档:让智能体了解何时/如何使用该技能
简单示例——一个分析情感倾向的技能:
module.exports = {
name: "sentiment-analysis",
description: "Analyze the emotional tone of text",
inputs: {
text: {
type: "string",
description: "Text to analyze",
required: true
}
},
outputs: {
sentiment: "enum:positive|negative|neutral",
confidence: "number",
reasoning: "string"
},
handler: async (inputs, context) => {
const response = await claude.ask(`
Analyze sentiment: ${inputs.text}
Respond in JSON: { sentiment, confidence, reasoning }
`);
return JSON.parse(response);
}
};
智能体会在其能力列表中看到该技能,并在相关时调用它:
- "我需要了解客户的情绪倾向"
- 智能体自动调用 sentiment-analysis 技能
- 获得结构化输出,继续工作流程
技能模式 1:简单的数据转换
人工智能图形
最简单的技能是适配器——接收数据、进行转换、返回结构化输出。
// Format raw notes into structured record
module.exports = {
name: "parse-meeting-notes",
description: "Convert raw meeting notes into structured format",
inputs: {
notes: { type: "string", description: "Raw meeting notes" }
},
outputs: {
attendees: "array:string",
topics: "array:object",
decisions: "array:string",
actionItems: "array:object"
},
handler: async (inputs) => {
const prompt = `Parse these meeting notes into structured format.
Respond with JSON:
{
"attendees": ["person1", "person2"],
"topics": [
{ "title": "...", "duration": "..." }
],
"decisions": ["decision 1", "decision 2"],
"actionItems": [
{ "owner": "...", "task": "...", "deadline": "..." }
]
}
Notes:
${inputs.notes}`;
const response = await claude.ask(prompt);
return JSON.parse(response);
}
};
此模式适用于:
- 转换格式(CSV→JSON、非结构化→结构化)
- 从文档中提取数据
- 对项目进行分类
- 文本摘要
技能模式 2:API 集成封装
电脑上的软件代码——示意图
封装 API,让智能体安全而智能地使用它们:
// Slack integration skill
module.exports = {
name: "send-slack-message",
description: "Send a message to a Slack channel",
inputs: {
channel: { type: "string", description: "#channel or @user" },
message: { type: "string", description: "Message to send" },
thread_ts: { type: "string", description: "Optional: reply in thread" }
},
handler: async (inputs, context) => {
// Validate channel name
if (!inputs.channel.match(/^[#@]/)) {
throw new Error("Channel must start with # or @");
}
// Rate limiting
const sentRecently = await checkRateLimit(context.agentId);
if (sentRecently > 10) {
throw new Error("Rate limit: max 10 messages per hour");
}
// Call Slack API
const response = await slackApi.postMessage({
channel: inputs.channel,
text: inputs.message,
thread_ts: inputs.thread_ts
});
return {
success: true,
channelId: response.channel,
timestamp: response.ts
};
}
};
直接访问 API 的优势:
- 速率限制(防止滥用)
- 验证(智能体无法发送无效请求)
- 错误恢复(优雅地处理 API 故障)
- 日志记录(追踪智能体的操作)
- 权限管理(控制哪些智能体可以使用哪些 API)
技能模式 3:多步骤工作流技能
电脑上的软件代码——示意图
复杂的工作流可以变成可复用的技能:
// "获取客户信息"可能涉及多个步骤
module.exports = {
name: "get-customer-info",
description: "Retrieve all relevant customer data",
inputs: {
customerId: { type: "string", required: true }
},
outputs: {
profile: "object",
recentOrders: "array",
supportHistory: "array",
churnRisk: "boolean"
},
handler: async (inputs) => {
// 步骤 1:获取基本档案
const profile = await database.customers.get(inputs.customerId);
// 步骤 2:获取近期订单
const orders = await database.orders.query({
customerId: inputs.customerId,
limit: 10,
sort: "date desc"
});
// 步骤 3:获取客服历史记录
const support = await database.support.query({
customerId: inputs.customerId,
limit: 5
});
// 步骤 4:分析流失风险
const riskAnalysis = await claude.ask(`
Based on this customer data, assess churn risk:
Profile: ${JSON.stringify(profile)}
Recent orders: ${orders.length > 0 ? 'active' : 'inactive'}
Support issues: ${support.length}
Is this customer at risk of churning? (respond: true/false)
`);
return {
profile,
recentOrders: orders,
supportHistory: support,
churnRisk: riskAnalysis.includes("true")
};
}
};
智能体无需了解所有这些步骤,只需调用一个在内部处理一切的技能即可。
技能模式 4:上下文感知决策
电脑上的软件代码——示意图
有些技能应当基于细微差别而非僵化的逻辑来做决策:
// 确定针对客户请求的适当处理方式
module.exports = {
name: "classify-customer-request",
description: "Determine how to handle a customer request",
inputs: {
request: { type: "string", description: "Customer message" },
customerHistory: { type: "string", description: "Customer profile" }
},
outputs: {
category: "enum:refund|replacement|support|escalate",
reasoning: "string",
recommendedAction: "string"
},
handler: async (inputs) => {
const decision = await claude.ask(`
You're a customer service decision engine.
Request: "${inputs.request}"
Customer history: ${inputs.customerHistory}
How should this be handled?
Respond in JSON:
{
"category": "refund|replacement|support|escalate",
"reasoning": "why this category",
"recommendedAction": "specific next step"
}
`);
return JSON.parse(decision);
}
};
Claude 会结合上下文进行推理——忠实客户还是新客户、简单请求还是复杂问题、合理投诉还是滥用模式。这些决策不应由人类逐案处理。
技能开发工作流
电脑上的软件代码——示意图
步骤 1:定义技能
创建技能定义文件:
mkdir -p skills/my-skill
touch skills/my-skill/index.js
touch skills/my-skill/test.js
touch skills/my-skill/README.md
步骤 2:实现处理程序
编写逻辑。从简单开始,逐步增加复杂度。
步骤 3:全面测试
// test.js
const skill = require('./index.js');
async function test() {
const result = await skill.handler({
text: "Sample input for testing"
});
console.log("Result:", result);
// 断言输出结构与定义相符
assert(result.hasOwnProperty('expectedField'));
}
test();
步骤 4:编写文档
# 我的技能
## 功能说明
...
## 使用时机
...
## 示例
...
## 局限性
...
步骤 5:在 OpenClaw 中注册
添加到您的配置中:
skills:
- path: ./skills/my-skill
enabled: true
步骤 6:部署
openclaw deploy --skill my-skill
组织您的技能库
电脑上的软件代码——示意图
随着技能不断增多,请对它们进行整理:
skills/
├── data/
│ ├── parse-json/
│ ├── transform-csv/
│ └── extract-entities/
├── integrations/
│ ├── slack/
│ ├── github/
│ └── stripe/
├── analysis/
│ ├── sentiment/
│ ├── summarize/
│ └── classify/
└── business/
├── customer-score/
├── contract-analysis/
└── pricing-calculator/
这样可以让技能更易于发现。智能体(和人类)都能轻松找到所需的技能。
技能开发最佳实践
电脑上的软件代码——示意图
1. 单一职责 每个技能只做好一件事。不要构建“万能”技能。
2. 清晰的输入/输出 准确记录输入和输出的内容。为所有内容指定类型。
3. 优雅地失败 返回有帮助的错误信息,而不是堆栈跟踪。
if (!inputs.required_field) {
throw new Error("customer_id is required to fetch orders");
}
4. 测试边界情况 空输入、超长输入、特殊字符、边界情况。
5. 记录一切 返回关于执行情况的元数据:
return {
result: processedData,
executionTime: 245, // ms
tokensUsed: 1523,
cached: false
};
6. 超时处理 长时间运行的技能应设置超时:
const timeout = setTimeout(() => {
throw new Error("Skill execution exceeded 30s timeout");
}, 30000);
const result = await doLongWork();
clearTimeout(timeout);
return result;
7. 为技能进行版本管理 破坏性变更 → 升级主版本号。
技能发布与分享
电脑上的软件代码——示意图
测试完成后,即可分享技能:
# Publish to community registry
openclaw publish skill my-skill --description "What it does"
# Share with team (private)
openclaw share skill my-skill --team my-company
OpenClaw 社区注册中心让其他人可以发现并使用您的技能。一次构建,多方受益。
结语
电脑上的软件代码——示意图
技能是效率倍增器。一个花 2 小时构建的技能,每年可能为您的团队节省 100 小时。规模化之后,一个精心构建的技能库将从根本上改变智能体的能力。
从识别团队中重复性的任务开始,为这些任务构建技能。随着技能库不断壮大,智能体无需新增代码就会变得更加强大。
最好的智能体并不是最聪明的——而是拥有最多实用工具的。
常见问题
问:我可以在技能中使用现有的 npm 包吗?
答:可以。技能就是 Node.js 模块。使用 require() 来导入包。
问:智能体如何发现可用的技能? 答:OpenClaw 提供了一个注册中心。Claude 可以看到所有可用的技能,并根据任务决定使用哪一个。
问:如果技能在执行过程中失败了怎么办? 答:智能体会处理错误。设计良好的技能会返回有用的错误信息,以便智能体重试、上报或绕过问题。
问:我可以在不部署的情况下测试技能吗? 答:可以。在本地测试、查看结果并反复迭代,准备就绪后再部署即可。
问:如何在技能中处理身份验证? 答:将凭据存储在环境变量或安全配置中。切勿将密钥硬编码。
更多文章
终极 OpenClaw AWS 部署指南

在 AWS 上部署 OpenClaw 的权威指南。包括 Spot 实例配置、成本优化以及分步说明。
在 OpenClaw 中使用工具链构建 AI 工作流
掌握工具链式调用与函数调用的技巧,构建强大的多步骤 AI 自动化工作流——从数据提取到内容生成与部署。
自托管 AI 助手成本优化指南:低预算运行 Claude
降低自托管 AI 助手 API 成本的实用策略——智能模型路由、缓存、批处理,以及针对 OpenClaw 的优化方法,让您以更低成本运行 Claude。