Skip to main content

acosmi/models/
wire_openai.rs

1//! OpenAI 兼容 wire-format 响应 DTO(非 Anthropic 厂商)。端口自 `models/wire-openai.ts`
2//! (其端口自 `acosmi-sdk-go/types.go` v0.19.0 的 OpenAI 兼容响应类型段)。
3//!
4//! 命名约定:字段名 = Go json tag 字面量(wire format),不做 camelCase 重映射。
5
6use serde::{Deserialize, Deserializer, Serialize};
7use serde_json::Value;
8
9/// 反序列化 `string | null` 为 `String`:`null` 落成空串。配合 `#[serde(default)]` 时键缺席同样
10/// 落成空串,于是「缺席」「`null`」「空串」在下游三者同形。
11///
12/// 参照 TS `models/adapters/openai.ts`:那边读这些字段一律走 truthiness
13/// (`if (choice.message.content && choice.message.content !== '')`),`null` / `undefined` / `''`
14/// 走同一条分支。Rust 侧字段类型保持 `String`(不改公开签名、序列化形态不变),只把反序列化的
15/// 宽容度对齐过去。
16fn de_string_or_empty<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
17where
18    D: Deserializer<'de>,
19{
20    Ok(Option::<String>::deserialize(deserializer)?.unwrap_or_default())
21}
22
23/// 反序列化 `arguments`:按 OpenAI 规范是 JSON 字符串,但部分兼容实现直接给对象/数组/数字。
24/// 非字符串一律用其 JSON 文本形态落成串(等价 TS 的 `JSON.stringify(fn.arguments)`),
25/// `null` 落成空串(等价 TS 的 `fn.arguments !== null` 守卫:不发 delta)。
26///
27/// 字段类型仍是 `String`,`Serialize` 形态不变。
28fn de_arguments_as_string<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
29where
30    D: Deserializer<'de>,
31{
32    Ok(match Value::deserialize(deserializer)? {
33        Value::Null => String::new(),
34        Value::String(s) => s,
35        other => other.to_string(),
36    })
37}
38
39/// 反序列化非流式 `usage`:`null` 落成三计数皆 0 的默认值。配合 `#[serde(default)]` 时键缺席同样
40/// 落成默认值,于是「缺席」与「`null`」在下游同形 —— 两者说的是同一件事:上游没有用量数据。
41///
42/// 参照 TS:`JSON.parse` 之后 `oai.usage` 为 `null` / `undefined` 时读 `oai.usage.prompt_tokens`
43/// 会抛,但 `convertOpenAIToChatResponse` 读的是可选链后的值,两种形态都不让整个响应失败。
44fn de_usage_or_default<'de, D>(deserializer: D) -> std::result::Result<OpenAIUsage, D::Error>
45where
46    D: Deserializer<'de>,
47{
48    Ok(Option::<OpenAIUsage>::deserialize(deserializer)?.unwrap_or_default())
49}
50
51/// 反序列化**非流式** `choices`:`null` 落成空 `Vec`。配合 `#[serde(default)]` 时键缺席同样落成空
52/// `Vec`,于是「缺席」与「`null`」在下游同形 —— 两者说的是同一件事:上游没有 choices。
53///
54/// 与流式那侧的 [`de_choices_lenient`] **刻意不是同一个函数**:元素类型不同([`OpenAIChatChoice`]
55/// vs [`OpenAIStreamChoice`]),为复用把两个 wire 类型合并就是在制造下一个 bug。宽容度也刻意窄一档
56/// —— 只收 `null`,对象 / 标量仍然报错:一帧异形的流式 chunk 只该让那一帧零事件(流还要继续),
57/// 而整个非流式响应体的 `choices` 不是数组,是这次调用彻底坏掉,不该被悄悄抹成「没有内容」。
58/// 这一档与 Go 的 `[]OpenAIChatChoice` 相同(`json.Unmarshal` 收 `null`、拒对象)。
59fn de_choices_or_empty<'de, D>(
60    deserializer: D,
61) -> std::result::Result<Vec<OpenAIChatChoice>, D::Error>
62where
63    D: Deserializer<'de>,
64{
65    Ok(Option::<Vec<OpenAIChatChoice>>::deserialize(deserializer)?.unwrap_or_default())
66}
67
68/// 反序列化流式 `choices`:不是数组(对象 / `null` / 标量)时落成空 `Vec` 而不是报错。
69///
70/// 等价 TS `OpenAIStreamConverter.convert` 的 `if (!Array.isArray(chunk.choices) …) return`:
71/// 病态上游或网关异形帧只该让这一帧零事件,不该让整条流终止。数组内元素本身形态不对仍然报错
72/// ——那是「有 choices 但解不动」,与「压根不是 choices 数组」是两回事。
73fn de_choices_lenient<'de, D>(
74    deserializer: D,
75) -> std::result::Result<Vec<OpenAIStreamChoice>, D::Error>
76where
77    D: Deserializer<'de>,
78{
79    match Value::deserialize(deserializer)? {
80        value @ Value::Array(_) => serde_json::from_value(value).map_err(serde::de::Error::custom),
81        _ => Ok(Vec::new()),
82    }
83}
84
85/// OpenAI 兼容同步响应。
86#[derive(Debug, Clone, Default, Serialize, Deserialize)]
87pub struct OpenAIChatResponse {
88    pub id: String,
89    /// "chat.completion"
90    pub object: String,
91    pub model: String,
92    /// 缺席**或显式 `null`** 落成空 `Vec`:零内容块,`id` / `model` / `usage` 照常转换。此前必填且
93    /// 非 null,两种形态分别以 `missing field \`choices\`` 与 `invalid type: null, expected a
94    /// sequence` 让整个非流式响应解码失败(`parse_response` / `parse_openai_response_to_anthropic` /
95    /// 直接 `from_str` 三个入口同时失败)—— 正文再完整,调用方一个字节也拿不到。
96    ///
97    /// 缺席那一半不是 Rust 比 TS 严:TS 此前在 `oai.choices.length` 处同样炸
98    /// (`Cannot read properties of undefined`);`null` 那一半 Rust 曾是三份里唯一的异类
99    /// —— TS 的 `Array.isArray(oai.choices)` 守卫与 Go 的 `[]OpenAIChatChoice`(`json.Unmarshal`
100    /// 把 `null` 解成 nil slice、`len(nil) == 0`)都容忍。2026-09-17 三份一并对齐到「容忍」:
101    /// 消除异类就是这个立项存在的理由,留着它等于亲手制造一条新的三份分歧。
102    ///
103    /// 宽容度到 `null` 为止:对象 / 标量形态的 `choices` 仍然报错,理由见源码中 `de_choices_or_empty`
104    /// 的注释(该函数是私有的,这里刻意不写成 intra-doc 链接 —— 公开文档链到私有项会被
105    /// `rustdoc::private_intra_doc_links` 判错)。
106    #[serde(default, deserialize_with = "de_choices_or_empty")]
107    pub choices: Vec<OpenAIChatChoice>,
108    /// 缺席**或显式 `null`** 时三个计数都落成 0。此前必填且非 null,不结算用量的兼容实现(以及被
109    /// 上游省略 `usage` 的错误回包)会以 `missing field \`usage\`` / `invalid type: null, expected
110    /// struct OpenAIUsage` 让**整个非流式响应**解码失败 —— 正文明明在,调用方却什么都拿不到。
111    /// TS 那边 `JSON.parse` 后读 `oai.usage.prompt_tokens` 得 `undefined`,两种形态都不会失败。
112    ///
113    /// 「缺席 / `null`」与「usage 在场但计数是 0」在本字段上同形:[`OpenAIUsage`] 的计数是 `i64`
114    /// 不是 `Option<i64>`,这一点不在本次改动面内(流式路径另有 [`OpenAIStreamUsage`])。
115    #[serde(default, deserialize_with = "de_usage_or_default")]
116    pub usage: OpenAIUsage,
117}
118
119/// OpenAI choices 元素。
120#[derive(Debug, Clone, Default, Serialize, Deserialize)]
121pub struct OpenAIChatChoice {
122    pub index: i64,
123    pub message: OpenAIChatMessage,
124    /// "stop", "tool_calls", "length"。
125    ///
126    /// nullable:被截断 / 未结算的回包上是 `null`。此前必填且非 null,那类回包在反序列化这一步就
127    /// 报 `invalid type: null, expected a string`,整个非流式响应失败。TS 的 `switch` 默认臂
128    /// (`resp.stop_reason = choice.finish_reason`)原样赋值、不抛错。
129    #[serde(default, deserialize_with = "de_string_or_empty")]
130    pub finish_reason: String,
131}
132
133/// OpenAI message。
134#[derive(Debug, Clone, Default, Serialize, Deserialize)]
135pub struct OpenAIChatMessage {
136    pub role: String,
137    /// nullable,且可缺席:OpenAI 规范对「只有工具调用」的响应返回 `"content": null`,部分兼容
138    /// 实现干脆不写这个键。此前必填且非 null,**标准的工具调用回包在反序列化这一步就失败**
139    /// (`invalid type: null, expected a string` / `missing field \`content\``)。
140    ///
141    /// 三种形态统一落成空串,与同文件转换器的 `if !content.is_empty()` 一起复刻 TS 的
142    /// truthiness 守卫:没有正文就不产 text 块。
143    #[serde(default, deserialize_with = "de_string_or_empty")]
144    pub content: String,
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub tool_calls: Option<Vec<OpenAIToolCall>>,
147    /// GLM/DeepSeek thinking。
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub reasoning_content: Option<String>,
150}
151
152/// OpenAI tool_call。
153#[derive(Debug, Clone, Default, Serialize, Deserialize)]
154pub struct OpenAIToolCall {
155    pub id: String,
156    /// "function"
157    pub r#type: String,
158    pub function: OpenAIFunctionCall,
159}
160
161/// OpenAI function call。
162///
163/// 两个字段在**流式**续片上都可能缺席:OpenAI 规范只在工具调用的首片给 `name`,后续增量只带
164/// `index` + `arguments` 分片。此前两者必填,每一次 OpenAI 线的工具调用都在第二帧
165/// `missing field \`name\`` 直接终止整条流。参照 TS 读的是 `fn?.name` / `fn?.arguments`。
166#[derive(Debug, Clone, Default, Serialize, Deserialize)]
167pub struct OpenAIFunctionCall {
168    /// `Option<String>` 而不是「缺席落空串」:空串与缺席必须可分辨。转换器据此决定
169    /// `content_block.name` 这个键**写不写**(TS `JSON.stringify` 对 `undefined` 省略该键),
170    /// 落成 `""` 会让下游的「有 name 键」判据收到一个空名字。`null` 与缺席同落 `None`。
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub name: Option<String>,
173    #[serde(default, deserialize_with = "de_arguments_as_string")]
174    pub arguments: String,
175}
176
177/// OpenAI token 用量(**非流式**响应)。三个计数都必填。
178#[derive(Debug, Clone, Default, Serialize, Deserialize)]
179pub struct OpenAIUsage {
180    pub prompt_tokens: i64,
181    pub completion_tokens: i64,
182    pub total_tokens: i64,
183}
184
185/// **流式** chunk 上的 usage 对象。与非流式的 [`OpenAIUsage`] 分开声明:流式帧上各计数都可能缺席
186/// (线上常见 `{"prompt_tokens":1,"completion_tokens":2}` 而无 `total_tokens`),还带明细子对象。
187/// 沿用 [`OpenAIUsage`] 等于把「三个计数一定在且是整数」的承诺强加给流式帧 —— 直接按公开类型
188/// [`OpenAIStreamChunk`] 解帧的库用户会撞上 `missing field \`total_tokens\``。
189///
190/// 与 TS `models/wire-openai.ts::OpenAIStreamUsage` 逐字对齐。SDK 只搬 `prompt_tokens` /
191/// `completion_tokens`(见 `models/adapters/openai.rs::read_stream_usage`);明细字段仅作类型声明,
192/// **不映射、不做净额换算** —— usage 的语义归一只在网关。
193#[derive(Debug, Clone, Default, Serialize, Deserialize)]
194pub struct OpenAIStreamUsage {
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub prompt_tokens: Option<i64>,
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub completion_tokens: Option<i64>,
199    #[serde(default, skip_serializing_if = "Option::is_none")]
200    pub total_tokens: Option<i64>,
201    /// 上游输入明细(如 `cached_tokens`);SDK 不读取。
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub prompt_tokens_details: Option<OpenAIStreamUsagePromptDetails>,
204    /// 上游输出明细(如 `reasoning_tokens`);SDK 不读取。
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub completion_tokens_details: Option<OpenAIStreamUsageCompletionDetails>,
207}
208
209/// [`OpenAIStreamUsage::prompt_tokens_details`] 的形状。
210#[derive(Debug, Clone, Default, Serialize, Deserialize)]
211pub struct OpenAIStreamUsagePromptDetails {
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub cached_tokens: Option<i64>,
214}
215
216/// [`OpenAIStreamUsage::completion_tokens_details`] 的形状。
217#[derive(Debug, Clone, Default, Serialize, Deserialize)]
218pub struct OpenAIStreamUsageCompletionDetails {
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub reasoning_tokens: Option<i64>,
221}
222
223/// OpenAI SSE delta 格式。
224///
225/// `id` / `object` / `choices` 反序列化时可缺省(缺省即空值),序列化形态不变。线上确实存在没有
226/// 这些字段的 data 帧:网关的错误契约帧,以及部分兼容实现的 usage-only 尾帧(证据见 TS
227/// `models/wire-openai.ts` 同名类型 `choices` 字段的注释)。此前三者都是必填,这类帧在反序列化
228/// 这一步就报错,整条流随之失败。
229#[derive(Debug, Clone, Default, Serialize, Deserialize)]
230pub struct OpenAIStreamChunk {
231    #[serde(default)]
232    pub id: String,
233    /// "chat.completion.chunk"
234    #[serde(default)]
235    pub object: String,
236    /// 非数组形态(对象 / `null` / 标量)落成空 `Vec`,见源码中 `de_choices_lenient` 的注释
237    /// (私有项,刻意不写成 intra-doc 链接,理由同上)。
238    #[serde(default, deserialize_with = "de_choices_lenient")]
239    pub choices: Vec<OpenAIStreamChoice>,
240    /// 按 `stream_options.include_usage` 的帧序,非尾帧上为 null 或缺失,带值的是 `[DONE]` 之前的
241    /// 尾帧 `{"choices":[],"usage":{...}}`。形状见 [`OpenAIStreamUsage`](各计数皆可缺席)。
242    ///
243    /// 流式转换器仍不经本字段读 usage:它按原始 `Value` 读(见
244    /// `models/adapters/openai.rs::read_stream_usage`),以免任何类型化约束决定整帧能否解析。
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub usage: Option<OpenAIStreamUsage>,
247}
248
249/// OpenAI SSE choice。
250#[derive(Debug, Clone, Default, Serialize, Deserialize)]
251pub struct OpenAIStreamChoice {
252    /// 兼容实现常省略。转换器从不读它(只取 `choices[0]`),缺席按 0 处理即可;此前必填,
253    /// 缺它的帧会以 `missing field \`index\`` 终止整条流。
254    #[serde(default)]
255    pub index: i64,
256    /// 缺席落成「各字段皆 `None`」的空 delta:该 choice 零事件、不报错、不终止流。此前必填,
257    /// 缺它的帧以 `missing field \`delta\`` 终止整条流。
258    ///
259    /// 这不是 Rust 比 TS 严:TS 在 `choice.delta.reasoning_content` 处同样炸(`undefined is not
260    /// an object`),Go 反而给零值。三份实现在 2026-09-17 一并对齐到「容忍」。
261    #[serde(default)]
262    pub delta: OpenAIStreamDelta,
263    /// nullable(`string | null`)。
264    #[serde(default)]
265    pub finish_reason: Option<String>,
266}
267
268/// OpenAI SSE delta。
269#[derive(Debug, Clone, Default, Serialize, Deserialize)]
270pub struct OpenAIStreamDelta {
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub role: Option<String>,
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub content: Option<String>,
275    #[serde(default, skip_serializing_if = "Option::is_none")]
276    pub reasoning_content: Option<String>,
277    #[serde(default, skip_serializing_if = "Option::is_none")]
278    pub tool_calls: Option<Vec<OpenAIStreamToolCall>>,
279}
280
281/// OpenAI SSE tool_call delta。
282#[derive(Debug, Clone, Default, Serialize, Deserialize)]
283pub struct OpenAIStreamToolCall {
284    /// OpenAI 流式规范里必填,但兼容实现常省略。`i64` 时「省略」与「`index: 0`」同形,两个都不带
285    /// index 的 tool_call 于是共用键 0 —— 只开一个块、两段参数拼进同一条 `partial_json` 流,产出
286    /// `{…}{…}` 这种必然非法的 JSON,第二个调用彻底丢失(Go 侧实测正是这个形态)。
287    ///
288    /// 缺席时归属由 `models/adapters/openai.rs` 的 `resolve_tool_key` 按 index → `id:` → 沿用上一个
289    /// 三级降级决定(对齐 TS `resolveToolKey`)。
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub index: Option<i64>,
292    #[serde(default, skip_serializing_if = "Option::is_none")]
293    pub id: Option<String>,
294    #[serde(default, skip_serializing_if = "Option::is_none")]
295    pub r#type: Option<String>,
296    /// OpenAI 流式规范允许后续增量只带 `{index}` 而不带 `function`。缺席落成两字段皆空串的
297    /// 默认值,于是既不建块也不发 delta;此前必填,这类空心增量会以 `missing field \`function\``
298    /// 终止整条流。参照 TS 的 `const fn = tc.function as {…} | undefined`。
299    #[serde(default)]
300    pub function: OpenAIFunctionCall,
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306
307    /// 序列化形态是 wire 契约的一半,必须被钉住、只在 major 版本上有意变更
308    /// (`docs/开发与发布手册.md`:wire-format 不兼容变更 = major)。
309    ///
310    /// 5.0.0 有意改了两处:`OpenAIStreamToolCall.index` 与 `OpenAIFunctionCall.name` 变
311    /// `Option` + `skip_serializing_if`,于是「上游没给」不再被写成 `0` / `""`。其余字段一字不动 ——
312    /// 这条断言同时守住「改了的两个」和「没改的一批」:任何一处再动都必红。
313    #[test]
314    fn serialized_shape_is_pinned() {
315        let message = OpenAIChatMessage {
316            role: "assistant".to_string(),
317            content: String::new(),
318            tool_calls: None,
319            reasoning_content: None,
320        };
321        // 非流式 message 的空 `content` 仍然照写(它必填、语义是「空正文」而非「没给」)。
322        assert_eq!(
323            serde_json::to_string(&message).unwrap_or_default(),
324            r#"{"role":"assistant","content":""}"#
325        );
326
327        // 5.0.0:`name` 为 `None` ⇒ 省略该键(此前写 `"name":""`)。`arguments` 仍是 `String`。
328        let function = OpenAIFunctionCall::default();
329        assert_eq!(
330            serde_json::to_string(&function).unwrap_or_default(),
331            r#"{"arguments":""}"#
332        );
333        assert_eq!(
334            serde_json::to_string(&OpenAIFunctionCall {
335                name: Some("get_weather".to_string()),
336                arguments: "{}".to_string(),
337            })
338            .unwrap_or_default(),
339            r#"{"name":"get_weather","arguments":"{}"}"#
340        );
341
342        let choice = OpenAIChatChoice::default();
343        assert_eq!(
344            serde_json::to_string(&choice).unwrap_or_default(),
345            r#"{"index":0,"message":{"role":"","content":""},"finish_reason":""}"#
346        );
347
348        let chunk = OpenAIStreamChunk::default();
349        assert_eq!(
350            serde_json::to_string(&chunk).unwrap_or_default(),
351            r#"{"id":"","object":"","choices":[]}"#
352        );
353
354        // 5.0.0:`index` 为 `None` ⇒ 省略该键(此前写 `"index":0`,与真的 `index: 0` 撞形)。
355        let tool_call = OpenAIStreamToolCall::default();
356        assert_eq!(
357            serde_json::to_string(&tool_call).unwrap_or_default(),
358            r#"{"function":{"arguments":""}}"#
359        );
360        assert_eq!(
361            serde_json::to_string(&OpenAIStreamToolCall {
362                index: Some(0),
363                ..Default::default()
364            })
365            .unwrap_or_default(),
366            r#"{"index":0,"function":{"arguments":""}}"#
367        );
368
369        // 流式 usage:全 `Option` + 全省略,空对象也是合法形态。
370        assert_eq!(
371            serde_json::to_string(&OpenAIStreamUsage::default()).unwrap_or_default(),
372            "{}"
373        );
374    }
375
376    /// R-12:直接按公开类型解流式帧的库用户不该被非流式 [`OpenAIUsage`] 的必填计数打死。
377    /// 线上 `{"prompt_tokens":1,"completion_tokens":2}`(无 `total_tokens`)是常见形态。
378    ///
379    /// 断言刻意**不解引用 `chunk.usage` 的字段**,而是把它序列化回 JSON 再比:把
380    /// `OpenAIStreamChunk::usage` 的类型改回 `Option<OpenAIUsage>` 时,这条是**运行期**红
381    /// (`missing field \`total_tokens\``)而不是编译不过 —— 编译不过会把下一条正向对照一起拖红,
382    /// 「红了」与「看不清为什么红」就成了同一件事。同一条断言还顺带钉住「缺席的计数不被补成 0」。
383    #[test]
384    fn stream_usage_type_accepts_partial_counts() {
385        let partial = r#"{"choices":[],"usage":{"prompt_tokens":1,"completion_tokens":2}}"#;
386        let chunk: OpenAIStreamChunk =
387            serde_json::from_str(partial).expect("partial usage counts must decode");
388        let usage = serde_json::to_value(&chunk.usage).unwrap_or(Value::Null);
389        assert_eq!(
390            usage,
391            serde_json::json!({ "prompt_tokens": 1, "completion_tokens": 2 })
392        );
393    }
394
395    /// 上一条的正向对照,**独立用例**:三计数齐全(外加线上真有的两个明细子对象)同样解得动,
396    /// 且计数原样读出 —— 证明上一条钉的是「计数可缺席」,不是「usage 被整个忽略了」。
397    ///
398    /// 直接解 [`OpenAIStreamUsage`] 而不经 [`OpenAIStreamChunk`]:上一条的篡改动的是 chunk 上那个
399    /// 字段的类型,本条据此仍能编译、仍该绿。
400    #[test]
401    fn stream_usage_type_still_reads_full_counts_and_details() {
402        let full = r#"{"prompt_tokens":13171,"completion_tokens":16,"total_tokens":13187,"completion_tokens_details":{"reasoning_tokens":14},"prompt_tokens_details":{"cached_tokens":13056}}"#;
403        let usage: OpenAIStreamUsage = serde_json::from_str(full).expect("full usage must decode");
404        assert_eq!(usage.prompt_tokens, Some(13171));
405        assert_eq!(usage.completion_tokens, Some(16));
406        assert_eq!(usage.total_tokens, Some(13187));
407        assert_eq!(
408            usage.prompt_tokens_details.and_then(|d| d.cached_tokens),
409            Some(13056)
410        );
411        assert_eq!(
412            usage
413                .completion_tokens_details
414                .and_then(|d| d.reasoning_tokens),
415            Some(14)
416        );
417    }
418
419    /// C-4:非流式响应缺 `choices` 不该让整个响应解码失败。实测此前三个入口同时报
420    /// `missing field \`choices\``(`from_str` / `parse_response` / `parse_openai_response_to_anthropic`)。
421    #[test]
422    fn non_stream_response_without_choices_decodes_as_empty() {
423        let no_choices = r#"{"id":"c1","object":"chat.completion","model":"m","usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}"#;
424        let resp: OpenAIChatResponse =
425            serde_json::from_str(no_choices).expect("missing choices must decode");
426        assert!(resp.choices.is_empty());
427        // 其余字段照常转换 —— 「不报错」不是靠把整个响应丢掉换来的。
428        assert_eq!(resp.id, "c1");
429        assert_eq!(resp.model, "m");
430        assert_eq!(resp.usage.prompt_tokens, 3);
431        assert_eq!(resp.usage.total_tokens, 8);
432    }
433
434    /// C-4 的另一半:`"choices": null` 与缺席是同一件事(上游说「我没有 choices」),不该报
435    /// `invalid type: null, expected a sequence`。`#[serde(default)]` 只管缺席,显式 null 要靠
436    /// [`de_choices_or_empty`]。三份对齐:TS 的 `Array.isArray` 守卫与 Go 的 nil slice 都容忍,
437    /// 此前只有 Rust 是异类。
438    #[test]
439    fn non_stream_response_with_null_choices_decodes_as_empty() {
440        let null_choices = r#"{"id":"c1","object":"chat.completion","model":"m","choices":null,"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}"#;
441        let resp: OpenAIChatResponse =
442            serde_json::from_str(null_choices).expect("null choices must decode");
443        assert!(resp.choices.is_empty());
444        assert_eq!(resp.id, "c1");
445        assert_eq!(resp.usage.prompt_tokens, 3);
446    }
447
448    /// 宽容度的边界,**独立用例**:只收 `null`,对象形态的 `choices` 仍然报错。非流式响应体整个
449    /// 不是 choices 数组 = 这次调用彻底坏掉,不该被悄悄抹成「没有内容」(理由见
450    /// [`de_choices_or_empty`];流式那侧刻意宽一档,见 [`de_choices_lenient`])。
451    /// 这条同时是「null 被收下」不是靠「什么都收」换来的证明。
452    #[test]
453    fn non_stream_response_with_object_choices_is_still_an_error() {
454        let object_choices =
455            r#"{"id":"c1","object":"chat.completion","model":"m","choices":{"0":{}}}"#;
456        let err = serde_json::from_str::<OpenAIChatResponse>(object_choices)
457            .expect_err("object choices must stay an error");
458        assert!(err.to_string().contains("expected a sequence"), "{err}");
459    }
460
461    /// 上几条的正向对照,**独立用例**:`choices` 在场时元素被如实读出 —— 证明它们钉的是
462    /// 「缺席 / null 按空数组」,不是「choices 根本没被解析」。
463    #[test]
464    fn non_stream_response_with_choices_still_reads_them() {
465        let with_choices = r#"{"id":"c1","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":5,"total_tokens":8}}"#;
466        let resp: OpenAIChatResponse =
467            serde_json::from_str(with_choices).expect("choices present must decode");
468        assert_eq!(resp.choices.len(), 1);
469        assert_eq!(resp.choices[0].message.content, "hi");
470        assert_eq!(resp.choices[0].finish_reason, "stop");
471    }
472
473    /// C-2:非流式响应缺 `usage` 不该让整个响应解码失败。不结算用量的兼容实现、以及被上游省略
474    /// `usage` 的回包都是这个形态;正文明明在,此前调用方什么都拿不到。
475    #[test]
476    fn non_stream_response_without_usage_decodes_with_zero_counts() {
477        let no_usage = r#"{"id":"c1","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}"#;
478        let resp: OpenAIChatResponse =
479            serde_json::from_str(no_usage).expect("missing usage must decode");
480        assert_eq!(resp.usage.prompt_tokens, 0);
481        assert_eq!(resp.usage.completion_tokens, 0);
482        assert_eq!(resp.usage.total_tokens, 0);
483        // 正文没被这一步吃掉。
484        assert_eq!(resp.choices.len(), 1);
485        assert_eq!(resp.choices[0].message.content, "hi");
486    }
487
488    /// C-2 的另一半:`"usage": null` 与缺席是同一件事(上游说「我没有用量数据」),不该报
489    /// `invalid type: null, expected struct OpenAIUsage`。`#[serde(default)]` 只管缺席,
490    /// 显式 null 要靠 [`de_usage_or_default`]。
491    #[test]
492    fn non_stream_response_with_null_usage_decodes_with_zero_counts() {
493        let null_usage = r#"{"id":"c1","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":null}"#;
494        let resp: OpenAIChatResponse =
495            serde_json::from_str(null_usage).expect("null usage must decode");
496        assert_eq!(resp.usage.prompt_tokens, 0);
497        assert_eq!(resp.usage.completion_tokens, 0);
498        assert_eq!(resp.usage.total_tokens, 0);
499        // 正文没被这一步吃掉。
500        assert_eq!(resp.choices.len(), 1);
501        assert_eq!(resp.choices[0].message.content, "hi");
502    }
503
504    /// 上两条的正向对照,**独立用例**:usage 在场时三个计数被如实读出 —— 证明它们钉的是
505    /// 「缺席 / null 按 0」,不是「usage 根本没被读」。
506    #[test]
507    fn non_stream_response_with_usage_reads_the_counts() {
508        let with_usage = r#"{"id":"c1","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":7,"completion_tokens":9,"total_tokens":16}}"#;
509        let resp: OpenAIChatResponse =
510            serde_json::from_str(with_usage).expect("usage present must decode");
511        assert_eq!(resp.usage.prompt_tokens, 7);
512        assert_eq!(resp.usage.completion_tokens, 9);
513        assert_eq!(resp.usage.total_tokens, 16);
514    }
515
516    /// 流式那侧 [`de_choices_lenient`] 的宽容面**逐形态**钉住。此前只有「对象」形态被测到
517    /// (`non_array_choices_yields_zero_events_not_a_stream_error`),`null` / 标量 / 缺席三种
518    /// 从未被任何用例走过 —— 「它收 null」当时是读代码读出来的,不是跑出来的。
519    ///
520    /// 这条同时是非流式那侧刻意窄一档的对照:两个函数的宽容面不同是**有意**的,不是漂移。
521    #[test]
522    fn stream_choices_accepts_every_non_array_shape() {
523        for body in [
524            r#"{"id":"c1","choices":null}"#,
525            r#"{"id":"c1"}"#,
526            r#"{"id":"c1","choices":{"0":{}}}"#,
527            r#"{"id":"c1","choices":123}"#,
528        ] {
529            let chunk: OpenAIStreamChunk =
530                serde_json::from_str(body).unwrap_or_else(|e| panic!("{body} must decode: {e}"));
531            assert!(chunk.choices.is_empty(), "{body}");
532            // 「没报错」不是靠把整帧丢掉换来的:同帧的其它字段照常读出。
533            assert_eq!(chunk.id, "c1", "{body}");
534        }
535    }
536
537    /// 上一条的正向对照,**独立用例**:真数组照常解出元素 —— 证明上一条钉的是「非数组落空」,
538    /// 不是「流式 choices 永远是空的」。
539    #[test]
540    fn stream_choices_still_decodes_a_real_array() {
541        let real = r#"{"id":"c1","choices":[{"index":0,"delta":{"content":"hi"}}]}"#;
542        let chunk: OpenAIStreamChunk = serde_json::from_str(real).expect("real array must decode");
543        assert_eq!(chunk.choices.len(), 1);
544        assert_eq!(chunk.choices[0].delta.content.as_deref(), Some("hi"));
545    }
546
547    /// C-1:choice 缺 `delta` 不该终止整条流。此前必填,缺它的帧报 `missing field \`delta\``。
548    #[test]
549    fn stream_choice_without_delta_decodes_to_an_empty_delta() {
550        let no_delta = r#"{"id":"c1","choices":[{"index":0,"finish_reason":"stop"}]}"#;
551        let chunk: OpenAIStreamChunk =
552            serde_json::from_str(no_delta).expect("missing delta must decode");
553        let choice = chunk.choices.first().expect("choice present");
554        assert!(choice.delta.role.is_none());
555        assert!(choice.delta.content.is_none());
556        assert!(choice.delta.reasoning_content.is_none());
557        assert!(choice.delta.tool_calls.is_none());
558        assert_eq!(choice.finish_reason.as_deref(), Some("stop"));
559    }
560
561    /// 上一条的正向对照,**独立用例**:delta 在场时内容被如实读出 —— 证明上一条钉的是
562    /// 「delta 可缺席」,不是「delta 整个被丢掉了」。
563    #[test]
564    fn stream_choice_with_delta_still_reads_its_content() {
565        let with_delta = r#"{"id":"c1","choices":[{"index":0,"delta":{"content":"hi"}}]}"#;
566        let chunk: OpenAIStreamChunk =
567            serde_json::from_str(with_delta).expect("delta present must decode");
568        let choice = chunk.choices.first().expect("choice present");
569        assert_eq!(choice.delta.content.as_deref(), Some("hi"));
570    }
571
572    /// R-3:tool_call 的 `index` 缺席与 `index: 0` 必须可分辨 —— 归并键的降级判据全靠这一点。
573    #[test]
574    fn stream_tool_call_index_absent_is_not_zero() {
575        let absent: OpenAIStreamToolCall =
576            serde_json::from_str(r#"{"id":"call_1","function":{"arguments":"{}"}}"#)
577                .expect("absent index must decode");
578        assert_eq!(absent.index, None);
579        assert_eq!(absent.function.name, None);
580
581        // 正向对照:真的 `index: 0` 读出 `Some(0)`,不与缺席同形。
582        let zero: OpenAIStreamToolCall =
583            serde_json::from_str(r#"{"index":0,"function":{"name":"f","arguments":"{}"}}"#)
584                .expect("explicit index must decode");
585        assert_eq!(zero.index, Some(0));
586        assert_eq!(zero.function.name.as_deref(), Some("f"));
587    }
588}