diff --git a/crates/tw-dialect/src/bedrock/mod.rs b/crates/tw-dialect/src/bedrock/mod.rs new file mode 100644 index 00000000..b837a68b --- /dev/null +++ b/crates/tw-dialect/src/bedrock/mod.rs @@ -0,0 +1,13 @@ +//! Bedrock Converse(`/model/{id}/converse`)。 +//! +//! **和另外四种的一处根本差别:它的流不是 SSE**,是 AWS eventstream 的二进制帧 +//! (前导长度 + 头部 + 载荷 + CRC)。拆帧不在这个 crate 里 —— 那是传输层的事, +//! 和 SSE 平级;这里只管帧里装什么。传输层把每个事件交成一个 [`crate::frame::Frame`]: +//! `:event-type` 头进 `event`,载荷 JSON 进 `data`。 + +pub mod request; +pub mod response; +pub mod stream; + +pub use request::{decode_request, encode_request}; +pub use response::{decode_response, encode_response}; diff --git a/crates/tw-dialect/src/bedrock/request.rs b/crates/tw-dialect/src/bedrock/request.rs new file mode 100644 index 00000000..0c957a02 --- /dev/null +++ b/crates/tw-dialect/src/bedrock/request.rs @@ -0,0 +1,756 @@ +//! Bedrock Converse 请求 ⇄ 中间表示。 +//! +//! 模型名在路径里(`/model/{id}/converse`),不在请求体里 —— 和 Gemini 一样。 +//! +//! `inferenceConfig` 只有四个旋钮:`maxTokens`、`temperature`、`topP`、 +//! `stopSequences`。**别的一概走 `additionalModelRequestFields`** —— 那是个 +//! 原样透传给模型的口袋,Converse 自己不解释里面装的东西。`top_k` 就走它。 + +use serde_json::{Map, Value, json}; + +use crate::ir::*; + +/// 图片的 MIME → Converse 的 `format`。 +/// +/// **Converse 只认这四种**,而且写的是短名不是 MIME。认不出来的丢掉 —— 拿一个 +/// 猜的格式去发,模型收到的是一张解不开的图 +fn image_format(mime: &str) -> Option<&'static str> { + match mime.rsplit('/').next()? { + "png" => Some("png"), + "jpeg" | "jpg" => Some("jpeg"), + "gif" => Some("gif"), + "webp" => Some("webp"), + _ => None, + } +} + +/// 文件的 MIME 或扩展名 → `document.format`。 +fn document_format(mime: &str, name: Option<&str>) -> Option<&'static str> { + let by_ext = name + .and_then(|n| n.rsplit('.').next()) + .map(str::to_ascii_lowercase); + let candidate = match mime { + "application/pdf" => "pdf", + "text/csv" => "csv", + "application/msword" => "doc", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "docx", + "application/vnd.ms-excel" => "xls", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx", + "text/html" => "html", + "text/plain" => "txt", + "text/markdown" => "md", + _ => by_ext.as_deref().unwrap_or_default(), + }; + match candidate { + "pdf" => Some("pdf"), + "csv" => Some("csv"), + "doc" => Some("doc"), + "docx" => Some("docx"), + "xls" => Some("xls"), + "xlsx" => Some("xlsx"), + "html" | "htm" => Some("html"), + "txt" | "text" => Some("txt"), + "md" | "markdown" => Some("md"), + _ => None, + } +} + +/// Converse 要求文档有名字,而且同一个请求里不能重名。 +fn document_name(name: Option<&str>, index: usize) -> String { + match name { + Some(n) if !n.trim().is_empty() => n.to_string(), + _ => format!("document-{index}"), + } +} + +// ───────────────────────────────────────────── 中间表示 → Converse + +pub fn encode_request(r: &Request, t: &Target, dropped: &mut Dropped) -> Value { + let mut out = Map::new(); + + if !r.system.is_empty() { + let blocks: Vec = r.system.iter().map(|s| json!({ "text": s })).collect(); + out.insert("system".into(), Value::Array(blocks)); + } + + let mut messages = Vec::new(); + let mut doc_index = 0usize; + for m in merge_roles(r.messages.clone()) { + let mut content = Vec::new(); + for p in &m.parts { + match p { + Part::Text(text) if !text.is_empty() => content.push(json!({ "text": text })), + Part::Text(_) => {} + Part::Image(media) => match media { + Media::Base64 { mime, data } => match image_format(mime) { + Some(format) => content.push(json!({ + "image": { "format": format, "source": { "bytes": data } }, + })), + None => dropped.path("messages.content.image"), + }, + // Converse 只收字节和 S3,没有取 URL 这一说 + Media::Url(_) => dropped.feature(Feature::MediaUrl), + }, + Part::File { media, name } => match media { + Media::Base64 { mime, data } => match document_format(mime, name.as_deref()) { + Some(format) => { + content.push(json!({ + "document": { + "format": format, + "name": document_name(name.as_deref(), doc_index), + "source": { "bytes": data }, + }, + })); + doc_index += 1; + } + None => dropped.feature(Feature::File), + }, + Media::Url(_) => dropped.feature(Feature::MediaUrl), + }, + Part::Thinking(th) => match &th.signature { + // 签名是 Bedrock 上的 Anthropic 模型签的,带回去才算数 + Some(s) if s.vendor == Vendor::Anthropic && !s.redacted => { + content.push(json!({ + "reasoningContent": { + "reasoningText": { "text": th.text, "signature": s.value }, + }, + })) + } + Some(s) if s.redacted => content.push(json!({ + "reasoningContent": { "redactedContent": s.value }, + })), + _ => dropped.feature(Feature::ReasoningHistory), + }, + Part::ToolCall(c) => content.push(json!({ + "toolUse": { + "toolUseId": c.id, + "name": c.name, + "input": c.input.to_object(), + }, + })), + Part::ToolResult(res) => { + let mut blocks = Vec::new(); + for part in &res.content { + match part { + Part::Text(t) if !t.is_empty() => blocks.push(json!({ "text": t })), + Part::Text(_) => {} + // toolResult 的内容块里图片是一等公民,不用丢 + Part::Image(Media::Base64 { mime, data }) => match image_format(mime) { + Some(format) => blocks.push(json!({ + "image": { "format": format, "source": { "bytes": data } }, + })), + None => dropped.feature(Feature::ToolResultImage), + }, + Part::Image(Media::Url(_)) => dropped.feature(Feature::MediaUrl), + _ => {} + } + } + if blocks.is_empty() { + blocks.push(json!({ "text": res.text() })); + } + content.push(json!({ + "toolResult": { + "toolUseId": res.id, + "content": blocks, + "status": if res.is_error { "error" } else { "success" }, + }, + })); + } + } + } + if content.is_empty() { + continue; + } + messages.push(json!({ + "role": if m.role == Role::User { "user" } else { "assistant" }, + "content": content, + })); + } + out.insert("messages".into(), Value::Array(messages)); + + // ── inferenceConfig:只有这四个 ──────────────────────────── + let mut cfg = Map::new(); + cfg.insert( + "maxTokens".into(), + json!(r.max_tokens.unwrap_or(t.default_max_tokens)), + ); + if let Some(v) = r.temperature { + cfg.insert("temperature".into(), json!(v)); + } + if let Some(v) = r.top_p { + cfg.insert("topP".into(), json!(v)); + } + if !r.stop.is_empty() { + cfg.insert("stopSequences".into(), json!(r.stop)); + } + out.insert("inferenceConfig".into(), Value::Object(cfg)); + + // ── additionalModelRequestFields:Converse 不解释的都塞这儿 ── + let mut extra = Map::new(); + if let Some(k) = r.top_k { + extra.insert("top_k".into(), json!(k)); + } + if !extra.is_empty() { + out.insert("additionalModelRequestFields".into(), Value::Object(extra)); + } + + if !r.tools.is_empty() { + let tools: Vec = r + .tools + .iter() + .map(|tool| { + let schema = match &tool.kind { + ToolKind::Function { schema, .. } => schema.clone(), + ToolKind::Freeform { format } => { + if format.is_some() { + dropped.feature(Feature::FreeformFormat); + } + freeform_schema() + } + }; + let mut spec = json!({ "name": tool.name, "inputSchema": { "json": schema } }); + if let Some(desc) = &tool.description { + spec["description"] = json!(desc); + } + json!({ "toolSpec": spec }) + }) + .collect(); + + let mut config = json!({ "tools": tools }); + match &r.tool_choice { + Some(ToolChoice::Auto) => config["toolChoice"] = json!({ "auto": {} }), + Some(ToolChoice::Required) => config["toolChoice"] = json!({ "any": {} }), + Some(ToolChoice::Named(name)) => { + config["toolChoice"] = json!({ "tool": { "name": name } }) + } + // Converse 没有「一个都不要用」:不给 toolConfig 就是不用工具, + // 但那样工具定义也跟着没了。**宁可让模型看见工具** + Some(ToolChoice::None) => dropped.path("tool_choice"), + None => {} + } + out.insert("toolConfig".into(), config); + } else if r.tool_choice.is_some() { + dropped.path("tool_choice"); + } + + // Converse 自己没有的旋钮 + if r.seed.is_some() { + dropped.feature(Feature::Seed); + } + if r.presence_penalty.is_some() { + dropped.feature(Feature::PresencePenalty); + } + if r.frequency_penalty.is_some() { + dropped.feature(Feature::FrequencyPenalty); + } + if r.parallel_tool_calls.is_some() { + dropped.feature(Feature::ParallelToolCalls); + } + if r.reasoning.is_some() { + dropped.feature(Feature::Reasoning); + } + if r.format.is_some() { + dropped.feature(Feature::Format); + } + + Value::Object(out) +} + +// ───────────────────────────────────────────── Converse → 中间表示 + +/// 一个内容块 → 中间表示的若干 [`Part`]。 +fn part(b: &Value, dropped: &mut Dropped) -> Option { + if let Some(t) = b.get("text").and_then(Value::as_str) { + return Some(Part::Text(t.to_string())); + } + if let Some(img) = b.get("image") { + let format = img.get("format").and_then(Value::as_str).unwrap_or("png"); + let source = img.get("source")?; + if let Some(data) = source.get("bytes").and_then(Value::as_str) { + return Some(Part::Image(Media::Base64 { + mime: format!("image/{format}"), + data: data.to_string(), + })); + } + // S3 要拿 AWS 凭据去取,这一层没有,也不该有 + dropped.path("messages.content.image.source.s3Location"); + return None; + } + if let Some(doc) = b.get("document") { + let source = doc.get("source")?; + if let Some(data) = source.get("bytes").and_then(Value::as_str) { + let format = doc.get("format").and_then(Value::as_str).unwrap_or("txt"); + return Some(Part::File { + media: Media::Base64 { + mime: mime_of_document(format).to_string(), + data: data.to_string(), + }, + name: doc.get("name").and_then(Value::as_str).map(str::to_string), + }); + } + if let Some(text) = source.get("text").and_then(Value::as_str) { + return Some(Part::Text(text.to_string())); + } + dropped.path("messages.content.document.source"); + return None; + } + if let Some(r) = b.get("reasoningContent") { + if let Some(rt) = r.get("reasoningText") { + return Some(Part::Thinking(Thinking { + text: rt + .get("text") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + signature: rt + .get("signature") + .and_then(Value::as_str) + .and_then(|s| Signature::read(s, Vendor::Anthropic)), + })); + } + if let Some(red) = r.get("redactedContent").and_then(Value::as_str) { + return Some(Part::Thinking(Thinking { + text: String::new(), + signature: Some(Signature { + vendor: Vendor::Anthropic, + value: red.to_string(), + redacted: true, + }), + })); + } + return None; + } + if let Some(u) = b.get("toolUse") { + return Some(Part::ToolCall(ToolCall { + id: u + .get("toolUseId") + .and_then(Value::as_str) + .map(str::to_string) + .unwrap_or_else(|| new_id("tooluse_")), + name: u + .get("name") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + input: ToolInput::Json(u.get("input").cloned().unwrap_or_else(|| json!({}))), + })); + } + if let Some(res) = b.get("toolResult") { + let mut content = Vec::new(); + for c in res + .get("content") + .and_then(Value::as_array) + .unwrap_or(&vec![]) + { + if let Some(t) = c.get("text").and_then(Value::as_str) { + content.push(Part::Text(t.to_string())); + } else if let Some(j) = c.get("json") { + content.push(Part::Text(j.to_string())); + } else if let Some(img) = c.get("image") + && let Some(data) = img + .get("source") + .and_then(|s| s.get("bytes")) + .and_then(Value::as_str) + { + let format = img.get("format").and_then(Value::as_str).unwrap_or("png"); + content.push(Part::Image(Media::Base64 { + mime: format!("image/{format}"), + data: data.to_string(), + })); + } + } + return Some(Part::ToolResult(ToolResult { + id: res + .get("toolUseId") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + content, + is_error: res.get("status").and_then(Value::as_str) == Some("error"), + })); + } + // guardContent、cachePoint、citationsContent、video、audio、searchResult: + // 别的格式没有对应物 + for key in [ + "guardContent", + "cachePoint", + "citationsContent", + "video", + "audio", + "searchResult", + ] { + if b.get(key).is_some() { + dropped.path(format!("messages.content.{key}")); + return None; + } + } + None +} + +/// Converse 的 document `format` → MIME。 +fn mime_of_document(format: &str) -> &'static str { + match format { + "pdf" => "application/pdf", + "csv" => "text/csv", + "doc" => "application/msword", + "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "xls" => "application/vnd.ms-excel", + "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "html" => "text/html", + "md" => "text/markdown", + _ => "text/plain", + } +} + +/// `model` 是从路径上取来的 —— Converse 的请求体里没有它。 +pub fn decode_request( + v: &Value, + model: &str, + stream: bool, + dropped: &mut Dropped, +) -> Result { + let mut r = Request { + model: model.to_string(), + stream, + ..Default::default() + }; + + for s in v.get("system").and_then(Value::as_array).unwrap_or(&vec![]) { + if let Some(t) = s.get("text").and_then(Value::as_str) { + r.system.push(t.to_string()); + } else if s.get("guardContent").is_some() { + dropped.path("system.guardContent"); + } else if s.get("cachePoint").is_some() { + dropped.path("system.cachePoint"); + } + } + + for m in v + .get("messages") + .and_then(Value::as_array) + .unwrap_or(&vec![]) + { + let role = match m.get("role").and_then(Value::as_str) { + Some("assistant") => Role::Assistant, + _ => Role::User, + }; + let parts: Vec = m + .get("content") + .and_then(Value::as_array) + .unwrap_or(&vec![]) + .iter() + .filter_map(|b| part(b, dropped)) + .collect(); + if !parts.is_empty() { + r.messages.push(Message { role, parts }); + } + } + + if let Some(cfg) = v.get("inferenceConfig") { + r.max_tokens = cfg.get("maxTokens").and_then(Value::as_u64); + r.temperature = cfg.get("temperature").and_then(Value::as_f64); + r.top_p = cfg.get("topP").and_then(Value::as_f64); + if let Some(stops) = cfg.get("stopSequences").and_then(Value::as_array) { + r.stop = stops + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect(); + } + } + + // `top_k` 是我们自己编码时放进去的,读回来认它 + if let Some(k) = v + .get("additionalModelRequestFields") + .and_then(|e| e.get("top_k")) + .and_then(Value::as_u64) + { + r.top_k = Some(k); + } + + if let Some(cfg) = v.get("toolConfig") { + for t in cfg + .get("tools") + .and_then(Value::as_array) + .unwrap_or(&vec![]) + { + let Some(spec) = t.get("toolSpec") else { + for key in ["systemTool", "cachePoint"] { + if t.get(key).is_some() { + dropped.path(format!("toolConfig.tools.{key}")); + } + } + continue; + }; + r.tools.push(Tool { + name: spec + .get("name") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + description: spec + .get("description") + .and_then(Value::as_str) + .map(str::to_string), + kind: ToolKind::Function { + schema: spec + .get("inputSchema") + .and_then(|s| s.get("json")) + .cloned() + .unwrap_or_else(|| json!({})), + strict: spec.get("strict").and_then(Value::as_bool), + }, + }); + } + if let Some(choice) = cfg.get("toolChoice") { + r.tool_choice = if choice.get("any").is_some() { + Some(ToolChoice::Required) + } else if let Some(t) = choice.get("tool") { + t.get("name") + .and_then(Value::as_str) + .map(|n| ToolChoice::Named(n.to_string())) + } else { + Some(ToolChoice::Auto) + }; + } + } + + for key in ["guardrailConfig", "promptVariables", "outputConfig"] { + if v.get(key).is_some() { + dropped.path(key); + } + } + + Ok(r) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn target() -> Target { + Target { + dialect: Dialect::Bedrock, + official: true, + default_max_tokens: 4096, + } + } + + fn encode(r: &Request) -> (Value, Vec) { + let mut d = Dropped::new(Dialect::Chat); + let v = encode_request(r, &target(), &mut d); + (v, d.into_vec()) + } + + fn user(parts: Vec) -> Request { + Request { + model: "m".into(), + messages: vec![Message { + role: Role::User, + parts, + }], + ..Default::default() + } + } + + #[test] + fn an_image_becomes_bytes_under_the_format_converse_names() { + let (v, dropped) = encode(&user(vec![Part::Image(Media::Base64 { + mime: "image/jpeg".into(), + data: "AAAA".into(), + })])); + let img = &v["messages"][0]["content"][0]["image"]; + // Converse 要短名,不是 MIME + assert_eq!(img["format"], "jpeg"); + assert_eq!(img["source"]["bytes"], "AAAA"); + assert!(dropped.is_empty()); + } + + #[test] + fn an_image_converse_has_no_name_for_is_dropped_rather_than_guessed() { + // 猜一个格式发出去,模型收到的是一张解不开的图 + let (v, dropped) = encode(&user(vec![Part::Image(Media::Base64 { + mime: "image/bmp".into(), + data: "AAAA".into(), + })])); + assert!(v["messages"].as_array().unwrap().is_empty()); + assert_eq!(dropped, ["messages.content.image"]); + } + + #[test] + fn an_image_given_as_a_url_is_reported_because_converse_only_takes_bytes() { + let (_, dropped) = encode(&user(vec![Part::Image(Media::Url( + "https://example.com/a.png".into(), + ))])); + assert_eq!(dropped, ["messages.content.image_url"]); + } + + #[test] + fn a_file_carries_a_name_because_converse_requires_one() { + let (v, _) = encode(&user(vec![Part::File { + media: Media::Base64 { + mime: "application/pdf".into(), + data: "AAAA".into(), + }, + name: None, + }])); + let doc = &v["messages"][0]["content"][0]["document"]; + assert_eq!(doc["format"], "pdf"); + assert!( + doc["name"].as_str().is_some_and(|n| !n.is_empty()), + "没名字的文档要替它起一个:{doc}" + ); + } + + #[test] + fn top_k_goes_into_the_passthrough_pocket_because_converse_has_no_field_for_it() { + let r = Request { + model: "m".into(), + top_k: Some(200), + ..Default::default() + }; + let (v, dropped) = encode(&r); + assert_eq!(v["additionalModelRequestFields"]["top_k"], 200); + assert!(v["inferenceConfig"].get("topK").is_none()); + assert!(dropped.is_empty(), "它没有被丢掉:{dropped:?}"); + } + + #[test] + fn max_tokens_is_always_written_because_converse_wants_a_number() { + let (v, _) = encode(&Request { + model: "m".into(), + ..Default::default() + }); + assert_eq!(v["inferenceConfig"]["maxTokens"], 4096); + } + + #[test] + fn the_three_tool_choices_converse_has() { + let tool = Tool { + name: "t".into(), + description: None, + kind: ToolKind::Function { + schema: json!({}), + strict: None, + }, + }; + let with = |c: ToolChoice| { + let r = Request { + model: "m".into(), + tools: vec![tool.clone()], + tool_choice: Some(c), + ..Default::default() + }; + encode(&r) + }; + assert!(with(ToolChoice::Auto).0["toolConfig"]["toolChoice"]["auto"].is_object()); + assert!(with(ToolChoice::Required).0["toolConfig"]["toolChoice"]["any"].is_object()); + assert_eq!( + with(ToolChoice::Named("t".into())).0["toolConfig"]["toolChoice"]["tool"]["name"], + "t" + ); + } + + #[test] + fn asking_for_no_tools_is_reported_because_converse_cannot_say_it() { + // 不给 toolConfig 就是不用工具,但那样工具定义也跟着没了 —— + // 宁可让模型看见工具,把这件事记下来 + let (v, dropped) = encode(&Request { + model: "m".into(), + tools: vec![Tool { + name: "t".into(), + description: None, + kind: ToolKind::Function { + schema: json!({}), + strict: None, + }, + }], + tool_choice: Some(ToolChoice::None), + ..Default::default() + }); + assert!( + v["toolConfig"]["tools"] + .as_array() + .is_some_and(|a| a.len() == 1) + ); + assert_eq!(dropped, ["tool_choice"]); + } + + #[test] + fn a_thinking_block_keeps_its_signature_so_the_next_turn_is_accepted() { + let (v, dropped) = encode(&user(vec![Part::Thinking(Thinking { + text: "想".into(), + signature: Some(Signature { + vendor: Vendor::Anthropic, + value: "sig".into(), + redacted: false, + }), + })])); + let rc = &v["messages"][0]["content"][0]["reasoningContent"]; + assert_eq!(rc["reasoningText"]["text"], "想"); + assert_eq!(rc["reasoningText"]["signature"], "sig"); + assert!(dropped.is_empty()); + } + + #[test] + fn a_thinking_block_signed_by_someone_else_is_reported_not_forwarded() { + // 别家的签名在 Bedrock 上验不过,带过去会被整个请求拒掉 + let (_, dropped) = encode(&user(vec![Part::Thinking(Thinking { + text: "想".into(), + signature: Some(Signature { + vendor: Vendor::Google, + value: "sig".into(), + redacted: false, + }), + })])); + assert_eq!(dropped, ["messages.reasoning_content"]); + } + + #[test] + fn a_tool_result_keeps_its_image_because_converse_takes_one() { + let (v, dropped) = encode(&user(vec![Part::ToolResult(ToolResult { + id: "tu_1".into(), + content: vec![ + Part::Text("看这个".into()), + Part::Image(Media::Base64 { + mime: "image/png".into(), + data: "AAAA".into(), + }), + ], + is_error: false, + })])); + let res = &v["messages"][0]["content"][0]["toolResult"]; + assert_eq!(res["toolUseId"], "tu_1"); + assert_eq!(res["status"], "success"); + assert_eq!(res["content"][0]["text"], "看这个"); + assert_eq!(res["content"][1]["image"]["format"], "png"); + assert!(dropped.is_empty()); + } + + #[test] + fn a_request_round_trips_through_converse() { + let before = Request { + model: "m".into(), + system: vec!["你是助手".into()], + messages: vec![Message { + role: Role::User, + parts: vec![Part::Text("你好".into())], + }], + max_tokens: Some(100), + temperature: Some(0.5), + top_p: Some(0.9), + stop: vec!["END".into()], + ..Default::default() + }; + let (v, _) = encode(&before); + let mut d = Dropped::new(Dialect::Bedrock); + let after = decode_request(&v, "m", false, &mut d).unwrap(); + + assert_eq!(after.system, before.system); + assert_eq!(after.messages, before.messages); + assert_eq!(after.max_tokens, before.max_tokens); + assert_eq!(after.temperature, before.temperature); + assert_eq!(after.top_p, before.top_p); + assert_eq!(after.stop, before.stop); + } +} diff --git a/crates/tw-dialect/src/bedrock/response.rs b/crates/tw-dialect/src/bedrock/response.rs new file mode 100644 index 00000000..0ef0e6da --- /dev/null +++ b/crates/tw-dialect/src/bedrock/response.rs @@ -0,0 +1,263 @@ +//! Bedrock Converse 响应 ⇄ 中间表示。 + +use serde_json::{Value, json}; + +use crate::convert::Session; +use crate::ir::*; + +/// Converse 的 `stopReason` → 中间表示。 +/// +/// 九个值里有三个是别家没有的失败态(`malformed_*`、`guardrail_intervened`)。 +/// **它们不是「说完了」** —— 记成 `Other` 保留原文,比硬塞进 `EndTurn` 诚实: +/// 客户端看到 `end_turn` 会以为回答是完整的 +pub fn stop_reason(s: &str) -> StopReason { + match s { + "end_turn" => StopReason::EndTurn, + "tool_use" => StopReason::ToolUse, + "max_tokens" => StopReason::MaxTokens, + "stop_sequence" => StopReason::StopSequence(None), + "content_filtered" | "guardrail_intervened" => StopReason::ContentFilter, + "model_context_window_exceeded" => StopReason::ContextWindow, + other => StopReason::Other(other.to_string()), + } +} + +/// 中间表示 → Converse 的 `stopReason`。 +pub fn stop_reason_str(s: &StopReason) -> &str { + match s { + StopReason::EndTurn | StopReason::Paused => "end_turn", + StopReason::ToolUse => "tool_use", + StopReason::MaxTokens => "max_tokens", + StopReason::StopSequence(_) => "stop_sequence", + StopReason::ContentFilter | StopReason::Refusal => "content_filtered", + StopReason::ContextWindow => "model_context_window_exceeded", + StopReason::Other(s) => s, + } +} + +/// Converse 的 `usage` → 中间表示。 +/// +/// **`inputTokens` 含不含缓存,AWS 没有明说**,但 Bedrock 上跑的是各家原厂模型, +/// 而 Anthropic 的语义是不含。按不含读:读错的话缓存那部分会被少算,而按含读 +/// 再减一遍,读错时会把正常输入减成负数 +pub fn usage(u: &Value) -> Usage { + let n = |k: &str| u.get(k).and_then(Value::as_u64).unwrap_or(0); + Usage { + input: n("inputTokens"), + cache_read: n("cacheReadInputTokens"), + cache_write: n("cacheWriteInputTokens"), + output: n("outputTokens"), + reasoning: 0, + } +} + +/// 中间表示 → Converse 的 `usage`。 +pub fn usage_json(u: &Usage) -> Value { + let mut out = json!({ + "inputTokens": u.input, + "outputTokens": u.output, + "totalTokens": u.prompt_total() + u.output, + }); + if u.cache_read > 0 { + out["cacheReadInputTokens"] = json!(u.cache_read); + } + if u.cache_write > 0 { + out["cacheWriteInputTokens"] = json!(u.cache_write); + } + out +} + +/// 一个内容块 → 中间表示。 +pub(crate) fn block(b: &Value) -> Option { + if let Some(t) = b.get("text").and_then(Value::as_str) { + return (!t.is_empty()).then(|| Block::Text(t.to_string())); + } + if let Some(r) = b.get("reasoningContent") { + if let Some(rt) = r.get("reasoningText") { + return Some(Block::Thinking(Thinking { + text: rt + .get("text") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + signature: rt + .get("signature") + .and_then(Value::as_str) + .and_then(|s| Signature::read(s, Vendor::Anthropic)), + })); + } + // 打码过的推理:内容看不到,但签名要带回去,否则下一轮会被拒 + if let Some(red) = r.get("redactedContent").and_then(Value::as_str) { + return Some(Block::Thinking(Thinking { + text: String::new(), + signature: Some(Signature { + vendor: Vendor::Anthropic, + value: red.to_string(), + redacted: true, + }), + })); + } + return None; + } + if let Some(u) = b.get("toolUse") { + return Some(Block::ToolCall(ToolCall { + id: u + .get("toolUseId") + .and_then(Value::as_str) + .map(str::to_string) + .unwrap_or_else(|| new_id("tooluse_")), + name: u + .get("name") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + input: ToolInput::Json(u.get("input").cloned().unwrap_or_else(|| json!({}))), + })); + } + None +} + +pub fn decode_response(v: &Value) -> Response { + let message = v + .get("output") + .and_then(|o| o.get("message")) + .unwrap_or(&Value::Null); + + let blocks: Vec = message + .get("content") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(block).collect()) + .unwrap_or_default(); + + Response { + // Converse 不发响应 id。调用方按客户端的格式补一个 + id: None, + model: None, + blocks, + stop: v.get("stopReason").and_then(Value::as_str).map(stop_reason), + usage: v.get("usage").map(usage), + } +} + +pub fn encode_response(r: &Response, _s: &Session) -> Value { + let mut content = Vec::new(); + for b in &r.blocks { + match b { + Block::Text(t) if !t.is_empty() => content.push(json!({ "text": t })), + Block::Text(_) => {} + Block::Thinking(th) => match &th.signature { + Some(s) if s.redacted => { + content.push(json!({ "reasoningContent": { "redactedContent": s.value } })) + } + sig => content.push(json!({ + "reasoningContent": { + "reasoningText": { + "text": th.text, + "signature": sig.as_ref().map(|s| s.value.clone()).unwrap_or_default(), + }, + }, + })), + }, + Block::ToolCall(c) => content.push(json!({ + "toolUse": { "toolUseId": c.id, "name": c.name, "input": c.input.to_object() }, + })), + } + } + + let mut out = json!({ + "output": { "message": { "role": "assistant", "content": content } }, + "stopReason": stop_reason_str(r.stop.as_ref().unwrap_or(&StopReason::EndTurn)), + }); + out["usage"] = usage_json(&r.usage.unwrap_or_default()); + out +} + +/// Converse 的错误体。状态码走 HTTP,正文只有一句话。 +pub fn error_body(_status: u16, message: &str) -> Value { + json!({ "message": message }) +} + +pub fn error_message(v: &Value) -> Option { + v.get("message").and_then(Value::as_str).map(str::to_string) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_failure_stop_reason_is_not_flattened_into_end_turn() { + // Converse 有三个别家没有的失败态。说成 end_turn 会让客户端 + // 以为回答是完整的 + for raw in [ + "malformed_model_output", + "malformed_tool_use", + "guardrail_intervened", + ] { + let s = stop_reason(raw); + assert_ne!(s, StopReason::EndTurn, "{raw} 被当成了正常收尾"); + } + assert_eq!( + stop_reason("malformed_tool_use"), + StopReason::Other("malformed_tool_use".into()), + "原文要保留下来" + ); + // 这个有对应物 + assert_eq!( + stop_reason("guardrail_intervened"), + StopReason::ContentFilter + ); + } + + #[test] + fn the_context_window_reason_has_a_home() { + assert_eq!( + stop_reason("model_context_window_exceeded"), + StopReason::ContextWindow + ); + } + + #[test] + fn cache_tokens_are_kept_apart_from_plain_input() { + let u = usage(&json!({ + "inputTokens": 60, "cacheReadInputTokens": 40, + "cacheWriteInputTokens": 10, "outputTokens": 20, "totalTokens": 130 + })); + assert_eq!(u.input, 60); + assert_eq!(u.cache_read, 40); + assert_eq!(u.cache_write, 10); + assert_eq!(u.output, 20); + // 三者不重叠,加起来才是全部输入 + assert_eq!(u.prompt_total(), 110); + } + + #[test] + fn a_response_round_trips_through_converse() { + let before = Response { + id: None, + model: None, + blocks: vec![ + Block::Text("天气晴".into()), + Block::ToolCall(ToolCall { + id: "tu_1".into(), + name: "get_weather".into(), + input: ToolInput::Json(json!({"city": "北京"})), + }), + ], + stop: Some(StopReason::ToolUse), + usage: Some(Usage { + input: 60, + cache_read: 40, + cache_write: 0, + output: 20, + reasoning: 0, + }), + }; + let s = Session::for_test(Dialect::Bedrock, Dialect::Bedrock); + let after = decode_response(&encode_response(&before, &s)); + + assert_eq!(after.blocks, before.blocks); + assert_eq!(after.stop, before.stop); + assert_eq!(after.usage, before.usage); + } +} diff --git a/crates/tw-dialect/src/bedrock/stream.rs b/crates/tw-dialect/src/bedrock/stream.rs new file mode 100644 index 00000000..2eb82ba3 --- /dev/null +++ b/crates/tw-dialect/src/bedrock/stream.rs @@ -0,0 +1,421 @@ +//! Bedrock ConverseStream 流 ⇄ 事件。 +//! +//! # 帧的边界在哪 +//! +//! Converse 的流是 AWS eventstream 的二进制帧,不是 SSE。**拆帧和封帧都不在这里** —— +//! 那是传输层的事,和 SSE 平级: +//! +//! - 读:传输层拆出每个事件,交成一个 [`Frame`],`:event-type` 头进 `event`,载荷 JSON 进 `data` +//! - 写:这里照常吐 SSE 帧文本(和另外四种方言一致),传输层要发给 Bedrock 客户端时再封成二进制帧 +//! +//! 这样这个 crate 仍然只依赖 serde,而"帧里装什么"和"帧怎么封"各归各的。 +//! +//! # 和 Anthropic 同构 +//! +//! 事件序列是一样的形状:`messageStart` / `contentBlockStart` / `contentBlockDelta` / +//! `contentBlockStop` / `messageStop` / `metadata`。一处差别:**文本块不发 +//! `contentBlockStart`**,直接就是 delta,所以读的时候要替它补一个块开始。 + +use std::collections::HashMap; + +use serde_json::{Value, json}; + +use crate::convert::Session; +use crate::frame::{self, Frame}; +use crate::ir::*; + +use super::response::{stop_reason, stop_reason_str, usage, usage_json}; + +// ───────────────────────────────────────────────────────── 读 + +#[derive(Default)] +pub struct Parser { + /// 已经报过 `BlockStart` 的块。**文本块没有 `contentBlockStart`**, + /// 要在第一个 delta 到达时替它补一个 + open: HashMap, +} + +impl Parser { + pub fn frame(&mut self, f: &Frame, out: &mut Vec) { + let Ok(v) = serde_json::from_str::(&f.data) else { + return; + }; + // 传输层把 `:event-type` 放进 event。没有的话退回看载荷的形状 + let kind = f.event.as_deref().unwrap_or_else(|| shape_of(&v)); + let index = |v: &Value| { + v.get("contentBlockIndex") + .and_then(Value::as_u64) + .unwrap_or(0) as usize + }; + + match kind { + "messageStart" => out.push(Event::Start { + id: None, + model: None, + }), + + "contentBlockStart" => { + let i = index(&v); + if let Some(t) = v.get("start").and_then(|s| s.get("toolUse")) { + self.open.insert(i, ()); + out.push(Event::BlockStart { + index: i, + kind: BlockKind::ToolCall { + id: t + .get("toolUseId") + .and_then(Value::as_str) + .map(str::to_string) + .unwrap_or_else(|| new_id("tooluse_")), + name: t + .get("name") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(), + }, + }); + } + } + + "contentBlockDelta" => { + let i = index(&v); + let Some(d) = v.get("delta") else { return }; + + if let Some(t) = d.get("text").and_then(Value::as_str) { + self.begin(i, BlockKind::Text, out); + out.push(Event::Delta { + index: i, + delta: Delta::Text(t.to_string()), + }); + } else if let Some(t) = d.get("toolUse").and_then(|u| u.get("input")) { + // 工具参数是 JSON 文本的片段,不是对象 + let piece = t + .as_str() + .map(str::to_string) + .unwrap_or_else(|| t.to_string()); + out.push(Event::Delta { + index: i, + delta: Delta::ToolInput(piece), + }); + } else if let Some(r) = d.get("reasoningContent") { + if let Some(t) = r.get("text").and_then(Value::as_str) { + self.begin(i, BlockKind::Thinking, out); + out.push(Event::Delta { + index: i, + delta: Delta::Thinking(t.to_string()), + }); + } + // 签名单独来一帧,收尾时才到 + if let Some(s) = r.get("signature").and_then(Value::as_str) { + self.begin(i, BlockKind::Thinking, out); + out.push(Event::Delta { + index: i, + delta: Delta::Signature(Signature { + vendor: Vendor::Anthropic, + value: s.to_string(), + redacted: false, + }), + }); + } + if let Some(s) = r.get("redactedContent").and_then(Value::as_str) { + self.begin(i, BlockKind::Thinking, out); + out.push(Event::Delta { + index: i, + delta: Delta::Signature(Signature { + vendor: Vendor::Anthropic, + value: s.to_string(), + redacted: true, + }), + }); + } + } + } + + "contentBlockStop" => { + let i = index(&v); + if self.open.remove(&i).is_some() { + out.push(Event::BlockStop { index: i }); + } + } + + "messageStop" => { + if let Some(s) = v.get("stopReason").and_then(Value::as_str) { + out.push(Event::Stop(stop_reason(s))); + } + } + + "metadata" => { + if let Some(u) = v.get("usage") { + out.push(Event::Usage(usage(u))); + } + } + + // 流中途的异常事件。**它们是流的一部分,不是 HTTP 错误** —— + // 头已经发出去了,出错只能在流里说 + "internalServerException" + | "modelStreamErrorException" + | "validationException" + | "throttlingException" + | "serviceUnavailableException" => { + out.push(Event::Error { + message: v + .get("message") + .and_then(Value::as_str) + .unwrap_or("The upstream ended the stream with an error.") + .to_string(), + }); + } + + _ => {} + } + } + + /// 补一个块开始。文本和推理块在 Converse 里没有 `contentBlockStart` + fn begin(&mut self, index: usize, kind: BlockKind, out: &mut Vec) { + if self.open.insert(index, ()).is_none() { + out.push(Event::BlockStart { index, kind }); + } + } + + pub fn finish(&mut self, out: &mut Vec) { + let mut open: Vec = self.open.keys().copied().collect(); + open.sort_unstable(); + for i in open { + out.push(Event::BlockStop { index: i }); + } + self.open.clear(); + } +} + +/// 传输层没给 `:event-type` 时,按载荷的形状认。 +fn shape_of(v: &Value) -> &'static str { + for (key, name) in [ + ("start", "contentBlockStart"), + ("delta", "contentBlockDelta"), + ("stopReason", "messageStop"), + ("usage", "metadata"), + ("role", "messageStart"), + ] { + if v.get(key).is_some() { + return name; + } + } + if v.get("contentBlockIndex").is_some() { + return "contentBlockStop"; + } + "" +} + +// ───────────────────────────────────────────────────────── 写 + +pub struct Writer { + usage: Usage, + stop: Option, + started: bool, +} + +impl Writer { + pub fn new(_s: &Session) -> Writer { + Writer { + usage: Usage::default(), + stop: None, + started: false, + } + } + + pub fn event(&mut self, e: &Event) -> String { + match e { + Event::Start { .. } => { + self.started = true; + frame::named("messageStart", &json!({ "role": "assistant" })) + } + Event::BlockStart { index, kind } => match kind { + BlockKind::ToolCall { id, name } => frame::named( + "contentBlockStart", + &json!({ + "contentBlockIndex": index, + "start": { "toolUse": { "toolUseId": id, "name": name } }, + }), + ), + // 文本和推理块在 Converse 里不发块开始 + _ => String::new(), + }, + Event::Delta { index, delta } => { + let d = match delta { + Delta::Text(t) => json!({ "text": t }), + Delta::Thinking(t) => json!({ "reasoningContent": { "text": t } }), + Delta::Signature(s) if s.redacted => { + json!({ "reasoningContent": { "redactedContent": s.value } }) + } + Delta::Signature(s) => { + json!({ "reasoningContent": { "signature": s.value } }) + } + Delta::ToolInput(t) => json!({ "toolUse": { "input": t } }), + }; + frame::named( + "contentBlockDelta", + &json!({ "contentBlockIndex": index, "delta": d }), + ) + } + Event::BlockStop { index } => { + frame::named("contentBlockStop", &json!({ "contentBlockIndex": index })) + } + // 用量和停止原因攒到收尾:Converse 把它们放在最后两个事件里 + Event::Usage(u) => { + self.usage.merge(u); + String::new() + } + Event::Stop(s) => { + self.stop = Some(s.clone()); + String::new() + } + Event::Error { message } => { + frame::named("modelStreamErrorException", &json!({ "message": message })) + } + } + } + + pub fn finish(&mut self) -> String { + if !self.started { + return String::new(); + } + let mut out = frame::named( + "messageStop", + &json!({ + "stopReason": stop_reason_str(self.stop.as_ref().unwrap_or(&StopReason::EndTurn)), + }), + ); + out.push_str(&frame::named( + "metadata", + &json!({ "usage": usage_json(&self.usage) }), + )); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn feed(frames: &[(&str, Value)]) -> Vec { + let mut p = Parser::default(); + let mut out = Vec::new(); + for (event, data) in frames { + p.frame( + &Frame { + event: Some((*event).to_string()), + data: data.to_string(), + }, + &mut out, + ); + } + p.finish(&mut out); + out + } + + #[test] + fn a_text_block_gets_the_start_converse_never_sends() { + // Converse 只给工具块发 contentBlockStart。文本直接就是 delta, + // 而中间表示要求块先开始 + let events = feed(&[( + "contentBlockDelta", + json!({"contentBlockIndex": 0, "delta": {"text": "你好"}}), + )]); + assert!( + matches!( + events.first(), + Some(Event::BlockStart { + index: 0, + kind: BlockKind::Text + }) + ), + "第一个事件应该是补出来的块开始:{events:?}" + ); + } + + #[test] + fn a_text_block_only_starts_once() { + let events = feed(&[ + ( + "contentBlockDelta", + json!({"contentBlockIndex": 0, "delta": {"text": "你"}}), + ), + ( + "contentBlockDelta", + json!({"contentBlockIndex": 0, "delta": {"text": "好"}}), + ), + ]); + let starts = events + .iter() + .filter(|e| matches!(e, Event::BlockStart { .. })) + .count(); + assert_eq!(starts, 1, "{events:?}"); + } + + #[test] + fn a_tool_call_keeps_its_id_and_name_from_the_start_event() { + let events = feed(&[ + ( + "contentBlockStart", + json!({"contentBlockIndex": 1, "start": {"toolUse": {"toolUseId": "tu_1", "name": "get_weather"}}}), + ), + ( + "contentBlockDelta", + json!({"contentBlockIndex": 1, "delta": {"toolUse": {"input": "{\"city\":"}}}), + ), + ]); + assert!( + matches!( + &events[0], + Event::BlockStart { index: 1, kind: BlockKind::ToolCall { id, name } } + if id == "tu_1" && name == "get_weather" + ), + "{events:?}" + ); + assert!( + matches!( + &events[1], + Event::Delta { index: 1, delta: Delta::ToolInput(s) } if s == "{\"city\":" + ), + "{events:?}" + ); + } + + #[test] + fn the_metadata_frame_is_where_usage_comes_from() { + let events = feed(&[( + "metadata", + json!({"usage": {"inputTokens": 60, "cacheReadInputTokens": 40, "outputTokens": 20}}), + )]); + let Some(Event::Usage(u)) = events.first() else { + panic!("没有用量:{events:?}"); + }; + assert_eq!((u.input, u.cache_read, u.output), (60, 40, 20)); + } + + #[test] + fn an_exception_frame_becomes_an_error_event_not_silence() { + // 头已经发出去了,出错只能在流里说。吞掉它客户端就只看到流突然停了 + let events = feed(&[( + "throttlingException", + json!({"message": "Too many requests"}), + )]); + assert!( + matches!(events.first(), Some(Event::Error { message }) if message == "Too many requests"), + "{events:?}" + ); + } + + #[test] + fn an_unfinished_block_is_closed_when_the_stream_ends() { + let events = feed(&[( + "contentBlockDelta", + json!({"contentBlockIndex": 0, "delta": {"text": "半句"}}), + )]); + assert!( + events + .iter() + .any(|e| matches!(e, Event::BlockStop { index: 0 })), + "流结束时没收尾:{events:?}" + ); + } +} diff --git a/crates/tw-dialect/src/convert.rs b/crates/tw-dialect/src/convert.rs index 0a38f216..8bdf6fd7 100644 --- a/crates/tw-dialect/src/convert.rs +++ b/crates/tw-dialect/src/convert.rs @@ -16,7 +16,7 @@ use serde_json::Value; use crate::frame::{self, Frame}; use crate::ir::*; -use crate::{anthropic, chat, gemini, responses}; +use crate::{anthropic, bedrock, chat, gemini, responses}; /// 改写好的上游请求。 #[derive(Debug, Clone)] @@ -67,6 +67,14 @@ pub fn decode( shape.gemini_sse = query.is_some_and(|q| q.split('&').any(|kv| kv == "alt=sse")); gemini::decode_request(body, &model, stream, &mut dropped)? } + Dialect::Bedrock => { + let (model, stream) = bedrock_path(path).ok_or_else(|| { + Rejection(format!( + "The path {path} does not say which Bedrock model to call, or how." + )) + })?; + bedrock::decode_request(body, &model, stream, &mut dropped)? + } }; Ok(Decoded { client, @@ -97,6 +105,18 @@ impl Decoded { "/v1/responses".to_string(), None, ), + Dialect::Bedrock => { + let action = if request.stream { + "converse-stream" + } else { + "converse" + }; + ( + bedrock::encode_request(request, target, &mut dropped), + format!("/model/{}/{action}", request.model), + None, + ) + } Dialect::Gemini => { let model = request .model @@ -153,6 +173,20 @@ pub fn prepare( Ok(decode(client, &v, path, query)?.encode(target)) } +/// `/model/anthropic.claude-sonnet-4-v1:0/converse-stream` → (模型, 是否流式) +/// +/// 模型 id 自己带冒号和点,所以按最后一段分,不是按分隔符找 +fn bedrock_path(path: &str) -> Option<(String, bool)> { + let rest = path.split_once("/model/")?.1; + let (model, action) = rest.rsplit_once('/')?; + let stream = match action { + "converse-stream" => true, + "converse" => false, + _ => return None, + }; + Some((model.to_string(), stream)) +} + /// `/v1beta/models/gemini-2.5-pro:streamGenerateContent` → (模型, 是否流式) fn gemini_path(path: &str) -> Option<(String, bool)> { let (_, rest) = path.split_once("/models/")?; @@ -220,6 +254,7 @@ impl Session { Dialect::Chat => chat::decode_response(&v), Dialect::Responses => responses::decode_response(&v), Dialect::Gemini => gemini::decode_response(&v), + Dialect::Bedrock => bedrock::decode_response(&v), }; self.normalize(&mut r); Some(self.encode(&r)) @@ -231,6 +266,7 @@ impl Session { Dialect::Chat => chat::encode_response(r, self), Dialect::Responses => responses::encode_response(r, self), Dialect::Gemini => gemini::encode_response(r, self), + Dialect::Bedrock => bedrock::encode_response(r, self), }; v.to_string().into_bytes() } @@ -257,6 +293,7 @@ impl Session { Dialect::Chat => chat::decode_response(&v), Dialect::Responses => responses::decode_response(&v), Dialect::Gemini => gemini::decode_response(&v), + Dialect::Bedrock => bedrock::decode_response(&v), }; self.normalize(&mut r); let mut w = Writer::new(self); @@ -276,6 +313,7 @@ impl Session { Dialect::Anthropic => anthropic::response::error_message(&v), Dialect::Chat | Dialect::Responses => chat::response::error_message(&v), Dialect::Gemini => gemini::response::error_message(&v), + Dialect::Bedrock => bedrock::response::error_message(&v), }) .unwrap_or_else(|| { let text = String::from_utf8_lossy(body); @@ -348,6 +386,7 @@ pub fn error_body(client: Dialect, status: u16, message: &str) -> Vec { Dialect::Anthropic => anthropic::response::error_body(status, message), Dialect::Chat | Dialect::Responses => chat::response::error_body(status, message), Dialect::Gemini => gemini::response::error_body(status, message), + Dialect::Bedrock => bedrock::response::error_body(status, message), }; v.to_string().into_bytes() } @@ -408,6 +447,7 @@ enum Parser { Chat(chat::stream::Parser), Responses(responses::stream::Parser), Gemini(gemini::stream::Parser), + Bedrock(bedrock::stream::Parser), } impl Parser { @@ -417,6 +457,7 @@ impl Parser { Dialect::Chat => Parser::Chat(Default::default()), Dialect::Responses => Parser::Responses(Default::default()), Dialect::Gemini => Parser::Gemini(Default::default()), + Dialect::Bedrock => Parser::Bedrock(Default::default()), } } @@ -426,6 +467,7 @@ impl Parser { Parser::Chat(p) => p.frame(f, out), Parser::Responses(p) => p.frame(f, out), Parser::Gemini(p) => p.frame(f, out), + Parser::Bedrock(p) => p.frame(f, out), } } @@ -435,6 +477,7 @@ impl Parser { Parser::Chat(p) => p.finish(out), Parser::Responses(p) => p.finish(out), Parser::Gemini(p) => p.finish(out), + Parser::Bedrock(p) => p.finish(out), } } } @@ -444,6 +487,7 @@ enum Writer { Chat(chat::stream::Writer), Responses(responses::stream::Writer), Gemini(gemini::stream::Writer), + Bedrock(bedrock::stream::Writer), } impl Writer { @@ -453,6 +497,7 @@ impl Writer { Dialect::Chat => Writer::Chat(chat::stream::Writer::new(s)), Dialect::Responses => Writer::Responses(responses::stream::Writer::new(s)), Dialect::Gemini => Writer::Gemini(gemini::stream::Writer::new(s)), + Dialect::Bedrock => Writer::Bedrock(bedrock::stream::Writer::new(s)), } } @@ -462,6 +507,7 @@ impl Writer { Writer::Chat(w) => w.event(e), Writer::Responses(w) => w.event(e), Writer::Gemini(w) => w.event(e), + Writer::Bedrock(w) => w.event(e), } } @@ -471,6 +517,7 @@ impl Writer { Writer::Chat(w) => w.finish(), Writer::Responses(w) => w.finish(), Writer::Gemini(w) => w.finish(), + Writer::Bedrock(w) => w.finish(), } } } @@ -768,6 +815,20 @@ pub fn strip_carried(client: Dialect, body: &[u8]) -> Option> { }; let mut changed = false; match client { + Dialect::Bedrock => { + let messages = v.get_mut("messages")?.as_array_mut()?; + for m in messages.iter_mut() { + if let Some(blocks) = m.get_mut("content").and_then(Value::as_array_mut) { + let before = blocks.len(); + blocks.retain(|b| { + !b.get("reasoningContent") + .and_then(|r| r.get("reasoningText")) + .is_some_and(|t| carried(t.get("signature"))) + }); + changed |= blocks.len() != before; + } + } + } Dialect::Anthropic => { let messages = v.get_mut("messages")?.as_array_mut()?; for m in messages.iter_mut() { diff --git a/crates/tw-dialect/src/ir.rs b/crates/tw-dialect/src/ir.rs index d89fdbff..b185f690 100644 --- a/crates/tw-dialect/src/ir.rs +++ b/crates/tw-dialect/src/ir.rs @@ -29,6 +29,8 @@ pub enum Dialect { Responses, /// Gemini:`/v1beta/models/{model}:generateContent` Gemini, + /// Bedrock Converse:`/model/{id}/converse` + Bedrock, } impl Dialect { @@ -39,6 +41,7 @@ impl Dialect { Dialect::Chat => "openai-chat", Dialect::Responses => "openai-responses", Dialect::Gemini => "gemini", + Dialect::Bedrock => "bedrock", } } @@ -48,6 +51,9 @@ impl Dialect { Dialect::Anthropic => Vendor::Anthropic, Dialect::Chat | Dialect::Responses => Vendor::OpenAi, Dialect::Gemini => Vendor::Google, + // Converse 上跑的是各家原厂模型。推理签名按 Anthropic 认 —— + // Bedrock 上有推理的就是 Claude + Dialect::Bedrock => Vendor::Anthropic, } } } @@ -552,26 +558,32 @@ impl Feature { (Reasoning, Chat) => "reasoning_effort", (Reasoning, Responses) => "reasoning", (Reasoning, Gemini) => "generationConfig.thinkingConfig", + (Reasoning, Bedrock) => "additionalModelRequestFields.thinking", (ReasoningHistory, Anthropic) => "messages.content.thinking", (ReasoningHistory, Chat) => "messages.reasoning_content", (ReasoningHistory, Responses) => "input.reasoning", (ReasoningHistory, Gemini) => "contents.parts.thought", + (ReasoningHistory, Bedrock) => "messages.content.reasoningContent", (Format, Anthropic) => "output_config.format", (Format, Chat) => "response_format", (Format, Responses) => "text.format", (Format, Gemini) => "generationConfig.responseJsonSchema", + (Format, Bedrock) => "outputConfig.textFormat", (MediaUrl, Anthropic) => "messages.content.image.source.url", (MediaUrl, Chat) => "messages.content.image_url", (MediaUrl, Responses) => "input.content.input_image.image_url", (MediaUrl, Gemini) => "contents.parts.fileData", + (MediaUrl, Bedrock) => "messages.content.image.source.s3Location", (File, Anthropic) => "messages.content.document", (File, Chat) => "messages.content.file", (File, Responses) => "input.content.input_file", (File, Gemini) => "contents.parts.inlineData", + (File, Bedrock) => "messages.content.document", (ToolResultImage, Anthropic) => "messages.content.tool_result.content.image", (ToolResultImage, Chat) => "messages.content", (ToolResultImage, Responses) => "input.function_call_output.output.input_image", (ToolResultImage, Gemini) => "contents.parts.functionResponse.parts", + (ToolResultImage, Bedrock) => "messages.content.toolResult.content.image", (FreeformFormat, _) => "tools.custom.format", } } diff --git a/crates/tw-dialect/src/lib.rs b/crates/tw-dialect/src/lib.rs index e3314c17..e9746b27 100644 --- a/crates/tw-dialect/src/lib.rs +++ b/crates/tw-dialect/src/lib.rs @@ -6,6 +6,7 @@ //! [`ir`] 里的中间表示。这个 crate 只依赖 serde,不碰网络,企业版网关也可以直接用。 pub mod anthropic; +pub mod bedrock; pub mod chat; pub mod convert; pub mod frame; diff --git a/crates/tw-dialect/tests/matrix.rs b/crates/tw-dialect/tests/matrix.rs index ee952463..916b6334 100644 --- a/crates/tw-dialect/tests/matrix.rs +++ b/crates/tw-dialect/tests/matrix.rs @@ -15,7 +15,7 @@ use serde_json::{Value, json}; use tw_dialect::convert::{Session, prepare}; use tw_dialect::frame::Decoder; use tw_dialect::ir::*; -use tw_dialect::{anthropic, chat, gemini, responses}; +use tw_dialect::{anthropic, bedrock, chat, gemini, responses}; const ALL: [Dialect; 4] = [ Dialect::Anthropic, @@ -49,6 +49,11 @@ fn client_request(d: Dialect, stream: bool) -> (Vec, String, Option) "contents": [{"role": "user", "parts": [{"text": "北京天气?"}]}], "tools": [{"functionDeclarations": [{"name": "get_weather", "description": "查天气", "parametersJsonSchema": schema()}]}], }), + Dialect::Bedrock => json!({ + "messages": [{"role": "user", "content": [{"text": "北京天气?"}]}], + "inferenceConfig": {"maxTokens": 1024}, + "toolConfig": {"tools": [{"toolSpec": {"name": "get_weather", "description": "查天气", "inputSchema": {"json": schema()}}}]}, + }), }; let (path, query) = match d { Dialect::Anthropic => ("/v1/messages".to_string(), None), @@ -65,6 +70,14 @@ fn client_request(d: Dialect, stream: bool) -> (Vec, String, Option) stream.then(|| "alt=sse".to_string()), ) } + Dialect::Bedrock => { + let action = if stream { + "converse-stream" + } else { + "converse" + }; + (format!("/model/test-model/{action}"), None) + } }; (body.to_string().into_bytes(), path, query) } @@ -105,6 +118,14 @@ fn upstream_response(d: Dialect) -> Value { "usageMetadata": {"promptTokenCount": 100, "cachedContentTokenCount": 40, "candidatesTokenCount": 20}, "modelVersion": "up-model", "responseId": "r_up" }), + Dialect::Bedrock => json!({ + "output": {"message": {"role": "assistant", "content": [ + {"text": "天气晴"}, + {"toolUse": {"toolUseId": "call_up_1", "name": "get_weather", "input": {"city": "北京"}}} + ]}}, + "stopReason": "tool_use", + "usage": {"inputTokens": 60, "cacheReadInputTokens": 40, "outputTokens": 20, "totalTokens": 120} + }), } } @@ -179,6 +200,21 @@ fn upstream_stream(d: Dialect) -> String { ] .concat() } + // 传输层已经把 eventstream 的二进制帧拆成了这个形状: + // `:event-type` 头进 event,载荷进 data + Dialect::Bedrock => [ + named("messageStart", json!({"role": "assistant"})), + named("contentBlockDelta", json!({"contentBlockIndex": 0, "delta": {"text": "天气"}})), + named("contentBlockDelta", json!({"contentBlockIndex": 0, "delta": {"text": "晴"}})), + named("contentBlockStop", json!({"contentBlockIndex": 0})), + named("contentBlockStart", json!({"contentBlockIndex": 1, "start": {"toolUse": {"toolUseId": "call_up_1", "name": "get_weather"}}})), + named("contentBlockDelta", json!({"contentBlockIndex": 1, "delta": {"toolUse": {"input": "{\"city\":"}}})), + named("contentBlockDelta", json!({"contentBlockIndex": 1, "delta": {"toolUse": {"input": "\"北京\"}"}}})), + named("contentBlockStop", json!({"contentBlockIndex": 1})), + named("messageStop", json!({"stopReason": "tool_use"})), + named("metadata", json!({"usage": {"inputTokens": 60, "cacheReadInputTokens": 40, "outputTokens": 20, "totalTokens": 120}})), + ] + .concat(), } } @@ -225,6 +261,7 @@ fn decode_client_response(d: Dialect, body: &[u8]) -> Response { Dialect::Chat => chat::decode_response(&v), Dialect::Responses => responses::decode_response(&v), Dialect::Gemini => gemini::decode_response(&v), + Dialect::Bedrock => bedrock::decode_response(&v), } } @@ -254,6 +291,11 @@ fn decode_client_stream(d: Dialect, bytes: &[u8]) -> Response { frames.iter().for_each(|f| p.frame(f, &mut events)); p.finish(&mut events); } + Dialect::Bedrock => { + let mut p = bedrock::stream::Parser::default(); + frames.iter().for_each(|f| p.frame(f, &mut events)); + p.finish(&mut events); + } } let mut r = Response::default(); let mut open = std::collections::HashMap::new(); @@ -326,6 +368,7 @@ fn the_request_reaches_every_upstream_in_its_own_shape() { 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 at = format!("{client:?} → {upstream:?}"); diff --git a/crates/tw-gateway/src/chatgpt.rs b/crates/tw-gateway/src/chatgpt.rs index e90834e9..c401ef09 100644 --- a/crates/tw-gateway/src/chatgpt.rs +++ b/crates/tw-gateway/src/chatgpt.rs @@ -78,6 +78,7 @@ pub fn drop_output_limit(request: &mut tw_dialect::ir::Request, client: Dialect) Dialect::Anthropic | Dialect::Chat => "max_tokens", Dialect::Responses => "max_output_tokens", Dialect::Gemini => "generationConfig.maxOutputTokens", + Dialect::Bedrock => "inferenceConfig.maxTokens", } .to_string(), ) diff --git a/crates/tw-gateway/src/forward.rs b/crates/tw-gateway/src/forward.rs index e40960ce..f883f7b0 100644 --- a/crates/tw-gateway/src/forward.rs +++ b/crates/tw-gateway/src/forward.rs @@ -185,6 +185,14 @@ pub fn apply_set( g.insert("maxOutputTokens".into(), t); } } + Dialect::Bedrock => { + let c = obj + .entry("inferenceConfig") + .or_insert_with(|| serde_json::json!({})); + if let Some(c) = c.as_object_mut() { + c.insert("maxTokens".into(), t); + } + } } } if let Some(th) = set.thinking { @@ -213,6 +221,15 @@ pub fn apply_set( g.remove("thinkingConfig"); } } + // Converse 没有一等公民的思考开关,它在透传口袋里 + Dialect::Bedrock => { + if let Some(f) = obj + .get_mut("additionalModelRequestFields") + .and_then(serde_json::Value::as_object_mut) + { + f.remove("thinking"); + } + } } } } diff --git a/crates/tw-gateway/src/translate.rs b/crates/tw-gateway/src/translate.rs index 54a21502..baa2ea41 100644 --- a/crates/tw-gateway/src/translate.rs +++ b/crates/tw-gateway/src/translate.rs @@ -59,6 +59,8 @@ pub fn keeps_header(client: Dialect, name: &str) -> bool { "conversation_id", "version", ], + // SigV4 签的是这一次请求的内容,转发给别的上游只会是一个签错的头 + Dialect::Bedrock => &["x-amzn-bedrock-accept", "x-amzn-bedrock-save"], Dialect::Gemini => &["x-goog-api-client", "x-goog-user-project"], }; !own.contains(&name.as_str())