From bdc9fde3ae933e921c71212df62525d882f91b57 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sat, 10 Oct 2026 18:18:06 +0800 Subject: [PATCH] feat(dialect): keep Gemini thought signatures that sit on functionCall parts Gemini with thinking enabled puts a turn's thought signature on the first functionCall part rather than on the thought text. The Gemini decoders only read `thoughtSignature` from `thought: true` parts, so a signature on a call was lost in the client's request history, in whole upstream responses and in upstream streams; on the way back the functionCall always got the `skip_thought_signature_validator` placeholder, and the conversation lost its reasoning continuity. The IR gets no new field: a signature on a functionCall part is represented as a Google-signed Thinking block with empty text placed immediately before the ToolCall it belongs to (`gemini::request:: call_signature` documents the shape). Other clients already carry such a block with the `tw1.g.` scheme and hand it back on the next turn, and the Gemini encoder recognises the shape and writes the signature on the functionCall part again, using the placeholder only when the call has no real signature. The placeholder itself is not read back as a signature, and adjacent thought parts without a signature are merged into the signed one so the signature covers the whole text. When the client is Gemini and the gateway streams a reply, a thought part's text and signature are emitted in the same part (the writer holds back one text delta per thinking block), and a function call's signature is emitted on the functionCall part. On same-format passthrough a carried signature on a functionCall part is replaced by the placeholder rather than removing the part. Co-Authored-By: Claude Fable 5.1 --- crates/tw-dialect/src/convert.rs | 30 +++ crates/tw-dialect/src/gemini/request.rs | 195 ++++++++++++++-- crates/tw-dialect/src/gemini/response.rs | 105 +++++++-- crates/tw-dialect/src/gemini/stream.rs | 278 +++++++++++++++++++++-- crates/tw-dialect/tests/matrix.rs | 146 ++++++++++++ 5 files changed, 702 insertions(+), 52 deletions(-) diff --git a/crates/tw-dialect/src/convert.rs b/crates/tw-dialect/src/convert.rs index 4fe02870..8f0a7bea 100644 --- a/crates/tw-dialect/src/convert.rs +++ b/crates/tw-dialect/src/convert.rs @@ -980,6 +980,16 @@ pub fn strip_carried(client: Dialect, body: &[u8]) -> Option> { )) }); changed |= parts.len() != before; + // functionCall 上别家的签名:这一格要留,签名换成迁移历史用的占位值, + // 和转换时给无签名调用写的一样 + for p in parts.iter_mut().filter(|p| p.get("functionCall").is_some()) { + for key in ["thoughtSignature", "thought_signature"] { + if carried(p.get(key)) { + p[key] = Value::from(gemini::request::SYNTHETIC_SIGNATURE); + changed = true; + } + } + } } } contents.retain(|c| { @@ -1451,6 +1461,26 @@ mod tests { .unwrap(); assert_eq!(out["input"].as_array().unwrap().len(), 1); assert_eq!(out["input"][0]["id"], "rs_1"); + + let body = json!({"contents": [ + {"role": "model", "parts": [ + {"text": "x", "thought": true, "thoughtSignature": "tw1.a.sig"}, + {"functionCall": {"name": "ls", "args": {}}, "thoughtSignature": "tw1.ar.data"}, + {"functionCall": {"name": "cat", "args": {}}, "thoughtSignature": "CiQB"} + ]} + ]}) + .to_string(); + let out: Value = + serde_json::from_slice(&strip_carried(Dialect::Gemini, body.as_bytes()).unwrap()) + .unwrap(); + assert_eq!( + out["contents"][0]["parts"], + json!([ + {"functionCall": {"name": "ls", "args": {}}, "thoughtSignature": gemini::request::SYNTHETIC_SIGNATURE}, + {"functionCall": {"name": "cat", "args": {}}, "thoughtSignature": "CiQB"} + ]), + "functionCall 那一格要留,别家的签名换成占位值" + ); } /// 独立的错误帧:每种格式都是客户端认得的那种事件,类别跟着状态码走。 diff --git a/crates/tw-dialect/src/gemini/request.rs b/crates/tw-dialect/src/gemini/request.rs index 384a2444..80e21ee6 100644 --- a/crates/tw-dialect/src/gemini/request.rs +++ b/crates/tw-dialect/src/gemini/request.rs @@ -15,6 +15,24 @@ use crate::think; /// 历史修复也用它) pub const SYNTHETIC_SIGNATURE: &str = "skip_thought_signature_validator"; +/// functionCall 这一格上的思考签名在中间表示里怎么放。 +/// +/// Gemini 开着思考时把一轮的签名放在第一个 functionCall 上,不放在思考文字上。 +/// 中间表示的工具调用没有签名字段,也不为一家加一个:记成一个**紧挨在那个工具调用 +/// 前面、没有文字的 Google 签名思考块**。别家客户端照常把它当一段推理带出去、下一轮 +/// 带回来;编码回 Gemini 时认出这个形状,把签名放回 functionCall 上,而不是写成一格 +/// 单独的思考。 +/// +/// `parts[i]` 是这样的块时给出它的签名(不论哪家签发的,由调用方决定要不要)。 +pub(crate) fn call_signature(parts: &[Part], i: usize) -> Option<&Signature> { + match (&parts[i], parts.get(i + 1)) { + (Part::Thinking(th), Some(Part::ToolCall(_))) if th.text.is_empty() => { + th.signature.as_ref() + } + _ => None, + } +} + /// 按驼峰名取字段,取不到再试下划线写法 pub(crate) fn field<'a>(v: &'a Value, camel: &str) -> Option<&'a Value> { v.get(camel).or_else(|| { @@ -80,11 +98,20 @@ pub fn decode_request( for (pi, p) in arr_of(content, "parts").iter().enumerate() { if let Some(t) = fstr(p, "text") { if p.get("thought").and_then(Value::as_bool) == Some(true) { - parts.push(Part::Thinking(Thinking { - text: t.to_string(), - signature: fstr(p, "thoughtSignature") - .and_then(|s| Signature::read(s, Vendor::Google)), - })); + let signature = fstr(p, "thoughtSignature") + .and_then(|s| Signature::read(s, Vendor::Google)); + // 流式写出去的思考是一格一段,签名在最后一格:没签名的前几格并进来, + // 签名才对得上整段文字 + match parts.last_mut() { + Some(Part::Thinking(prev)) if prev.signature.is_none() => { + prev.text.push_str(t); + prev.signature = signature; + } + _ => parts.push(Part::Thinking(Thinking { + text: t.to_string(), + signature, + })), + } } else if !t.is_empty() { parts.push(Part::Text(t.to_string())); } @@ -102,6 +129,17 @@ pub fn decode_request( dropped.path("contents.parts.inlineData"); } } else if let Some(call) = field(p, "functionCall") { + // 这一格上的签名记成紧挨在前面的空思考块(见 [`call_signature`])。 + // 迁移历史用的占位值不是签名 + if let Some(sig) = fstr(p, "thoughtSignature") + .filter(|s| *s != SYNTHETIC_SIGNATURE) + .and_then(|s| Signature::read(s, Vendor::Google)) + { + parts.push(Part::Thinking(Thinking { + text: String::new(), + signature: Some(sig), + })); + } let name = fstr(call, "name").unwrap_or_default().to_string(); let id = fstr(call, "id") .map(str::to_string) @@ -328,7 +366,9 @@ pub fn encode_request(r: &Request, _t: &Target, dropped: &mut Dropped) -> Value let mut contents = Vec::new(); for m in merge_roles(r.messages.clone()) { let mut parts = Vec::new(); - for p in &m.parts { + // 空思考块上的 Google 签名,放到紧接着的 functionCall 上 + let mut call_sig: Option<&str> = None; + for (i, p) in m.parts.iter().enumerate() { match p { Part::Text(t) if !t.is_empty() => parts.push(json!({ "text": t })), Part::Text(_) => {} @@ -339,16 +379,28 @@ pub fn encode_request(r: &Request, _t: &Target, dropped: &mut Dropped) -> Value Media::Url(_) => dropped.feature(Feature::MediaUrl), }, Part::Thinking(th) => match &th.signature { - Some(s) if s.vendor == Vendor::Google => parts.push(json!({ - "text": th.text, - "thought": true, - "thoughtSignature": s.value, - })), + Some(s) if s.vendor == Vendor::Google => { + if call_signature(&m.parts, i).is_some() { + call_sig = Some(&s.value); + } else { + parts.push(json!({ + "text": th.text, + "thought": true, + "thoughtSignature": s.value, + })); + } + } _ => dropped.feature(Feature::ReasoningHistory), }, - Part::ToolCall(c) => parts.push(json!({ - "functionCall": { "id": c.id, "name": c.name, "args": c.input.to_object() }, - })), + Part::ToolCall(c) => { + let mut part = json!({ + "functionCall": { "id": c.id, "name": c.name, "args": c.input.to_object() }, + }); + if let Some(sig) = call_sig.take() { + part["thoughtSignature"] = json!(sig); + } + parts.push(part); + } Part::ToolResult(res) => { if res.has_image() { dropped.feature(Feature::ToolResultImage); @@ -565,6 +617,121 @@ mod tests { assert_eq!(dropped, ["tools.googleSearch", "safetySettings"]); } + /// 签名在 functionCall 那一格上:读成紧挨在前面的空思考块,占位值不算签名; + /// 一段一格的思考文字并成一块。 + #[test] + fn a_signature_on_a_function_call_is_kept_and_the_placeholder_is_not() { + let (r, _) = decode( + r#"{"contents": [ + {"role": "user", "parts": [{"text": "读 a"}]}, + {"role": "model", "parts": [ + {"text": "先", "thought": true}, + {"text": "想想", "thought": true, "thoughtSignature": "tw1.a.sig"}, + {"functionCall": {"name": "Read", "args": {"p": "a"}}, "thoughtSignature": "CiQB"}, + {"functionCall": {"name": "Read", "args": {"p": "b"}}, "thoughtSignature": "skip_thought_signature_validator"}, + {"functionCall": {"name": "Read", "args": {"p": "c"}}, "thoughtSignature": "tw1.ar.data"} + ]} + ]}"#, + ); + let parts = &r.messages[1].parts; + assert_eq!(parts.len(), 6, "{parts:?}"); + assert_eq!( + parts[0], + Part::Thinking(Thinking { + text: "先想想".into(), + signature: Some(Signature::new(Vendor::Anthropic, "sig")), + }) + ); + assert_eq!( + parts[1], + Part::Thinking(Thinking { + text: String::new(), + signature: Some(Signature::new(Vendor::Google, "CiQB")), + }) + ); + assert!( + matches!(&parts[2], Part::ToolCall(c) if c.input == ToolInput::Json(json!({"p": "a"}))) + ); + assert!( + matches!(&parts[3], Part::ToolCall(c) if c.input == ToolInput::Json(json!({"p": "b"}))) + ); + assert_eq!( + parts[4], + Part::Thinking(Thinking { + text: String::new(), + signature: Some(Signature { + vendor: Vendor::Anthropic, + value: "data".into(), + redacted: true, + }), + }) + ); + assert!(matches!(&parts[5], Part::ToolCall(_))); + } + + /// 回 Gemini 时签名放回 functionCall 那一格,不写成单独的思考,也不写占位值。 + #[test] + fn a_calls_signature_goes_back_on_the_function_call() { + let r = Request { + model: "gemini-3-pro-preview".into(), + messages: vec![ + Message { + role: Role::User, + parts: vec![Part::Text("读 a".into())], + }, + Message { + role: Role::Assistant, + parts: vec![ + Part::Thinking(Thinking { + text: "想".into(), + signature: Some(Signature::new(Vendor::Google, "thought_sig")), + }), + Part::Thinking(Thinking { + text: String::new(), + signature: Some(Signature::new(Vendor::Google, "CiQB")), + }), + Part::ToolCall(ToolCall { + id: "call_1".into(), + name: "Read".into(), + input: ToolInput::Json(json!({"p": "a"})), + }), + Part::ToolCall(ToolCall { + id: "call_2".into(), + name: "Read".into(), + input: ToolInput::Json(json!({"p": "b"})), + }), + ], + }, + Message { + role: Role::User, + parts: vec![ + Part::ToolResult(ToolResult { + id: "call_1".into(), + content: vec![Part::Text("A".into())], + is_error: false, + }), + Part::ToolResult(ToolResult { + id: "call_2".into(), + content: vec![Part::Text("B".into())], + is_error: false, + }), + ], + }, + ], + ..Default::default() + }; + let (v, dropped) = encode(&r, Dialect::Anthropic); + assert!(dropped.is_empty(), "{dropped:?}"); + let parts = v["contents"][1]["parts"].as_array().unwrap(); + assert_eq!(parts.len(), 3, "{parts:?}"); + assert_eq!(parts[0]["thought"], true); + assert_eq!(parts[0]["thoughtSignature"], "thought_sig"); + assert_eq!(parts[1]["functionCall"]["args"]["p"], "a"); + assert_eq!(parts[1]["thoughtSignature"], "CiQB"); + assert_eq!(parts[2]["functionCall"]["args"]["p"], "b"); + assert!(parts[2].get("thoughtSignature").is_none()); + } + #[test] fn cached_content_is_refused() { let mut d = Dropped::new(Dialect::Gemini); diff --git a/crates/tw-dialect/src/gemini/response.rs b/crates/tw-dialect/src/gemini/response.rs index 9a6f5389..2468be0f 100644 --- a/crates/tw-dialect/src/gemini/response.rs +++ b/crates/tw-dialect/src/gemini/response.rs @@ -86,6 +86,16 @@ pub fn decode_response(v: &Value) -> Response { blocks.push(Block::Text(t.to_string())); } } else if let Some(call) = field(p, "functionCall") { + // 这一格上的签名记成紧挨在前面的空思考块(见 `request::call_signature`) + if let Some(sig) = field(p, "thoughtSignature") + .and_then(Value::as_str) + .and_then(|s| Signature::read(s, Vendor::Google)) + { + blocks.push(Block::Thinking(Thinking { + text: String::new(), + signature: Some(sig), + })); + } blocks.push(Block::ToolCall(ToolCall { id: field(call, "id") .and_then(Value::as_str) @@ -121,28 +131,49 @@ pub fn decode_response(v: &Value) -> Response { } } -pub(crate) fn part(b: &Block) -> Option { - Some(match b { - Block::Text(t) => json!({ "text": t }), - Block::Thinking(th) => { - if th.text.is_empty() && th.signature.is_none() { - return None; - } - let mut p = json!({ "text": th.text, "thought": true }); - if let Some(s) = &th.signature { - p["thoughtSignature"] = json!(s.carried_in(Vendor::Google)); - } - p +pub(crate) fn call_part(c: &ToolCall, signature: Option<&Signature>) -> Value { + let mut p = json!({ + "functionCall": { "id": c.id, "name": c.name, "args": c.input.to_object() }, + }); + if let Some(s) = signature { + p["thoughtSignature"] = json!(s.carried_in(Vendor::Google)); + } + p +} + +/// 给 Gemini 客户端的 parts。没有文字、紧挨着工具调用的思考块只是那个调用的签名 +/// (见 `request::call_signature`),写在 functionCall 那一格上 +pub(crate) fn parts(blocks: &[Block]) -> Vec { + let mut out = Vec::new(); + let mut call_sig: Option<&Signature> = None; + for (i, b) in blocks.iter().enumerate() { + match b { + Block::Text(t) => out.push(json!({ "text": t })), + Block::Thinking(th) => match &th.signature { + Some(s) + if th.text.is_empty() + && matches!(blocks.get(i + 1), Some(Block::ToolCall(_))) => + { + call_sig = Some(s); + } + None if th.text.is_empty() => {} + sig => { + let mut p = json!({ "text": th.text, "thought": true }); + if let Some(s) = sig { + p["thoughtSignature"] = json!(s.carried_in(Vendor::Google)); + } + out.push(p); + } + }, + Block::ToolCall(c) => out.push(call_part(c, call_sig.take())), } - Block::ToolCall(c) => json!({ - "functionCall": { "id": c.id, "name": c.name, "args": c.input.to_object() }, - }), - }) + } + out } /// 中间表示 → 给 Gemini 客户端的整包响应。 pub fn encode_response(r: &Response, s: &Session) -> Value { - let parts: Vec = r.blocks.iter().filter_map(part).collect(); + let parts = parts(&r.blocks); let mut out = json!({ "candidates": [{ "content": { "role": "model", "parts": parts }, @@ -212,7 +243,45 @@ mod tests { ]}, "finishReason": "STOP"}] })); assert_eq!(r.stop, Some(StopReason::ToolUse)); - assert!(matches!(&r.blocks[1], Block::ToolCall(c) if c.id.starts_with("call_"))); + assert_eq!( + r.blocks[1], + Block::Thinking(Thinking { + text: String::new(), + signature: Some(Signature::new(Vendor::Google, "CiQB")), + }), + "functionCall 上的签名记成紧挨在前面的空思考块" + ); + assert!(matches!(&r.blocks[2], Block::ToolCall(c) if c.id.starts_with("call_"))); + } + + #[test] + fn a_calls_signature_goes_back_on_the_function_call_part() { + let r = Response { + blocks: vec![ + Block::Thinking(Thinking { + text: "想".into(), + signature: Some(Signature::new(Vendor::Anthropic, "sig_a")), + }), + Block::Thinking(Thinking { + text: String::new(), + signature: Some(Signature::new(Vendor::Google, "CiQB")), + }), + Block::ToolCall(ToolCall { + id: "call_1".into(), + name: "ls".into(), + input: ToolInput::Json(json!({"p": "."})), + }), + ], + stop: Some(StopReason::ToolUse), + ..Default::default() + }; + let v = encode_response(&r, &Session::for_test(Dialect::Gemini, Dialect::Gemini)); + let parts = v["candidates"][0]["content"]["parts"].as_array().unwrap(); + assert_eq!(parts.len(), 2, "{parts:?}"); + assert_eq!(parts[0]["thought"], true); + assert_eq!(parts[0]["thoughtSignature"], "tw1.a.sig_a"); + assert_eq!(parts[1]["functionCall"]["name"], "ls"); + assert_eq!(parts[1]["thoughtSignature"], "CiQB"); } #[test] diff --git a/crates/tw-dialect/src/gemini/stream.rs b/crates/tw-dialect/src/gemini/stream.rs index 59ee9583..e1d39326 100644 --- a/crates/tw-dialect/src/gemini/stream.rs +++ b/crates/tw-dialect/src/gemini/stream.rs @@ -92,6 +92,23 @@ impl Parser { } } else if let Some(call) = field(p, "functionCall") { self.close(out); + // 这一格上的签名记成紧挨在前面的空思考块(见 `request::call_signature`) + if let Some(sig) = field(p, "thoughtSignature") + .and_then(Value::as_str) + .and_then(|s| Signature::read(s, Vendor::Google)) + { + let index = self.next; + self.next += 1; + out.push(Event::BlockStart { + index, + kind: BlockKind::Thinking, + }); + out.push(Event::Delta { + index, + delta: Delta::Signature(sig), + }); + out.push(Event::BlockStop { index }); + } let index = self.next; self.next += 1; self.tool_call = true; @@ -169,8 +186,14 @@ pub struct Writer { model: String, /// 工具块 → (id, 名字, 攒着的参数) tools: HashMap, + /// 思考块最后一段还没写出的文字:块结束时和签名写在同一格里,所以每段都压一段 + /// 再写,只晚一段 + thoughts: HashMap, /// 思考块的签名,块结束时写出 signatures: HashMap, + /// 没有文字的思考块只是签名(functionCall 的签名、改写过的思考):等着写到下一个 + /// functionCall 那一格上;下一格不是 functionCall 就单独写一格 + pending: Vec, usage: Option, stop: Option, done: bool, @@ -184,7 +207,9 @@ impl Writer { id: new_id(""), model: s.model.clone(), tools: HashMap::new(), + thoughts: HashMap::new(), signatures: HashMap::new(), + pending: Vec::new(), usage: None, stop: None, done: false, @@ -201,7 +226,24 @@ impl Writer { self.wrote_any = true; } - fn chunk(&mut self, parts: Vec, out: &mut String) { + /// 等着放到 functionCall 上的签名各自写成一格空思考 + fn flush_pending(&mut self, parts: &mut Vec) { + for s in self.pending.drain(..) { + parts.push(json!({ + "text": "", + "thought": true, + "thoughtSignature": s.carried_in(Vendor::Google), + })); + } + } + + fn chunk(&mut self, mut parts: Vec, out: &mut String) { + if !self.pending.is_empty() { + let mut all = Vec::new(); + self.flush_pending(&mut all); + all.append(&mut parts); + parts = all; + } let v = json!({ "candidates": [{ "content": { "role": "model", "parts": parts }, "index": 0 }], "modelVersion": self.model, @@ -234,9 +276,12 @@ impl Writer { Event::BlockStart { .. } => {} Event::Delta { index, delta } => match delta { Delta::Text(t) => self.chunk(vec![json!({ "text": t })], &mut out), - Delta::Thinking(t) => { - self.chunk(vec![json!({ "text": t, "thought": true })], &mut out) + Delta::Thinking(t) if !t.is_empty() => { + if let Some(prev) = self.thoughts.insert(*index, t.clone()) { + self.chunk(vec![json!({ "text": prev, "thought": true })], &mut out); + } } + Delta::Thinking(_) => {} Delta::Signature(s) => { self.signatures.insert(*index, s.clone()); } @@ -248,20 +293,29 @@ impl Writer { }, Event::BlockStop { index } => { if let Some((id, name, args)) = self.tools.remove(index) { - let args = ToolInput::from_json_text(&args).to_object(); - self.chunk( - vec![json!({ "functionCall": { "id": id, "name": name, "args": args } })], - &mut out, - ); - } else if let Some(s) = self.signatures.remove(index) { - self.chunk( - vec![json!({ - "text": "", - "thought": true, - "thoughtSignature": s.carried_in(Vendor::Google), - })], - &mut out, - ); + let call = ToolCall { + id, + name, + input: ToolInput::from_json_text(&args), + }; + // 一格只放一个签名:攒了几个时前面的各自写一格 + let sig = self.pending.pop(); + let mut parts = Vec::new(); + self.flush_pending(&mut parts); + parts.push(super::response::call_part(&call, sig.as_ref())); + self.chunk(parts, &mut out); + } else { + match (self.thoughts.remove(index), self.signatures.remove(index)) { + (Some(text), sig) => { + let mut p = json!({ "text": text, "thought": true }); + if let Some(s) = sig { + p["thoughtSignature"] = json!(s.carried_in(Vendor::Google)); + } + self.chunk(vec![p], &mut out); + } + (None, Some(s)) => self.pending.push(s), + (None, None) => {} + } } } Event::Usage(u) => self.usage.get_or_insert_default().merge(u), @@ -287,9 +341,21 @@ impl Writer { if self.done { return out; } + let mut parts = Vec::new(); + self.flush_pending(&mut parts); + // 没等到块结束的思考文字也不能丢 + let mut open: Vec<(usize, String)> = self.thoughts.drain().collect(); + open.sort_by_key(|(i, _)| *i); + for (index, text) in open { + let mut p = json!({ "text": text, "thought": true }); + if let Some(s) = self.signatures.remove(&index) { + p["thoughtSignature"] = json!(s.carried_in(Vendor::Google)); + } + parts.push(p); + } let mut v = json!({ "candidates": [{ - "content": { "role": "model", "parts": [] }, + "content": { "role": "model", "parts": parts }, "finishReason": finish_reason(self.stop.as_ref().unwrap_or(&StopReason::EndTurn)), "index": 0, }], @@ -337,8 +403,17 @@ mod tests { _ => None, }) .collect(); - assert_eq!(kinds.len(), 3); - assert!(matches!(kinds[2], BlockKind::ToolCall { name, .. } if name == "ls")); + assert_eq!(kinds.len(), 4); + assert_eq!( + kinds[2], + &BlockKind::Thinking, + "functionCall 上的签名是紧挨在调用前面的一个空思考块" + ); + assert!(matches!(kinds[3], BlockKind::ToolCall { name, .. } if name == "ls")); + assert!(ev.contains(&Event::Delta { + index: 2, + delta: Delta::Signature(Signature::new(Vendor::Google, "CiQB")), + })); let text: String = ev .iter() .filter_map(|e| match e { @@ -431,6 +506,169 @@ mod tests { assert_eq!(chunks[0]["modelVersion"], "claude-opus-4-7"); } + fn chunks_of(events: &[Event]) -> Vec { + let s = Session::for_test(Dialect::Gemini, Dialect::Anthropic); + let mut w = Writer::new(&s); + let mut out = String::new(); + for e in events { + out.push_str(&w.event(e)); + } + out.push_str(&w.finish()); + let mut d = Decoder::default(); + d.feed(out.as_bytes()) + .into_iter() + .map(|f| serde_json::from_str(&f.data).unwrap()) + .collect() + } + + fn parts_of(chunks: &[Value]) -> Vec { + chunks + .iter() + .flat_map(|c| { + c["candidates"][0]["content"]["parts"] + .as_array() + .cloned() + .unwrap_or_default() + }) + .collect() + } + + /// 思考文字一段一段写,签名和最后一段写在同一格里,不单独占一格。 + #[test] + fn a_thoughts_signature_is_written_in_the_same_part_as_its_last_text() { + let chunks = chunks_of(&[ + Event::BlockStart { + index: 0, + kind: BlockKind::Thinking, + }, + Event::Delta { + index: 0, + delta: Delta::Thinking("先".into()), + }, + Event::Delta { + index: 0, + delta: Delta::Thinking("想想".into()), + }, + Event::Delta { + index: 0, + delta: Delta::Signature(Signature::new(Vendor::Anthropic, "sig")), + }, + Event::BlockStop { index: 0 }, + Event::BlockStart { + index: 1, + kind: BlockKind::Text, + }, + Event::Delta { + index: 1, + delta: Delta::Text("好".into()), + }, + Event::BlockStop { index: 1 }, + Event::Stop(StopReason::EndTurn), + ]); + let parts = parts_of(&chunks); + assert_eq!( + parts, + json!([ + {"text": "先", "thought": true}, + {"text": "想想", "thought": true, "thoughtSignature": "tw1.a.sig"}, + {"text": "好"}, + ]) + .as_array() + .unwrap() + .as_slice(), + "{chunks:?}" + ); + } + + /// 没有文字的签名块跟着工具调用:签名写在 functionCall 那一格上。 + #[test] + fn a_calls_signature_is_written_on_the_function_call_part() { + let chunks = chunks_of(&[ + Event::BlockStart { + index: 0, + kind: BlockKind::Thinking, + }, + Event::Delta { + index: 0, + delta: Delta::Thinking(String::new()), + }, + Event::Delta { + index: 0, + delta: Delta::Signature(Signature::new(Vendor::Google, "CiQB")), + }, + Event::BlockStop { index: 0 }, + Event::BlockStart { + index: 1, + kind: BlockKind::ToolCall { + id: "call_1".into(), + name: "ls".into(), + }, + }, + Event::Delta { + index: 1, + delta: Delta::ToolInput("{\"p\":\".\"}".into()), + }, + Event::BlockStop { index: 1 }, + Event::Stop(StopReason::ToolUse), + ]); + let parts = parts_of(&chunks); + assert_eq!(parts.len(), 1, "{chunks:?}"); + assert_eq!(parts[0]["functionCall"]["name"], "ls"); + assert_eq!(parts[0]["thoughtSignature"], "CiQB"); + } + + /// 签名块后面不是工具调用:单独写一格,不能丢。 + #[test] + fn a_signature_without_a_call_after_it_still_gets_a_part() { + let chunks = chunks_of(&[ + Event::BlockStart { + index: 0, + kind: BlockKind::Thinking, + }, + Event::Delta { + index: 0, + delta: Delta::Signature(Signature { + vendor: Vendor::Anthropic, + value: "data".into(), + redacted: true, + }), + }, + Event::BlockStop { index: 0 }, + Event::BlockStart { + index: 1, + kind: BlockKind::Text, + }, + Event::Delta { + index: 1, + delta: Delta::Text("好".into()), + }, + Event::BlockStop { index: 1 }, + ]); + assert_eq!( + parts_of(&chunks), + json!([ + {"text": "", "thought": true, "thoughtSignature": "tw1.ar.data"}, + {"text": "好"}, + ]) + .as_array() + .unwrap() + .as_slice() + ); + // 流结束时还挂着的也写出来 + let chunks = chunks_of(&[ + Event::BlockStart { + index: 0, + kind: BlockKind::Thinking, + }, + Event::Delta { + index: 0, + delta: Delta::Signature(Signature::new(Vendor::Google, "CiQB")), + }, + Event::BlockStop { index: 0 }, + ]); + assert_eq!(parts_of(&chunks)[0]["thoughtSignature"], "CiQB"); + } + #[test] fn without_alt_sse_the_stream_is_one_json_array() { let out = write(false); diff --git a/crates/tw-dialect/tests/matrix.rs b/crates/tw-dialect/tests/matrix.rs index 916b6334..3869c2f9 100644 --- a/crates/tw-dialect/tests/matrix.rs +++ b/crates/tw-dialect/tests/matrix.rs @@ -318,6 +318,8 @@ 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::ToolCall(c), Delta::ToolInput(x)) => { if let ToolInput::Text(t) = &mut c.input { t.push_str(&x); @@ -475,3 +477,147 @@ fn a_stream_collected_for_a_client_that_wanted_a_whole_response() { } } } + +// ───────────────────────────────────────────────────────── Gemini 的调用签名 + +/// 上游 Gemini 开着思考时,一轮的思考签名放在第一个 functionCall 那一格上。 +fn gemini_signed_call_response() -> Value { + json!({ + "candidates": [{"content": {"role": "model", "parts": [ + {"text": "想想", "thought": true}, + {"text": "天气晴"}, + {"functionCall": {"name": "get_weather", "args": {"city": "北京"}}, "thoughtSignature": "CiQB"} + ]}, "finishReason": "STOP"}], + "usageMetadata": {"promptTokenCount": 100, "cachedContentTokenCount": 40, "candidatesTokenCount": 20}, + "modelVersion": "up-model", "responseId": "r_up" + }) +} + +fn gemini_signed_call_stream() -> String { + 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": "天气晴"}])), + data(json!({"candidates": [{"content": {"role": "model", "parts": [ + {"functionCall": {"name": "get_weather", "args": {"city": "北京"}}, "thoughtSignature": "CiQB"} + ]}, "finishReason": "STOP"}], + "usageMetadata": {"promptTokenCount": 100, "cachedContentTokenCount": 40, "candidatesTokenCount": 20}})), + ] + .concat() +} + +/// 客户端把上一轮的回答原样带回来,再加工具结果:用客户端格式自己的编码器写回答, +/// 和客户端 SDK 保存的东西一个形状。 +fn second_turn(client: Dialect, first: &Response, s: &Session) -> Vec { + let call_id = first + .blocks + .iter() + .find_map(|b| match b { + Block::ToolCall(c) => Some(c.id.clone()), + _ => None, + }) + .unwrap(); + let body = match client { + Dialect::Anthropic => { + let answer = anthropic::encode_response(first, s); + json!({ + "model": "test-model", "max_tokens": 1024, + "messages": [ + {"role": "user", "content": "北京天气?"}, + {"role": "assistant", "content": answer["content"]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": call_id, "content": "晴,25 度"}]} + ], + "tools": [{"name": "get_weather", "description": "查天气", "input_schema": schema()}], + }) + } + Dialect::Responses => { + let answer = responses::encode_response(first, s); + let mut input = + vec![json!({"type": "message", "role": "user", "content": "北京天气?"})]; + input.extend(answer["output"].as_array().unwrap().iter().cloned()); + input.push( + json!({"type": "function_call_output", "call_id": call_id, "output": "晴,25 度"}), + ); + json!({ + "model": "test-model", "input": input, + "tools": [{"type": "function", "name": "get_weather", "description": "查天气", "parameters": schema(), "strict": false}], + }) + } + other => panic!("{other:?}"), + }; + body.to_string().into_bytes() +} + +/// 上游 Gemini 的工具调用带着思考签名:Anthropic、Responses 客户端把它当一段推理 +/// 带出去,下一轮带回来时它回到 functionCall 那一格上,不写占位值、不另开一格思考。 +#[test] +fn a_gemini_calls_signature_comes_back_on_the_call_through_other_clients() { + for client in [Dialect::Anthropic, Dialect::Responses] { + for stream in [false, true] { + let at = format!( + "{client:?} ← Gemini({})", + if stream { "流式" } else { "整包" } + ); + let s = session(client, Dialect::Gemini, stream); + let first = if stream { + let mut c = s.stream(); + let mut out = Vec::new(); + for piece in gemini_signed_call_stream().as_bytes().chunks(7) { + out.extend(c.process(piece)); + } + out.extend(c.finish()); + decode_client_stream(client, &out) + } else { + let out = s + .response(gemini_signed_call_response().to_string().as_bytes()) + .unwrap(); + decode_client_response(client, &out) + }; + check(client, Dialect::Gemini, "签名", seen_response(&first)); + // 客户端拿到的:签名是紧挨在调用前面的一块空推理,签发方认成 Google + let sig = first + .blocks + .iter() + .position(|b| matches!(b, Block::Thinking(th) if th.text.is_empty())) + .unwrap_or_else(|| panic!("{at}:没有带签名的推理块:{:?}", first.blocks)); + assert_eq!( + first.blocks[sig], + Block::Thinking(Thinking { + text: String::new(), + signature: Some(Signature::new(Vendor::Google, "CiQB")), + }), + "{at}" + ); + assert!(matches!(first.blocks[sig + 1], Block::ToolCall(_)), "{at}"); + + let (_, path, query) = client_request(client, false); + let body = second_turn(client, &first, &s); + let p = prepare( + client, + &body, + &path, + query.as_deref(), + &target(Dialect::Gemini), + ) + .unwrap_or_else(|e| panic!("{at}:{e}")); + let v: Value = serde_json::from_slice(&p.body).unwrap(); + let model_turn = &v["contents"][1]; + assert_eq!(model_turn["role"], "model", "{at}: {v}"); + let parts = model_turn["parts"].as_array().unwrap(); + let call = parts + .iter() + .find(|p| p.get("functionCall").is_some()) + .unwrap_or_else(|| panic!("{at}:没有 functionCall:{parts:?}")); + assert_eq!(call["thoughtSignature"], "CiQB", "{at}: {parts:?}"); + // 没签名的思考摘要照旧带不回去,签名不该另占一格思考 + assert!( + !parts.iter().any(|p| p.get("thought").is_some()), + "{at}:{parts:?}" + ); + } + } +}