当我们希望 text-generation AI 模型以编程方式与数据库、服务和外部系统交互时——通常在使用 tool calling 或构建 AI agent 时——我们必须使用结构化响应格式,而非自然语言。
Workers AI 支持 JSON Mode,使应用在与 AI 模型交互时可以请求结构化输出响应。
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 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 的模型列表:
- @cf/meta/llama-3.1-8b-instruct-fast
- @cf/meta/llama-3.1-70b-instruct
- @cf/meta/llama-3.3-70b-instruct-fp8-fast
- @cf/meta/llama-3-8b-instruct
- @cf/meta/llama-3.1-8b-instruct
- @cf/meta/llama-3.2-11b-vision-instruct
- @hf/nousresearch/hermes-2-pro-mistral-7b
- @hf/thebloke/deepseek-coder-6.7b-instruct-awq
- @cf/deepseek-ai/deepseek-r1-distill-qwen-32b
我们将继续扩展此列表,以跟进新模型和用户请求的模型。
请注意,Workers AI 无法保证模型按请求的 JSON Schema 响应。根据任务复杂度和 JSON Schema 的适当性,在极端情况下模型可能无法满足请求。如果发生这种情况,将返回错误 JSON Mode couldn't be met,必须进行处理。
JSON Mode 目前不支持 streaming。