Skip to content
广告 · 本站推荐广告

TypeBox

TypeBox 是 OpenClaw 使用的 JSON Schema 类型构建库,用于在运行时验证配置、工具参数和 API 请求的数据结构。

什么是 TypeBox

TypeBox 提供编译时类型安全加运行时数据验证的双重保障。它将 TypeScript 类型定义编译为标准的 JSON Schema,用于校验外部输入。

typescript
import { Type, Static } from '@sinclair/typebox'

// 定义 Schema(同时生成 TypeScript 类型和 JSON Schema)
const AgentConfig = Type.Object({
  name: Type.String(),
  model: Type.String(),
  timezone: Type.Optional(Type.String()),
  maxTokens: Type.Optional(Type.Number({ minimum: 1 }))
})

// 提取 TypeScript 类型
type AgentConfig = Static<typeof AgentConfig>
// { name: string; model: string; timezone?: string; maxTokens?: number }

OpenClaw 中的使用

TypeBox 在 OpenClaw 中用于以下场景:

配置验证

Agent 配置文件在加载时通过 TypeBox Schema 校验:

typescript
import { Type } from '@sinclair/typebox'
import { Value } from '@sinclair/typebox/value'

const ConfigSchema = Type.Object({
  model: Type.String({ pattern: '^[a-z]+/.+$' }),
  timezone: Type.Optional(
    Type.String({ pattern: '^[A-Z][a-z]+/[A-Z][a-z_]+$' })
  ),
  steering: Type.Optional(
    Type.Union([
      Type.Literal('steer'),
      Type.Literal('followup'),
      Type.Literal('collect')
    ])
  ),
  failover: Type.Optional(Type.Array(Type.String()))
})

// 验证配置
const config = loadConfig()
const isValid = Value.Check(ConfigSchema, config)

if (!isValid) {
  const errors = [...Value.Errors(ConfigSchema, config)]
  console.error('Config validation failed:', errors)
}

工具参数定义

自定义工具的输入参数使用 TypeBox 定义 Schema:

typescript
const WebSearchParams = Type.Object({
  query: Type.String({
    description: 'Search keywords',
    minLength: 1,
    maxLength: 500
  }),
  limit: Type.Optional(Type.Number({
    description: 'Max number of results',
    minimum: 1,
    maximum: 50,
    default: 10
  })),
  language: Type.Optional(Type.String({
    description: 'Search language',
    default: 'zh-CN'
  }))
})

生成的 JSON Schema:

json
{
  "type": "object",
  "properties": {
    "query": {
      "type": "string",
      "description": "Search keywords",
      "minLength": 1,
      "maxLength": 500
    },
    "limit": {
      "type": "number",
      "description": "Max number of results",
      "minimum": 1,
      "maximum": 50,
      "default": 10
    },
    "language": {
      "type": "string",
      "description": "Search language",
      "default": "zh-CN"
    }
  },
  "required": ["query"]
}

API 请求验证

Gateway API 端点的请求体验证:

typescript
const MessageRequest = Type.Object({
  sessionKey: Type.String(),
  content: Type.String({ minLength: 1 }),
  type: Type.Optional(
    Type.Union([
      Type.Literal('text'),
      Type.Literal('image'),
      Type.Literal('voice'),
      Type.Literal('document')
    ])
  ),
  media: Type.Optional(Type.Object({
    url: Type.String({ format: 'uri' }),
    mimeType: Type.String()
  }))
})

常用 TypeBox 类型

TypeBox 方法JSON Schema 输出说明
Type.String(){ "type": "string" }字符串
Type.Number(){ "type": "number" }数字
Type.Boolean(){ "type": "boolean" }布尔
Type.Array(T){ "type": "array", "items": T }数组
Type.Object({}){ "type": "object" }对象
Type.Optional(T)从 required 中移除可选字段
Type.Union([]){ "anyOf": [...] }联合类型
Type.Literal(v){ "const": v }字面量

验证错误处理

TypeBox 的验证错误提供详细的路径和原因:

typescript
import { Value } from '@sinclair/typebox/value'

const config = {
  model: 'invalid',
  timezone: 123,
  steering: 'unknown'
}

for (const error of Value.Errors(ConfigSchema, config)) {
  console.log(`Path: ${error.path}`)
  console.log(`Message: ${error.message}`)
  console.log(`Value: ${error.value}`)
}

// Path: /model
// Message: Expected string to match pattern '^[a-z]+/.+$'
// Value: invalid
//
// Path: /timezone
// Message: Expected string
// Value: 123

用户友好的错误提示

OpenClaw 将 TypeBox 验证错误转换为人类可读的提示,帮助用户快速定位配置问题。

与 LLM 工具调用的关系

TypeBox 生成的 JSON Schema 直接用于 LLM 的 Function Calling(函数调用)参数定义:

TypeBox Schema
      |
      v
JSON Schema  --> 发送给 LLM(参数描述)
      |
      v
运行时验证  --> 校验 LLM 返回的工具参数

这确保了:

  1. LLM 知道如何构造正确的参数
  2. Agent 在执行工具前验证参数合法性
  3. 非法参数在到达工具代码前被拦截

Schema 一致性

TypeBox 确保 TypeScript 类型与 JSON Schema 始终同步。修改类型定义时无需手动更新 Schema。

下一步

基于MIT协议开源 | 内容翻译自 官方文档,同步更新