diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f0d7a1d7..4fa1e70f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,6 +36,12 @@ jobs: - name: Test run: cargo test --workspace + # 桌面版不开 `bedrock`,上面两步就一行都不编它。企业版开,所以单独查 + - name: clippy + test (tw-upstream, bedrock) + run: | + cargo clippy -p tw-upstream --all-targets --features bedrock -- -D warnings + cargo test -p tw-upstream --features bedrock + - name: Build run: cargo build --release -p twcore diff --git a/Cargo.lock b/Cargo.lock index 4c55846a..9bebe45d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2963,43 +2963,6 @@ dependencies = [ "tw-types", ] -[[package]] -name = "tw-protocol" -version = "0.34.0" -dependencies = [ - "bytes", - "futures", - "metrics", - "reqwest", - "serde_json", - "tracing", -] - -[[package]] -name = "tw-provider" -version = "0.34.0" -dependencies = [ - "async-stream", - "aws-credential-types", - "aws-sigv4", - "aws-smithy-eventstream", - "bytes", - "chrono", - "futures", - "hex", - "hmac", - "http 1.5.0", - "reqwest", - "serde", - "serde_json", - "sha2", - "tracing", - "tw-protocol", - "tw-types", - "urlencoding", - "uuid", -] - [[package]] name = "tw-redact" version = "0.34.0" @@ -3081,10 +3044,15 @@ version = "0.34.0" dependencies = [ "aws-credential-types", "aws-sigv4", + "aws-smithy-eventstream", + "aws-smithy-types", + "bytes", "http 1.5.0", "reqwest", "serde_json", "tokio", + "tw-dialect", + "tw-wire", ] [[package]] @@ -3183,12 +3151,6 @@ dependencies = [ "serde", ] -[[package]] -name = "urlencoding" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" - [[package]] name = "utf-8" version = "0.7.6" diff --git a/Cargo.toml b/Cargo.toml index 8961b210..6a2593fc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,8 +5,6 @@ members = [ "crates/tw-types", "crates/tw-upstream", "crates/tw-wire", - "crates/tw-protocol", - "crates/tw-provider", "crates/tw-resil", "crates/tw-crypto", # ── 第二层 · 桌面网关(企业版永不依赖)──────────────── @@ -47,8 +45,6 @@ version = "0.34.0" tw-types = { path = "crates/tw-types" } tw-upstream = { path = "crates/tw-upstream" } tw-wire = { path = "crates/tw-wire" } -tw-protocol = { path = "crates/tw-protocol" } -tw-provider = { path = "crates/tw-provider" } tw-resil = { path = "crates/tw-resil" } tw-crypto = { path = "crates/tw-crypto" } tw-api = { path = "crates/tw-api" } @@ -132,12 +128,11 @@ rand = "0.10" aes-gcm = "=0.10.3" clap = { version = "4", features = ["derive"] } -# ── Bedrock 的 SigV4 签名(tw-provider)────────────────── +# ── Bedrock:SigV4 签名与 eventstream 拆帧(tw-upstream 的 bedrock feature)── aws-sigv4 = "1" aws-credential-types = { version = "1", features = ["hardcoded-credentials"] } aws-smithy-eventstream = "0.60" -http_1x = { package = "http", version = "1" } -urlencoding = "2" +aws-smithy-types = "1" [profile.release] diff --git a/README.md b/README.md index db160d33..30011b5f 100644 --- a/README.md +++ b/README.md @@ -43,10 +43,10 @@ Point a client (Claude Code, Codex, and friends) at a local port, and: ## Crate layers ``` -tw-types · tw-protocol · tw-provider · tw-resil · tw-crypto ← shape fixed by the outside world -tw-engine · tw-pricing · tw-redact · tw-yaml · tw-secret ← domain logic -tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← assembly -tw-gateway · tw-control ← data plane / control plane +tw-types · tw-dialect · tw-wire · tw-upstream · tw-resil · tw-crypto ← shape fixed by the outside world +tw-engine · tw-pricing · tw-redact · tw-yaml · tw-secret ← domain logic +tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← assembly +tw-gateway · tw-control ← data plane / control plane ``` The top two layers are stable against external reality — the server edition diff --git a/README.zh-CN.md b/README.zh-CN.md index 0067305c..fc9302e8 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -38,10 +38,10 @@ cargo run -p twcore -- serve # 起网关和控制面 ## crate 分层 ``` -tw-types · tw-protocol · tw-provider · tw-resil · tw-crypto ← 形状由外部现实决定 -tw-engine · tw-pricing · tw-redact · tw-yaml · tw-secret ← 领域逻辑 -tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← 装配 -tw-gateway · tw-control ← 数据面 / 控制面 +tw-types · tw-dialect · tw-wire · tw-upstream · tw-resil · tw-crypto ← 形状由外部现实决定 +tw-engine · tw-pricing · tw-redact · tw-yaml · tw-secret ← 领域逻辑 +tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← 装配 +tw-gateway · tw-control ← 数据面 / 控制面 ``` 上面两层对外部稳定,服务端版本直接依赖它们。下面两层是单机的实现 diff --git a/crates/tw-protocol/Cargo.toml b/crates/tw-protocol/Cargo.toml deleted file mode 100644 index 382f58a4..00000000 --- a/crates/tw-protocol/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "tw-protocol" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -repository.workspace = true -description = "SSE framing and content extraction across API dialects" - -[dependencies] -bytes = { workspace = true } -futures = { workspace = true } -serde_json = { workspace = true } -reqwest = { workspace = true } -tracing = { workspace = true } -metrics = { workspace = true } diff --git a/crates/tw-protocol/src/lib.rs b/crates/tw-protocol/src/lib.rs deleted file mode 100644 index dff128aa..00000000 --- a/crates/tw-protocol/src/lib.rs +++ /dev/null @@ -1,12 +0,0 @@ -//! SSE 分帧与方言间的内容提取。 -//! -//! 注意这里**不含** `streaming.rs`。原计划把它算进来 -//! (sse_parser + streaming + transform = 900 行),但实测它依赖 axum -//! 的 SSE 响应类型、metrics、以及企业版的 PII 流式还原器 —— -//! **那是 HTTP 层的东西,不是协议层的**。把它搬进来会让共用层背上 -//! axum,而桌面版的数据面会自己写响应封装。 - -pub mod sse; -pub mod transform; - -pub use sse::{SseEvent, SseStreamExt}; diff --git a/crates/tw-protocol/src/sse.rs b/crates/tw-protocol/src/sse.rs deleted file mode 100644 index c9b33f3c..00000000 --- a/crates/tw-protocol/src/sse.rs +++ /dev/null @@ -1,338 +0,0 @@ -//! Minimal SSE (Server-Sent Events) parser. -//! -//! Replaces `eventsource-stream` with ~60 lines of code to eliminate the -//! only HIGH-risk supply-chain dependency. -//! -//! Spec: https://html.spec.whatwg.org/multipage/server-sent-events.html - -use bytes::Bytes; -use futures::stream::Stream; -use std::pin::Pin; -use std::task::{Context, Poll}; - -/// A parsed SSE event. -#[derive(Debug, Clone)] -pub struct SseEvent { - /// The `event:` field (empty string if not set). - pub event: String, - /// The `data:` field (concatenated if multiple `data:` lines). - pub data: String, -} - -/// Cap on the in-memory buffer between SSE event boundaries (`\n\n`). -/// An upstream that streams without ever emitting the boundary would -/// otherwise grow `buffer` unbounded → OOM. 8 MiB is well above any -/// real LLM chunk (full responses are typically tens of KiB) but small -/// enough that an attacker can't pin a process. When exceeded the -/// stream surfaces an error and is dropped by the parser. -const MAX_SSE_EVENT_BYTES: usize = 8 * 1024 * 1024; - -/// Stream adapter that parses raw bytes into `SseEvent`s. -pub struct SseStream { - inner: S, - /// Decoded text accumulated between event boundaries (`\n\n`). - buffer: String, - /// Trailing bytes from the last upstream chunk that didn't form a - /// complete UTF-8 sequence on their own. A multi-byte codepoint - /// can land split across two TCP reads; without this, the prior - /// `from_utf8` check silently dropped the entire chunk. - pending_bytes: Vec, - /// Sticky terminal state — once we surface an error we stop polling - /// the inner stream. Avoids the consumer accidentally re-driving - /// us back into the same error. - errored: bool, -} - -impl SseStream { - pub fn new(inner: S) -> Self { - Self { - inner, - buffer: String::new(), - pending_bytes: Vec::new(), - errored: false, - } - } -} - -/// Append a freshly-received byte chunk to `buffer`, carrying any -/// partial-UTF-8 tail through `pending_bytes`. Invalid sequences -/// (not merely incomplete) are replaced with U+FFFD so the stream -/// remains parseable rather than silently truncating. -/// -/// Returns `Err` when appending the chunk would push the buffer over -/// [`MAX_SSE_EVENT_BYTES`]. The check happens BEFORE the allocation -/// so a single oversized chunk (e.g. a 50 MiB gzip-decoded SSE -/// payload) can't momentarily blow past the cap. -fn extend_buffer_with_chunk( - buffer: &mut String, - pending: &mut Vec, - fresh: &[u8], -) -> Result<(), BufferOverflow> { - if buffer.len() + pending.len() + fresh.len() > MAX_SSE_EVENT_BYTES { - return Err(BufferOverflow); - } - // Merge any prior partial bytes with the fresh ones — placement - // matters because the previous tail is the *start* of the new - // codepoint. - let mut staging: Vec = Vec::with_capacity(pending.len() + fresh.len()); - staging.extend_from_slice(pending); - staging.extend_from_slice(fresh); - pending.clear(); - - let mut cursor = 0usize; - while cursor < staging.len() { - match std::str::from_utf8(&staging[cursor..]) { - Ok(s) => { - buffer.push_str(s); - cursor = staging.len(); - } - Err(e) => { - let valid_up_to = e.valid_up_to(); - // SAFETY: `valid_up_to` is by definition the length of - // the longest valid UTF-8 prefix. - let valid = unsafe { - std::str::from_utf8_unchecked(&staging[cursor..cursor + valid_up_to]) - }; - buffer.push_str(valid); - cursor += valid_up_to; - match e.error_len() { - None => { - // Trailing bytes form an *incomplete* codepoint — - // park them for the next chunk. - pending.extend_from_slice(&staging[cursor..]); - cursor = staging.len(); - } - Some(invalid_len) => { - // Genuinely invalid bytes — emit the replacement - // codepoint and skip past them. - buffer.push('\u{FFFD}'); - cursor += invalid_len; - } - } - } - } - } - Ok(()) -} - -/// Sentinel returned by [`extend_buffer_with_chunk`] when the -/// post-append size would exceed [`MAX_SSE_EVENT_BYTES`]. The caller -/// is expected to tear the stream down — there is no recovery once -/// an SSE event payload outgrows the cap. -#[derive(Debug)] -struct BufferOverflow; - -/// Extension trait to convert a bytes stream into an SSE event stream. -pub trait SseStreamExt: Stream> + Sized { - fn sse_events(self) -> SseStream { - SseStream::new(self) - } -} - -impl>> SseStreamExt for S {} - -impl Stream for SseStream -where - S: Stream> + Unpin, -{ - type Item = Result; - - fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - let this = self.get_mut(); - if this.errored { - return Poll::Ready(None); - } - - loop { - // Try to extract a complete event from the buffer. - // Events are delimited by a blank line (\n\n). - if let Some(event) = try_parse_event(&mut this.buffer) { - return Poll::Ready(Some(Ok(event))); - } - - // Need more data from the underlying stream. - match Pin::new(&mut this.inner).poll_next(cx) { - Poll::Ready(Some(Ok(bytes))) => { - // Cap check happens INSIDE `extend_buffer_with_chunk` - // and runs BEFORE the allocation, so even a single - // chunk that would push us over `MAX_SSE_EVENT_BYTES` - // is rejected without ever being copied into the - // buffer. Tear the stream down on overflow. - if extend_buffer_with_chunk(&mut this.buffer, &mut this.pending_bytes, &bytes) - .is_err() - { - this.errored = true; - tracing::error!( - buffered_bytes = this.buffer.len() + this.pending_bytes.len(), - incoming_chunk_bytes = bytes.len(), - "SSE event would exceed {MAX_SSE_EVENT_BYTES} bytes — terminating stream" - ); - metrics::counter!("gateway_sse_buffer_overflow_total").increment(1); - this.buffer.clear(); - this.pending_bytes.clear(); - return Poll::Ready(None); - } - // Loop back to try parsing again. - } - Poll::Ready(Some(Err(e))) => { - this.errored = true; - return Poll::Ready(Some(Err(e))); - } - Poll::Ready(None) => { - // Stream ended — flush any leftover partial UTF-8 - // as the replacement codepoint, then try a final - // force-parse so a graceful upstream that omits - // the trailing `\n\n` still yields its last event. - if !this.pending_bytes.is_empty() { - this.buffer.push('\u{FFFD}'); - this.pending_bytes.clear(); - } - if !this.buffer.trim().is_empty() - && let Some(event) = try_parse_event_force(&mut this.buffer) - { - return Poll::Ready(Some(Ok(event))); - } - return Poll::Ready(None); - } - Poll::Pending => return Poll::Pending, - } - } - } -} - -/// Try to parse one SSE event from the front of the buffer. -/// Returns `None` if no complete event (terminated by `\n\n`) is available yet. -fn try_parse_event(buffer: &mut String) -> Option { - // Look for double newline (event boundary) - let boundary = buffer.find("\n\n")?; - let raw = buffer[..boundary].to_string(); - // Remove the consumed bytes + the two newlines - buffer.drain(..boundary + 2); - Some(parse_fields(&raw)) -} - -/// Force-parse whatever remains in the buffer as a final event. -fn try_parse_event_force(buffer: &mut String) -> Option { - let raw = std::mem::take(buffer); - let trimmed = raw.trim(); - if trimmed.is_empty() { - return None; - } - Some(parse_fields(trimmed)) -} - -/// Parse SSE field lines into an `SseEvent`. -fn parse_fields(raw: &str) -> SseEvent { - let mut event_type = String::new(); - let mut data_parts: Vec<&str> = Vec::new(); - - for line in raw.lines() { - if let Some(value) = line.strip_prefix("data:") { - data_parts.push(value.strip_prefix(' ').unwrap_or(value)); - } else if let Some(value) = line.strip_prefix("event:") { - event_type = value.strip_prefix(' ').unwrap_or(value).to_string(); - } - // Ignore `id:`, `retry:`, and comments (lines starting with `:`) - } - - SseEvent { - event: event_type, - data: data_parts.join("\n"), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_simple_data() { - let mut buf = "data: hello world\n\n".to_string(); - let event = try_parse_event(&mut buf).unwrap(); - assert_eq!(event.data, "hello world"); - assert_eq!(event.event, ""); - assert!(buf.is_empty()); - } - - #[test] - fn parse_event_with_type() { - let mut buf = "event: message_start\ndata: {\"type\":\"start\"}\n\n".to_string(); - let event = try_parse_event(&mut buf).unwrap(); - assert_eq!(event.event, "message_start"); - assert_eq!(event.data, "{\"type\":\"start\"}"); - } - - #[test] - fn parse_multi_line_data() { - let mut buf = "data: line1\ndata: line2\n\n".to_string(); - let event = try_parse_event(&mut buf).unwrap(); - assert_eq!(event.data, "line1\nline2"); - } - - #[test] - fn parse_multiple_events() { - let mut buf = "data: first\n\ndata: second\n\n".to_string(); - let e1 = try_parse_event(&mut buf).unwrap(); - assert_eq!(e1.data, "first"); - let e2 = try_parse_event(&mut buf).unwrap(); - assert_eq!(e2.data, "second"); - } - - #[test] - fn incomplete_event_returns_none() { - let mut buf = "data: partial".to_string(); - assert!(try_parse_event(&mut buf).is_none()); - } - - #[test] - fn done_marker() { - let mut buf = "data: [DONE]\n\n".to_string(); - let event = try_parse_event(&mut buf).unwrap(); - assert_eq!(event.data, "[DONE]"); - } - - #[test] - fn extend_buffer_handles_split_utf8_codepoint() { - // U+4E2D (中) encodes as E4 B8 AD. Split it across two chunks - // — the old `from_utf8` check silently dropped any chunk that - // failed to decode, losing the entire fragment. - let mut buf = String::new(); - let mut pending = Vec::new(); - extend_buffer_with_chunk(&mut buf, &mut pending, &[0xE4, 0xB8]).unwrap(); - // First chunk is incomplete — nothing emitted yet, bytes held. - assert_eq!(buf, ""); - assert_eq!(pending, vec![0xE4, 0xB8]); - extend_buffer_with_chunk(&mut buf, &mut pending, &[0xAD]).unwrap(); - assert_eq!(buf, "中"); - assert!(pending.is_empty()); - } - - #[test] - fn extend_buffer_emits_replacement_for_invalid_utf8() { - // 0xFF on its own is never valid UTF-8 — produce U+FFFD rather - // than dropping it (or worse, dropping the whole containing - // chunk like the previous implementation). - let mut buf = String::new(); - let mut pending = Vec::new(); - extend_buffer_with_chunk(&mut buf, &mut pending, b"ok-").unwrap(); - extend_buffer_with_chunk(&mut buf, &mut pending, &[0xFF]).unwrap(); - extend_buffer_with_chunk(&mut buf, &mut pending, b"-done").unwrap(); - assert_eq!(buf, "ok-\u{FFFD}-done"); - assert!(pending.is_empty()); - } - - #[test] - fn extend_buffer_rejects_oversized_chunk_before_allocating() { - // The cap defends against a single oversized chunk (e.g. a - // multi-MB gzip-decoded SSE payload) blowing past MAX_SSE_EVENT_BYTES - // momentarily. Pin: when the post-append size would cross - // the cap, the function returns Err WITHOUT mutating buffer - // or pending. - let mut buf = String::new(); - let mut pending = Vec::new(); - let oversized = vec![b'a'; MAX_SSE_EVENT_BYTES + 1]; - assert!(extend_buffer_with_chunk(&mut buf, &mut pending, &oversized).is_err()); - assert!(buf.is_empty()); - assert!(pending.is_empty()); - } -} diff --git a/crates/tw-protocol/src/transform.rs b/crates/tw-protocol/src/transform.rs deleted file mode 100644 index de1779b1..00000000 --- a/crates/tw-protocol/src/transform.rs +++ /dev/null @@ -1,114 +0,0 @@ -/// Strip common provider prefixes from a model name. -/// -/// Examples: -/// - `"openai/gpt-4o"` -> `"gpt-4o"` -/// - `"anthropic/claude-sonnet-4"` -> `"claude-sonnet-4"` -/// - `"gpt-4o"` -> `"gpt-4o"` (unchanged) -pub fn normalize_model_name(model: &str) -> &str { - // Strip "provider/" prefix if present - if let Some(idx) = model.find('/') { - let prefix = &model[..idx]; - let known_prefixes = ["openai", "anthropic", "google", "azure", "custom", "vertex"]; - if known_prefixes.contains(&prefix) { - return &model[idx + 1..]; - } - } - model -} - -/// Detect the likely provider for a model based on its name. -/// -/// Returns one of: `"openai"`, `"anthropic"`, `"google"`, or `"unknown"`. -pub fn detect_provider(model: &str) -> &'static str { - let normalized = normalize_model_name(model).to_lowercase(); - - if normalized.starts_with("gpt-") - || normalized.starts_with("o1") - || normalized.starts_with("o3") - || normalized.starts_with("o4") - || normalized.starts_with("chatgpt") - { - return "openai"; - } - - if normalized.starts_with("claude") { - return "anthropic"; - } - - if normalized.starts_with("gemini") { - return "google"; - } - - "unknown" -} - -/// Extract plain text from a message content value. -/// -/// Handles both `"string"` content and the array-of-parts format -/// (`[{"type": "text", "text": "..."}]`). -pub fn extract_text_content(content: &serde_json::Value) -> String { - match content { - serde_json::Value::String(s) => s.clone(), - serde_json::Value::Array(parts) => parts - .iter() - .filter_map(|part| { - if part.get("type").and_then(|t| t.as_str()) == Some("text") { - part.get("text").and_then(|t| t.as_str()).map(String::from) - } else { - None - } - }) - .collect::>() - .join(""), - other => other.to_string(), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn strip_known_prefix() { - assert_eq!(normalize_model_name("openai/gpt-4o"), "gpt-4o"); - assert_eq!( - normalize_model_name("anthropic/claude-sonnet-4"), - "claude-sonnet-4" - ); - } - - #[test] - fn preserve_unknown_prefix() { - // "mycompany/my-model" should NOT be stripped since "mycompany" is not known - assert_eq!( - normalize_model_name("mycompany/my-model"), - "mycompany/my-model" - ); - } - - #[test] - fn no_prefix() { - assert_eq!(normalize_model_name("gpt-4o"), "gpt-4o"); - } - - #[test] - fn detect_providers() { - assert_eq!(detect_provider("gpt-4o"), "openai"); - assert_eq!(detect_provider("claude-sonnet-4"), "anthropic"); - assert_eq!(detect_provider("gemini-2.0-flash"), "google"); - assert_eq!(detect_provider("llama-3"), "unknown"); - } - - #[test] - fn text_extraction() { - let simple = serde_json::json!("hello world"); - assert_eq!(extract_text_content(&simple), "hello world"); - - let parts = serde_json::json!([ - {"type": "text", "text": "Hello "}, - {"type": "image_url", "image_url": {"url": "..."}}, - {"type": "text", "text": "world"}, - ]); - assert_eq!(extract_text_content(&parts), "Hello world"); - } -} diff --git a/crates/tw-provider/Cargo.toml b/crates/tw-provider/Cargo.toml deleted file mode 100644 index 8f911007..00000000 --- a/crates/tw-provider/Cargo.toml +++ /dev/null @@ -1,29 +0,0 @@ -[package] -name = "tw-provider" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -repository.workspace = true -description = "Provider abstraction and per-provider implementations" - -[dependencies] -tw-types = { workspace = true } -tw-protocol = { workspace = true } -async-stream = { workspace = true } -bytes = { workspace = true } -chrono = { workspace = true } -futures = { workspace = true } -hex = "0.4" -hmac = "=0.13.0" -reqwest = { workspace = true } -serde = { workspace = true } -serde_json = { workspace = true } -sha2 = "=0.11.0" -tracing = { workspace = true } -uuid = { workspace = true } -urlencoding = { workspace = true } -aws-sigv4 = { workspace = true } -aws-credential-types = { workspace = true } -aws-smithy-eventstream = { workspace = true } -http_1x = { workspace = true } diff --git a/crates/tw-provider/src/lib.rs b/crates/tw-provider/src/lib.rs deleted file mode 100644 index 4c96ac7f..00000000 --- a/crates/tw-provider/src/lib.rs +++ /dev/null @@ -1,263 +0,0 @@ -//! provider 抽象与各家实现。 -//! -//! DTO 和 `CallCtx` 在 `tw-types`;这里只有「怎么把一个请求发出去」。 - -use futures::Stream; -use std::pin::Pin; - -// 整体再导出:调用方只需要 `use tw_provider::*` 就能同时拿到 DTO 和 -// provider 抽象。注意不要在这里再写一遍具名 `use tw_types::{...}` —— -// 私有具名导入会盖掉同名的 glob 再导出,外部就看不见那些类型了。 -pub use tw_types::*; - -pub mod providers; - -pub use providers::protocol::UpstreamProtocol; - -/// Shared base for all AI providers. Holds the HTTP client, base URL, -/// and custom header templates. Previously each provider duplicated -/// these three fields and the identical `new()`, `with_custom_headers()`, -/// and `resolve_headers()` methods. -pub struct ProviderBase { - pub base_url: String, - pub client: reqwest::Client, - pub custom_headers: Vec<(String, String)>, -} - -impl ProviderBase { - pub fn new(base_url: String) -> Self { - // Wall-clock bounds on upstream HTTP. Without these a hung - // upstream pins a connection forever; failover only retries - // across routes, not within a stuck attempt. The 5-min total - // is generous enough for slow LLM completions but cuts off - // truly stuck calls; the 10s connect timeout is short because - // a healthy upstream resolves and TCPs in well under that. - // SSRF defense: don't follow upstream redirects on the LLM - // gateway hot path. `base_url` is admin-supplied; a malicious - // (or compromised) provider returning `302 Location: http:// - // 169.254.169.254/...` would silently steer traffic into - // internal infra. Same reasoning as the MCP pool client and - // the shared http_client in init.rs. - let client = reqwest::Client::builder() - .connect_timeout(std::time::Duration::from_secs(10)) - .timeout(std::time::Duration::from_secs(300)) - .redirect(reqwest::redirect::Policy::none()) - .build() - .expect("reqwest client builder cannot fail on stable inputs"); - Self { - // Normalize here, once, for every provider: each one builds - // its endpoint as `format!("{base_url}/v1/…")`, so an - // admin-entered trailing slash (the browser hands you one - // for free when you paste a URL) produced `https://host//v1/ - // chat/completions` and a bare 404 from upstream. The - // "Test connection" probe trimmed already, which is why a - // provider could pass its check and still fail every real - // inference call. - base_url: base_url.trim_end_matches('/').to_string(), - client, - custom_headers: Vec::new(), - } - } - - pub fn with_custom_headers(mut self, headers: Vec<(String, String)>) -> Self { - self.custom_headers = headers; - self - } - - /// Resolve `{{...}}` template variables in custom header values from - /// `ctx.attrs`. A placeholder whose key is absent resolves to the - /// empty string rather than being left literal — an upstream that - /// receives `X-User: {{user_id}}` is worse than one that receives - /// `X-User:`, because the literal looks like a working config. - pub fn resolve_headers(&self, ctx: &CallCtx) -> Vec<(String, String)> { - self.custom_headers - .iter() - .map(|(k, v)| (k.clone(), substitute_template(v, &ctx.attrs))) - .collect() - } - - /// Append the caller-resolved custom headers to a `RequestBuilder`. - /// Centralizes what would otherwise be duplicated in every - /// provider's `chat_completion` and `stream_chat_completion`. - /// Also injects `x-trace-id` from `ctx` so the upstream log line and - /// the gateway log line share a correlation id (OBS-01). - pub fn apply_custom_headers( - &self, - builder: reqwest::RequestBuilder, - ctx: &CallCtx, - ) -> reqwest::RequestBuilder { - let mut builder = Self::apply_headers(builder, &self.resolve_headers(ctx)); - if let Some(ref trace_id) = ctx.trace_id { - builder = builder.header("x-trace-id", trace_id.as_str()); - } - builder - } - - /// Append a pre-resolved header list to a `RequestBuilder`. - /// Streaming providers resolve headers before spawning the - /// `async_stream!` block (since `&self` can't cross the `'static` - /// boundary) and call this from inside the stream. - pub fn apply_headers( - mut builder: reqwest::RequestBuilder, - headers: &[(String, String)], - ) -> reqwest::RequestBuilder { - for (k, v) in headers { - builder = builder.header(k, v); - } - builder - } - - /// Validate an upstream response status and translate non-2xx - /// outcomes into the canonical `GatewayError` variants - /// (`UpstreamRateLimited` / `UpstreamAuthError` / `ProviderError`). - /// On a 2xx response the response is returned unchanged so the - /// caller can continue parsing the body. - /// - /// `provider_label` appears in the user-visible error message, so - /// each provider passes its own friendly name (e.g. "OpenAI", - /// "Anthropic", "Bedrock"). - pub async fn check_status( - resp: reqwest::Response, - provider_label: &str, - ) -> Result { - let status = resp.status(); - if status == reqwest::StatusCode::TOO_MANY_REQUESTS { - // Snag the upstream's own `Retry-After` (if it sent one) - // so we can echo it to our client; without this, a client - // with naive 3× retry policies just hammers the upstream - // through the same quota window — observed in the field. - let retry_after_secs = resp - .headers() - .get(reqwest::header::RETRY_AFTER) - .and_then(|v| v.to_str().ok()) - .and_then(parse_retry_after_seconds); - return Err(GatewayError::UpstreamRateLimited { retry_after_secs }); - } - if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN { - return Err(GatewayError::UpstreamAuthError); - } - if !status.is_success() { - let body = resp.text().await.unwrap_or_default(); - // Upstream error bodies sometimes carry sensitive operational - // detail (internal stack traces on 500, AWS request-ids / - // account-ids on Bedrock, full debug strings on Vertex AI). - // Previously we forwarded the body verbatim into the client- - // facing JSON `error.message` field, turning the gateway into - // a leak vector for whatever the upstream chose to surface. - // - // Log the full body server-side at WARN so operators can still - // debug, but truncate the client-facing copy to a length that - // captures the standard `{"error": {"message": "...", ...}}` - // shape from OpenAI / Anthropic / Gemini without leaking - // multi-page debug payloads. - const CLIENT_MAX: usize = 512; - tracing::warn!( - provider = provider_label, - status = %status, - body = %body, - "upstream provider returned non-2xx" - ); - let truncated = if body.len() > CLIENT_MAX { - // Char-boundary safe truncation — `body.split_at(N)` - // would panic if N lands inside a multibyte UTF-8 - // sequence, and provider errors regularly include - // non-ASCII (i18n'd messages from Bedrock, Chinese - // model-name errors from Tongyi, etc.). - let mut end = CLIENT_MAX; - while end > 0 && !body.is_char_boundary(end) { - end -= 1; - } - format!("{}…[truncated]", &body[..end]) - } else { - body - }; - return Err(GatewayError::ProviderError(format!( - "{provider_label} returned {status}: {truncated}" - ))); - } - Ok(resp) - } - - /// Wrap `RequestBuilder::send` to map transport-level failures into - /// `GatewayError::NetworkError` so callers don't have to repeat the - /// `.map_err(|e| GatewayError::NetworkError(e.to_string()))?` line. - pub async fn send(builder: reqwest::RequestBuilder) -> Result { - builder - .send() - .await - .map_err(|e| GatewayError::NetworkError(e.to_string())) - } -} - -pub trait AiProvider: Send + Sync { - fn name(&self) -> &str; - - fn chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> impl std::future::Future> + Send; - - /// `ctx` is taken by value, like `request`: the returned stream is - /// `'static` and outlives any borrow the caller could lend us. - fn stream_chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Pin> + Send>>; -} - -/// Dyn-compatible version of `AiProvider` that boxes the future returned by -/// `chat_completion`. This is necessary because `AiProvider::chat_completion` -/// uses `impl Future` (RPITIT) which is not dyn-compatible. -/// -/// All types implementing `AiProvider` automatically implement `DynAiProvider`. -pub trait DynAiProvider: Send + Sync { - fn name(&self) -> &str; - - fn chat_completion_boxed( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Pin< - Box< - dyn std::future::Future> - + Send - + '_, - >, - >; - - fn stream_chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Pin> + Send>>; -} - -impl DynAiProvider for T { - fn name(&self) -> &str { - AiProvider::name(self) - } - - fn chat_completion_boxed( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Pin< - Box< - dyn std::future::Future> - + Send - + '_, - >, - > { - Box::pin(AiProvider::chat_completion(self, request, ctx)) - } - - fn stream_chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Pin> + Send>> { - AiProvider::stream_chat_completion(self, request, ctx) - } -} diff --git a/crates/tw-provider/src/providers/anthropic.rs b/crates/tw-provider/src/providers/anthropic.rs deleted file mode 100644 index 87efb077..00000000 --- a/crates/tw-provider/src/providers/anthropic.rs +++ /dev/null @@ -1,391 +0,0 @@ -use crate::{AiProvider, ProviderBase}; -use futures::Stream; -use futures::stream::StreamExt; -use serde::{Deserialize, Serialize}; -use std::pin::Pin; -use tw_protocol::SseStreamExt; -use tw_types::*; - -pub struct AnthropicProvider { - pub base: ProviderBase, -} - -impl AnthropicProvider { - pub fn new(base_url: String) -> Self { - Self { - base: ProviderBase::new(base_url), - } - } - - pub fn with_custom_headers(mut self, headers: Vec<(String, String)>) -> Self { - self.base = self.base.with_custom_headers(headers); - self - } -} - -// ---------- Anthropic-native request/response types ---------- - -#[derive(Debug, Serialize)] -struct AnthropicRequest { - model: String, - max_tokens: u32, - messages: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - system: Option, - #[serde(skip_serializing_if = "Option::is_none")] - temperature: Option, - #[serde(skip_serializing_if = "Option::is_none")] - stream: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -struct AnthropicMessage { - role: String, - content: serde_json::Value, -} - -#[derive(Debug, Deserialize)] -struct AnthropicResponse { - id: String, - model: String, - content: Vec, - stop_reason: Option, - usage: AnthropicUsage, -} - -#[derive(Debug, Deserialize)] -struct AnthropicContentBlock { - #[serde(rename = "type")] - content_type: String, - text: Option, -} - -#[derive(Debug, Deserialize)] -struct AnthropicUsage { - input_tokens: u32, - output_tokens: u32, -} - -// ---------- Anthropic SSE event types ---------- - -#[derive(Debug, Deserialize)] -struct MessageStartEvent { - message: MessageStartMessage, -} - -#[derive(Debug, Deserialize)] -struct MessageStartMessage { - id: String, - model: String, - // The Anthropic SSE protocol carries `input_tokens` here in the - // very first event of a stream — prior code prefixed this with - // `_` and discarded it, then the `message_delta` handler hard- - // coded `prompt_tokens: 0`. That forced the downstream - // estimator to invent prompt tokens from the request body and - // over-billed every Anthropic streaming request. We now capture - // the value, carry it through the stream loop, and merge it - // into the final usage chunk so streaming reports the same - // prompt-token count as the non-streaming code path. - usage: Option, -} - -#[derive(Debug, Deserialize)] -struct ContentBlockDeltaEvent { - index: u32, - delta: ContentBlockDelta, -} - -#[derive(Debug, Deserialize)] -struct ContentBlockDelta { - #[serde(rename = "type")] - _delta_type: String, - #[serde(default)] - text: Option, -} - -#[derive(Debug, Deserialize)] -struct MessageDeltaEvent { - delta: MessageDelta, - usage: Option, -} - -#[derive(Debug, Deserialize)] -struct MessageDelta { - stop_reason: Option, -} - -#[derive(Debug, Deserialize)] -struct MessageDeltaUsage { - output_tokens: u32, -} - -// ---------- Conversion helpers ---------- - -fn convert_request(req: ChatCompletionRequest) -> AnthropicRequest { - let mut system_text: Option = None; - let mut messages = Vec::new(); - - for msg in &req.messages { - if msg.role == "system" { - // Extract system messages into the top-level system field - let text = match &msg.content { - serde_json::Value::String(s) => s.clone(), - other => other.to_string(), - }; - system_text = Some(match system_text { - Some(existing) => format!("{existing}\n{text}"), - None => text, - }); - } else { - // Map roles: user->user, assistant->assistant, anything else pass through - let role = match msg.role.as_str() { - "user" => "user".to_string(), - "assistant" => "assistant".to_string(), - other => other.to_string(), - }; - messages.push(AnthropicMessage { - role, - content: msg.content.clone(), - }); - } - } - - let max_tokens = req.max_tokens.unwrap_or(4096); - - AnthropicRequest { - model: req.model.clone(), - max_tokens, - messages, - system: system_text, - temperature: req.temperature, - stream: req.stream, - } -} - -fn convert_response(resp: AnthropicResponse) -> ChatCompletionResponse { - let text = resp - .content - .iter() - .filter_map(|block| { - if block.content_type == "text" { - block.text.clone() - } else { - None - } - }) - .collect::>() - .join(""); - - let finish_reason = resp.stop_reason.map(|r| match r.as_str() { - "end_turn" => "stop".to_string(), - "max_tokens" => "length".to_string(), - "stop_sequence" => "stop".to_string(), - other => other.to_string(), - }); - - let total = resp.usage.input_tokens + resp.usage.output_tokens; - - ChatCompletionResponse { - id: resp.id, - object: "chat.completion".to_string(), - created: chrono::Utc::now().timestamp(), - model: resp.model, - choices: vec![Choice { - index: 0, - message: ChatMessage { - role: "assistant".to_string(), - content: serde_json::Value::String(text), - ..Default::default() - }, - finish_reason, - }], - usage: Some(Usage { - prompt_tokens: resp.usage.input_tokens, - completion_tokens: resp.usage.output_tokens, - total_tokens: total, - }), - } -} - -fn map_anthropic_stop_reason(reason: &str) -> String { - match reason { - "end_turn" => "stop".to_string(), - "max_tokens" => "length".to_string(), - "stop_sequence" => "stop".to_string(), - other => other.to_string(), - } -} - -// ---------- AiProvider implementation ---------- - -impl AiProvider for AnthropicProvider { - fn name(&self) -> &str { - "anthropic" - } - - async fn chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Result { - let builder = self - .base - .client - .post(format!("{}/v1/messages", self.base.base_url)) - .header("anthropic-version", "2023-06-01") - .header("content-type", "application/json"); - let builder = self.base.apply_custom_headers(builder, &ctx); - - let anthropic_req = convert_request(request); - let builder = builder.json(&anthropic_req); - - let resp = ProviderBase::send(builder).await?; - let resp = ProviderBase::check_status(resp, "Anthropic").await?; - - let anthropic_resp: AnthropicResponse = resp - .json() - .await - .map_err(|e| GatewayError::ProviderError(e.to_string()))?; - - Ok(convert_response(anthropic_resp)) - } - - fn stream_chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Pin> + Send>> { - let client = self.base.client.clone(); - let url = format!("{}/v1/messages", self.base.base_url); - let headers = self.base.resolve_headers(&ctx); - - let mut anthropic_req = convert_request(request); - anthropic_req.stream = Some(true); - - Box::pin(async_stream::stream! { - let builder = client - .post(&url) - .header("anthropic-version", "2023-06-01") - .header("content-type", "application/json"); - let builder = ProviderBase::apply_headers(builder, &headers).json(&anthropic_req); - - let resp = match ProviderBase::send(builder).await { - Ok(r) => r, - Err(e) => { yield Err(e); return; } - }; - let resp = match ProviderBase::check_status(resp, "Anthropic").await { - Ok(r) => r, - Err(e) => { yield Err(e); return; } - }; - - let mut event_stream = resp.bytes_stream().sse_events(); - - // Track message-level state from message_start. The - // input_tokens value lives ONLY in the first message_start - // event — subsequent `message_delta` chunks only carry - // running output_tokens — so we have to thread it through - // the loop to attach to the final usage chunk. - let mut message_id = String::new(); - let mut model = String::new(); - let mut input_tokens: u32 = 0; - - while let Some(event_result) = event_stream.next().await { - match event_result { - Ok(event) => { - let event_type = event.event.as_str(); - let data = event.data.trim().to_string(); - - if data.is_empty() { - continue; - } - - match event_type { - "message_start" => { - if let Ok(ev) = serde_json::from_str::(&data) { - message_id = ev.message.id.clone(); - model = ev.message.model.clone(); - if let Some(u) = ev.message.usage { - input_tokens = u.input_tokens; - } - - // Emit an initial chunk with role delta - let chunk = ChatCompletionChunk { - id: message_id.clone(), - object: "chat.completion.chunk".to_string(), - created: chrono::Utc::now().timestamp(), - model: model.clone(), - choices: vec![ChunkChoice { - index: 0, - delta: serde_json::json!({"role": "assistant"}), - finish_reason: None, - }], - usage: None, - }; - yield Ok(chunk); - } - } - "content_block_delta" => { - if let Ok(ev) = serde_json::from_str::(&data) - && let Some(text) = &ev.delta.text { - let chunk = ChatCompletionChunk { - id: message_id.clone(), - object: "chat.completion.chunk".to_string(), - created: chrono::Utc::now().timestamp(), - model: model.clone(), - choices: vec![ChunkChoice { - index: ev.index, - delta: serde_json::json!({"content": text}), - finish_reason: None, - }], - usage: None, - }; - yield Ok(chunk); - } - } - "message_delta" => { - if let Ok(ev) = serde_json::from_str::(&data) { - let finish_reason = ev.delta.stop_reason - .as_deref() - .map(map_anthropic_stop_reason); - - let usage = ev.usage.map(|u| Usage { - prompt_tokens: input_tokens, - completion_tokens: u.output_tokens, - total_tokens: input_tokens - .saturating_add(u.output_tokens), - }); - - let chunk = ChatCompletionChunk { - id: message_id.clone(), - object: "chat.completion.chunk".to_string(), - created: chrono::Utc::now().timestamp(), - model: model.clone(), - choices: vec![ChunkChoice { - index: 0, - delta: serde_json::json!({}), - finish_reason, - }], - usage, - }; - yield Ok(chunk); - } - } - "message_stop" => { - // Stream is complete - break; - } - // Ignore ping, content_block_start, content_block_stop, etc. - _ => {} - } - } - Err(e) => { - yield Err(GatewayError::ProviderError(format!( - "Anthropic SSE stream error: {e}" - ))); - break; - } - } - } - }) - } -} diff --git a/crates/tw-provider/src/providers/azure_openai.rs b/crates/tw-provider/src/providers/azure_openai.rs deleted file mode 100644 index 40e86693..00000000 --- a/crates/tw-provider/src/providers/azure_openai.rs +++ /dev/null @@ -1,124 +0,0 @@ -use crate::{AiProvider, ProviderBase}; -use futures::Stream; -use futures::stream::StreamExt; -use std::pin::Pin; -use tw_protocol::SseStreamExt; -use tw_types::*; - -/// Azure OpenAI provider. -/// -/// Uses the same request/response format as OpenAI, but with a different -/// URL structure and authentication header. -/// -/// URL pattern: `{base_url}/openai/deployments/{model}/chat/completions?api-version={api_version}` -/// Auth header: `api-key: {api_key}` (not `Authorization: Bearer`) -pub struct AzureOpenAiProvider { - pub base: ProviderBase, - pub api_version: String, -} - -impl AzureOpenAiProvider { - pub fn new(base_url: String, api_version: Option) -> Self { - // Trailing-slash normalization now lives in `ProviderBase::new` - // so every provider gets it, not just this one. - Self { - base: ProviderBase::new(base_url), - api_version: api_version.unwrap_or_else(|| "2024-12-01-preview".to_string()), - } - } - - pub fn with_custom_headers(mut self, headers: Vec<(String, String)>) -> Self { - self.base = self.base.with_custom_headers(headers); - self - } - - fn completions_url(&self, deployment: &str) -> String { - format!( - "{}/openai/deployments/{}/chat/completions?api-version={}", - self.base.base_url, deployment, self.api_version - ) - } -} - -impl AiProvider for AzureOpenAiProvider { - fn name(&self) -> &str { - "azure_openai" - } - - async fn chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Result { - // In Azure, the "model" field is the deployment name - let url = self.completions_url(&request.model); - let builder = self - .base - .client - .post(&url) - .header("content-type", "application/json"); - let builder = self.base.apply_custom_headers(builder, &ctx).json(&request); - - let resp = ProviderBase::send(builder).await?; - let resp = ProviderBase::check_status(resp, "Azure OpenAI").await?; - - resp.json::() - .await - .map_err(|e| GatewayError::ProviderError(e.to_string())) - } - - fn stream_chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Pin> + Send>> { - let client = self.base.client.clone(); - let url = self.completions_url(&request.model); - let headers = self.base.resolve_headers(&ctx); - - let mut stream_request = request; - stream_request.stream = Some(true); - - Box::pin(async_stream::stream! { - let builder = client.post(&url).header("content-type", "application/json"); - let builder = ProviderBase::apply_headers(builder, &headers).json(&stream_request); - - let resp = match ProviderBase::send(builder).await { - Ok(r) => r, - Err(e) => { yield Err(e); return; } - }; - let resp = match ProviderBase::check_status(resp, "Azure OpenAI").await { - Ok(r) => r, - Err(e) => { yield Err(e); return; } - }; - - let mut event_stream = resp.bytes_stream().sse_events(); - - while let Some(event_result) = event_stream.next().await { - match event_result { - Ok(event) => { - let data = event.data.trim(); - if data == "[DONE]" { - break; - } - if data.is_empty() { - continue; - } - match serde_json::from_str::(data) { - Ok(chunk) => yield Ok(chunk), - Err(e) => { - tracing::warn!("Failed to parse Azure OpenAI chunk: {e}"); - } - } - } - Err(e) => { - yield Err(GatewayError::ProviderError(format!( - "Azure OpenAI SSE error: {e}" - ))); - break; - } - } - } - }) - } -} diff --git a/crates/tw-provider/src/providers/bedrock.rs b/crates/tw-provider/src/providers/bedrock.rs deleted file mode 100644 index 4c819ef9..00000000 --- a/crates/tw-provider/src/providers/bedrock.rs +++ /dev/null @@ -1,804 +0,0 @@ -use crate::{AiProvider, ProviderBase}; -use futures::Stream; -use futures::stream::StreamExt; -use serde::{Deserialize, Serialize}; -use std::pin::Pin; -use tw_types::*; - -/// AWS Bedrock provider using the Converse API. -/// -/// Authentication uses AWS SigV4 signing. Two modes: -/// - Static credentials: `api_key` = `{access_key_id}:{secret_access_key}` -/// - IMDSv2 (EC2): `api_key` is empty — credentials are fetched from -/// the instance metadata service at request time. -/// -/// The `base_url` field stores the region (e.g. "us-east-1"). -pub struct BedrockProvider { - pub region: String, - pub access_key_id: Option, - pub secret_access_key: Option, - pub base: ProviderBase, -} - -impl BedrockProvider { - /// Create a new Bedrock provider. - /// - /// - `region`: AWS region (e.g. "us-east-1") - /// - `credentials`: `{access_key_id}:{secret_access_key}`, or empty for IMDSv2 - pub fn new(region: String, credentials: String) -> Self { - let (access_key_id, secret_access_key) = if credentials.is_empty() { - (None, None) - } else { - let (a, s) = credentials - .split_once(':') - .map(|(a, s)| (a.to_string(), s.to_string())) - .unwrap_or_else(|| (credentials.clone(), String::new())); - (Some(a), Some(s)) - }; - - Self { - region, - access_key_id, - secret_access_key, - base: ProviderBase::new(String::new()), - } - } - - pub fn with_custom_headers(mut self, headers: Vec<(String, String)>) -> Self { - self.base = self.base.with_custom_headers(headers); - self - } - - fn endpoint_url(&self, model_id: &str) -> String { - format!( - "https://bedrock-runtime.{}.amazonaws.com/model/{}/converse", - self.region, model_id - ) - } - - fn stream_endpoint_url(&self, model_id: &str) -> String { - format!( - "https://bedrock-runtime.{}.amazonaws.com/model/{}/converse-stream", - self.region, model_id - ) - } - - /// Fetch temporary credentials from EC2 IMDSv2. - async fn fetch_imdsv2_credentials( - &self, - ) -> Result { - use aws_credential_types::Credentials; - - let imds_base = "http://169.254.169.254"; - let client = &self.base.client; - - // Step 1: Get IMDSv2 token - let token = client - .put(format!("{imds_base}/latest/api/token")) - .header("X-aws-ec2-metadata-token-ttl-seconds", "300") - .send() - .await - .map_err(|e| GatewayError::ProviderError(format!("IMDSv2 token request failed: {e}")))? - .text() - .await - .map_err(|e| GatewayError::ProviderError(format!("IMDSv2 token read failed: {e}")))?; - - // Step 2: Get IAM role name - let role = client - .get(format!( - "{imds_base}/latest/meta-data/iam/security-credentials/" - )) - .header("X-aws-ec2-metadata-token", &token) - .send() - .await - .map_err(|e| GatewayError::ProviderError(format!("IMDSv2 role lookup failed: {e}")))? - .text() - .await - .map_err(|e| GatewayError::ProviderError(format!("IMDSv2 role read failed: {e}")))?; - let role = role.trim(); - - // Step 3: Get credentials for that role - let creds_json: serde_json::Value = client - .get(format!( - "{imds_base}/latest/meta-data/iam/security-credentials/{role}" - )) - .header("X-aws-ec2-metadata-token", &token) - .send() - .await - .map_err(|e| { - GatewayError::ProviderError(format!("IMDSv2 credentials fetch failed: {e}")) - })? - .json() - .await - .map_err(|e| { - GatewayError::ProviderError(format!("IMDSv2 credentials parse failed: {e}")) - })?; - - let ak = creds_json["AccessKeyId"] - .as_str() - .ok_or_else(|| GatewayError::ProviderError("IMDSv2: missing AccessKeyId".into()))?; - let sk = creds_json["SecretAccessKey"] - .as_str() - .ok_or_else(|| GatewayError::ProviderError("IMDSv2: missing SecretAccessKey".into()))?; - let session_token = creds_json["Token"].as_str().map(|s| s.to_string()); - - Ok(Credentials::new(ak, sk, session_token, None, "imdsv2")) - } - - async fn sign_request( - &self, - url: &str, - body: &[u8], - ) -> Result, GatewayError> { - use aws_credential_types::Credentials; - use aws_sigv4::http_request::{ - PayloadChecksumKind, SignableBody, SignableRequest, SignatureLocation, SigningSettings, - sign, - }; - use aws_sigv4::sign::v4; - use std::time::SystemTime; - - let credentials = match (&self.access_key_id, &self.secret_access_key) { - (Some(ak), Some(sk)) => Credentials::new(ak, sk, None, None, "think-watch"), - _ => self.fetch_imdsv2_credentials().await?, - }; - - let identity = credentials.into(); - let mut signing_settings = SigningSettings::default(); - signing_settings.payload_checksum_kind = PayloadChecksumKind::XAmzSha256; - signing_settings.signature_location = SignatureLocation::Headers; - - let signing_params = v4::SigningParams::builder() - .identity(&identity) - .region(&self.region) - .name("bedrock") - .time(SystemTime::now()) - .settings(signing_settings) - .build() - .map_err(|e| GatewayError::ProviderError(format!("SigV4 params error: {e}")))?; - - let signable_request = SignableRequest::new( - "POST", - url, - std::iter::once(("content-type", "application/json")), - SignableBody::Bytes(body), - ) - .map_err(|e| GatewayError::ProviderError(format!("Signable request error: {e}")))?; - - let (signing_instructions, _signature) = sign(signable_request, &signing_params.into()) - .map_err(|e| GatewayError::ProviderError(format!("SigV4 signing error: {e}")))? - .into_parts(); - - // Build a dummy http 1.x request to extract signed headers - let mut http_req = http_1x::Request::builder() - .method("POST") - .uri(url) - .header("content-type", "application/json") - .body(()) - .map_err(|e| GatewayError::ProviderError(format!("HTTP request build error: {e}")))?; - - signing_instructions.apply_to_request_http1x(&mut http_req); - - let headers: Vec<(String, String)> = http_req - .headers() - .iter() - .filter(|(name, _)| { - // Only include AWS-specific headers (authorization, x-amz-*) - let n = name.as_str(); - n == "authorization" || n.starts_with("x-amz-") - }) - .map(|(name, value)| { - ( - name.to_string(), - value.to_str().unwrap_or_default().to_string(), - ) - }) - .collect(); - - Ok(headers) - } -} - -// ---------- Bedrock Converse API types ---------- - -#[derive(Debug, Serialize)] -struct BedrockConverseRequest { - messages: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - system: Option>, - #[serde(rename = "inferenceConfig")] - #[serde(skip_serializing_if = "Option::is_none")] - inference_config: Option, -} - -#[derive(Debug, Serialize)] -struct BedrockMessage { - role: String, - content: Vec, -} - -#[derive(Debug, Serialize)] -struct BedrockContent { - text: String, -} - -#[derive(Debug, Serialize)] -struct BedrockSystemContent { - text: String, -} - -#[derive(Debug, Serialize)] -struct BedrockInferenceConfig { - #[serde(rename = "maxTokens")] - #[serde(skip_serializing_if = "Option::is_none")] - max_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - temperature: Option, -} - -#[derive(Debug, Deserialize)] -struct BedrockConverseResponse { - output: BedrockOutput, - usage: BedrockUsage, - #[serde(rename = "stopReason")] - stop_reason: Option, -} - -#[derive(Debug, Deserialize)] -struct BedrockOutput { - message: BedrockOutputMessage, -} - -#[derive(Debug, Deserialize)] -struct BedrockOutputMessage { - // `role` is present in the Bedrock API response; serde requires the - // field for deserialization even though we don't read it. - #[allow(dead_code)] - role: String, - content: Vec, -} - -#[derive(Debug, Deserialize)] -struct BedrockOutputContent { - text: Option, -} - -#[derive(Debug, Deserialize)] -struct BedrockUsage { - #[serde(rename = "inputTokens")] - input_tokens: u32, - #[serde(rename = "outputTokens")] - output_tokens: u32, - #[serde(rename = "totalTokens")] - total_tokens: u32, -} - -// ---------- Conversion ---------- - -fn convert_to_bedrock(req: &ChatCompletionRequest) -> BedrockConverseRequest { - let mut system = Vec::new(); - let mut messages = Vec::new(); - - for msg in &req.messages { - let text = match &msg.content { - serde_json::Value::String(s) => s.clone(), - other => other.to_string(), - }; - - if msg.role == "system" { - system.push(BedrockSystemContent { text }); - } else { - messages.push(BedrockMessage { - role: msg.role.clone(), - content: vec![BedrockContent { text }], - }); - } - } - - BedrockConverseRequest { - messages, - system: if system.is_empty() { - None - } else { - Some(system) - }, - inference_config: Some(BedrockInferenceConfig { - max_tokens: req.max_tokens, - temperature: req.temperature, - }), - } -} - -fn convert_from_bedrock(resp: BedrockConverseResponse, model: &str) -> ChatCompletionResponse { - let text = resp - .output - .message - .content - .iter() - .filter_map(|c| c.text.clone()) - .collect::>() - .join(""); - - let finish_reason = resp.stop_reason.map(|r| match r.as_str() { - "end_turn" => "stop".to_string(), - "max_tokens" => "length".to_string(), - "stop_sequence" => "stop".to_string(), - other => other.to_string(), - }); - - ChatCompletionResponse { - id: format!("bedrock-{}", uuid::Uuid::new_v4()), - object: "chat.completion".to_string(), - created: chrono::Utc::now().timestamp(), - model: model.to_string(), - choices: vec![Choice { - index: 0, - message: ChatMessage { - role: "assistant".to_string(), - content: serde_json::Value::String(text), - ..Default::default() - }, - finish_reason, - }], - usage: Some(Usage { - prompt_tokens: resp.usage.input_tokens, - completion_tokens: resp.usage.output_tokens, - total_tokens: resp.usage.total_tokens, - }), - } -} - -// ---------- AiProvider ---------- - -impl AiProvider for BedrockProvider { - fn name(&self) -> &str { - "bedrock" - } - - async fn chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Result { - let url = self.endpoint_url(&request.model); - let bedrock_req = convert_to_bedrock(&request); - let body_bytes = serde_json::to_vec(&bedrock_req) - .map_err(|e| GatewayError::TransformError(e.to_string()))?; - - let signed_headers = self.sign_request(&url, &body_bytes).await?; - - let builder = self - .base - .client - .post(&url) - .header("content-type", "application/json") - .body(body_bytes); - let builder = ProviderBase::apply_headers(builder, &signed_headers); - let builder = self.base.apply_custom_headers(builder, &ctx); - - let resp = ProviderBase::send(builder).await?; - let resp = ProviderBase::check_status(resp, "Bedrock").await?; - - let bedrock_resp: BedrockConverseResponse = resp - .json() - .await - .map_err(|e| GatewayError::ProviderError(e.to_string()))?; - - Ok(convert_from_bedrock(bedrock_resp, &request.model)) - } - - fn stream_chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Pin> + Send>> { - let client = self.base.client.clone(); - let url = self.stream_endpoint_url(&request.model); - let model = request.model.clone(); - let region = self.region.clone(); - let access_key_id = self.access_key_id.clone(); - let secret_access_key = self.secret_access_key.clone(); - let provider_client = self.base.client.clone(); - let custom_headers = self.base.resolve_headers(&ctx); - - let bedrock_req = convert_to_bedrock(&request); - - Box::pin(async_stream::stream! { - let body_bytes = match serde_json::to_vec(&bedrock_req) { - Ok(b) => b, - Err(e) => { - yield Err(GatewayError::TransformError(e.to_string())); - return; - } - }; - - // Sign the request - let provider = BedrockProvider { - region, access_key_id, secret_access_key, - base: ProviderBase { base_url: String::new(), client: provider_client, custom_headers: Vec::new() }, - }; - let signed_headers = match provider.sign_request(&url, &body_bytes).await { - Ok(h) => h, - Err(e) => { - yield Err(e); - return; - } - }; - - let builder = client - .post(&url) - .header("content-type", "application/json") - .body(body_bytes); - let builder = ProviderBase::apply_headers(builder, &signed_headers); - let builder = ProviderBase::apply_headers(builder, &custom_headers); - - let resp = match ProviderBase::send(builder).await { - Ok(r) => r, - Err(e) => { yield Err(e); return; } - }; - let resp = match ProviderBase::check_status(resp, "Bedrock").await { - Ok(r) => r, - Err(e) => { yield Err(e); return; } - }; - - let message_id = format!("bedrock-{}", uuid::Uuid::new_v4()); - - // Emit initial role chunk - yield Ok(ChatCompletionChunk { - id: message_id.clone(), - object: "chat.completion.chunk".to_string(), - created: chrono::Utc::now().timestamp(), - model: model.clone(), - choices: vec![ChunkChoice { - index: 0, - delta: serde_json::json!({"role": "assistant"}), - finish_reason: None, - }], - usage: None, - }); - - // Read the binary event-stream response - let mut byte_stream = resp.bytes_stream(); - let mut buffer = bytes::BytesMut::new(); - - while let Some(chunk_result) = byte_stream.next().await { - let chunk = match chunk_result { - Ok(c) => c, - Err(e) => { - yield Err(GatewayError::NetworkError(e.to_string())); - break; - } - }; - - buffer.extend_from_slice(&chunk); - - // Try to decode event-stream frames from the buffer - // AWS event-stream binary format: - // [4 bytes total_len] [4 bytes headers_len] [4 bytes prelude_crc] - // [headers] [payload] [4 bytes message_crc] - while buffer.len() >= 12 { - let total_len = u32::from_be_bytes([buffer[0], buffer[1], buffer[2], buffer[3]]) as usize; - - if buffer.len() < total_len { - break; // Need more data - } - - let headers_len = u32::from_be_bytes([buffer[4], buffer[5], buffer[6], buffer[7]]) as usize; - - // Payload starts after prelude (12 bytes) + headers - let payload_start = 12 + headers_len; - let payload_end = total_len - 4; // Exclude message CRC - - if payload_start <= payload_end && payload_end <= buffer.len() { - let payload = &buffer[payload_start..payload_end]; - - // Try to parse as JSON — Bedrock wraps events in typed envelopes - if let Ok(event) = serde_json::from_slice::(payload) { - // contentBlockDelta contains text chunks - if let Some(text) = event.get("contentBlockDelta") - .and_then(|d| d.get("delta")) - .and_then(|d| d.get("text")) - .and_then(|t| t.as_str()) { - yield Ok(ChatCompletionChunk { - id: message_id.clone(), - object: "chat.completion.chunk".to_string(), - created: chrono::Utc::now().timestamp(), - model: model.clone(), - choices: vec![ChunkChoice { - index: 0, - delta: serde_json::json!({"content": text}), - finish_reason: None, - }], - usage: None, - }); - } - - // messageStop signals end of stream - if event.get("messageStop").is_some() { - let stop_reason = event.get("messageStop") - .and_then(|s| s.get("stopReason")) - .and_then(|r| r.as_str()) - .unwrap_or("end_turn"); - - let finish_reason = match stop_reason { - "end_turn" => "stop", - "max_tokens" => "length", - other => other, - }; - - yield Ok(ChatCompletionChunk { - id: message_id.clone(), - object: "chat.completion.chunk".to_string(), - created: chrono::Utc::now().timestamp(), - model: model.clone(), - choices: vec![ChunkChoice { - index: 0, - delta: serde_json::json!({}), - finish_reason: Some(finish_reason.to_string()), - }], - usage: None, - }); - } - - // metadata contains usage info - if let Some(usage) = event.get("metadata").and_then(|m| m.get("usage")) { - let input = usage.get("inputTokens").and_then(|v| v.as_u64()).unwrap_or(0) as u32; - let output = usage.get("outputTokens").and_then(|v| v.as_u64()).unwrap_or(0) as u32; - yield Ok(ChatCompletionChunk { - id: message_id.clone(), - object: "chat.completion.chunk".to_string(), - created: chrono::Utc::now().timestamp(), - model: model.clone(), - choices: vec![], - usage: Some(Usage { - prompt_tokens: input, - completion_tokens: output, - total_tokens: input + output, - }), - }); - } - } - } - - // Advance buffer past this frame - let _ = buffer.split_to(total_len); - } - } - }) - } -} - -// --------------------------------------------------------------------------- -// Conversion-layer unit tests -// -// `BedrockProvider` itself can't be exercised in integration tests: -// the endpoint URL is hard-coded to the public AWS host -// (`bedrock-runtime.{region}.amazonaws.com`) with no `base_url` -// override hook, so wiremock can't intercept it without DNS -// hijacking. The conversion functions are pure, so we test them -// directly against the wire shapes the AWS SDK documents — this -// catches the high-frequency regression: someone tweaks an OpenAI -// field name and the Bedrock translation silently drops it. -// --------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn req(messages: Vec<(&str, &str)>) -> ChatCompletionRequest { - ChatCompletionRequest { - model: "anthropic.claude-3-haiku".into(), - messages: messages - .into_iter() - .map(|(role, text)| ChatMessage { - role: role.into(), - content: serde_json::Value::String(text.into()), - ..Default::default() - }) - .collect(), - temperature: Some(0.7), - max_tokens: Some(256), - stream: None, - extra: serde_json::Value::Null, - } - } - - // ---- convert_to_bedrock ---- - - #[test] - fn system_messages_are_hoisted_to_top_level_system_block() { - // OpenAI puts the system prompt inside `messages[]`; Bedrock's - // Converse API expects it at the top level. Failing to hoist - // it leaves the system instruction inside `messages` where - // Bedrock ignores it — silent quality regression. - let r = req(vec![("system", "you are concise"), ("user", "hi")]); - let out = convert_to_bedrock(&r); - let system = out - .system - .as_ref() - .expect("system block must be present when a system message exists"); - assert_eq!(system.len(), 1); - assert_eq!(system[0].text, "you are concise"); - // The user message survives, the system message must NOT. - assert_eq!(out.messages.len(), 1); - assert_eq!(out.messages[0].role, "user"); - assert_eq!(out.messages[0].content[0].text, "hi"); - } - - #[test] - fn no_system_messages_yields_none_system_block() { - // Serializing `Some(vec![])` would emit an empty `system: []` - // — Bedrock rejects it. Verify we project to None and the - // skip_serializing_if drops the field entirely. - let r = req(vec![("user", "hello")]); - let out = convert_to_bedrock(&r); - assert!(out.system.is_none()); - let body = serde_json::to_value(&out).unwrap(); - assert!( - body.get("system").is_none(), - "system field must be omitted when empty: {body}" - ); - } - - #[test] - fn inference_config_carries_max_tokens_and_temperature() { - let r = req(vec![("user", "x")]); - let out = convert_to_bedrock(&r); - let cfg = out.inference_config.as_ref().expect("inferenceConfig set"); - assert_eq!(cfg.max_tokens, Some(256)); - assert_eq!(cfg.temperature, Some(0.7)); - // Wire shape: camelCase keys (Bedrock spec). - let body = serde_json::to_value(&out).unwrap(); - assert_eq!(body["inferenceConfig"]["maxTokens"], 256); - assert!( - body["inferenceConfig"]["temperature"].as_f64().unwrap() > 0.69, - "temperature must round-trip: {body}" - ); - } - - #[test] - fn multiple_user_assistant_turns_preserve_order() { - // Bedrock requires strictly alternating user/assistant turns. - // The converter must keep every non-system message and - // preserve the order, otherwise multi-turn context breaks. - let r = req(vec![ - ("user", "first"), - ("assistant", "reply 1"), - ("user", "second"), - ("assistant", "reply 2"), - ("user", "third"), - ]); - let out = convert_to_bedrock(&r); - let roles: Vec<&str> = out.messages.iter().map(|m| m.role.as_str()).collect(); - assert_eq!( - roles, - vec!["user", "assistant", "user", "assistant", "user"] - ); - let texts: Vec<&str> = out - .messages - .iter() - .map(|m| m.content[0].text.as_str()) - .collect(); - assert_eq!( - texts, - vec!["first", "reply 1", "second", "reply 2", "third"] - ); - } - - #[test] - fn non_string_content_serializes_to_json_text() { - // OpenAI clients sometimes send `content` as an array (image - // parts). Bedrock's Converse API takes plain text; we collapse - // the structured content into its JSON representation so the - // upstream still gets *something* meaningful instead of - // silently dropping the message. - let mut r = req(vec![]); - r.messages.push(ChatMessage { - role: "user".into(), - content: json!([{"type": "text", "text": "hi"}]), - ..Default::default() - }); - let out = convert_to_bedrock(&r); - assert_eq!(out.messages.len(), 1); - assert!( - out.messages[0].content[0].text.contains("\"hi\""), - "non-string content must collapse to JSON text, got {:?}", - out.messages[0].content[0].text - ); - } - - // ---- convert_from_bedrock ---- - - fn bedrock_response(text: &str, stop_reason: Option<&str>) -> BedrockConverseResponse { - BedrockConverseResponse { - output: BedrockOutput { - message: BedrockOutputMessage { - role: "assistant".into(), - content: vec![BedrockOutputContent { - text: Some(text.into()), - }], - }, - }, - usage: BedrockUsage { - input_tokens: 12, - output_tokens: 5, - total_tokens: 17, - }, - stop_reason: stop_reason.map(|s| s.into()), - } - } - - #[test] - fn bedrock_response_round_trips_into_openai_shape() { - let resp = bedrock_response("hello world", Some("end_turn")); - let out = convert_from_bedrock(resp, "anthropic.claude-3-haiku"); - assert_eq!(out.object, "chat.completion"); - assert_eq!(out.model, "anthropic.claude-3-haiku"); - assert_eq!(out.choices.len(), 1); - assert_eq!(out.choices[0].message.role, "assistant"); - assert_eq!(out.choices[0].message.content, json!("hello world")); - // OpenAI's `finish_reason` mapping: end_turn → stop, max_tokens → - // length. Anything else passes through verbatim. - assert_eq!(out.choices[0].finish_reason.as_deref(), Some("stop")); - let usage = out.usage.expect("usage must be Some"); - assert_eq!(usage.prompt_tokens, 12); - assert_eq!(usage.completion_tokens, 5); - assert_eq!(usage.total_tokens, 17); - } - - #[test] - fn stop_reason_max_tokens_maps_to_length() { - // Pin the OpenAI-side mapping — clients use this field to - // decide whether to retry-with-bigger-budget vs accept the - // truncated answer. Mis-mapping it == "user thinks they got - // a complete answer when they didn't". - let resp = bedrock_response("partial", Some("max_tokens")); - let out = convert_from_bedrock(resp, "x"); - assert_eq!(out.choices[0].finish_reason.as_deref(), Some("length")); - } - - #[test] - fn unknown_stop_reason_passes_through_verbatim() { - // A future Bedrock release that introduces a new stop reason - // shouldn't be silently mapped to a wrong OpenAI value. Pass - // it through so dashboards can see "unknown" buckets. - let resp = bedrock_response("blocked", Some("content_filtered")); - let out = convert_from_bedrock(resp, "x"); - assert_eq!( - out.choices[0].finish_reason.as_deref(), - Some("content_filtered") - ); - } - - #[test] - fn multiple_text_content_blocks_concatenate() { - // Bedrock can return multiple content blocks (e.g. tool-use - // splits the response). The OpenAI envelope is a single - // string, so we join them — losing the boundary is acceptable - // since the OpenAI shape doesn't model it anyway. - let resp = BedrockConverseResponse { - output: BedrockOutput { - message: BedrockOutputMessage { - role: "assistant".into(), - content: vec![ - BedrockOutputContent { - text: Some("part one ".into()), - }, - BedrockOutputContent { - text: Some("part two".into()), - }, - ], - }, - }, - usage: BedrockUsage { - input_tokens: 1, - output_tokens: 1, - total_tokens: 2, - }, - stop_reason: Some("end_turn".into()), - }; - let out = convert_from_bedrock(resp, "x"); - assert_eq!(out.choices[0].message.content, json!("part one part two")); - } -} diff --git a/crates/tw-provider/src/providers/custom.rs b/crates/tw-provider/src/providers/custom.rs deleted file mode 100644 index 50a126cf..00000000 --- a/crates/tw-provider/src/providers/custom.rs +++ /dev/null @@ -1,47 +0,0 @@ -use super::openai::OpenAiProvider; -use crate::AiProvider; -use futures::Stream; -use std::pin::Pin; -use tw_types::*; - -/// Custom provider that proxies to any OpenAI-compatible endpoint. -pub struct CustomProvider { - inner: OpenAiProvider, - provider_name: String, -} - -impl CustomProvider { - pub fn new(name: String, base_url: String) -> Self { - Self { - inner: OpenAiProvider::new(base_url), - provider_name: name, - } - } - - pub fn with_custom_headers(mut self, headers: Vec<(String, String)>) -> Self { - self.inner = self.inner.with_custom_headers(headers); - self - } -} - -impl AiProvider for CustomProvider { - fn name(&self) -> &str { - &self.provider_name - } - - async fn chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Result { - self.inner.chat_completion(request, ctx).await - } - - fn stream_chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Pin> + Send>> { - self.inner.stream_chat_completion(request, ctx) - } -} diff --git a/crates/tw-provider/src/providers/google.rs b/crates/tw-provider/src/providers/google.rs deleted file mode 100644 index b25e6018..00000000 --- a/crates/tw-provider/src/providers/google.rs +++ /dev/null @@ -1,418 +0,0 @@ -use crate::{AiProvider, ProviderBase}; -use futures::Stream; -use serde::{Deserialize, Serialize}; -use std::pin::Pin; -use tw_protocol::SseStreamExt; -use tw_types::*; - -pub struct GoogleProvider { - pub base: ProviderBase, -} - -impl GoogleProvider { - pub fn new(base_url: String) -> Self { - Self { - base: ProviderBase::new(base_url), - } - } - - pub fn with_custom_headers(mut self, headers: Vec<(String, String)>) -> Self { - self.base = self.base.with_custom_headers(headers); - self - } -} - -// ---------- Gemini API types ---------- - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct GeminiRequest { - contents: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - system_instruction: Option, - #[serde(skip_serializing_if = "Option::is_none")] - generation_config: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -struct GeminiContent { - #[serde(skip_serializing_if = "Option::is_none")] - role: Option, - parts: Vec, -} - -#[derive(Debug, Serialize, Deserialize)] -struct GeminiPart { - #[serde(skip_serializing_if = "Option::is_none")] - text: Option, -} - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct GeminiGenerationConfig { - #[serde(skip_serializing_if = "Option::is_none")] - temperature: Option, - #[serde(skip_serializing_if = "Option::is_none")] - max_output_tokens: Option, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -struct GeminiResponse { - candidates: Option>, - usage_metadata: Option, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -struct GeminiCandidate { - content: Option, - finish_reason: Option, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -struct GeminiUsageMetadata { - prompt_token_count: Option, - candidates_token_count: Option, - total_token_count: Option, -} - -// ---------- Conversion ---------- - -fn convert_request(req: &ChatCompletionRequest) -> GeminiRequest { - let mut system_instruction: Option = None; - let mut contents = Vec::new(); - - for msg in &req.messages { - let text = match &msg.content { - serde_json::Value::String(s) => s.clone(), - other => other.to_string(), - }; - - if msg.role == "system" { - system_instruction = Some(GeminiContent { - role: None, - parts: vec![GeminiPart { text: Some(text) }], - }); - } else { - let role = match msg.role.as_str() { - "assistant" => "model", - _ => "user", - }; - contents.push(GeminiContent { - role: Some(role.to_string()), - parts: vec![GeminiPart { text: Some(text) }], - }); - } - } - - GeminiRequest { - contents, - system_instruction, - generation_config: Some(GeminiGenerationConfig { - temperature: req.temperature, - max_output_tokens: req.max_tokens, - }), - } -} - -/// Gemini 的停止原因 → OpenAI 的写法。 -/// -/// 整包和流式都要用:**流式那条路原先什么都不映射**,见 `stream_chat_completion`。 -fn finish_reason_of(raw: &str) -> String { - match raw { - "STOP" => "stop".to_string(), - "MAX_TOKENS" => "length".to_string(), - other => other.to_lowercase(), - } -} - -/// Gemini 报的用量 → 我们的 `Usage`。 -/// -/// **流式的每一帧都带着累计值**,所以每一帧都要填:调用方取的是最后 -/// 一个带用量的块,而那一帧上的数就是这次请求的最终用量。 -fn usage_of(u: GeminiUsageMetadata) -> Usage { - Usage { - prompt_tokens: u.prompt_token_count.unwrap_or(0), - completion_tokens: u.candidates_token_count.unwrap_or(0), - total_tokens: u.total_token_count.unwrap_or(0), - } -} - -fn convert_response(resp: GeminiResponse, model: &str) -> ChatCompletionResponse { - let (text, finish_reason) = resp - .candidates - .and_then(|c| c.into_iter().next()) - .map(|c| { - let text = c - .content - .and_then(|content| { - content - .parts - .into_iter() - .filter_map(|p| p.text) - .collect::>() - .first() - .cloned() - }) - .unwrap_or_default(); - let reason = c.finish_reason.as_deref().map(finish_reason_of); - (text, reason) - }) - .unwrap_or_default(); - - let usage = resp.usage_metadata.map(usage_of); - - ChatCompletionResponse { - id: format!("gemini-{}", uuid::Uuid::new_v4()), - object: "chat.completion".to_string(), - created: chrono::Utc::now().timestamp(), - model: model.to_string(), - choices: vec![Choice { - index: 0, - message: ChatMessage { - role: "assistant".to_string(), - content: serde_json::Value::String(text), - ..Default::default() - }, - finish_reason, - }], - usage, - } -} - -/// 流式的一帧 → 一个块。 -/// -/// **用量和停止原因原先在这里被丢掉**:两个字段都写死 `None`,而 Gemini -/// 每一帧都带着累计用量。丢掉的后果不是少一个数字 —— 调用方拿不到用量 -/// 就只能按字符数估算计费,于是经 Gemini 的流式请求从来没有按真实用量 -/// 记过账。 -fn convert_chunk(resp: GeminiResponse, chunk_id: &str, model: &str) -> ChatCompletionChunk { - // 每一帧都填:用量是累计的,调用方取最后一个带用量的块 - let usage = resp.usage_metadata.map(usage_of); - let (text, finish_reason) = resp - .candidates - .and_then(|c| c.into_iter().next()) - .map(|c| { - let text = c - .content - .and_then(|content| content.parts.into_iter().next()) - .and_then(|p| p.text) - .unwrap_or_default(); - (text, c.finish_reason.as_deref().map(finish_reason_of)) - }) - .unwrap_or_default(); - - ChatCompletionChunk { - id: chunk_id.to_string(), - object: "chat.completion.chunk".to_string(), - created: chrono::Utc::now().timestamp(), - model: model.to_string(), - choices: vec![ChunkChoice { - index: 0, - delta: serde_json::json!({ "content": text }), - finish_reason, - }], - usage, - } -} - -// ---------- AiProvider ---------- - -impl AiProvider for GoogleProvider { - fn name(&self) -> &str { - "google" - } - - async fn chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Result { - let model = request.model.clone(); - let gemini_req = convert_request(&request); - - let url = format!( - "{}/v1beta/models/{}:generateContent", - self.base.base_url, model - ); - - let builder = self - .base - .apply_custom_headers(self.base.client.post(&url), &ctx) - .json(&gemini_req); - - let resp = ProviderBase::send(builder).await?; - let resp = ProviderBase::check_status(resp, "Gemini").await?; - - let gemini_resp: GeminiResponse = resp - .json() - .await - .map_err(|e| GatewayError::ProviderError(e.to_string()))?; - - Ok(convert_response(gemini_resp, &model)) - } - - fn stream_chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Pin> + Send>> { - let client = self.base.client.clone(); - let base_url = self.base.base_url.clone(); - let model = request.model.clone(); - let headers = self.base.resolve_headers(&ctx); - - let gemini_req = convert_request(&request); - - Box::pin(async_stream::stream! { - let url = format!( - "{}/v1beta/models/{}:streamGenerateContent?alt=sse", - base_url, model - ); - - let builder = ProviderBase::apply_headers(client.post(&url), &headers).json(&gemini_req); - - let resp = match ProviderBase::send(builder).await { - Ok(r) => r, - Err(e) => { yield Err(e); return; } - }; - let resp = match ProviderBase::check_status(resp, "Gemini").await { - Ok(r) => r, - Err(e) => { yield Err(e); return; } - }; - - use futures::StreamExt; - let mut stream = resp.bytes_stream().sse_events(); - let chunk_id = format!("gemini-{}", uuid::Uuid::new_v4()); - - while let Some(event) = stream.next().await { - let event = match event { - Ok(e) => e, - Err(e) => { - yield Err(GatewayError::NetworkError(e.to_string())); - return; - } - }; - - let data = event.data.trim().to_string(); - if data.is_empty() || data == "[DONE]" { - break; - } - - if let Ok(gemini_resp) = serde_json::from_str::(&data) { - yield Ok(convert_chunk(gemini_resp, &chunk_id, &model)); - } - } - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn frame(json: &str) -> GeminiResponse { - serde_json::from_str(json).expect("frame parses") - } - - #[test] - fn a_streamed_frame_carries_the_usage_gemini_reported() { - // 这正是原先丢掉的东西:帧里有用量,块上却是 None,于是计费 - // 退回按字符数估算 - let chunk = convert_chunk( - frame( - r#"{"candidates":[{"content":{"parts":[{"text":"hi"}]}}], - "usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":3,"totalTokenCount":14}}"#, - ), - "id", - "gemini-2.5-pro", - ); - - let usage = chunk.usage.expect("the frame reported usage"); - assert_eq!(usage.prompt_tokens, 11); - assert_eq!(usage.completion_tokens, 3); - assert_eq!(usage.total_tokens, 14); - } - - #[test] - fn a_frame_without_usage_reports_none_rather_than_zeros() { - // 早期的帧不带用量。**零和「没说」不是一回事** —— 报成零会让 - // 调用方以为这次请求真的没花 token - let chunk = convert_chunk( - frame(r#"{"candidates":[{"content":{"parts":[{"text":"hi"}]}}]}"#), - "id", - "gemini-2.5-pro", - ); - assert!(chunk.usage.is_none()); - } - - #[test] - fn the_last_frames_cumulative_count_is_the_one_that_counts() { - // Gemini 每一帧都报累计值,所以每一帧都要填:调用方取最后一个 - // 带用量的块,而那一帧上的数就是这次请求的最终用量 - let first = convert_chunk( - frame( - r#"{"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":1,"totalTokenCount":12}}"#, - ), - "id", - "m", - ); - let last = convert_chunk( - frame( - r#"{"usageMetadata":{"promptTokenCount":11,"candidatesTokenCount":9,"totalTokenCount":20}}"#, - ), - "id", - "m", - ); - assert_eq!(first.usage.expect("first").completion_tokens, 1); - assert_eq!(last.usage.expect("last").completion_tokens, 9); - } - - #[test] - fn a_streamed_frame_translates_the_stop_reason() { - // 和用量一样,这个字段原先也写死 None - let stop = convert_chunk( - frame(r#"{"candidates":[{"finishReason":"STOP"}]}"#), - "id", - "m", - ); - assert_eq!(stop.choices[0].finish_reason.as_deref(), Some("stop")); - - let cut = convert_chunk( - frame(r#"{"candidates":[{"finishReason":"MAX_TOKENS"}]}"#), - "id", - "m", - ); - assert_eq!(cut.choices[0].finish_reason.as_deref(), Some("length")); - - let unknown = convert_chunk( - frame(r#"{"candidates":[{"finishReason":"SAFETY"}]}"#), - "id", - "m", - ); - assert_eq!(unknown.choices[0].finish_reason.as_deref(), Some("safety")); - } - - #[test] - fn the_whole_response_and_a_frame_agree_on_the_numbers() { - // 两条路读的是同一个字段。它们曾经不一致过 —— 整包读了, - // 流式没读 - let json = r#"{"candidates":[{"content":{"parts":[{"text":"hi"}]},"finishReason":"STOP"}], - "usageMetadata":{"promptTokenCount":7,"candidatesTokenCount":2,"totalTokenCount":9}}"#; - let whole = convert_response(frame(json), "m"); - let streamed = convert_chunk(frame(json), "id", "m"); - - let w = whole.usage.expect("whole"); - let s = streamed.usage.expect("streamed"); - assert_eq!( - (w.prompt_tokens, w.completion_tokens), - (s.prompt_tokens, s.completion_tokens) - ); - assert_eq!( - whole.choices[0].finish_reason, - streamed.choices[0].finish_reason - ); - } -} diff --git a/crates/tw-provider/src/providers/mod.rs b/crates/tw-provider/src/providers/mod.rs deleted file mode 100644 index 1680af3e..00000000 --- a/crates/tw-provider/src/providers/mod.rs +++ /dev/null @@ -1,10 +0,0 @@ -//! 各家 provider 的实现,外加一个 dyn-兼容的包装。 - -pub mod anthropic; -pub mod azure_openai; -pub mod bedrock; -pub mod custom; -pub mod google; -pub mod openai; -pub mod openai_responses; -pub mod protocol; diff --git a/crates/tw-provider/src/providers/openai.rs b/crates/tw-provider/src/providers/openai.rs deleted file mode 100644 index 817eda36..00000000 --- a/crates/tw-provider/src/providers/openai.rs +++ /dev/null @@ -1,128 +0,0 @@ -use crate::{AiProvider, ProviderBase}; -use futures::Stream; -use futures::stream::StreamExt; -use std::pin::Pin; -use tw_protocol::SseStreamExt; -use tw_types::*; - -pub struct OpenAiProvider { - pub base: ProviderBase, -} - -impl OpenAiProvider { - pub fn new(base_url: String) -> Self { - Self { - base: ProviderBase::new(base_url), - } - } - - pub fn with_custom_headers(mut self, headers: Vec<(String, String)>) -> Self { - self.base = self.base.with_custom_headers(headers); - self - } - - fn completions_url(&self) -> String { - format!("{}/v1/chat/completions", self.base.base_url) - } -} - -impl AiProvider for OpenAiProvider { - fn name(&self) -> &str { - "openai" - } - - async fn chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Result { - let builder = self.base.client.post(self.completions_url()); - let builder = self.base.apply_custom_headers(builder, &ctx).json(&request); - - let resp = ProviderBase::send(builder).await?; - let resp = ProviderBase::check_status(resp, "OpenAI").await?; - - resp.json::() - .await - .map_err(|e| GatewayError::ProviderError(e.to_string())) - } - - fn stream_chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Pin> + Send>> { - let client = self.base.client.clone(); - let url = self.completions_url(); - let custom_headers = self.base.resolve_headers(&ctx); - - // Ensure stream is set to true in the outgoing request - let mut request = request; - request.stream = Some(true); - - Box::pin(async_stream::stream! { - let builder = ProviderBase::apply_headers(client.post(&url), &custom_headers) - .json(&request); - - let resp = match ProviderBase::send(builder).await { - Ok(r) => r, - Err(e) => { yield Err(e); return; } - }; - let resp = match ProviderBase::check_status(resp, "OpenAI").await { - Ok(r) => r, - Err(e) => { yield Err(e); return; } - }; - - let mut event_stream = resp.bytes_stream().sse_events(); - - while let Some(event_result) = event_stream.next().await { - match event_result { - Ok(event) => { - let data = event.data.trim().to_string(); - - // OpenAI signals end of stream with [DONE] - if data == "[DONE]" { - break; - } - - if data.is_empty() { - continue; - } - - match serde_json::from_str::(&data) { - Ok(chunk) => yield Ok(chunk), - Err(e) => { - tracing::warn!("Failed to parse SSE chunk: {e}, data: {data}"); - // Skip unparseable chunks rather than breaking the stream - continue; - } - } - } - Err(e) => { - yield Err(GatewayError::ProviderError(format!( - "SSE stream error: {e}" - ))); - break; - } - } - } - }) - } -} - -#[cfg(test)] -mod base_url_tests { - use super::*; - - #[test] - fn trailing_slash_in_base_url_does_not_double_up() { - // Regression: an admin-entered `https://host/` produced - // `https://host//v1/chat/completions`, which upstreams answer - // with a bare 404 — while the "Test connection" probe, which - // trimmed the slash itself, reported the provider healthy. - let trimmed = OpenAiProvider::new("https://api.example.com".into()).completions_url(); - let slashed = OpenAiProvider::new("https://api.example.com/".into()).completions_url(); - assert_eq!(trimmed, "https://api.example.com/v1/chat/completions"); - assert_eq!(slashed, trimmed); - } -} diff --git a/crates/tw-provider/src/providers/openai_responses.rs b/crates/tw-provider/src/providers/openai_responses.rs deleted file mode 100644 index 2c9aada0..00000000 --- a/crates/tw-provider/src/providers/openai_responses.rs +++ /dev/null @@ -1,366 +0,0 @@ -//! OpenAI **Responses** API adapter (`POST {base}/v1/responses`). -//! -//! Distinct from [`super::openai::OpenAiProvider`], which speaks Chat -//! Completions. Some upstreams expose a model on one dialect and not -//! the other — an aggregator that answers `/v1/responses` for its newer -//! models while 400-ing them on `/v1/chat/completions` is exactly the -//! case `UpstreamProtocol` exists to route around. -//! -//! Note the symmetry with `proxy::handlers::responses`, which converts -//! the *inbound* Responses format into the internal request. This is -//! the outbound half of the same mapping. - -use crate::{AiProvider, ProviderBase}; -use futures::Stream; -use futures::stream::StreamExt; -use std::pin::Pin; -use tw_protocol::SseStreamExt; -use tw_types::*; - -pub struct OpenAiResponsesProvider { - pub base: ProviderBase, -} - -impl OpenAiResponsesProvider { - pub fn new(base_url: String) -> Self { - Self { - base: ProviderBase::new(base_url), - } - } - - pub fn with_custom_headers(mut self, headers: Vec<(String, String)>) -> Self { - self.base = self.base.with_custom_headers(headers); - self - } - - fn responses_url(&self) -> String { - format!("{}/v1/responses", self.base.base_url) - } -} - -/// Internal request → Responses request body. -/// -/// `messages` map onto `input` items one-for-one; the Responses API -/// accepts the same `{role, content}` shape Chat Completions uses, so -/// tool calls and multimodal content parts ride through untouched in -/// `ChatMessage::extra` / `content`. -fn convert_request(request: &ChatCompletionRequest, stream: bool) -> serde_json::Value { - let input: Vec = request - .messages - .iter() - .map(|m| { - let mut item = serde_json::json!({ "role": m.role, "content": m.content }); - // Preserve tool_call_id / tool_calls / name / refusal — - // the same passthrough contract `ChatMessage::extra` has - // on the Chat Completions path. - if let (Some(obj), Some(extra)) = (item.as_object_mut(), m.extra.as_object()) { - for (k, v) in extra { - obj.insert(k.clone(), v.clone()); - } - } - item - }) - .collect(); - - let mut body = serde_json::json!({ - "model": request.model, - "input": input, - }); - let obj = body.as_object_mut().expect("just built as an object"); - if stream { - obj.insert("stream".into(), serde_json::Value::Bool(true)); - } - if let Some(t) = request.temperature { - obj.insert("temperature".into(), serde_json::json!(t)); - } - // Responses renamed the cap; Chat Completions' `max_tokens` is not - // accepted and upstreams reject it as an unknown field. - if let Some(m) = request.max_tokens { - obj.insert("max_output_tokens".into(), serde_json::json!(m)); - } - // Anything the caller sent that we don't model (tools, reasoning - // effort, structured-output schemas) rides through as-is — dropping - // it silently is how a gateway breaks tool use. - if let Some(extra) = request.extra.as_object() { - for (k, v) in extra { - if k == "max_tokens" || k == "stream" { - continue; - } - obj.entry(k.clone()).or_insert_with(|| v.clone()); - } - } - body -} - -/// Concatenate every `output_text` part of a Responses reply. Reasoning -/// items and tool calls carry no `output_text`, so they contribute -/// nothing here and stay out of the assistant message body. -fn extract_output_text(resp: &serde_json::Value) -> String { - let Some(output) = resp.get("output").and_then(|v| v.as_array()) else { - return String::new(); - }; - let mut text = String::new(); - for item in output { - let Some(parts) = item.get("content").and_then(|v| v.as_array()) else { - continue; - }; - for part in parts { - if let Some(t) = part.get("text").and_then(|v| v.as_str()) { - text.push_str(t); - } - } - } - text -} - -/// Responses reply → internal response. -fn convert_response(resp: serde_json::Value, request_model: &str) -> ChatCompletionResponse { - let usage = resp.get("usage").map(|u| { - let prompt = u.get("input_tokens").and_then(|v| v.as_u64()).unwrap_or(0) as u32; - let completion = u.get("output_tokens").and_then(|v| v.as_u64()).unwrap_or(0) as u32; - Usage { - prompt_tokens: prompt, - completion_tokens: completion, - total_tokens: u - .get("total_tokens") - .and_then(|v| v.as_u64()) - .unwrap_or((prompt + completion) as u64) as u32, - } - }); - - ChatCompletionResponse { - id: resp - .get("id") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(), - object: "chat.completion".to_string(), - created: resp - .get("created_at") - .and_then(|v| v.as_i64()) - .unwrap_or_default(), - model: resp - .get("model") - .and_then(|v| v.as_str()) - .unwrap_or(request_model) - .to_string(), - choices: vec![Choice { - index: 0, - message: ChatMessage { - role: "assistant".to_string(), - content: serde_json::Value::String(extract_output_text(&resp)), - ..Default::default() - }, - finish_reason: Some("stop".to_string()), - }], - usage, - } -} - -impl AiProvider for OpenAiResponsesProvider { - fn name(&self) -> &str { - "openai_responses" - } - - async fn chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Result { - let body = convert_request(&request, false); - let builder = self - .base - .client - .post(self.responses_url()) - .header("content-type", "application/json"); - let builder = self.base.apply_custom_headers(builder, &ctx).json(&body); - - let resp = ProviderBase::send(builder).await?; - let resp = ProviderBase::check_status(resp, "OpenAI Responses").await?; - let raw: serde_json::Value = resp - .json() - .await - .map_err(|e| GatewayError::ProviderError(e.to_string()))?; - Ok(convert_response(raw, &request.model)) - } - - fn stream_chat_completion( - &self, - request: ChatCompletionRequest, - ctx: CallCtx, - ) -> Pin> + Send>> { - let client = self.base.client.clone(); - let url = self.responses_url(); - let headers = self.base.resolve_headers(&ctx); - let model = request.model.clone(); - let body = convert_request(&request, true); - - Box::pin(async_stream::stream! { - let builder = client - .post(&url) - .header("content-type", "application/json"); - let builder = ProviderBase::apply_headers(builder, &headers).json(&body); - - let resp = match ProviderBase::send(builder).await { - Ok(r) => r, - Err(e) => { yield Err(e); return; } - }; - let resp = match ProviderBase::check_status(resp, "OpenAI Responses").await { - Ok(r) => r, - Err(e) => { yield Err(e); return; } - }; - - let mut event_stream = resp.bytes_stream().sse_events(); - // The Responses stream carries the id on the first event - // only; later deltas reference it implicitly, so thread it - // through for the chunks we synthesize. - let mut response_id = String::new(); - - while let Some(event_result) = event_stream.next().await { - let event = match event_result { - Ok(e) => e, - Err(e) => { yield Err(GatewayError::ProviderError(e.to_string())); return; } - }; - let data = event.data.trim(); - if data.is_empty() || data == "[DONE]" { - continue; - } - let Ok(parsed) = serde_json::from_str::(data) else { - continue; - }; - if response_id.is_empty() - && let Some(id) = parsed - .get("response") - .and_then(|r| r.get("id")) - .and_then(|v| v.as_str()) - { - response_id = id.to_string(); - } - - match event.event.as_str() { - "response.output_text.delta" => { - let Some(delta) = parsed.get("delta").and_then(|v| v.as_str()) else { - continue; - }; - yield Ok(ChatCompletionChunk { - id: response_id.clone(), - object: "chat.completion.chunk".to_string(), - created: 0, - model: model.clone(), - choices: vec![ChunkChoice { - index: 0, - delta: serde_json::json!({"content": delta}), - finish_reason: None, - }], - usage: None, - }); - } - // Terminal event — carries the final usage totals, - // which the accounting stage needs to bill the call. - "response.completed" => { - let usage = parsed - .get("response") - .and_then(|r| r.get("usage")) - .map(|u| { - let prompt = u.get("input_tokens").and_then(|v| v.as_u64()).unwrap_or(0) as u32; - let completion = u.get("output_tokens").and_then(|v| v.as_u64()).unwrap_or(0) as u32; - Usage { - prompt_tokens: prompt, - completion_tokens: completion, - total_tokens: u - .get("total_tokens") - .and_then(|v| v.as_u64()) - .unwrap_or((prompt + completion) as u64) as u32, - } - }); - yield Ok(ChatCompletionChunk { - id: response_id.clone(), - object: "chat.completion.chunk".to_string(), - created: 0, - model: model.clone(), - choices: vec![ChunkChoice { - index: 0, - delta: serde_json::json!({}), - finish_reason: Some("stop".to_string()), - }], - usage, - }); - return; - } - "response.failed" | "error" => { - let message = parsed - .get("response") - .and_then(|r| r.get("error")) - .or_else(|| parsed.get("error")) - .map(|e| e.to_string()) - .unwrap_or_else(|| "upstream reported a failed response".to_string()); - yield Err(GatewayError::ProviderError(message)); - return; - } - _ => {} - } - } - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn req(model: &str) -> ChatCompletionRequest { - ChatCompletionRequest { - model: model.to_string(), - messages: vec![ChatMessage { - role: "user".to_string(), - content: serde_json::Value::String("hi".to_string()), - ..Default::default() - }], - temperature: None, - max_tokens: Some(16), - stream: None, - extra: serde_json::json!({"tools": [{"type": "web_search"}]}), - } - } - - #[test] - fn request_uses_responses_field_names_and_keeps_unmodelled_fields() { - let body = convert_request(&req("gpt-5"), false); - // `max_tokens` is not a Responses field — upstreams reject it. - assert!(body.get("max_tokens").is_none()); - assert_eq!(body["max_output_tokens"], 16); - assert_eq!(body["input"][0]["role"], "user"); - // Tool definitions must survive the hop or tool use silently breaks. - assert_eq!(body["tools"][0]["type"], "web_search"); - } - - #[test] - fn response_text_parts_concatenate_into_the_assistant_message() { - let raw = serde_json::json!({ - "id": "resp_1", - "model": "gpt-5", - "created_at": 42, - "output": [ - {"type": "reasoning", "summary": []}, - {"type": "message", "content": [ - {"type": "output_text", "text": "he"}, - {"type": "output_text", "text": "llo"} - ]} - ], - "usage": {"input_tokens": 3, "output_tokens": 2, "total_tokens": 5} - }); - let converted = convert_response(raw, "fallback"); - assert_eq!(converted.model, "gpt-5"); - assert_eq!(converted.choices[0].message.content, "hello"); - let usage = converted.usage.unwrap(); - assert_eq!((usage.prompt_tokens, usage.completion_tokens), (3, 2)); - } - - #[test] - fn missing_usage_and_output_degrade_to_an_empty_answer_not_a_panic() { - let converted = convert_response(serde_json::json!({"id": "resp_2"}), "fallback"); - assert_eq!(converted.model, "fallback"); - assert_eq!(converted.choices[0].message.content, ""); - assert!(converted.usage.is_none()); - } -} diff --git a/crates/tw-provider/src/providers/protocol.rs b/crates/tw-provider/src/providers/protocol.rs deleted file mode 100644 index aad7547b..00000000 --- a/crates/tw-provider/src/providers/protocol.rs +++ /dev/null @@ -1,190 +0,0 @@ -//! Upstream wire protocol — which API dialect the gateway speaks to a -//! given route's upstream. -//! -//! This used to be implied by `providers.provider_type`: one provider -//! record meant one adapter for every model behind it. That breaks on -//! aggregators that serve several model families over one host and one -//! credential but expose a *different* API per family — e.g. an -//! endpoint that answers `anthropic.*` only on `/v1/messages` while -//! everything else lives on `/v1/chat/completions`. Modelling the -//! protocol per route lets one provider record cover all of them. -//! -//! `model_routes.upstream_protocol` stores the resolved value; NULL -//! means "not determined yet" and the runtime falls back to -//! [`UpstreamProtocol::default_for_provider_type`]. - -use std::fmt; - -/// Wire dialect used when talking to an upstream. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum UpstreamProtocol { - /// `POST {base}/v1/chat/completions` — OpenAI Chat Completions. - OpenAiChat, - /// `POST {base}/v1/responses` — OpenAI Responses API (2025+). - OpenAiResponses, - /// `POST {base}/v1/messages` — Anthropic Messages. - AnthropicMessages, - /// `POST {base}/v1beta/models/{model}:generateContent` — Gemini. - GoogleGenerate, - /// AWS Bedrock Runtime with SigV4 — no base URL, region-derived host. - BedrockNative, -} - -impl UpstreamProtocol { - pub fn as_str(self) -> &'static str { - match self { - Self::OpenAiChat => "openai_chat", - Self::OpenAiResponses => "openai_responses", - Self::AnthropicMessages => "anthropic_messages", - Self::GoogleGenerate => "google_generate", - Self::BedrockNative => "bedrock_native", - } - } - - pub fn parse(s: &str) -> Option { - match s { - "openai_chat" => Some(Self::OpenAiChat), - "openai_responses" => Some(Self::OpenAiResponses), - "anthropic_messages" => Some(Self::AnthropicMessages), - "google_generate" => Some(Self::GoogleGenerate), - "bedrock_native" => Some(Self::BedrockNative), - _ => None, - } - } - - /// What a provider of this type speaks unless a route says - /// otherwise. Preserves the pre-per-route-protocol behaviour, so an - /// un-probed route behaves exactly as it did before. - pub fn default_for_provider_type(provider_type: &str) -> Self { - match provider_type { - "anthropic" => Self::AnthropicMessages, - "google" => Self::GoogleGenerate, - "bedrock" => Self::BedrockNative, - // openai, azure_openai, custom, and anything unknown. - _ => Self::OpenAiChat, - } - } - - /// Ordered candidates to try for `upstream_model` behind a provider - /// of `provider_type`, best guess first. - /// - /// Used by the import-time probe and by the runtime relearn path. - /// The ordering is a heuristic on the model id — never a decision - /// on its own, always confirmed by an actual upstream response. - /// - /// Providers whose transport is fixed (Bedrock SigV4, Gemini) get a - /// single candidate: there is no second dialect to fall back to on - /// the same host, so probing them would just burn a request. - pub fn candidates_for(provider_type: &str, upstream_model: &str) -> Vec { - let default = Self::default_for_provider_type(provider_type); - if matches!(default, Self::BedrockNative | Self::GoogleGenerate) { - return vec![default]; - } - - let model = upstream_model.to_ascii_lowercase(); - // Match on the family segment, not the whole id: aggregators - // prefix the vendor (`anthropic.claude-…`, `openai.gpt-…`) - // while first-party endpoints don't (`claude-…`, `gpt-…`). - let native = if model.contains("claude") || model.starts_with("anthropic") { - Self::AnthropicMessages - } else if model.contains("gemini") || model.starts_with("google") { - Self::GoogleGenerate - } else { - Self::OpenAiChat - }; - - // The native guess first, then the OpenAI dialects — nearly - // every aggregator speaks at least one of them, and Responses - // is the one newer models are increasingly exposed on. - let mut out = vec![native]; - for fallback in [Self::OpenAiChat, Self::OpenAiResponses, default] { - if !out.contains(&fallback) { - out.push(fallback); - } - } - out - } -} - -impl fmt::Display for UpstreamProtocol { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(self.as_str()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn round_trips_through_its_string_form() { - for p in [ - UpstreamProtocol::OpenAiChat, - UpstreamProtocol::OpenAiResponses, - UpstreamProtocol::AnthropicMessages, - UpstreamProtocol::GoogleGenerate, - UpstreamProtocol::BedrockNative, - ] { - assert_eq!(UpstreamProtocol::parse(p.as_str()), Some(p)); - } - assert_eq!(UpstreamProtocol::parse("nonsense"), None); - } - - #[test] - fn unprobed_route_keeps_the_provider_type_behaviour() { - assert_eq!( - UpstreamProtocol::default_for_provider_type("custom"), - UpstreamProtocol::OpenAiChat - ); - assert_eq!( - UpstreamProtocol::default_for_provider_type("anthropic"), - UpstreamProtocol::AnthropicMessages - ); - } - - #[test] - fn candidates_lead_with_the_model_family_then_cover_the_rest() { - // The case this whole mechanism exists for: a `custom` - // (OpenAI-compatible) aggregator serving Anthropic models that - // only answer on /v1/messages. - let c = UpstreamProtocol::candidates_for("custom", "anthropic.claude-opus-4"); - assert_eq!(c[0], UpstreamProtocol::AnthropicMessages); - assert!(c.contains(&UpstreamProtocol::OpenAiChat)); - assert!(c.contains(&UpstreamProtocol::OpenAiResponses)); - - let c = UpstreamProtocol::candidates_for("custom", "openai.gpt-oss-20b"); - assert_eq!(c[0], UpstreamProtocol::OpenAiChat); - assert!(c.contains(&UpstreamProtocol::OpenAiResponses)); - } - - #[test] - fn fixed_transport_providers_get_a_single_candidate() { - // Nothing to fall back to on the same host — probing would - // only burn a request. - assert_eq!( - UpstreamProtocol::candidates_for("bedrock", "anthropic.claude-opus-4"), - vec![UpstreamProtocol::BedrockNative] - ); - assert_eq!( - UpstreamProtocol::candidates_for("google", "gemini-2.0-flash"), - vec![UpstreamProtocol::GoogleGenerate] - ); - } - - #[test] - fn candidate_lists_never_repeat_a_protocol() { - for (ty, model) in [ - ("custom", "claude-3-5-sonnet"), - ("custom", "gpt-4o"), - ("openai", "gpt-4o"), - ("anthropic", "claude-3-5-sonnet"), - ("azure_openai", "my-deployment"), - ] { - let c = UpstreamProtocol::candidates_for(ty, model); - let mut seen = c.clone(); - seen.sort_by_key(|p| p.as_str()); - seen.dedup(); - assert_eq!(seen.len(), c.len(), "duplicate candidate for {ty}/{model}"); - } - } -} diff --git a/crates/tw-upstream/Cargo.toml b/crates/tw-upstream/Cargo.toml index 4c078f4b..da344136 100644 --- a/crates/tw-upstream/Cargo.toml +++ b/crates/tw-upstream/Cargo.toml @@ -13,14 +13,30 @@ description = "Talking to an upstream: URL assembly and header handling, shared http = "1" reqwest = { workspace = true } -# ── SigV4:只有 Bedrock 要,桌面版不接它 ───────────────────── +# ── Bedrock:SigV4 签名、eventstream 拆帧。桌面版不接它 ───────── # 这一串会连同一个 http 0.2 一起进来,所以关在 feature 后面 aws-sigv4 = { workspace = true, optional = true } aws-credential-types = { workspace = true, optional = true } +aws-smithy-eventstream = { workspace = true, optional = true } +bytes = { workspace = true, optional = true } serde_json = { workspace = true, optional = true } [features] -sigv4 = ["dep:aws-sigv4", "dep:aws-credential-types", "dep:serde_json"] +bedrock = [ + "dep:aws-sigv4", + "dep:aws-credential-types", + "dep:aws-smithy-eventstream", + "dep:bytes", + "dep:serde_json", +] [dev-dependencies] tokio = { version = "1", features = ["rt", "macros"] } +aws-smithy-types = { workspace = true } +# 从线上的二进制帧一路走到客户端格式,证明拆帧和方言的约定对得上 +tw-dialect = { workspace = true } +tw-wire = { workspace = true } + +[[test]] +name = "bedrock_stream" +required-features = ["bedrock"] diff --git a/crates/tw-upstream/src/eventstream.rs b/crates/tw-upstream/src/eventstream.rs new file mode 100644 index 00000000..c9e7df1f --- /dev/null +++ b/crates/tw-upstream/src/eventstream.rs @@ -0,0 +1,226 @@ +//! AWS eventstream → SSE。 +//! +//! Bedrock 的 ConverseStream 不是 SSE,是 AWS eventstream 的二进制帧: +//! 每帧一段前导(总长、头长、前导 CRC)、一串带类型的头、载荷、整帧 CRC。 +//! 另外四种方言的流都是 SSE,下游的一切 —— 方言转换、usage 嗅探、流的 +//! 组装 —— 都按 SSE 读。所以**在字节进门的地方就把它转成 SSE**,后面 +//! 不需要知道 Bedrock 有什么不同。 +//! +//! 转出来的形状是 `tw-dialect` 约定好的:`:event-type` 头进 `event:`, +//! 载荷 JSON 进 `data:`。 +//! +//! **帧可能被切在任意一个字节上**,没收齐的那部分留到下一块。CRC 由 +//! `aws-smithy-eventstream` 校验 —— 校验不过就是坏了,不要猜着往下读。 + +use aws_smithy_eventstream::frame::{DecodedFrame, MessageFrameDecoder}; +use bytes::{Buf, BytesMut}; + +/// 流里出的错。 +/// +/// **这一层不认识调用方的错误体系**,理由同 [`crate::sigv4::SignError`]。 +#[derive(Debug)] +pub enum StreamError { + /// 帧坏了:长度不对、CRC 不对 + Malformed(String), + /// 上游在流里报了错(`:message-type` 是 `exception` 或 `error`), + /// 比如半路被限流。`kind` 是 AWS 的异常名 + Upstream { kind: String, message: String }, +} + +impl std::fmt::Display for StreamError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + StreamError::Malformed(m) => write!(f, "malformed AWS eventstream frame: {m}"), + StreamError::Upstream { kind, message } => write!(f, "{kind}: {message}"), + } + } +} + +impl std::error::Error for StreamError {} + +/// 一边收一边转。 +#[derive(Debug, Default)] +pub struct Transcoder { + buf: BytesMut, + decoder: MessageFrameDecoder, +} + +impl Transcoder { + pub fn new() -> Self { + Self::default() + } + + /// 喂一块,返回这一块里收齐了的所有帧,已经写成 SSE 文本。 + /// + /// 出错之后这个转码器就不该再用了:帧的边界已经对不上。 + pub fn feed(&mut self, chunk: &[u8]) -> Result, StreamError> { + self.buf.extend_from_slice(chunk); + let mut out = Vec::new(); + loop { + let before = self.buf.remaining(); + let frame = self + .decoder + .decode_frame(&mut self.buf) + .map_err(|e| StreamError::Malformed(e.to_string()))?; + match frame { + DecodedFrame::Complete(message) => { + let header = |name: &str| { + message + .headers() + .iter() + .find(|h| h.name().as_str() == name) + .and_then(|h| h.value().as_string().ok()) + .map(|s| s.as_str().to_string()) + }; + let payload = String::from_utf8_lossy(message.payload()); + match header(":message-type").as_deref() { + Some("event") | None => { + let event = header(":event-type").unwrap_or_default(); + write_frame(&mut out, &event, &payload); + } + Some("exception") => { + return Err(StreamError::Upstream { + kind: header(":exception-type").unwrap_or_default(), + message: message_of(&payload), + }); + } + Some(other) => { + return Err(StreamError::Upstream { + kind: header(":error-code").unwrap_or_else(|| other.to_string()), + message: header(":error-message").unwrap_or_default(), + }); + } + } + } + // 前导读走了但整帧没收齐时,缓冲区也会变短 —— 只有什么都没 + // 读走才是真的要等下一块 + DecodedFrame::Incomplete if self.buf.remaining() == before => return Ok(out), + DecodedFrame::Incomplete => {} + } + } + } +} + +/// 写一帧 SSE。载荷按行拆成多个 `data:` —— SSE 读回来会用换行拼上, +/// 多行 JSON 原样还原。 +fn write_frame(out: &mut Vec, event: &str, payload: &str) { + out.extend_from_slice(b"event: "); + out.extend_from_slice(event.as_bytes()); + out.push(b'\n'); + for line in payload.split('\n') { + out.extend_from_slice(b"data: "); + out.extend_from_slice(line.as_bytes()); + out.push(b'\n'); + } + out.push(b'\n'); +} + +/// 异常的载荷是 `{"message": "..."}`;不是的话原样给出。 +fn message_of(payload: &str) -> String { + serde_json::from_str::(payload) + .ok() + .and_then(|v| { + v.get("message") + .or_else(|| v.get("Message")) + .and_then(|m| m.as_str()) + .map(str::to_string) + }) + .unwrap_or_else(|| payload.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use aws_smithy_eventstream::frame::write_message_to; + use aws_smithy_types::event_stream::{Header, HeaderValue, Message}; + + fn event(kind: &str, payload: &str) -> Vec { + let m = Message::new(payload.as_bytes().to_vec()) + .add_header(Header::new( + ":message-type", + HeaderValue::String("event".into()), + )) + .add_header(Header::new( + ":event-type", + HeaderValue::String(kind.to_string().into()), + )) + .add_header(Header::new( + ":content-type", + HeaderValue::String("application/json".into()), + )); + let mut out = Vec::new(); + write_message_to(&m, &mut out).unwrap(); + out + } + + fn exception(kind: &str, message: &str) -> Vec { + let m = Message::new(format!(r#"{{"message":"{message}"}}"#).into_bytes()) + .add_header(Header::new( + ":message-type", + HeaderValue::String("exception".into()), + )) + .add_header(Header::new( + ":exception-type", + HeaderValue::String(kind.to_string().into()), + )); + let mut out = Vec::new(); + write_message_to(&m, &mut out).unwrap(); + out + } + + #[test] + fn each_frame_becomes_one_sse_event() { + let mut wire = event("messageStart", r#"{"role":"assistant"}"#); + wire.extend(event( + "contentBlockDelta", + r#"{"contentBlockIndex":0,"delta":{"text":"晴"}}"#, + )); + let sse = Transcoder::new().feed(&wire).unwrap(); + assert_eq!( + String::from_utf8(sse).unwrap(), + "event: messageStart\ndata: {\"role\":\"assistant\"}\n\n\ + event: contentBlockDelta\ndata: {\"contentBlockIndex\":0,\"delta\":{\"text\":\"晴\"}}\n\n" + ); + } + + #[test] + fn a_frame_cut_on_any_byte_comes_out_whole() { + let mut wire = event("messageStart", r#"{"role":"assistant"}"#); + wire.extend(event( + "metadata", + r#"{"usage":{"inputTokens":3,"outputTokens":5}}"#, + )); + let whole = Transcoder::new().feed(&wire).unwrap(); + // 逐字节喂:前导、头、载荷、CRC 每一处都会被切到 + let mut t = Transcoder::new(); + let mut pieced = Vec::new(); + for b in &wire { + pieced.extend(t.feed(std::slice::from_ref(b)).unwrap()); + } + assert_eq!(pieced, whole); + } + + #[test] + fn an_exception_in_the_stream_is_an_error_not_an_event() { + let mut wire = event("messageStart", r#"{"role":"assistant"}"#); + wire.extend(exception("throttlingException", "Too many requests")); + match Transcoder::new().feed(&wire) { + Err(StreamError::Upstream { kind, message }) => { + assert_eq!(kind, "throttlingException"); + assert_eq!(message, "Too many requests"); + } + other => panic!("expected an upstream error, got {other:?}"), + } + } + + #[test] + fn a_corrupted_frame_is_refused() { + let mut wire = event("messageStart", r#"{"role":"assistant"}"#); + let n = wire.len(); + wire[n - 6] ^= 0xff; // 载荷里改一个字节,整帧 CRC 就对不上 + assert!(matches!( + Transcoder::new().feed(&wire), + Err(StreamError::Malformed(_)) + )); + } +} diff --git a/crates/tw-upstream/src/lib.rs b/crates/tw-upstream/src/lib.rs index b18ac7e7..603e5d84 100644 --- a/crates/tw-upstream/src/lib.rs +++ b/crates/tw-upstream/src/lib.rs @@ -11,7 +11,9 @@ //! 企业版设 300 秒并禁止重定向,因为它是多租户而且 base_url 由管理员填), //! 那是各自的权衡,不是共用件。 -#[cfg(feature = "sigv4")] +#[cfg(feature = "bedrock")] +pub mod eventstream; +#[cfg(feature = "bedrock")] pub mod sigv4; use http::{HeaderMap, HeaderName, HeaderValue}; diff --git a/crates/tw-upstream/src/sigv4.rs b/crates/tw-upstream/src/sigv4.rs index 93e63b52..a47c8149 100644 --- a/crates/tw-upstream/src/sigv4.rs +++ b/crates/tw-upstream/src/sigv4.rs @@ -4,7 +4,7 @@ //! 方法、URL、时间和请求体的哈希。所以**签名必须在请求体最终定稿之后**, //! 改一个字节签名就失效。 //! -//! 桌面版不接 Bedrock,所以这一整套在 `sigv4` feature 后面 —— 否则它会把 +//! 桌面版不接 Bedrock,所以这一整套在 `bedrock` feature 后面 —— 否则它会把 //! `aws-sigv4`、`aws-credential-types`、`aws-smithy-*` 连同一个 `http 0.2` //! 拖给每一个依赖这个 crate 的人。 diff --git a/crates/tw-upstream/tests/bedrock_stream.rs b/crates/tw-upstream/tests/bedrock_stream.rs new file mode 100644 index 00000000..6c80454b --- /dev/null +++ b/crates/tw-upstream/tests/bedrock_stream.rs @@ -0,0 +1,94 @@ +//! 从线上的二进制帧一路走到客户端的格式。 +//! +//! 拆帧(这里)和读帧(`tw-dialect`)是分开写的,两边靠一个约定对接: +//! `:event-type` 进 `event:`,载荷进 `data:`。这条测试证明约定对得上 —— +//! 任何一边改了形状,它就断。 + +use aws_smithy_eventstream::frame::write_message_to; +use aws_smithy_types::event_stream::{Header, HeaderValue, Message}; +use tw_dialect::convert::decode; +use tw_dialect::ir::{Dialect, Target}; +use tw_upstream::eventstream::Transcoder; + +fn event(kind: &str, payload: &str) -> Vec { + let m = Message::new(payload.as_bytes().to_vec()) + .add_header(Header::new( + ":message-type", + HeaderValue::String("event".into()), + )) + .add_header(Header::new( + ":event-type", + HeaderValue::String(kind.to_string().into()), + )); + let mut out = Vec::new(); + write_message_to(&m, &mut out).unwrap(); + out +} + +fn converse_stream() -> Vec { + [ + event("messageStart", r#"{"role":"assistant"}"#), + event( + "contentBlockDelta", + r#"{"contentBlockIndex":0,"delta":{"text":"天气"}}"#, + ), + event( + "contentBlockDelta", + r#"{"contentBlockIndex":0,"delta":{"text":"晴"}}"#, + ), + event("contentBlockStop", r#"{"contentBlockIndex":0}"#), + event("messageStop", r#"{"stopReason":"end_turn"}"#), + event( + "metadata", + r#"{"usage":{"inputTokens":60,"cacheReadInputTokens":40,"outputTokens":20,"totalTokens":120}}"#, + ), + ] + .concat() +} + +#[test] +fn a_converse_stream_reaches_a_chat_client_with_its_text_and_usage() { + // 客户端说 Chat,路由到 Bedrock + let body = serde_json::json!({ + "model": "anthropic.claude", + "stream": true, + "messages": [{"role": "user", "content": "天气?"}], + }); + let converted = decode(Dialect::Chat, &body, "/v1/chat/completions", None) + .unwrap() + .encode(&Target { + dialect: Dialect::Bedrock, + official: true, + default_max_tokens: 4096, + }); + let mut to_client = converted.session.stream(); + let mut sniffer = tw_wire::Sniffer::new(); + + // 线上的字节七个一块地到,帧边界随便落在哪 + let mut transcoder = Transcoder::new(); + let mut chat = Vec::new(); + for chunk in converse_stream().chunks(7) { + let sse = transcoder.feed(chunk).unwrap(); + sniffer.feed(&sse); + chat.extend(to_client.process(&sse)); + } + chat.extend(to_client.finish()); + let chat = String::from_utf8(chat).unwrap(); + + let text: String = chat + .lines() + .filter_map(|l| l.strip_prefix("data: ")) + .filter_map(|d| serde_json::from_str::(d).ok()) + .filter_map(|v| { + v["choices"][0]["delta"]["content"] + .as_str() + .map(str::to_string) + }) + .collect(); + assert_eq!(text, "天气晴"); + assert!(chat.contains(r#""finish_reason":"stop""#), "{chat}"); + + // 用量从转出来的 SSE 里就嗅得到,不必等转成客户端格式 + let usage = sniffer.finish().expect("usage"); + assert_eq!((usage.input, usage.cache_read, usage.output), (60, 40, 20)); +} diff --git a/crates/tw-wire/src/usage.rs b/crates/tw-wire/src/usage.rs index 92fde01f..5a0d2f39 100644 --- a/crates/tw-wire/src/usage.rs +++ b/crates/tw-wire/src/usage.rs @@ -7,17 +7,19 @@ //! 所以这里是个**旁路嗅探器**:字节照常流向客户端,同时喂它一份。它只 //! 记那几个数字,内存是有界的。 //! -//! 四种格式、两种模式都要认: +//! 五种格式、两种模式都要认: //! -//! | | Anthropic | OpenAI Chat | OpenAI Responses | Gemini | -//! |---|---|---|---|---| -//! | 非流式 | 末尾一个 `usage` | 同 | 同 | `usageMetadata` | -//! | 流式 | `message_start` 给输入、`message_delta` 给输出 | 末尾一个带 `usage` 的 chunk | `response.completed` 里的 `usage` | 每一帧都带累计的 `usageMetadata` | +//! | | Anthropic | OpenAI Chat | OpenAI Responses | Gemini | Bedrock | +//! |---|---|---|---|---|---| +//! | 非流式 | 末尾一个 `usage` | 同 | 同 | `usageMetadata` | 末尾一个 `usage` | +//! | 流式 | `message_start` 给输入、`message_delta` 给输出 | 末尾一个带 `usage` 的 chunk | `response.completed` 里的 `usage` | 每一帧都带累计的 `usageMetadata` | `metadata` 事件里的 `usage` | +//! +//! Bedrock 的流是二进制帧,要先经 `tw_upstream::eventstream` 转成 SSE 再喂进来。 //! //! 流式那一行决定了实现形状:usage **可能出现在流的任何位置,而且不止 //! 一次**,所以不能只看结尾。 //! -//! **三家对「输入」的定义不一样**:Anthropic 的 `input_tokens` 不含缓存命中; +//! **几家对「输入」的定义不一样**:Anthropic 的 `input_tokens` 和 Bedrock 的 `inputTokens` 不含缓存命中; //! OpenAI(两种格式)和 Gemini 的输入数**包含**缓存命中。不减掉的话,命中缓存的 //! 那部分会按输入价再算一遍。 @@ -153,7 +155,7 @@ impl Sniffer { fn merge(&mut self, v: &Value) { let n = |k: &str| v.get(k).and_then(Value::as_u64).unwrap_or(0); let mut got = false; - // Anthropic 和 OpenAI 各叫各的名字,两套都认 + // Anthropic、OpenAI、Bedrock 各叫各的名字,都认 let mut take = |keys: &[&str], slot: &mut u64| { for k in keys { let x = n(k); @@ -163,13 +165,22 @@ impl Sniffer { } } }; - take(&["input_tokens", "prompt_tokens"], &mut self.seen.input); take( - &["output_tokens", "completion_tokens"], + &["input_tokens", "prompt_tokens", "inputTokens"], + &mut self.seen.input, + ); + take( + &["output_tokens", "completion_tokens", "outputTokens"], &mut self.seen.output, ); - take(&["cache_read_input_tokens"], &mut self.seen.cache_read); - take(&["cache_creation_input_tokens"], &mut self.seen.cache_write); + take( + &["cache_read_input_tokens", "cacheReadInputTokens"], + &mut self.seen.cache_read, + ); + take( + &["cache_creation_input_tokens", "cacheWriteInputTokens"], + &mut self.seen.cache_write, + ); // OpenAI 把缓存读写放在明细里(Chat 叫 `prompt_tokens_details`,Responses // 叫 `input_tokens_details`),**而且它们是输入数的子集** —— 直接相加会 // 重复计费。 @@ -313,6 +324,27 @@ mod tests { assert_eq!((u.input, u.cache_read, u.output), (400, 600, 130)); } + #[test] + fn a_bedrock_response_is_read_by_its_own_names() { + // Converse 用驼峰,而且和 Anthropic 一样:`inputTokens` 不含缓存。 + // 以前一个都不认,Bedrock 的请求全按估算记账 + let whole = r#"{"output":{"message":{"role":"assistant","content":[{"text":"hi"}]}},"stopReason":"end_turn", + "usage":{"inputTokens":60,"outputTokens":20,"cacheReadInputTokens":40,"cacheWriteInputTokens":5,"totalTokens":125}}"#; + let u = sniff(&[whole]).unwrap(); + assert_eq!( + (u.input, u.cache_read, u.cache_write, u.output), + (60, 40, 5, 20) + ); + + // 流:拆帧之后是 `metadata` 事件 + let u = sniff(&[ + "event: messageStop\ndata: {\"stopReason\":\"end_turn\"}\n\n", + "event: metadata\ndata: {\"usage\":{\"inputTokens\":60,\"outputTokens\":20,\"totalTokens\":80},\"metrics\":{\"latencyMs\":300}}\n\n", + ]) + .unwrap(); + assert_eq!((u.input, u.output), (60, 20)); + } + #[test] fn a_needle_cut_between_chunks_still_finds_usage_metadata() { let whole = r#"{"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":5}}"#;