OriginTensorDOCS
返回主站 创建 API Key
开发指南 · API v1

结构化输出

使用 response_format 与 JSON Schema 请求结构化结果,并在应用侧做解析和校验。

OpenAI 兼容Anthropic 原生更新于 2026-12-05
管理 API Key

Response formats

三种常见输出形式

形式请求适用场景
纯文本不设置 response_format自然语言回复。
JSON 对象{"type":"json_object"}需要 JSON,但 schema 较简单。
JSON Schema{"type":"json_schema","json_schema":{...}}字段、类型与必需项明确的业务结果。

网关会识别并保留 response_format 与 json_schema,但最终约束能力取决于目标模型和上游渠道。不要让关键业务只依赖模型“保证合法”。

JSON Schema

请求 schema 化输出

Schema request + validation
import json
import os
from openai import OpenAI
from pydantic import BaseModel, ValidationError

class Invoice(BaseModel):
    vendor: str
    total: float
    currency: str

client = OpenAI(
    api_key=os.environ["ORIGINTENSOR_API_KEY"],
    base_url="https://api.origintensor.com/v1",
    timeout=60.0,
)

schema = {
    "name": "invoice",
    "strict": True,
    "schema": {
        "type": "object",
        "properties": {
            "vendor": {"type": "string"},
            "total": {"type": "number"},
            "currency": {"type": "string"},
        },
        "required": ["vendor", "total", "currency"],
        "additionalProperties": False,
    },
}

response = client.chat.completions.create(
    model="glm-5.3",
    messages=[{
        "role": "user",
        "content": "提取发票信息:供应商 源点智算,金额 128.50 美元。",
    }],
    response_format={"type": "json_schema", "json_schema": schema},
)

raw = response.choices[0].message.content or "{}"
try:
    invoice = Invoice.model_validate(json.loads(raw))
except (json.JSONDecodeError, ValidationError) as exc:
    raise RuntimeError("Model returned invalid structured output") from exc

print(invoice.model_dump())

Validation

应用侧校验不可省略

  1. 解析 JSON,捕获语法错误。
  2. 用 Pydantic、JSON Schema Validator 或业务校验器验证字段、类型与范围。
  3. 校验失败时进行有限次数重试或转人工,不要静默使用空值。
  4. 记录原始响应片段、request id 与校验错误,注意敏感信息脱敏。

Compatibility

跨协议注意事项

  • OpenAI 使用 response_format;Anthropic 原生协议使用 output_format。
  • 两者不是完全等价字段,迁移时要按目标协议重写。
  • 流式结构化输出仍然是文本增量;应累积完整文本后再解析。
  • 如果模型不支持严格 schema,退化为“JSON 提示 + 应用校验”,不要假设网关会补足约束。
输入 API 名称、参数、错误码或场景,例如「stream」「429」「Anthropic」「缓存」。