创建结构化输出
POST/v1/chat/completions 创建结构化输出
使用 POST /v1/chat/completions 可以让模型按照指定的 JSON Schema 返回结果。结构化输出适用于需要稳定解析模型回复的场景,例如信息抽取、表单生成、分类结果返回、函数参数生成等。
接口地址
POST https://www.vortapapi.com/v1/chat/completions
请求头
| 名称 | 必填 | 说明 |
|---|---|---|
Content-Type | 是 | 请求体格式,通常为 application/json |
Accept | 是 | 响应格式,通常为 application/json |
Authorization | 否 | API Key 鉴权信息,格式为 Bearer sk-*** |
请求体
结构化输出通过 response_format 字段指定。你可以将 type 设置为 json_schema,并在 json_schema 中定义期望模型返回的 JSON 结构。
参数示例
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "你是一个数据抽取助手。请严格按照给定的 JSON Schema 返回结果。"
},
{
"role": "user",
"content": "从这句话中提取事件信息:张三将在 2025 年 3 月 12 日下午 2 点参加产品发布会。"
}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "event_info",
"strict": true,
"schema": {
"type": "object",
"properties": {
"person": {
"type": "string",
"description": "参与事件的人"
},
"event": {
"type": "string",
"description": "事件名称"
},
"date": {
"type": "string",
"description": "事件日期"
},
"time": {
"type": "string",
"description": "事件时间"
}
},
"required": ["person", "event", "date", "time"],
"additionalProperties": false
}
}
}
}
请求示例
curl https://www.vortapapi.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "你是一个数据抽取助手。请严格按照给定的 JSON Schema 返回结果。"
},
{
"role": "user",
"content": "从这句话中提取事件信息:张三将在 2025 年 3 月 12 日下午 2 点参加产品发布会。"
}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "event_info",
"strict": true,
"schema": {
"type": "object",
"properties": {
"person": {
"type": "string"
},
"event": {
"type": "string"
},
"date": {
"type": "string"
},
"time": {
"type": "string"
}
},
"required": ["person", "event", "date", "time"],
"additionalProperties": false
}
}
}
}'
响应示例
模型返回的结构化内容位于 choices[0].message.content 中,内容是一个符合指定 Schema 的 JSON 字符串。
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "{\"person\":\"张三\",\"event\":\"产品发布会\",\"date\":\"2025 年 3 月 12 日\",\"time\":\"下午 2 点\"}"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 86,
"completion_tokens": 28,
"total_tokens": 114
}
}
字段说明
response_format
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
type | string | 是 | 输出格式类型。使用结构化输出时设置为 json_schema |
json_schema | object | 是 | JSON Schema 配置 |
response_format.json_schema
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
name | string | 是 | Schema 名称,用于标识该结构化输出格式 |
strict | boolean | 否 | 设置为 true 时,模型会更严格地遵循 Schema |
schema | object | 是 | 标准 JSON Schema 定义 |
使用建议
- 如果需要稳定解析结果,建议设置
"strict": true。 - 在 Schema 中使用
required明确必须返回的字段。 - 设置
"additionalProperties": false可以避免模型输出未定义字段。 choices[].message.content通常是 JSON 字符串,客户端需要自行反序列化为对象。