OpenAI 响应、流式与错误处理
本文档详细说明通过 UniGateway 调用 OpenAI 规范端点时的响应体结构对照、网关可观测性审计标头、Server-Sent Events (SSE) 与 WebSocket 流式事件生命周期,以及标准错误处理和网关运行模式。
章节导引
本篇为 OpenAI API 参考文档的第 6 章节:
- Responses 概述与快速开始
- 请求参数与输入格式
- 扩展推理与会话状态
- 结构化输出与采样参数
- 工具调用与内置工具
- 响应、流式与错误处理(当前章节)
响应结构详解
1. Responses API 响应结构(POST /v1/responses)
{
"id": "resp_67ccd2bed1ec8190b14f964abc054267",
"object": "response",
"created_at": 1741476542,
"status": "completed",
"model": "gpt-5.4",
"output": [
{
"type": "reasoning",
"id": "rs_67ccd2bf17f0819081ff3bb2cf6508e6",
"summary": [
{
"type": "summary_text",
"text": "正在分析 Raft 选举超时与心跳机制..."
}
]
},
{
"type": "message",
"id": "msg_67ccd2bf17f0819081ff3bb2cf6508e7",
"status": "completed",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "在 Raft 共识算法中,Leader 选举由 Follower 节点的选举超时(Election Timeout)触发...",
"annotations": []
}
]
}
],
"usage": {
"input_tokens": 42,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens": 318,
"output_tokens_details": {
"reasoning_tokens": 128
},
"total_tokens": 360
},
"service_tier": "default"
}
2. Chat Completions API 响应结构(POST /v1/chat/completions)
{
"id": "chatcmpl-b9d2a1c4e8f0123456789abc",
"object": "chat.completion",
"created": 1741476542,
"model": "gpt-5.4",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "在 Raft 共识算法中,Leader 选举由 Follower 节点的选举超时(Election Timeout)触发...",
"reasoning_content": "正在分析 Raft 选举超时与心跳机制..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 42,
"completion_tokens": 318,
"total_tokens": 360,
"prompt_tokens_details": {
"cached_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 128
}
},
"service_tier": "default"
}
3. 响应字段三维对照表
| 响应字段对照 | /v1/responses | /v1/chat/completions | UniGateway 处理说明 |
|---|---|---|---|
| 输出文本与拒绝信息 | output[] 中 type == "message" 项下的 content[].text(output_text)或 content[].refusal | choices[0].message.content 与 choices[0].message.refusal | 在非流式响应中,若上游流式终止事件的 output 数组为空,网关自动使用流式增量累加器回填完整文本与工具参数,防止出现空回复。 |
| 推理思维链摘要 | output[] 中 type == "reasoning" 项下的 summary[].text(summary_text) | choices[0].message.reasoning_content(流式为 delta.reasoning_content) | 当 /v1/chat/completions 请求经由 Responses 转换时,网关自动将 summary_text 与 reasoning_text 映射至 reasoning_content。 |
| 工具调用输出 | output[] 中 type == "function_call" 项(含 call_id、name、arguments) | choices[0].message.tool_calls[](含 id、type: "function"、function.name、function.arguments) | 自动完成双向结构映射;当输出包含工具调用时,Chat Completions 的 finish_reason 自动设为 "tool_calls"。 |
| 完成状态与停止原因 | status: "completed" / "incomplete" / "failed"(配合 incomplete_details.reason) | choices[0].finish_reason: "stop" / "length" / "tool_calls" / "content_filter" | status: "incomplete" 且原因为 "max_output_tokens" 时映射为 "length";原因为 "content_filter" 时映射为 "content_filter"。 |
| Token 用量统计 | usage.input_tokens、usage.output_tokens、input_tokens_details.cached_tokens、output_tokens_details.reasoning_tokens | usage.prompt_tokens、usage.completion_tokens、prompt_tokens_details.cached_tokens、completion_tokens_details.reasoning_tokens | 完整保留缓存命中 Token(cached_tokens)、缓存写入 Token 与推理 Token(reasoning_tokens)细分明细。 |
| 内部 ID 规范化与响应净化 | Responses API 要求标准 msg_ / rs_ / fc_ 格式 ID | 标准 Chat 消息对象 | 针对内部 Agent 消息生成的 amsg_ 前缀 ID,网关在出站前统一规范化为标准 msg_ 前缀;当请求设置 store: false 时,自动剥离残留未持久化 ID 与孤立 item_reference 引用。 |
| 思考签名透传与多轮绑定 | output[] 中 function_call.signature 或非工具轮次 type == "function_call_signature" 输出项 | message.thought_signature / tool_calls[].extra_content.google.thought_signature | 无论是否触发工具调用,均完整保留并无损回传跨协议推理模型生成的 thoughtSignature,确保多轮工具与纯文本推理会话验证顺利闭环。 |
| 流式占位符清洗 | 标准事件流无冗余帧 | 标准 Chunk 流无空白延续块 | 自动过滤清洗底层订阅通道产生的内部延续占位帧与空数据块,确保下游客户端接收干净合规的标准 SSE 事件。 |
响应审计头与请求控制头
当网关通过主动规范化或自适应重试对请求体执行了修正时,会在 HTTP 响应头中附加以下审计标头:
| HTTP 头名称 | 方向 | 示例取值 | 说明 |
|---|---|---|---|
x-gateway-modified | 响应头 | temperature=0.7=>@absent,reasoning.effort=max=>xhigh | 逗号分隔的已应用字段变更摘要,格式为 path=from=>to(字段新增或移除记为 @absent,脱敏字段记为 @redacted,复杂对象记为 @details,单响应头上限 1024 字节)。 |
x-gateway-modified-count | 响应头 | 2 | 本次请求实际应用的规范化变更总次数。 |
x-gateway-modified-truncated | 响应头 | true | 当 x-gateway-modified 渲染长度超过 1024 字节上限发生截断时输出 "true"。 |
x-gateway-modified-state | 响应头 | final / pending / not_committed | 审计头状态:final 表示所有改写已定稿。 |
x-gateway-degraded | 响应头 | reasoning_effort_clamped | 当应用的兼容变更涉及能力降级时,标识对应的降级规则摘要。 |
x-gateway-rectified | 响应头 | temperature_stripped,corrupted_encrypted_content | 逗号分隔的主动规范化或反应式重试修正标签(如 sanitize_chat_completions、corrupted_encrypted_content、rejected_field_retry、missing_tool_description 等)。 |
X-Gateway-Error-Class | 错误响应头 | inference_service_error | 非 200 错误响应的标准化错误分类标识(如 invalid_request_error、inference_capability_unavailable、inference_undetermined_rejection、inference_model_unavailable、inference_service_error)。 |
X-Gateway-Retryable | 错误响应头 | true / false | 指示当前错误响应是否建议重试(可重试时同步返回 Retry-After 头)。 |
x-gateway-rectify-opt-out | 请求头 | 1 或 true | 客户端在请求中携带该标头时,可针对单次请求关闭主动规范化与自适应重试(等同于单次官方严格直通模式)。 |
流式输出
1. Responses API 流式事件(POST /v1/responses 且 "stream": true)
开启流式后,响应 Content-Type 为 text/event-stream,按顺序推送标准语义化 SSE 事件:
event: response.created/event: response.in_progress:流式响应初始化,包含响应id与初始状态。event: response.output_item.added:新增输出项(如reasoning、message或function_call)。event: response.reasoning_summary_text.delta:思维链摘要文本增量(delta字段)。event: response.output_text.delta:正文文本增量(delta字段)。event: response.function_call_arguments.delta/event: response.function_call_arguments.done:工具调用 JSON 参数增量与完成事件。event: response.output_item.done:单个输出项生成完毕。event: response.completed(或response.incomplete/response.failed):流式正常结束,内嵌完整response对象及最终usage统计。
WebSocket 模式支持:
/v1/responses同时支持 WebSocket 协议升级(wss://api.unigateway.ai/v1/responses),适用于 Codex CLI 等需要长连接双向事件流(发送response.create事件并接收实时事件帧)的客户端。
2. Chat Completions 流式块(POST /v1/chat/completions 且 "stream": true)
每个 SSE data: 行携带一个 "object": "chat.completion.chunk" 对象:
- 首帧携带
delta: {"role": "assistant"}; - 推理期间推送
delta: {"reasoning_content": "..."}; - 正文生成期间推送
delta: {"content": "..."}或delta: {"tool_calls": [...]}; - 结束帧携带
finish_reason: "stop"(或"tool_calls"/"length"); - 若请求设置了
stream_options: {"include_usage": true},在结束帧之后额外推送一帧choices: []且包含完整usage对象的统计块,最后以data: [DONE]结束流。
错误处理与状态码
1. 标准错误响应格式
网关遵循 OpenAI 统一的错误 JSON 结构:
{
"error": {
"message": "Invalid 'max_output_tokens': integer below minimum value. Expected a value >= 1, but got 0 instead.",
"type": "invalid_request_error",
"param": "max_output_tokens",
"code": "integer_below_min_value"
}
}
2. 常见状态码与网关行为
| HTTP 状态码 | 错误类型 (error.type / error.code) | 触发原因与网关行为说明 |
|---|---|---|
400 Bad Request(参数校验拦截) | invalid_request_error | 如 max_output_tokens < 1(integer_below_min_value)、在 gpt-6.1-sol 上将 effort 设为 "none" 或 "minimal"、在 gpt-6.1-terra 上请求 effort: "minimal"、或在仅支持 Responses 工具调用的模型上通过原生 /v1/chat/completions 发送 tools。 |
400 Bad Request(输入或参数错误) | invalid_request_error | 请求体 JSON 语法损坏,或包含明确参数定位且经自适应重试后仍无法恢复的传参错误(无具体参数诊断的笼统拒绝将自动故障转移,耗尽后转为 502 inference_undetermined_rejection)。 |
401 Unauthorized | authentication_error | UniGateway API Key 缺失、格式错误、已过期或已被禁用。 |
403 Forbidden | forbidden_error | API Key 权限不足,或目标分组启用了专属客户端限制(如仅允许官方 Codex CLI 客户端访问)。 |
404 Not Found | model_not_found | 请求的模型未在网关发布,或请求了已在当前订阅通道下线的模型(如在仅配置了 OAuth 账号的分组中请求 gpt-5.5 / gpt-5.5-pro,网关返回 404 model_not_found 并提示切换至替代模型 GPT-6.1 Sol 或 GPT-6 Luna)。 |
413 Payload Too Large | request_body_too_large | 请求体大小超过网关单次请求上限(256MB)。 |
429 Too Many Requests | rate_limit_error / insufficient_quota | 触发客户端 API Key 速率限制/配额上限;若为单个通道触发 429,网关调度器会自动将该通道临时冷却并切换至池内其他健康通道重试。 |
502 Bad Gateway / 503 | api_error(inference_*) | 推理服务或容量异常,细分 error.code 包括:inference_capability_unavailable(当前无支持请求特性的推理容量)、inference_model_unavailable(已发布模型在候选推理通道均暂不可用)、inference_undetermined_rejection(无明确参数诊断的后端拒绝)、inference_service_error / inference_capacity_exhausted(502)及 inference_overloaded(503)。可重试错误同步返回 X-Gateway-Retryable: true 与 Retry-After。 |
网关运行模式说明
租户可在网关配置中按服务特性(主动规范化、自适应重试)进行分级控制:
compatible(默认推荐):完整启用参数规范化与自适应重试,自动处理跨代际模型与跨协议迁移中的参数不兼容问题,并在响应头中输出x-gateway-modified与x-gateway-rectified。official(官方严格直通模式):关闭面向兼容性的主动规范化改写与反应式重试,将客户端原始参数原样透传给上游并返回上游原生响应(适合需要严格验证客户端 SDK 参数合规性的测试环境)。observe(灰度观测模式):评估主动规范化规则并将命中项以未应用状态记录至后台请求审计快照,但不修改发往上游的请求体,也不向客户端输出x-gateway-modified变更响应头。