引言

本文是 OpenClaw API 的快速参考表,适合在开发过程中快速查阅。建议收藏本文,遇到具体场景再深入阅读对应模块的详细文档。

一、Runtime API

runtime.New()

创建一个新的 Runtime 实例。

import "github.com/opencLaw/opencLaw/pkg/runtime"

rt := runtime.New(runtime.WithConfig("./config.yaml"))
参数类型说明
WithConfigstring指定配置文件路径
WithLoggerLogger自定义日志实现
WithMetricsMetrics自定义 metrics 上报地址

rt.Register(name, component)

注册一个组件到 Runtime。

rt.Register("http-server", &HttpServer{
    Addr: ":8080",
})

rt.Start(ctx) / rt.Shutdown(ctx)

启动 / 停机 Runtime。

ctx := context.Background()
go func() {
    sigCh := make(chan os.Signal, 1)
    signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
    <-sigCh
    rt.Shutdown(context.WithTimeout(ctx, 30*time.Second))
}()

if err := rt.Start(ctx); err != nil {
    log.Fatal(err)
}

二、Plugin API

plugin.Load(path, opts...)

从本地路径或远程 URL 加载插件。

err := plugin.Load("./plugins/weather", plugin.WithAutoUpdate(true))

plugin.Call(name, input)

同步调用插件。

result, err := plugin.Call("weather", []byte(`{"city":"Beijing"}`))
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(result))

plugin.CallAsync(name, input)

异步调用,立即返回 channel。

ch := plugin.CallAsync("weather", input)
result := <-ch

三、Engine API

engine.NewTaskEngine(opts)

eng := engine.NewTaskEngine(
    engine.WithConcurrency(64),
    engine.WithQueueSize(10000),
)

eng.Submit(task)

eng.Submit(&engine.Task{
    Name:    "send-email",
    Fn:      sendEmailFn,
    Retry:   3,
    Timeout: 30 * time.Second,
    Metadata: map[string]any{
        "user_id": 12345,
    },
})

四、Config API

config.Get(key, defaultValue)

dbDSN := config.GetString("database.dsn", "postgres://localhost:5432/dev")

支持的类型:

  • GetString / GetInt / GetBool / GetFloat
  • GetDuration / GetStringSlice / GetStringMap

config.Watch(key, callback)

监听配置变更:

config.Watch("feature_flags.new_ui", func(newVal bool) {
    if newVal {
        enableNewUI()
    } else {
        rollbackToOldUI()
    }
})

五、NetworkSync API

netsync.AcquireLock(key, ttl)

获取分布式锁。

lock, err := netsync.AcquireLock(ctx, "order:create", 30*time.Second)
if err != nil {
    return err
}
defer lock.Release(ctx)

netsync.LeaderElection(name, callback)

竞选 Leader 节点。

netsync.LeaderElection("cron-master", func(isLeader bool) {
    if isLeader {
        go startCronWorker()
    }
})

多语言对照示例

以下 Demo 展示如何用不同语言调用同一个 weather 插件。

Go

result, _ := plugin.Call("weather", []byte(`{"city":"Shanghai"}`))

Python

from openclaw import Client

client = Client(host="http://localhost:8080")
result = client.plugin.call("weather", {"city": "Shanghai"})
print(result)

Node.js

const { OpenClaw } = require('@opencLaw/sdk');

const client = new OpenClaw({ host: 'http://localhost:8080' });
client.plugin.call('weather', { city: 'Shanghai' })
  .then(result => console.log(result));

错误码参考

错误码含义处理建议
OC_001插件不存在检查 plugin.yaml name 字段
OC_101参数校验失败参考 API 文档确认参数类型
OC_202内部超时增加 timeout 或优化插件逻辑
OC_303权限不足检查 plugin.yaml permissions 字段
OC_404网络后端不可用检查 etcd/Consul 连接

总结

这份速查表覆盖了 80% 日常开发会用到的接口。完整 API 参考请查阅 OpenClaw 官方文档站

延伸阅读