跳转到内容
搜索文档

JSON Mode

最后更新 查看 MarkdownAgent 设置

当我们希望 text-generation AI 模型以编程方式与数据库、服务和外部系统交互时——通常在使用 tool calling 或构建 AI agent 时——我们必须使用结构化响应格式,而非自然语言。

Workers AI 支持 JSON Mode,使应用在与 AI 模型交互时可以请求结构化输出响应。

Schema

JSON Mode 与 OpenAI 的实现兼容;要启用,请使用以下约定在请求对象中添加 response_format 属性:

{
  response_format: {
    title: "JSON Mode",
    type: "object",
    properties: {
      type: {
        type: "string",
        enum: ["json_object", "json_schema"],
      },
      json_schema: {},
    }
  }
}

其中 json_schema 必须是有效的 JSON Schema 声明。

JSON Mode 示例

使用 JSON Format 时,将 schema 作为以下示例的一部分传递给 LLM 的请求。

{
  "messages": [
    {
      "role": "system",
      "content": "Extract data about a country."
    },
    {
      "role": "user",
      "content": "Tell me about India."
    }
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "capital": {
          "type": "string"
        },
        "languages": {
          "type": "array",
          "items": {
            "type": "string"
          }
        }
      },
      "required": [
        "name",
        "capital",
        "languages"
      ]
    }
  }
}

LLM 将遵循 schema,并返回如下响应:

{
  "response": {
    "name": "India",
    "capital": "New Delhi",
    "languages": [
      "Hindi",
      "English",
      "Bengali",
      "Telugu",
      "Marathi",
      "Tamil",
      "Gujarati",
      "Urdu",
      "Kannada",
      "Odia",
      "Malayalam",
      "Punjabi",
      "Sanskrit"
    ]
  }
}

可以看到,模型遵循请求中的 JSON schema 定义,并返回经过验证的 JSON 对象。

支持的模型

以下是现在支持 JSON Mode 的模型列表:

我们将继续扩展此列表,以跟进新模型和用户请求的模型。

请注意,Workers AI 无法保证模型按请求的 JSON Schema 响应。根据任务复杂度和 JSON Schema 的适当性,在极端情况下模型可能无法满足请求。如果发生这种情况,将返回错误 JSON Mode couldn't be met,必须进行处理。

JSON Mode 目前不支持 streaming。

这篇文档对您有帮助吗?