第七章:工具系统与斜杠命令

工具系统概述

OpenClaw 的工具系统是一个灵活的扩展机制,允许 AI 模型在对话过程中调用外部功能。工具本质上是一段可执行的代码,它接收结构化的输入参数,执行特定操作后返回结果。通过工具系统,聊天机器人可以实现诸如查询数据库、调用 API、执行计算等超出语言模型本身能力范围的任务。

工具系统的执行流程如下:用户发送消息 → AI 模型识别需要调用工具 → 参数解析与验证 → 工具执行 → 结果返回给模型 → 模型生成最终回复。整个流程对用户透明,但开发者可以通过日志详细追踪每一步的执行情况。

内置工具列表与功能

OpenClaw 提供了一套丰富的内置工具,覆盖了最常见的需求场景:

工具名称功能描述输入参数输出格式
web_search网络搜索query, max_results搜索结果列表
web_fetch网页内容抓取url, selector结构化文本
calculator数学计算器expression计算结果
datetime日期时间查询timezone, format格式化时间
translate文本翻译text, target_lang翻译结果
weather天气查询city, country天气信息

这些内置工具通过 tools.builtin 配置项启用或禁用。例如:

// openclaw.config.ts
export default defineConfig({
  tools: {
    builtin: {
      web_search: { enabled: true, maxResults: 5 },
      web_fetch: { enabled: true },
      calculator: { enabled: true },
      datetime: { enabled: true },
      translate: { enabled: false },
      weather: { enabled: true, defaultUnit: 'celsius' },
    },
  },
});

斜杠命令开发流程

斜杠命令(Slash Command)是用户通过输入 / 前缀触发的快捷指令,是实现用户交互最直观的方式。开发一个斜杠命令通常包含以下几个步骤:

步骤一:定义命令结构

创建命令描述文件,声明命令的名称、参数和说明:

// commands/weather.ts
import { defineSlashCommand } from 'openclaw/commands';

export default defineSlashCommand({
  name: 'weather',
  description: '查询指定城市的天气信息',
  usage: '/weather <城市名> [国家]',
  parameters: [
    {
      name: 'city',
      type: 'string',
      required: true,
      description: '城市名称',
    },
    {
      name: 'country',
      type: 'string',
      required: false,
      description: '国家代码(可选,如 CN, US)',
    },
  ],
});

步骤二:实现命令逻辑

// commands/weather.handler.ts
import { CommandHandler, CommandContext } from 'openclaw/commands';

export const handler: CommandHandler = async (ctx: CommandContext) => {
  const { city, country } = ctx.parameters;
  const apiKey = process.env.WEATHER_API_KEY;

  const url = `https://api.openweathermap.org/data/2.5/weather`
    + `?q=${encodeURIComponent(city)}`
    + (country ? `,${country}` : '')
    + `&appid=${apiKey}&units=metric&lang=zh_cn`;

  const response = await fetch(url);
  const data = await response.json();

  if (data.cod !== 200) {
    return `❌ 无法获取 ${city} 的天气信息:${data.message}`;
  }

  return [
    \`🌤 **${data.name} 当前天气**\`,
    \`温度:${data.main.temp}°C(体感 ${data.main.feels_like}°C)\`,
    \`天气:${data.weather[0].description}\`,
    \`湿度:${data.main.humidity}%\`,
    \`风速:${data.wind.speed} m/s\`,
    \`气压:${data.main.pressure} hPa\`,
  ].join('\n');
};

参数解析与验证

参数解析是斜杠命令开发中最容易出错的部分。OpenClaw 提供了内置的参数验证机制,支持以下规则:

验证规则说明示例
required必填参数{ required: true }
enum枚举值限制{ enum: ['celsius', 'fahrenheit'] }
pattern正则验证{ pattern: '^[a-zA-Z]+$' }
min/max数值范围{ min: 1, max: 100 }
minLength/maxLength字符串长度{ minLength: 2, maxLength: 50 }
// 高级参数验证示例
parameters: [
  {
    name: 'count',
    type: 'number',
    required: true,
    min: 1,
    max: 50,
    description: '返回结果数量(1-50)',
  },
  {
    name: 'format',
    type: 'string',
    required: false,
    enum: ['json', 'text', 'table'],
    defaultValue: 'text',
    description: '输出格式',
  },
],

工具执行上下文

每个工具和斜杠命令在执行时都会获得一个上下文对象(CommandContext),其中包含了丰富的运行时信息:

interface CommandContext {
  // 用户信息
  userId: string;
  userName: string;
  platform: 'telegram' | 'discord' | 'wechat' | 'web';

  // 会话信息
  sessionId: string;
  chatId: string;
  messageId: string;

  // 解析后的参数
  parameters: Record<string, any>;
  rawInput: string;

  // 运行时工具
  helpers: {
    reply(text: string): Promise<void>;
    fetch(url: string, init?: RequestInit): Promise<Response>;
    getSessionData(key: string): Promise<any>;
    setSessionData(key: string, value: any): Promise<void>;
  };
}

上下文对象使开发者能够获取当前会话的完整信息,实现上下文感知的命令逻辑。

实战:创建一个天气查询斜杠命令

综合以上知识点,完整实现一个天气查询斜杠命令。首先在 openclaw.config.ts 中注册命令:

export default defineConfig({
  commands: {
    custom: [
      {
        path: './commands/weather',
        handler: './commands/weather.handler',
      },
    ],
    prefix: '/',
    fuzzyMatch: true,
  },
});

启动后用户在聊天窗口输入 /weather 北京 CN,即可实时获取北京的天气信息。如果参数缺失,框架会自动返回使用帮助。整个开发流程不涉及复杂的框架知识,开发者只需关注命令的业务逻辑即可快速完成功能交付。