diff --git a/crates/tw-dialect/src/chat/request.rs b/crates/tw-dialect/src/chat/request.rs index bcd8e5b3..6a749440 100644 --- a/crates/tw-dialect/src/chat/request.rs +++ b/crates/tw-dialect/src/chat/request.rs @@ -255,11 +255,15 @@ fn user_parts(content: &Value, dropped: &mut Dropped) -> Vec { fn assistant_parts(m: &Value, dropped: &mut Dropped) -> Vec { let mut parts = Vec::new(); - // DeepSeek 等实现的推理字段,不在 OpenAI 的定义里 - if let Some(t) = str_of(m, "reasoning_content").filter(|t| !t.is_empty()) { + // DeepSeek 等实现的推理字段,不在 OpenAI 的定义里。DeepSeek 叫 reasoning_content, + // OpenRouter、vLLM 叫 reasoning + if let Some(t) = str_of(m, "reasoning_content") + .or_else(|| str_of(m, "reasoning")) + .filter(|t| !t.is_empty()) + { parts.push(Part::Thinking(Thinking { text: t.to_string(), - signature: None, + signature: Some(Signature::new(Vendor::Chat, "")), })); } match m.get("content") { @@ -308,7 +312,10 @@ pub fn encode_request(r: &Request, t: &Target, dropped: &mut Dropped) -> Value { if !r.system.is_empty() { messages.push(json!({ "role": "system", "content": r.system.join("\n\n") })); } - for m in &r.messages { + // 连着的几条助手消息并成一条:Responses 客户端一项一条消息,推理、文字、工具调用 + // 各在一条里,而 DeepSeek 要 reasoning_content 和 tool_calls 写在同一条助手消息上。 + // 用户那一侧不并:对话中途折成用户消息的系统提示要留在原位(见 `fold_system_turns`) + for m in &merge_assistant_turns(&r.messages) { match m.role { Role::User | Role::System => user_messages(m, dropped, &mut messages), Role::Assistant => { @@ -498,8 +505,23 @@ fn user_messages(m: &Message, dropped: &mut Dropped, out: &mut Vec) { out.push(json!({ "role": "user", "content": content })); } +/// 连着的助手消息并成一条,别的原样 +fn merge_assistant_turns(messages: &[Message]) -> Vec { + let mut out: Vec = Vec::with_capacity(messages.len()); + for m in messages { + match out.last_mut() { + Some(last) if last.role == Role::Assistant && m.role == Role::Assistant => { + last.parts.extend(m.parts.iter().cloned()) + } + _ => out.push(m.clone()), + } + } + out +} + fn assistant_message(m: &Message, dropped: &mut Dropped) -> Option { let mut texts = Vec::new(); + let mut reasoning = Vec::new(); let mut calls = Vec::new(); for p in &m.parts { match p { @@ -509,7 +531,15 @@ fn assistant_message(m: &Message, dropped: &mut Dropped) -> Option { "type": "function", "function": { "name": c.name, "arguments": c.input.to_json_text() }, })), - Part::Thinking(_) => dropped.feature(Feature::ReasoningHistory), + // 只写回 Chat 上游自己给的推理:DeepSeek 在工具调用的那几轮要它原样带回; + // 别家签发的写过去没有意义,而且 OpenAI 自己的接口不认 reasoning_content + Part::Thinking(th) => match &th.signature { + Some(s) if s.vendor == Vendor::Chat && !th.text.is_empty() => { + reasoning.push(th.text.as_str()) + } + Some(s) if s.vendor == Vendor::Chat => {} + _ => dropped.feature(Feature::ReasoningHistory), + }, _ => {} } } @@ -520,6 +550,9 @@ fn assistant_message(m: &Message, dropped: &mut Dropped) -> Option { "role": "assistant", "content": if texts.is_empty() { Value::Null } else { json!(texts.join("\n")) }, }); + if !reasoning.is_empty() { + msg["reasoning_content"] = json!(reasoning.join("\n\n")); + } if !calls.is_empty() { msg["tool_calls"] = Value::Array(calls); } @@ -614,13 +647,54 @@ mod tests { m[3], json!({"role": "tool", "tool_call_id": "call_1", "content": "放大了"}) ); - // 兼容实现:max_tokens;推理内容不回传 + // 兼容实现:max_tokens;Chat 上游给的推理内容原样写回 assert_eq!(v["max_tokens"], 2000); - assert_eq!(dropped, ["messages.content.thinking"]); + assert_eq!(m[2]["reasoning_content"], "看图"); + assert!(dropped.is_empty(), "{dropped:?}"); assert_eq!(v["stream_options"]["include_usage"], true); assert_eq!(v["response_format"]["json_schema"]["strict"], true); } + #[test] + fn reasoning_signed_by_another_vendor_is_not_written_back() { + let r = Request { + model: "gpt-5".into(), + messages: vec![Message { + role: Role::Assistant, + parts: vec![ + Part::Thinking(Thinking { + text: "想".into(), + signature: Some(Signature::new(Vendor::Anthropic, "sig")), + }), + Part::Thinking(Thinking { + text: "想".into(), + signature: None, + }), + Part::Text("答".into()), + ], + }], + ..Default::default() + }; + let (v, dropped) = encode(&r, Dialect::Anthropic, true); + assert_eq!(v["messages"][0]["content"], "答"); + assert!(v["messages"][0].get("reasoning_content").is_none()); + assert_eq!(dropped, ["messages.content.thinking"]); + } + + #[test] + fn reasoning_is_read_too() { + let (r, _, _) = decode( + r#"{"model": "m", "messages": [{"role": "assistant", "content": "答", "reasoning": "想"}]}"#, + ); + assert_eq!( + r.messages[0].parts[0], + Part::Thinking(Thinking { + text: "想".into(), + signature: Some(Signature::new(Vendor::Chat, "")), + }) + ); + } + #[test] fn the_official_endpoint_gets_max_completion_tokens() { let (r, _, _) = decode(CLIENT); diff --git a/crates/tw-dialect/src/chat/response.rs b/crates/tw-dialect/src/chat/response.rs index b935aab6..c284e5a0 100644 --- a/crates/tw-dialect/src/chat/response.rs +++ b/crates/tw-dialect/src/chat/response.rs @@ -63,10 +63,14 @@ pub fn decode_response(v: &Value) -> Response { .unwrap_or(&Value::Null); let msg = choice.get("message").unwrap_or(&Value::Null); let mut blocks = Vec::new(); - if let Some(t) = str_of(msg, "reasoning_content").filter(|t| !t.is_empty()) { + // DeepSeek 叫 reasoning_content,OpenRouter、vLLM 叫 reasoning + if let Some(t) = str_of(msg, "reasoning_content") + .or_else(|| str_of(msg, "reasoning")) + .filter(|t| !t.is_empty()) + { blocks.push(Block::Thinking(Thinking { text: t.to_string(), - signature: None, + signature: Some(Signature::new(Vendor::Chat, "")), })); } for key in ["content", "refusal"] { @@ -212,7 +216,13 @@ mod tests { "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f", "arguments": ""}}]}, "finish_reason": "tool_calls"}] })); - assert!(matches!(&r.blocks[0], Block::Thinking(t) if t.text == "推理")); + assert_eq!( + r.blocks[0], + Block::Thinking(Thinking { + text: "推理".into(), + signature: Some(Signature::new(Vendor::Chat, "")), + }) + ); assert!( matches!(&r.blocks[2], Block::ToolCall(c) if c.input == ToolInput::Json(json!({}))) ); diff --git a/crates/tw-dialect/src/chat/stream.rs b/crates/tw-dialect/src/chat/stream.rs index 01c301d9..2130f871 100644 --- a/crates/tw-dialect/src/chat/stream.rs +++ b/crates/tw-dialect/src/chat/stream.rs @@ -143,7 +143,14 @@ impl Parser { } fn close(&mut self, out: &mut Vec) { - if let Some((index, _)) = self.open.take() { + if let Some((index, o)) = self.open.take() { + // 推理块结束时打上 Chat 的厂商:下一轮认得出该原样写回 reasoning_content + if o == Open::Thinking { + out.push(Event::Delta { + index, + delta: Delta::Signature(Signature::new(Vendor::Chat, "")), + }); + } out.push(Event::BlockStop { index }); } } @@ -367,6 +374,11 @@ mod tests { .filter(|e| matches!(e, Event::BlockStop { .. })) .count(); assert_eq!(stops, 4); + // 推理块带着 Chat 的厂商结束:客户端带回来时认得出该写回 reasoning_content + assert!(ev.contains(&Event::Delta { + index: 0, + delta: Delta::Signature(Signature::new(Vendor::Chat, "")), + })); assert!(ev.contains(&Event::Stop(StopReason::ToolUse))); assert!(ev.contains(&Event::Usage(Usage { input: 40, diff --git a/crates/tw-dialect/src/convert.rs b/crates/tw-dialect/src/convert.rs index 712b4144..bd1d64c6 100644 --- a/crates/tw-dialect/src/convert.rs +++ b/crates/tw-dialect/src/convert.rs @@ -1462,7 +1462,8 @@ mod tests { {"type": "thinking", "thinking": "x", "signature": "tw1.o.rs_1:enc"}, {"type": "text", "text": "answer"} ]}, - {"role": "assistant", "content": [{"type": "thinking", "thinking": "y", "signature": "tw1.n."}]} + {"role": "assistant", "content": [{"type": "thinking", "thinking": "y", "signature": "tw1.n."}]}, + {"role": "assistant", "content": [{"type": "thinking", "thinking": "z", "signature": "tw1.ch."}]} ]}) .to_string(); let out: Value = diff --git a/crates/tw-dialect/src/ir.rs b/crates/tw-dialect/src/ir.rs index be29046b..df773db8 100644 --- a/crates/tw-dialect/src/ir.rs +++ b/crates/tw-dialect/src/ir.rs @@ -428,6 +428,10 @@ pub enum Vendor { Anthropic, OpenAi, Google, + /// Chat 格式的上游(DeepSeek 等)的 `reasoning_content`。它们不签名,`value` 为空; + /// 打上厂商只为了下一轮认得出这段推理该原样写回 `reasoning_content` —— DeepSeek + /// 在工具调用的那几轮要求带回来,而 OpenAI 自己的 Chat 接口不认这个字段 + Chat, } /// 转换写出去的签名的前缀。**直通时看到它就知道这段推理不是那个上游签发的** @@ -448,6 +452,8 @@ impl Signature { (Vendor::Anthropic, true) => "ar", (Vendor::OpenAi, _) => "o", (Vendor::Google, _) => "g", + // `c` 是压缩项的(见 [`crate::compaction::CARRIED_PREFIX`]) + (Vendor::Chat, _) => "ch", } } @@ -471,7 +477,8 @@ impl Signature { "ar" => (Vendor::Anthropic, true), "o" => (Vendor::OpenAi, false), "g" => (Vendor::Google, false), - // `n`:没有签名的推理(比如 DeepSeek 的 reasoning_content) + "ch" => (Vendor::Chat, false), + // `n`:没有签名的推理 _ => return None, }; Some(Signature { diff --git a/crates/tw-dialect/tests/matrix.rs b/crates/tw-dialect/tests/matrix.rs index 3869c2f9..697781a0 100644 --- a/crates/tw-dialect/tests/matrix.rs +++ b/crates/tw-dialect/tests/matrix.rs @@ -319,7 +319,7 @@ fn decode_client_stream(d: Dialect, bytes: &[u8]) -> Response { Event::Delta { index, delta } => match (&mut r.blocks[open[&index]], delta) { (Block::Text(t), Delta::Text(x)) => t.push_str(&x), (Block::Thinking(th), Delta::Thinking(x)) => th.text.push_str(&x), - (Block::Thinking(th), Delta::Signature(s)) => th.signature = Some(s), + (Block::Thinking(th), Delta::Signature(sig)) => th.signature = Some(sig), (Block::ToolCall(c), Delta::ToolInput(x)) => { if let ToolInput::Text(t) = &mut c.input { t.push_str(&x); @@ -478,6 +478,374 @@ fn a_stream_collected_for_a_client_that_wanted_a_whole_response() { } } +// ───────────────────────────────────────────────────────── 推理内容 + +/// 这家上游签发的推理签名长什么样。Chat 上游(DeepSeek 等)不签名,只打厂商 +fn signed_by(upstream: Dialect) -> Signature { + match upstream { + Dialect::Anthropic | Dialect::Bedrock => Signature::new(Vendor::Anthropic, "sigA"), + Dialect::Chat => Signature::new(Vendor::Chat, ""), + Dialect::Responses => Signature::new(Vendor::OpenAi, "rs_1:encO"), + Dialect::Gemini => Signature::new(Vendor::Google, "sigG"), + } +} + +/// 客户端请求:上一轮上游想了想、调了工具,工具结果回来了。推理带着 `sig`, +/// 写在客户端格式的签名字段里(别家签发的加 `tw1.` 前缀,和写给客户端时一样)。 +/// Chat 客户端没有签名字段,只能带 Chat 上游自己的推理:别的签名是 `None` +fn client_request_with_thinking(d: Dialect, sig: &Signature) -> Option> { + let call = json!({"city": "北京"}); + let body = match d { + Dialect::Anthropic => json!({ + "model": "test-model", "max_tokens": 1024, + "messages": [ + {"role": "user", "content": "北京天气?"}, + {"role": "assistant", "content": [ + {"type": "thinking", "thinking": "想想", "signature": sig.carried_in(Vendor::Anthropic)}, + {"type": "tool_use", "id": "call_1", "name": "get_weather", "input": call} + ]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "晴"}]} + ], + "tools": [{"name": "get_weather", "description": "查天气", "input_schema": schema()}], + }), + Dialect::Chat => { + if sig.vendor != Vendor::Chat { + return None; + } + json!({ + "model": "test-model", + "messages": [ + {"role": "user", "content": "北京天气?"}, + {"role": "assistant", "content": null, "reasoning_content": "想想", + "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": call.to_string()}}]}, + {"role": "tool", "tool_call_id": "call_1", "content": "晴"} + ], + "tools": [{"type": "function", "function": {"name": "get_weather", "description": "查天气", "parameters": schema()}}], + }) + } + Dialect::Responses => { + // OpenAI 自己的签名是「项 id:密文」,拆开写;别家的整个放进 encrypted_content + let (id, enc) = match sig.vendor { + Vendor::OpenAi => sig.value.split_once(':').unwrap(), + _ => ("rs_tw", ""), + }; + let enc = if enc.is_empty() { + sig.carried_in(Vendor::OpenAi) + } else { + enc.to_string() + }; + json!({ + "model": "test-model", + "input": [ + {"type": "message", "role": "user", "content": "北京天气?"}, + {"type": "reasoning", "id": id, "summary": [{"type": "summary_text", "text": "想想"}], "encrypted_content": enc}, + {"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "get_weather", "arguments": call.to_string()}, + {"type": "function_call_output", "call_id": "call_1", "output": "晴"} + ], + "tools": [{"type": "function", "name": "get_weather", "description": "查天气", "parameters": schema(), "strict": false}], + }) + } + Dialect::Gemini => json!({ + "contents": [ + {"role": "user", "parts": [{"text": "北京天气?"}]}, + {"role": "model", "parts": [ + {"text": "想想", "thought": true, "thoughtSignature": sig.carried_in(Vendor::Google)}, + {"functionCall": {"id": "call_1", "name": "get_weather", "args": call}} + ]}, + {"role": "user", "parts": [{"functionResponse": {"id": "call_1", "name": "get_weather", "response": {"output": "晴"}}}]} + ], + "tools": [{"functionDeclarations": [{"name": "get_weather", "description": "查天气", "parametersJsonSchema": schema()}]}], + }), + Dialect::Bedrock => unreachable!("Bedrock is not among the client dialects here"), + }; + Some(body.to_string().into_bytes()) +} + +/// 上游的整包响应:想了想,答了一句 +fn upstream_response_with_thinking(d: Dialect) -> Value { + match d { + Dialect::Anthropic => json!({ + "id": "msg_up", "type": "message", "role": "assistant", "model": "up-model", + "content": [ + {"type": "thinking", "thinking": "想想", "signature": "sigA"}, + {"type": "text", "text": "天气晴"} + ], + "stop_reason": "end_turn", + "usage": {"input_tokens": 100, "output_tokens": 20} + }), + Dialect::Chat => json!({ + "id": "chatcmpl-up", "object": "chat.completion", "model": "up-model", + "choices": [{"index": 0, "finish_reason": "stop", "message": { + "role": "assistant", "reasoning_content": "想想", "content": "天气晴" + }}], + "usage": {"prompt_tokens": 100, "completion_tokens": 20} + }), + Dialect::Responses => json!({ + "id": "resp_up", "object": "response", "status": "completed", "model": "up-model", + "output": [ + {"type": "reasoning", "id": "rs_1", "summary": [{"type": "summary_text", "text": "想想"}], "encrypted_content": "encO"}, + {"type": "message", "id": "msg_1", "role": "assistant", "content": [{"type": "output_text", "text": "天气晴"}]} + ], + "usage": {"input_tokens": 100, "output_tokens": 20} + }), + Dialect::Gemini => json!({ + "candidates": [{"content": {"role": "model", "parts": [ + {"text": "想想", "thought": true, "thoughtSignature": "sigG"}, + {"text": "天气晴"} + ]}, "finishReason": "STOP"}], + "usageMetadata": {"promptTokenCount": 100, "candidatesTokenCount": 20}, + "modelVersion": "up-model", "responseId": "r_up" + }), + Dialect::Bedrock => unreachable!("Bedrock is not among the upstream dialects here"), + } +} + +/// 上游的流:推理分两片,签名在推理块结束前到 +fn upstream_stream_with_thinking(d: Dialect) -> String { + match d { + Dialect::Anthropic => [ + named("message_start", json!({"type": "message_start", "message": {"id": "msg_up", "model": "up-model", + "usage": {"input_tokens": 100, "output_tokens": 1}}})), + named("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": "", "signature": ""}})), + named("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "想"}})), + named("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "想"}})), + named("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "sigA"}})), + named("content_block_stop", json!({"type": "content_block_stop", "index": 0})), + named("content_block_start", json!({"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}})), + named("content_block_delta", json!({"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "天气晴"}})), + named("content_block_stop", json!({"type": "content_block_stop", "index": 1})), + named("message_delta", json!({"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 20}})), + named("message_stop", json!({"type": "message_stop"})), + ] + .concat(), + Dialect::Chat => { + let chunk = |delta: Value, finish: Value| { + data(json!({"id": "chatcmpl-up", "object": "chat.completion.chunk", "model": "up-model", + "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]})) + }; + [ + chunk(json!({"role": "assistant", "content": ""}), Value::Null), + chunk(json!({"reasoning_content": "想"}), Value::Null), + chunk(json!({"reasoning_content": "想"}), Value::Null), + chunk(json!({"content": "天气晴"}), Value::Null), + chunk(json!({}), json!("stop")), + data(json!({"id": "chatcmpl-up", "object": "chat.completion.chunk", "model": "up-model", "choices": [], + "usage": {"prompt_tokens": 100, "completion_tokens": 20}})), + "data: [DONE]\n\n".to_string(), + ] + .concat() + } + Dialect::Responses => [ + named("response.created", json!({"type": "response.created", "response": {"id": "resp_up", "model": "up-model", "status": "in_progress"}})), + named("response.output_item.added", json!({"type": "response.output_item.added", "output_index": 0, "item": {"type": "reasoning", "id": "rs_1", "summary": []}})), + named("response.reasoning_summary_text.delta", json!({"type": "response.reasoning_summary_text.delta", "output_index": 0, "summary_index": 0, "item_id": "rs_1", "delta": "想"})), + named("response.reasoning_summary_text.delta", json!({"type": "response.reasoning_summary_text.delta", "output_index": 0, "summary_index": 0, "item_id": "rs_1", "delta": "想"})), + named("response.output_item.done", json!({"type": "response.output_item.done", "output_index": 0, "item": {"type": "reasoning", "id": "rs_1", "summary": [{"type": "summary_text", "text": "想想"}], "encrypted_content": "encO"}})), + named("response.output_item.added", json!({"type": "response.output_item.added", "output_index": 1, "item": {"type": "message", "id": "msg_1", "role": "assistant", "content": []}})), + named("response.content_part.added", json!({"type": "response.content_part.added", "output_index": 1, "content_index": 0, "item_id": "msg_1", "part": {"type": "output_text", "text": ""}})), + named("response.output_text.delta", json!({"type": "response.output_text.delta", "output_index": 1, "content_index": 0, "item_id": "msg_1", "delta": "天气晴"})), + named("response.output_text.done", json!({"type": "response.output_text.done", "output_index": 1, "content_index": 0, "item_id": "msg_1", "text": "天气晴"})), + named("response.output_item.done", json!({"type": "response.output_item.done", "output_index": 1, "item": {"type": "message", "id": "msg_1", "role": "assistant", "content": [{"type": "output_text", "text": "天气晴"}]}})), + named("response.completed", json!({"type": "response.completed", "response": {"id": "resp_up", "status": "completed", + "usage": {"input_tokens": 100, "output_tokens": 20}}})), + ] + .concat(), + Dialect::Gemini => { + let chunk = |parts: Value| { + data(json!({"candidates": [{"content": {"role": "model", "parts": parts}}], "modelVersion": "up-model", "responseId": "r_up"})) + }; + [ + chunk(json!([{"text": "想", "thought": true}])), + chunk(json!([{"text": "想", "thought": true, "thoughtSignature": "sigG"}])), + data(json!({"candidates": [{"content": {"role": "model", "parts": [{"text": "天气晴"}]}, "finishReason": "STOP"}], + "usageMetadata": {"promptTokenCount": 100, "candidatesTokenCount": 20}})), + ] + .concat() + } + Dialect::Bedrock => unreachable!("Bedrock is not among the upstream dialects here"), + } +} + +/// 读回的推理块:(文字, 签名)。多块拼成一块 +fn seen_thinking(r: &Response) -> Option { + let mut seen: Option = None; + for b in &r.blocks { + if let Block::Thinking(th) = b { + match &mut seen { + Some(t) => { + t.text.push_str(&th.text); + t.signature = th.signature.clone().or(t.signature.take()); + } + None => seen = Some(th.clone()), + } + } + } + seen +} + +/// 客户端读回的签名和上游签发的是同一个。Responses 给自己的推理项起新的 id, +/// 比 OpenAI 的签名时只看密文那一半 +fn same_signature(seen: Option<&Signature>, want: &Signature) -> bool { + let Some(seen) = seen else { + return false; + }; + if seen.vendor != want.vendor || seen.redacted != want.redacted { + return false; + } + match want.vendor { + Vendor::OpenAi => { + seen.value.rsplit_once(':').map(|x| x.1) == want.value.rsplit_once(':').map(|x| x.1) + } + _ => seen.value == want.value, + } +} + +fn check_thinking(client: Dialect, upstream: Dialect, path: &str, r: &Response) { + let at = format!("{client:?} ← {upstream:?}({path})"); + let th = seen_thinking(r).unwrap_or_else(|| panic!("{at}:没有推理块\n{r:#?}")); + assert_eq!(th.text, "想想", "{at}"); + let (text, _, stop, _) = seen_response(r); + assert_eq!(text, "天气晴", "{at}"); + assert_eq!(stop, Some(StopReason::EndTurn), "{at}"); + // Chat 客户端没有签名字段:只拿得到文字 + if client != Dialect::Chat { + let want = signed_by(upstream); + assert!( + same_signature(th.signature.as_ref(), &want), + "{at}:签名 {:?},上游签的是 {want:?}", + th.signature + ); + } +} + +/// 历史里的推理内容:签发它的那家上游能原样收到,别家收不到(记在丢掉的字段里)。 +/// 四种客户端各带四家的签名都试一遍 +#[test] +fn thinking_in_the_history_reaches_the_upstream_that_signed_it() { + for client in ALL { + for upstream in ALL { + for signer in ALL { + let sig = signed_by(signer); + let Some(body) = client_request_with_thinking(client, &sig) else { + continue; + }; + let (_, path, query) = client_request(client, false); + let at = format!("{client:?} → {upstream:?},{signer:?} 签的"); + let p = prepare(client, &body, &path, query.as_deref(), &target(upstream)) + .unwrap_or_else(|e| panic!("{at}:{e}")); + let v: Value = serde_json::from_slice(&p.body).unwrap(); + let mut d = Dropped::new(upstream); + let mut shape = ClientShape::default(); + let r = match upstream { + Dialect::Anthropic => anthropic::decode_request(&v, &mut d), + Dialect::Chat => chat::decode_request(&v, &mut d, &mut shape), + Dialect::Responses => responses::decode_request(&v, &mut d, &mut shape), + Dialect::Gemini => gemini::decode_request(&v, "test-model", false, &mut d), + Dialect::Bedrock => bedrock::decode_request(&v, "test-model", false, &mut d), + } + .unwrap(); + // 有的格式一项一条消息:看所有助手消息里的块 + let assistant: Vec<&Part> = r + .messages + .iter() + .filter(|m| m.role == Role::Assistant) + .flat_map(|m| m.parts.iter()) + .collect(); + let thinking: Vec<&Thinking> = assistant + .iter() + .filter_map(|p| match p { + Part::Thinking(t) => Some(t), + _ => None, + }) + .collect(); + assert!( + assistant + .iter() + .any(|p| matches!(p, Part::ToolCall(c) if c.name == "get_weather")), + "{at}:工具调用丢了\n{v:#}" + ); + // 丢掉的字段按客户端的叫法记 + let path = Feature::ReasoningHistory.path(client); + if signer == upstream { + assert_eq!(thinking.len(), 1, "{at}\n{v:#}"); + assert_eq!(thinking[0].text, "想想", "{at}"); + assert_eq!(thinking[0].signature.as_ref(), Some(&sig), "{at}\n{v:#}"); + assert!( + !p.dropped.iter().any(|d| d == path), + "{at}:说丢了其实没丢 {:?}", + p.dropped + ); + } else { + assert!(thinking.is_empty(), "{at}:别家的推理发过去了\n{v:#}"); + assert!( + p.dropped.iter().any(|d| d == path), + "{at}:丢了没说 {:?}", + p.dropped + ); + } + } + } + } +} + +#[test] +fn a_whole_response_brings_its_thinking_and_signature_to_every_client() { + for client in ALL { + for upstream in ALL { + let s = session(client, upstream, false); + let body = upstream_response_with_thinking(upstream).to_string(); + let out = s.response(body.as_bytes()).unwrap(); + check_thinking( + client, + upstream, + "整包", + &decode_client_response(client, &out), + ); + } + } +} + +#[test] +fn a_stream_brings_its_thinking_and_signature_to_every_client() { + for client in ALL { + for upstream in ALL { + let s = session(client, upstream, true); + let mut c = s.stream(); + let mut out = Vec::new(); + for piece in upstream_stream_with_thinking(upstream).as_bytes().chunks(7) { + out.extend(c.process(piece)); + } + out.extend(c.finish()); + check_thinking( + client, + upstream, + "流式", + &decode_client_stream(client, &out), + ); + } + } +} + +#[test] +fn a_collected_stream_brings_its_thinking_and_signature_to_every_client() { + for client in ALL { + for upstream in ALL { + let s = session(client, upstream, false); + let mut c = s.collector(); + for piece in upstream_stream_with_thinking(upstream).as_bytes().chunks(7) { + c.process(piece); + } + let out = c.finish().unwrap(); + check_thinking( + client, + upstream, + "收集", + &decode_client_response(client, &out), + ); + } + } +} + // ───────────────────────────────────────────────────────── Gemini 的调用签名 /// 上游 Gemini 开着思考时,一轮的思考签名放在第一个 functionCall 那一格上。