Monoize
API 使用指南

结构化输出

让模型按 JSON Schema 返回结果。三种协议的写法和跨协议转换规则。

结构化输出要求模型返回符合 JSON Schema 的 JSON。网关在三种协议之间转换 Schema 设置。模型是否严格遵守 Schema,取决于上游模型的能力。

Chat Completions

import json, os
from openai import OpenAI

client = OpenAI(base_url="https://api.lynshen.org/v1", api_key=os.environ["LYNSHEN_API_KEY"])

completion = client.chat.completions.create(
    model="gpt-5.5",
    messages=[{"role": "user", "content": "从这句话中提取人名和城市:小林住在杭州。"}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {"name": {"type": "string"}, "city": {"type": "string"}},
                "required": ["name", "city"],
                "additionalProperties": False,
            },
        },
    },
)
data = json.loads(completion.choices[0].message.content)
print(data["name"], data["city"])

response_format 也可以是 {"type": "json_object"}。这种模式只要求输出合法的 JSON,不检查结构。

Responses

{
  "model": "gpt-5.5",
  "input": "从这句话中提取人名和城市:小林住在杭州。",
  "text": {
    "format": {
      "type": "json_schema",
      "name": "person",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": { "name": { "type": "string" }, "city": { "type": "string" } },
        "required": ["name", "city"],
        "additionalProperties": false
      }
    }
  }
}

结果在 message 项的 output_text 中,是一个 JSON 字符串。

Messages

{
  "model": "claude-sonnet-5",
  "max_tokens": 1024,
  "messages": [{ "role": "user", "content": "从这句话中提取人名和城市:小林住在杭州。" }],
  "output_config": {
    "format": {
      "type": "json_schema",
      "schema": {
        "type": "object",
        "properties": { "name": { "type": "string" }, "city": { "type": "string" } },
        "required": ["name", "city"],
        "additionalProperties": false
      }
    }
  }
}

结果在 text 块中,是一个 JSON 字符串。

跨协议转换

你的请求上游是 Chat 或 Responses上游是 Messages(Claude)
Chat json_schema转为对应的 Schema 设置转为 output_config.format
Chat json_object原样转发不转发。Messages 没有对应模式
Responses text.format转为对应的 Schema 设置转为 output_config.format
Messages output_config.format转为 json_schema,名称固定为 response原样转发

调用 Claude 模型时,请使用 json_schema,不要使用 json_object。使用 json_object 时,网关不会把 JSON 要求发给 Claude,模型可能返回普通文本。这种情况下,请在提示词中说明输出格式。

建议

  • 在 Schema 中写 "additionalProperties": false,并在 required 中列出所有字段。
  • 解析前检查 finish_reason 或 stop_reason。输出被截断时(length 或 max_tokens),JSON 不完整。
  • 结构化输出也可以与工具调用一起使用。工具参数本身也遵循 JSON Schema,见工具调用。

本页目录