Skip to content

Kimi API 工具调用(function calling)schema 字段不兼容导致请求失败

问题

在第三方工具(如 OpenClaw、OpenCode 等)中接入 Kimi/Moonshot API 并启用工具调用时,工具调用功能异常,API 返回错误。根本原因是 Kimi API 对 JSON Schema 的要求比 OpenAI API 更严格,会拒绝某些 OpenAI 允许但 Kimi 不支持的 schema 字段。

常见触发场景:

  • 工具定义中包含 additionalProperties: false(某些情况下 Kimi 不接受)
  • schema 中包含 $schema$defs 等 JSON Schema 元字段
  • 嵌套对象的 required 字段处理方式不一致

解决方案

在调用 Kimi API 之前对工具 schema 做清洗(schema cleaning),移除或调整 Kimi 不支持的字段:

typescript
function cleanSchemaForKimi(schema: Record<string, unknown>): Record<string, unknown> {
  const cleaned = { ...schema }
  // 移除顶层不支持的元字段
  delete cleaned['$schema']
  delete cleaned['$defs']
  // 递归处理 properties
  if (cleaned.properties && typeof cleaned.properties === 'object') {
    cleaned.properties = Object.fromEntries(
      Object.entries(cleaned.properties as Record<string, unknown>).map(([k, v]) => [
        k,
        cleanSchemaForKimi(v as Record<string, unknown>)
      ])
    )
  }
  return cleaned
}

// 在传递工具定义前清洗
const tools = rawTools.map(tool => ({
  ...tool,
  function: {
    ...tool.function,
    parameters: cleanSchemaForKimi(tool.function.parameters)
  }
}))

说明:OpenClaw 已通过 PR #39618 修复了此问题(fix(moonshot): add schema cleaning for Moonshot/Kimi tool definitions)。如果你在自己的代码中集成 Kimi 工具调用,需要自行做类似的 schema 清洗。

来源openclaw/openclaw #39603