OpenClaw 工具插件使用:搜索、代码执行、数据库查询

工具(Tool)是 OpenClaw 智能体的手脚,让智能体能够执行实际操作,而不仅仅是聊天。通过工具插件,智能体可以搜索网络、执行代码、查询数据库等。

工具插件概述

什么是工具?

工具是智能体用来执行特定操作的函数或服务,包括:

  • 搜索工具:搜索网络、文档、知识库
  • 代码执行:运行 Python、JavaScript 等代码
  • 数据库查询:查询 MySQL、Redis、MongoDB 等
  • 文件操作:读取、写入文件
  • API 调用:调用外部 REST API
  • 系统操作:执行系统命令

内置工具使用

1. 搜索工具

OpenClaw 内置了搜索工具,支持以下搜索引擎:

  • Google 搜索
  • Bing 搜索
  • DuckDuckGo 搜索

配置搜索工具

plugins:
  - type: "tool"
    name: "search"
    engine: "google"
    api_key: "${GOOGLE_API_KEY}"
    cx: "${GOOGLE_CX}"

在技能中使用搜索工具

from openclaw.core.tools import SearchTool

search_tool = SearchTool()

async def handle(self, context: SkillContext) -> SkillResponse:
    query = self._extract_query(context.message)
    results = await search_tool.search(query)
    response = self._format_search_results(results)
    return SkillResponse(message=response)

2. 代码执行工具

智能体可以执行 Python 代码,用于:

  • 数据分析和计算
  • 生成图表
  • 运行自动化脚本

配置代码执行工具

plugins:
  - type: "tool"
    name: "code_executor"
    timeout: 30
    max_output: 5000

在技能中使用代码执行

from openclaw.core.tools import CodeExecutor

executor = CodeExecutor()

async def handle(self, context: SkillContext) -> SkillResponse:
    code = self._extract_code(context.message)
    result = await executor.execute_python(code)
    return SkillResponse(message=result)

3. 数据库查询工具

支持查询多种数据库:

  • MySQL / PostgreSQL
  • Redis
  • MongoDB
  • Elasticsearch

配置数据库工具

plugins:
  - type: "tool"
    name: "database"
    db_type: "mysql"
    host: "${DB_HOST}"
    port: 3306
    user: "${DB_USER}"
    password: "${DB_PASSWORD}"

在技能中使用数据库查询

from openclaw.core.tools import DatabaseTool

db_tool = DatabaseTool()

async def handle(self, context: SkillContext) -> SkillResponse:
    query = self._extract_query(context.message)
    results = await db_tool.query(query)
    response = self._format_results(results)
    return SkillResponse(message=response)

开发自定义工具

1. 创建工具

from openclaw.core.tool import Tool

class WeatherAPI(Tool):
    """天气 API 工具"""

    def __init__(self, api_key: str):
        super().__init__()
        self.api_key = api_key
        self.base_url = "https://api.weather.com"

    async def get_weather(self, city: str) -> dict:
        async with aiohttp.ClientSession() as session:
            url = f"{self.base_url}/weather?city={city}&key={self.api_key}"
            async with session.get(url) as resp:
                return await resp.json()

2. 注册工具

在技能中使用自定义工具:

class WeatherSkill(Skill):
    def __init__(self):
        super().__init__()
        self.weather_api = WeatherAPI(api_key="your_api_key")

工具最佳实践

1. 安全性

  • 代码执行工具运行在沙箱环境中
  • 数据库工具限制 SQL 注入风险
  • 敏感操作需要权限验证

2. 性能优化

  • 设置合理的超时时间
  • 使用连接池复用数据库连接
  • 限制输出大小

3. 错误处理

  • 妥善处理网络错误
  • 提供友好的错误提示
  • 记录详细的错误日志

总结

通过工具插件,OpenClaw 智能体可以:

  • 搜索网络获取最新信息
  • 执行代码进行计算和分析
  • 查询数据库获取业务数据
  • 调用外部 API 完成特定任务

结合技能开发,你可以构建出强大的 AI 智能体,真正实现自动化办公和智能决策。

发表回复

后才能评论