邀请好友,获取免费 Tokens!了解更多

API 文档:创建结构化输出

接口说明

给定一个提示(Prompt),该模型将返回一个或多个预测的补全回复,并支持强制模型按指定的 JSON Schema 输出结构化数据。

官方参考文档OpenAI Structured Outputs

接口基础信息

  • 请求方式POST
  • 请求路径https://api.codingplanx.ai/v1/chat/completions
  • 数据格式application/json

请求头 (Headers)

参数名必填类型示例值描述
Content-Typestringapplication/json指定请求体数据类型
Acceptstringapplication/json指定客户端接收的数据类型
AuthorizationstringBearer {{YOUR_API_KEY}}身份验证凭证

请求体 (Request Body)

参数名必填类型描述
modelstring要使用的模型的 ID(如 gpt-4.1-2025-04-14)。
messagesarray至今为止对话所包含的消息列表。
? messages[].rolestring消息发送者的角色,如 system, user, assistant
? messages[].contentstring消息的具体内容。
toolsarray模型可以调用的一组工具列表。目前仅支持函数。用于提供模型可为其生成 JSON 输入的函数列表。
tool_choiceobject控制模型调用哪个函数。none 表示不调用,auto 表示自动选择。也可通过 {"type": "function", "function": {"name": "my_function"}} 强制调用。
temperatureinteger采样温度,介于 0 和 2 之间。值越高(如 0.8)输出越随机,值越低(如 0.2)输出越集中和确定。建议修改此项或 top_p,但不要同时修改两者。
top_pinteger核采样参数。0.1 意味着只考虑构成前 10% 概率质量的标记。建议修改此项或 temperature,但不要同时修改两者。
ninteger为每个输入消息生成多少个补全选择。默认为 1。
streamboolean是否启用流式输出。如果为 true,将以 Server-Sent Events (SSE) 形式发送部分消息增量,并以 data: [DONE] 终止。默认为 false。
stopstringAPI 将停止进一步生成标记的序列(最多 4 个)。默认为 null。
max_tokensinteger在聊天补全中生成的最大 Token 数。默认为 inf(无限)。
presence_penaltynumber存在惩罚(-2.0 到 2.0)。正值会根据新 Token 到目前为止是否出现在文本中来进行惩罚,增加模型谈论新主题的可能性。
frequency_penaltynumber频率惩罚(-2.0 到 2.0)。正值会根据文本目前的出现频率惩罚新 Token,降低模型重复相同内容的可能性。
logit_biasnull/object接受一个 JSON 对象,将 Token ID 映射到相关的偏差值(-100 到 100),用于修改指定标记出现在补全中的可能性。
userstring代表您最终用户的唯一标识符,帮助监控和检测滥用行为。
response_formatobject指定模型必须输出的格式对象。通过设置 {"type": "json_schema", "json_schema": {...}} 可启用结构化输出,确保模型生成有效的 JSON 格式。
seeninteger(Beta功能) 设定随机种子(Seed)。系统将尽最大努力确定性地进行采样,相同种子和参数的重复请求应返回相同结果。

请求示例 (Request Example)

{
  "model": "gpt-4.1-2025-04-14",
  "messages": [
    {
      "role": "system",
      "content": "Determine if the user input violates specific guidelines and explain if they do."
    },
    {
      "role": "user",
      "content": "How do I prepare for a job interview?"
    }
  ],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "content_compliance",
      "description": "Determines if content is violating specific moderation rules",
      "schema": {
        "type": "object",
        "properties": {
          "is_violating": {
            "type": "boolean",
            "description": "Indicates if the content is violating guidelines"
          },
          "category": {
            "type": ["string", "null"],
            "description": "Type of violation, if the content is violating guidelines. Null otherwise.",
            "enum": ["violence", "sexual", "self_harm"]
          },
          "explanation_if_violating": {
            "type": ["string", "null"],
            "description": "Explanation of why the content is violating"
          }
        },
        "required": ["is_violating", "category", "explanation_if_violating"],
        "additionalProperties": false
      },
      "strict": true
    }
  }
}

响应体 (Response Body)

参数名类型描述
idstring补全请求的唯一标识符。
objectstring对象类型,固定为 chat.completion
createdinteger创建时间的时间戳(Unix 秒)。
choicesarray补全选项的列表。
? choices[].indexinteger选项在列表中的索引。
? choices[].messageobject模型生成的消息对象。
? choices[].message.rolestring角色名称(通常为 assistant)。
? choices[].message.contentstring消息的具体内容。
? choices[].finish_reasonstring模型停止生成的原因(例如 stop, length)。
usageobjectToken 使用情况统计。
? usage.prompt_tokensinteger提示(Prompt)消耗的 Token 数量。
? usage.completion_tokensinteger生成的补全(Completion)消耗的 Token 数量。
? usage.total_tokensinteger总共消耗的 Token 数量。

响应示例 (Response Example)

{
    "id": "chatcmpl-123",
    "object": "chat.completion",
    "created": 1677652288,
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "\r
\r
Hello there, how may I assist you today?"
            },
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 9,
        "completion_tokens": 12,
        "total_tokens": 21
    }
}

常见问题解答 (FAQs)

1. 什么是 response_format 以及如何保证模型输出严格的 JSON?

response_format 参数允许您要求模型以特定的格式返回数据。如果您想使用“结构化输出”,需要将其设置为 {"type": "json_schema"} 并在内部定义您的 JSON Schema,并且将 strict: true 开启。这样可以确保模型100%按照您定义的字段和数据类型输出内容,无需您在代码中额外进行 JSON 容错解析。

2. 为什么我的 JSON 输出被截断了?

如果您的响应数据中,choices[0].finish_reason 的值为 length,说明生成的文本达到了 max_tokens 限制,或者超出了模型的最大上下文长度限制。建议在请求中调高 max_tokens 参数的值。

3. temperaturetop_p 参数有什么区别?我应该调整哪一个?

两者都是用来控制模型输出随机性的参数:

  • temperature 是缩放模型的输出概率分布。值越低,输出越严谨、确定;值越高,输出越具有发散性。
  • top_p(核采样)是限制模型只从累积概率达到 p 的最高频词汇中进行选择。 官方建议:只调整其中一个参数即可,不要同时修改 temperaturetop_p

4. 开启 stream: true 会发生什么?

当设置 stream: true 时,API 将不会等到整个回答生成完毕再返回,而是像打字机一样实时流式返回数据片段。返回的数据格式将变为 Server-Sent Events (SSE)。客户端需要通过监听数据流来拼接 delta.content,直到收到 [DONE] 标志表示结束。

5. 如何保证每次调用相同的 Prompt 得到完全相同的回答?

虽然大型语言模型具有随机性,但您可以通过传入指定的 seen (Seed) 参数,并将 temperature 设为 0 来实现最大程度的确定性输出。如果您看到返回结果中的 system_fingerprint 发生变化,说明后端模型配置有微调,此时即便 Seed 相同,结果也可能出现细微差异。