> ## Documentation Index
> Fetch the complete documentation index at: https://docs.inputapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 结构化输出

> 按指定结构读取 JSON，并处理拒答、截断与校验失败。

## 选择输出方式

| 方式 | 适用情况 | 应用仍需处理 |
| - | - | - |
| 普通文本提示“请输出 JSON” | 模型没有专用 JSON 能力时的尽力尝试 | 可能有 Markdown 包装或非 JSON 内容 |
| `response_format.type: json_object` | 模型支持 JSON 模式 | 明确要求 JSON，并自行验证字段和类型 |
| `response_format.type: json_schema` | 模型及渠道支持结构化输出 | 完成状态、拒答、业务规则及所支持的 Schema 子集 |

兼容接口不代表每个模型都支持 `json_schema`。先用最小 Schema 验证目标模型；遇到不支持的参数错误时，确认能力后再调整，不要悄悄降级并把不合格结果写入业务系统。

## 可运行示例：提取商品

先完成 [TypeScript SDK 配置](/zh/guides/typescript)，保存为 `structured-output.mts`，运行 `node structured-output.mts`。示例要求模型提取商品名称和数量，使用严格 Schema；解析后再次检查名称非空、数量为非负安全整数。

```typescript theme={null}
import OpenAI from 'openai';

const { API_BASE_URL, API_KEY, API_MODEL } = process.env;
if (!API_BASE_URL || !API_KEY || !API_MODEL) {
  throw new Error('Set API_BASE_URL, API_KEY, and API_MODEL first.');
}
const client = new OpenAI({
  baseURL: API_BASE_URL.replace(/\/+$/, ''),
  apiKey: API_KEY,
  timeout: 60_000,
  maxRetries: 0,
});

try {
  const result = await client.chat.completions.create({
    model: API_MODEL,
    messages: [{ role: 'user', content: 'Extract the product: three notebooks.' }],
    response_format: {
      type: 'json_schema',
      json_schema: {
        name: 'product',
        strict: true,
        schema: {
          type: 'object',
          properties: { name: { type: 'string' }, quantity: { type: 'integer' } },
          required: ['name', 'quantity'],
          additionalProperties: false,
        },
      },
    },
  });
  const choice = result.choices[0];
  if (!choice || choice.finish_reason !== 'stop' || choice.message.refusal
    || choice.message.tool_calls?.length || !choice.message.content) {
    throw new Error('No complete structured output.');
  }
  const product = JSON.parse(choice.message.content);
  if (!product || Array.isArray(product) || Object.keys(product).length !== 2
    || typeof product.name !== 'string' || !product.name.trim()
    || !Number.isSafeInteger(product.quantity) || product.quantity < 0) {
    throw new Error('Invalid product data.');
  }
  console.log(JSON.stringify(product));
} catch (error) {
  console.error(error instanceof OpenAI.APIError && error.status
    ? `Request failed (HTTP ${error.status}). Check the request logs.`
    : 'Invalid or incomplete structured output. Check the request logs.');
  process.exitCode = 1;
}
```

成功输出的结构示例：

```json theme={null}
{"name":"notebooks","quantity":3}
```

商品名称的具体文字可能不同。输出是 JSON 不等于内容符合业务事实；应用还需核对允许的商品、范围和操作规则。字段较多时，用已有的 JSON Schema 校验库或数据模型库替代手工逐字段检查。

## 失败处理

* `finish_reason=length`：输出可能被截断，不应拼补 JSON 后当作完整结果使用。
* `message.refusal` 或没有可用内容：交给拒答/失败分支，不要直接 `JSON.parse`。
* Schema 不支持或字段校验失败：保留失败状态，检查请求和模型能力；不要无限重试。
* 流式输出：JSON 文本片段通常不能单独解析，应确认完成后解析完整文本；流中断时放弃本次结构化结果。

OpenAI 风格严格 Schema 通常要求对象显式设置 `additionalProperties: false`，并将属性列入 `required`。需要可空字段时可用相应 Schema 表达，但仍应确认目标模型支持。

## Responses 写法不同

Chat Completions 使用 `response_format: {type: "json_schema", json_schema: {...}}`；Responses 使用 `text: {format: {type: "json_schema", name, schema, strict}}`。不要把 `response_format` 原样搬到 Responses 请求中。

[API 参数](/zh/api-reference/chat-completions) · [错误与重试](/zh/guides/errors)

## TypeScript：Responses 结构化提取

保存为 `responses-structured.mts`，按 [TypeScript SDK](/zh/guides/typescript)配置后运行 `node responses-structured.mts`。需要渠道支持 Responses 的 `text.format` 严格 Schema；不假设支持 Chat Completions 的模型同时支持该能力。

```typescript theme={null}
import OpenAI from 'openai';

const { API_BASE_URL, API_KEY, API_MODEL } = process.env;
if (!API_BASE_URL || !API_KEY || !API_MODEL) {
  throw new Error('Set API_BASE_URL, API_KEY, and API_MODEL first.');
}
const client = new OpenAI({
  baseURL: API_BASE_URL.replace(/\/+$/, ''), apiKey: API_KEY,
  timeout: 60_000, maxRetries: 0,
});

try {
  const result = await client.responses.create({
    model: API_MODEL,
    input: 'Extract the product: three notebooks.',
    text: {
      format: {
        type: 'json_schema', name: 'product', strict: true,
        schema: {
          type: 'object',
          properties: { name: { type: 'string' }, quantity: { type: 'integer' } },
          required: ['name', 'quantity'], additionalProperties: false,
        },
      },
    },
  });
  if (result.status !== 'completed' || !result.output_text.trim()) {
    throw new Error('No complete structured output.');
  }
  for (const item of result.output) {
    if (item.type === 'reasoning') continue;
    if (item.type !== 'message' || item.status !== 'completed'
      || item.content.some((part) => part.type !== 'output_text')) {
      throw new Error('Refusal or unexpected output.');
    }
  }
  const product = JSON.parse(result.output_text);
  if (!product || Array.isArray(product) || Object.keys(product).length !== 2
    || typeof product.name !== 'string' || !product.name.trim()
    || !Number.isSafeInteger(product.quantity) || product.quantity < 0) {
    throw new Error('Invalid product data.');
  }
  console.log(JSON.stringify(product));
} catch (error) {
  console.error(error instanceof OpenAI.APIError && error.status
    ? `Request failed (HTTP ${error.status}). Check the request logs.`
    : 'Invalid or incomplete structured output. Check the request logs.');
  process.exitCode = 1;
}
```

与前面的 Chat 示例一样，成功结构为商品名称和非负安全整数数量。此例在解析前检查整体及消息完成状态，拒绝拒答、工具调用、空文本；再对 JSON 与业务字段进行校验。拒答可能出现在 `output[].content[]` 中，即使整体状态为 `completed` 也不能跳过检查。

参考：[OpenAI 结构化输出说明](https://developers.openai.com/api/docs/guides/structured-outputs)。

[Read in English](/en/guides/structured-output)

## JSON 模式的完整示例

[JSON 模式与结果校验](/zh/guides/json-mode) 补充 Chat / Responses 的 json\_object 示例、必需 nullable 字段、整数范围和失败短路；它不替代本页的 json\_schema 示例。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.