Skip to content

JSON(Object/Schema) ​

用 response_format 让模型稳定输出 JSON,两种模式:

模式作用
json_object强制输出合法 JSON(不限字段)
json_schema按 JSON Schema 强约束字段 / 类型 / 必填(strict: true)

下面每个测试都可直接复制运行。示例模型 deepseek-v4-pro,按你的可用模型替换。

准备 ​

bash
export NOVAFARE_API_KEY=sk-xxxx

# 确认可用模型名(大小写敏感)
curl -s https://ai.jhdataops.com/v1/models \
  -H "Authorization: Bearer $NOVAFARE_API_KEY"

测试 1 · json_object ​

bash
curl https://ai.jhdataops.com/v1/chat/completions \
  -H "Authorization: Bearer $NOVAFARE_API_KEY" -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-v4-pro",
    "messages": [{"role": "user", "content": "用 json 返回一个人物,含 name 和 age"}],
    "response_format": {"type": "json_object"}
  }'

预期 —— content 是合法 JSON:

json
{ "name": "小明", "age": 20 }

✅ 能被 JSON.parse / json.loads 解析 = 通过。

测试 2 · json_schema(按 Schema 强约束) ​

bash
curl https://ai.jhdataops.com/v1/chat/completions \
  -H "Authorization: Bearer $NOVAFARE_API_KEY" -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-v4-pro",
    "messages": [
      {"role": "system", "content": "You extract book information into structured JSON."},
      {"role": "user", "content": "请提取《三体》刘慈欣 2006年出版 和 《流浪地球》刘慈欣 2000年出版 的信息。"}
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "book_list",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "books": {
              "type": "array",
              "items": {
                "type": "object",
                "properties": {
                  "title": {"type": "string"},
                  "author": {"type": "string"},
                  "published_year": {"type": "integer"}
                },
                "required": ["title", "author", "published_year"]
              }
            },
            "total_count": {"type": "integer"}
          },
          "required": ["books", "total_count"]
        }
      }
    }
  }'

预期 —— published_year、total_count 均为整数,结构符合 schema:

json
{
  "books": [
    { "title": "三体", "author": "刘慈欣", "published_year": 2006 },
    { "title": "流浪地球", "author": "刘慈欣", "published_year": 2000 }
  ],
  "total_count": 2
}

✅ 不报 400 且字段 / 类型符合 = 通过。

测试 3 · 验证「真强约束」(对抗测试) ​

提示词故意要求违反 schema(要 age 写成中文),看 schema 能否压过提示词:

bash
curl https://ai.jhdataops.com/v1/chat/completions \
  -H "Authorization: Bearer $NOVAFARE_API_KEY" -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-v4-pro",
    "messages": [{"role": "user", "content": "返回 json,字段 name 和 age。请把 age 写成中文文字(例如:三十),绝对不要用阿拉伯数字。"}],
    "response_format": {"type": "json_schema", "json_schema": {"name": "p", "strict": true, "schema": {"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer"}}, "required": ["name", "age"], "additionalProperties": false}}}
  }'

预期 —— age 仍是整数:

json
{ "name": "张三", "age": 30 }

✅ 返回整数 = 强约束真生效(不是靠提示词碰运气)。

进阶 · 多轮对话 → 记忆抽取 ​

复杂场景:嵌套数组 + additionalProperties: false + 采样参数。请求体较长,存为 case.json 后用 -d @case.json 调用:

json
{
  "model": "deepseek-v4-pro",
  "temperature": 1,
  "thinking": { "type": "disabled" },
  "messages": [
    {
      "role": "system",
      "content": "You are updating a MEMORY CONTEXT in APPEND-ONLY mode. Never invent facts.\nOUTPUT each line starting with one tag: [open thread] / [past event] / [fact & preference] / [relationships].\nRETURN STRICT JSON: {\"entries\":[{\"content\":string,\"message_id\":string}]}. Each message_id must be one of the provided IDs. If nothing to add, return {\"entries\":[]}."
    },
    {
      "role": "user",
      "content": "{\"new_messages\":[{\"id\":\"M1\",\"role\":\"user\",\"content\":\"先送我去你家吧\"},{\"id\":\"M2\",\"role\":\"assistant\",\"content\":\"Lance 替她开了车门,发动车子驶离路边。\"},{\"id\":\"M3\",\"role\":\"user\",\"content\":\"她把手搭在他胳膊上笑了笑\"}]}"
    }
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "append_only_entries",
      "strict": true,
      "schema": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "entries": {
            "type": "array",
            "items": {
              "type": "object",
              "additionalProperties": false,
              "properties": {
                "message_id": { "type": "string" },
                "content": { "type": "string" }
              },
              "required": ["content", "message_id"]
            }
          }
        },
        "required": ["entries"]
      }
    }
  }
}
bash
curl https://ai.jhdataops.com/v1/chat/completions \
  -H "Authorization: Bearer $NOVAFARE_API_KEY" -H "Content-Type: application/json" \
  -d @case.json

预期 —— 只含 entries,每项仅 message_id + content,每条以标签开头:

json
{
  "entries": [
    { "message_id": "M1", "content": "[open thread] User 要求 Lance 先送她回家。" },
    { "message_id": "M2", "content": "[past event] Lance 替 User 开车门并驶离路边。" },
    { "message_id": "M3", "content": "[relationships] Lance <-> User : 亲近。" }
  ]
}

返回验证脚本(可选,自动判 PASS / FAIL) ​

把任意 curl 的返回管道给它,自动校验「① 合法 JSON ② 符合 Schema」。存为 validate.py,SCHEMA 换成对应用例的 schema:

python
import json, sys
from jsonschema import validate, ValidationError   # pip install jsonschema

SCHEMA = {   # 这里放测试 2 的 book_list schema
    "type": "object",
    "properties": {
        "books": {"type": "array", "items": {"type": "object", "properties": {
            "title": {"type": "string"}, "author": {"type": "string"},
            "published_year": {"type": "integer"}},
            "required": ["title", "author", "published_year"]}},
        "total_count": {"type": "integer"}},
    "required": ["books", "total_count"],
}

content = json.load(sys.stdin)["choices"][0]["message"]["content"]
try:
    obj = json.loads(content)              # ① 合法 JSON?
    validate(instance=obj, schema=SCHEMA)  # ② 符合 Schema?
    print("PASS ✅", obj)
except (json.JSONDecodeError, ValidationError) as e:
    print("FAIL ❌", e)
bash
# 把测试 2 的请求体存为 body.json,一行串起来跑:
curl -s https://ai.jhdataops.com/v1/chat/completions \
  -H "Authorization: Bearer $NOVAFARE_API_KEY" -H "Content-Type: application/json" \
  -d @body.json | python3 validate.py

注意 ​

  • 模型名以 GET /v1/models 返回为准(大小写敏感)。
  • json_object 下部分模型(如 DeepSeek)要求提示词含 “json” 字样,否则可能返回空。
  • 测试设 temperature: 0 更稳定可复现。
  • json_schema 报 400 多为 schema 不合法:嵌套对象建议都加 required 与 additionalProperties: false。

浙中TOKEN运营中心-模型广场 · 一个 API Key 接入全量大模型