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

# JSON Mode 与 JSON Schema 结构化输出

阶跃星辰大模型可以用于情感分析、信息提取和内容评分等应用场景。[Step 5 Preview](https://platform.stepfun.com/docs/zh/guides/models/step-5-preview.md) 支持 JSON Mode 与 JSON Schema 结构化输出，您可以按业务需要选择输出方式。

## 选择输出方式

| 方式 | 请求参数 | 适用场景 |
| - | - | - |
| JSON Mode | `response_format: {"type": "json_object"}` | 需要可解析的 JSON，不要求由 API 约束具体字段和类型 |
| JSON Schema | `response_format.type: "json_schema"`，并设置 `json_schema.strict: true` | 需要按指定 Schema 约束字段、类型和必填项 |

在 prompt 中描述结构或放入 JSON Schema，可以引导 JSON Mode 的输出，但不等同于 API 层面的严格结构约束。需要严格结构约束时，请使用 `json_schema` 参数，而不只是将 Schema 写入 prompt。

## JSON Schema：通过 API 约束输出结构

以下用法适用于 `step-5-preview`、`step-3.7-flash`、`step-3.5-flash` 和 `step-3.5-flash-2603`。

将 `response_format.type` 设置为 `json_schema`，并在 `response_format.json_schema` 中填写：

* `name`：Schema 名称。
* `strict`：设置为 `true`，启用严格模式。
* `schema`：期望的 JSON 结构，包括属性、类型和必填字段。

以下示例使用 `step-5-preview` 提取姓名和年龄。Schema 直接通过 API 参数传入，无需在 prompt 中重复。将 `YOUR_STEP_API_KEY` 替换为您的 API Key，在终端设置 `STEPFUN_API_KEY` 环境变量，再执行请求；`$STEPFUN_API_KEY` 表示读取该变量的值。以下命令适用于 Bash 或 Zsh，使用按量付费 API。

```bash theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
export STEPFUN_API_KEY="YOUR_STEP_API_KEY"

curl --silent --show-error --fail-with-body \
  https://api.stepfun.com/v1/chat/completions \
  -H "Authorization: Bearer $STEPFUN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "step-5-preview",
    "messages": [{"role": "user", "content": "提取人物：王明 28 岁。"}],
    "stream": false,
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "person",
        "strict": true,
        "schema": {
          "type": "object",
          "additionalProperties": false,
          "required": ["name", "age"],
          "properties": {
            "name": {"type": "string"},
            "age": {"type": "integer"}
          }
        }
      }
    },
    "max_tokens": 1024
  }'
```

`choices[0].message.content` 是包含 JSON 的字符串，解析后的结果示例为：

```json theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
{"name": "王明", "age": 28}
```

本例通过 `required` 指定两个字段都必须返回，通过 `additionalProperties: false` 禁止额外字段。结构约束不代表提取内容在事实或业务含义上一定正确，应用仍需进行业务校验。完整参数说明见 [Chat Completions API](https://platform.stepfun.com/docs/zh/api-reference/chat/chat-completion-create.md)。

## JSON Mode：返回可解析的 JSON

### 使用方法

在使用 JSON Mode 时，您需要做三件事：

1. 在 System Prompt 中明确要求返回 JSON，并描述预期结构；也可以放入 JSON Schema 作为提示词引导，但这不提供严格的 Schema 约束。
2. 请求时，设置 response\_format 为 `{ "type": "json_object" }`，从而来让大模型返回可解析的 JSON 结果。
3. 解析大模型返回的结果，并验证是否符合预期。符合预期后即可使用在业务系统中对接。

### 参考代码

以使用大模型进行评论的情感分析为例子，您可以参考如下代码，让大模型返回 JSON 结果。

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
from openai import OpenAI

# 初始化 阶跃星辰 Client
STEPFUN_KEY = "YOUR_STEP_API_KEY"

client = OpenAI(
    base_url="https://api.stepfun.com/v1",
    api_key=STEPFUN_KEY
)

# 在 System Prompt 中定义返回结果
system_prompt = """
你是一个评论分析师，会根据用户的输入，分析用户输入的情感，并给出评论的情感分析结果
## 分析规则
1. 如果用户的评论中包含了负面情感词汇，那么情感分析结果为 negative
2. 如果用户的评论中包含了正面情感词汇，那么情感分析结果为 positive
3. 如果用户的评论中没有包含正面或者负面情感词汇，那么情感分析结果为 neutral
## 正面情感词汇
- 好
- 棒
- 优秀
## 负面情感词汇
- 差
- 糟糕
- 糟
## 例子
### 例子 1
#### 输入内容
"这个产品真的很好，我很喜欢"
####  输出内容
{  
    "emotion": "positive",
    "score": 0.9,
    "reason": "用户评论中包含了正面情感词汇"
}
### 例子 2
#### 输入内容
"这个产品好垃圾，我很讨厌"
####  输出内容
{  
    "emotion": "negative",
    "score": 0.9,
    "reason": "用户评论中包含了负面情感词汇"
}
## 输入内容
用户的评论文本
## 输出内容
按照如下结构输出 JSON 结果

class Response:
    emotion: str # 用户评论的情感分析结果，可选项为 positive, negative, neutral
    score: float # 用户评论的情感分析得分，范围为 0 到 1 之间
    reason: str # 用户评论的情感分析结果的原因

"""

response = client.chat.completions.create(
  model="step-5-preview",
  messages=[
    {"role": "system", "content": system_prompt},
    {"role": "user", "content": "这个产品还行？"}
  ],
  response_format={ "type": "json_object" },
)

print(response)
```

### 可选：在 prompt 中使用 Schema 引导 JSON Mode

JSON Schema 可以描述输出字段、类型和必填项。在 JSON Mode 的 prompt 中加入 Schema，可以引导输出结构，但不提供严格约束。

以下 Schema 定义了一个包含 `url` 和 `notes` 两个必填字段的对象：

```json theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "用户输入解析",
  "type": "object",
  "properties": {
    "url": {
      "type": "string",
     "description":"用户输入的 URL"
    },
    "notes": {
      "type": "string",
 "description":"用户对于输入的 URL 的评价"
    }
  },
  "required": [
    "url",
    "notes"
  ]
}
```

在您的 prompt 中加入 JSON Schema，并设置 `response_format: {"type": "json_object"}`，可以引导模型按预期结构输出。以下仍是提示词示例，不是 API 的 `json_schema` 参数用法：

```markdown theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
你是一个专业的文本处理工程师，会根据用户的输入，从中提取 URL 和 用户的评价内容，并以 JSON 的方式返回。

## 约束

- 你会以下方的 JSON Schema 的格式返回给用户

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "用户输入解析",
  "type": "object",
  "properties": {
    "url": {
      "type": "string",
     "description":"用户输入的 URL"
    },
    "notes": {
      "type": "string",
 "description":"用户对于输入的 URL 的评价"
    }
  },
  "required": [
    "url",
    "notes"
  ]
}
```

## 注意事项

* 两种方式都需要先检查请求是否成功，以及 `finish_reason` 是否为 `stop`。如果为 `length`，输出可能因 `max_tokens` 限制而被截断，不能按完整 JSON 使用；可提高输出上限后重试。
* 对于请求失败、拒绝回答或没有可用 `content` 的情况，请单独处理，不要直接作为业务 JSON 解析。
* 解析 `choices[0].message.content` 后，仍需校验数据是否满足业务要求。使用 JSON Mode 时，还需自行检查字段、类型和必填项。
* JSON Mode 可以通过 prompt 中的输入输出示例改善结构遵循效果，但不应据此承诺严格符合 Schema。
* 如果通过代理或网关调用，请确认 `response_format` 及其嵌套字段完整传递到 API 服务端；客户端请求中包含该字段，不代表中间链路一定保留了它。


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