From b87acfc6d6f7e2e454056fb62b40e161266d2669 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 24 Sep 2026 14:11:10 +0800 Subject: [PATCH] fix: bill cached input at cache prices, estimate missing usage, strip carried signatures Cached input was billed at the full input price. The prompt count put cache reads and writes together with plain input, so an Anthropic turn that read 10k tokens from its cache cost as much as sending them fresh, and weighed as much against rate limits and budgets. Models get three optional weights against the input baseline: cache read, cache write, and 1-hour cache write. Unset, they follow the input weight at Anthropic's ratios (0.1x, 1.25x, 2x). Cost and weighted tokens now price each bucket on its own weight. The audit row keeps the whole input in `input_tokens` and gains the cache split in its detail. The admin API and the model editor carry the new weights. A request the upstream reported no usage for was billed as zero tokens. #34 made Chat streams ask for usage, but usage can still be missing: the upstream ignores `stream_options`, or the caller leaves mid-stream and takes the final usage chunk with it. The count is now estimated at about four bytes a token from the request and from the answer that arrived, and the row says `usage_estimated`. A stream cut short keeps the upstream's input count and bills the larger of its running output count and the estimate. No answer at all still bills nothing. A request forwarded as sent now drops the `tw1.` reasoning signatures an earlier conversion wrote, via `tw_dialect::convert::strip_carried`, as the desktop gateway does. Anthropic refuses a whole request over them. Co-Authored-By: Claude Opus 5.5 --- crates/common/src/limits/weight.rs | 184 ++++++++++--- crates/common/src/models/provider.rs | 9 + crates/gateway/src/cost_tracker.rs | 130 ++++++---- crates/gateway/src/lib.rs | 1 + crates/gateway/src/lifecycle/mod.rs | 128 ++++++--- crates/gateway/src/proxy/accounting.rs | 10 +- crates/gateway/src/proxy/generate.rs | 48 +++- crates/gateway/src/proxy/routing.rs | 5 +- crates/gateway/src/usage_estimate.rs | 200 ++++++++++++++ crates/server/src/handlers/models.rs | 78 +++++- .../tests/analytics_clickhouse.rs | 243 ++++++++++++++++++ crates/test-support/tests/console_admin.rs | 73 ++++++ crates/test-support/tests/gateway_proxy.rs | 51 ++++ db/schema.sql | 16 ++ web/src/i18n/en.json | 17 +- web/src/i18n/zh.json | 17 +- .../gateway/models/ModelDetailSheet.tsx | 22 ++ .../gateway/models/ModelEditorDialog.tsx | 41 +++ web/src/routes/gateway/models/types.ts | 36 +++ 19 files changed, 1163 insertions(+), 146 deletions(-) create mode 100644 crates/gateway/src/usage_estimate.rs diff --git a/crates/common/src/limits/weight.rs b/crates/common/src/limits/weight.rs index d6571601..67411571 100644 --- a/crates/common/src/limits/weight.rs +++ b/crates/common/src/limits/weight.rs @@ -1,11 +1,18 @@ // ============================================================================ // Weighted-token converter // -// Maps `(model_id, raw_input_tokens, raw_output_tokens)` to a single -// integer "weighted token" cost using each model's per-direction -// weight from the `models` table. +// Maps a request's token counts to a single integer "weighted token" +// cost using each model's weights from the `models` table. // -// weighted = round(input × input_weight + output × output_weight) +// weighted = round(input × input_weight +// + cache_read × cache_read_weight +// + cache_write × cache_write_weight (or _1h_) +// + output × output_weight) +// +// Input read from or written to the upstream's prompt cache is priced +// apart from plain input: a cache read costs a fraction of it, a write a +// premium. Unset cache weights follow the input weight — see +// `Weights::resolve` for the ratios. // // Used by the gateway hot path to feed `sliding::check_and_record` // (tokens metric) and `budget::add_weighted_tokens`. The weights @@ -30,27 +37,76 @@ use std::collections::HashMap; use std::sync::Arc; use std::time::{Duration, Instant}; +use rust_decimal::Decimal; +use rust_decimal::prelude::ToPrimitive; use sqlx::PgPool; use tokio::sync::RwLock; const CACHE_TTL: Duration = Duration::from_secs(300); const MAX_ENTRIES: usize = 1024; -#[derive(Debug, Clone, Copy)] +/// Cache read, as a share of the input weight, when the model sets none. +/// Anthropic bills a cache read at 0.1× input, as do OpenAI's newest +/// models; older OpenAI models discount less (0.5×, 0.25×), and a model +/// served there should set its own. +pub const CACHE_READ_RATIO: f64 = 0.1; +/// Cache write (5-minute), as a share of the input weight, when unset. +/// Anthropic's 1.25×. OpenAI does not bill writes, and reports none. +pub const CACHE_WRITE_RATIO: f64 = 1.25; +/// Cache write with a 1-hour lifetime, as a share of the input weight, +/// when unset. Anthropic's 2×. +pub const CACHE_WRITE_1H_RATIO: f64 = 2.0; + +/// A model's weights, each against the platform baseline price for its +/// direction: the three cache weights, like the input weight, against +/// the input price. +#[derive(Debug, Clone, Copy, PartialEq)] pub struct Weights { pub input: f64, pub output: f64, + pub cache_read: f64, + pub cache_write: f64, + pub cache_write_1h: f64, } -impl Default for Weights { - fn default() -> Self { +impl Weights { + /// The weights in force, from a `models` row: an unset cache weight + /// is the input weight times its ratio above. + pub fn resolve( + input: f64, + output: f64, + cache_read: Option, + cache_write: Option, + cache_write_1h: Option, + ) -> Self { Self { - input: 1.0, - output: 1.0, + input, + output, + cache_read: cache_read.unwrap_or(input * CACHE_READ_RATIO), + cache_write: cache_write.unwrap_or(input * CACHE_WRITE_RATIO), + cache_write_1h: cache_write_1h.unwrap_or(input * CACHE_WRITE_1H_RATIO), } } } +impl Default for Weights { + fn default() -> Self { + Self::resolve(1.0, 1.0, None, None, None) + } +} + +/// One request's tokens, split the way they are priced. `input` is the +/// input that was neither read from nor written to the prompt cache. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct TokenCounts { + pub input: i64, + pub cache_read: i64, + pub cache_write: i64, + /// The cache writes had a 1-hour lifetime. + pub cache_write_1h: bool, + pub output: i64, +} + #[derive(Clone)] struct CacheEntry { weights: Weights, @@ -91,19 +147,25 @@ impl WeightCache { } // Slow path: query PG, then upsert into the cache. - let weights = match sqlx::query_as::<_, (rust_decimal::Decimal, rust_decimal::Decimal)>( - "SELECT input_weight, output_weight FROM models WHERE model_id = $1", + type Row = ( + Decimal, + Decimal, + Option, + Option, + Option, + ); + let weights = match sqlx::query_as::<_, Row>( + "SELECT input_weight, output_weight, \ + cache_read_weight, cache_write_weight, cache_write_1h_weight \ + FROM models WHERE model_id = $1", ) .bind(model_id) .fetch_optional(pool) .await { - Ok(Some((i, o))) => { - use rust_decimal::prelude::ToPrimitive; - Weights { - input: i.to_f64().unwrap_or(1.0), - output: o.to_f64().unwrap_or(1.0), - } + Ok(Some((i, o, cr, cw, cw1h))) => { + let f = |d: Decimal| d.to_f64().unwrap_or(1.0); + Weights::resolve(f(i), f(o), cr.map(f), cw.map(f), cw1h.map(f)) } Ok(None) => Weights::default(), Err(e) => { @@ -150,47 +212,95 @@ impl WeightCache { /// through. The hot path looks like: /// /// let mult = state.weight_cache.get(&state.db, &request.model).await; -/// let weighted = weighted_tokens(input, output, mult); -pub fn weighted_tokens(input_tokens: i64, output_tokens: i64, mult: Weights) -> i64 { - // Cast to f64 for the multiplication then round back. i64 is - // plenty for any token count (max ~9.2e18). - let w = (input_tokens.max(0) as f64) * mult.input + (output_tokens.max(0) as f64) * mult.output; - w.round().max(0.0) as i64 +/// let weighted = weighted_tokens(&counts, mult); +pub fn weighted_tokens(t: &TokenCounts, w: Weights) -> i64 { + let n = |x: i64| x.max(0) as f64; + let write = if t.cache_write_1h { + w.cache_write_1h + } else { + w.cache_write + }; + // f64 then round back. i64 is plenty for any token count (max ~9.2e18). + let sum = n(t.input) * w.input + + n(t.cache_read) * w.cache_read + + n(t.cache_write) * write + + n(t.output) * w.output; + sum.round().max(0.0) as i64 } #[cfg(test)] mod tests { use super::*; + fn plain(input: i64, output: i64) -> TokenCounts { + TokenCounts { + input, + output, + ..Default::default() + } + } + + fn weights(input: f64, output: f64) -> Weights { + Weights::resolve(input, output, None, None, None) + } + #[test] fn weighted_tokens_default_is_raw_sum() { - let m = Weights::default(); - assert_eq!(weighted_tokens(100, 50, m), 150); + assert_eq!(weighted_tokens(&plain(100, 50), Weights::default()), 150); } #[test] fn weighted_tokens_scales_each_direction() { - let m = Weights { - input: 1.0, - output: 3.0, - }; // 100 input + 50 output × 3 = 100 + 150 = 250 - assert_eq!(weighted_tokens(100, 50, m), 250); + assert_eq!(weighted_tokens(&plain(100, 50), weights(1.0, 3.0)), 250); } #[test] fn weighted_tokens_clamps_negatives() { - let m = Weights::default(); - assert_eq!(weighted_tokens(-1, -1, m), 0); + assert_eq!(weighted_tokens(&plain(-1, -1), Weights::default()), 0); } #[test] fn weighted_tokens_rounds() { - let m = Weights { - input: 1.5, - output: 0.5, - }; // 3 × 1.5 = 4.5 ; 1 × 0.5 = 0.5 ; sum = 5.0 - assert_eq!(weighted_tokens(3, 1, m), 5); + assert_eq!(weighted_tokens(&plain(3, 1), weights(1.5, 0.5)), 5); + } + + #[test] + fn cache_weights_follow_the_input_weight_when_unset() { + let w = weights(2.0, 1.0); + assert_eq!(w.cache_read, 0.2); + assert_eq!(w.cache_write, 2.5); + assert_eq!(w.cache_write_1h, 4.0); + } + + #[test] + fn cache_reads_and_writes_are_weighted_apart_from_plain_input() { + let t = TokenCounts { + input: 100, + cache_read: 1000, + cache_write: 400, + cache_write_1h: false, + output: 10, + }; + // 100 + 1000 × 0.1 + 400 × 1.25 + 10 = 100 + 100 + 500 + 10 + assert_eq!(weighted_tokens(&t, Weights::default()), 710); + let t = TokenCounts { + cache_write_1h: true, + ..t + }; + // 100 + 100 + 400 × 2 + 10 + assert_eq!(weighted_tokens(&t, Weights::default()), 1010); + } + + #[test] + fn a_set_cache_weight_is_used_as_is() { + let w = Weights::resolve(1.0, 1.0, Some(0.5), Some(1.0), None); + let t = TokenCounts { + cache_read: 100, + cache_write: 100, + ..Default::default() + }; + assert_eq!(weighted_tokens(&t, w), 150); } } diff --git a/crates/common/src/models/provider.rs b/crates/common/src/models/provider.rs index d2dd22a7..d2689c00 100644 --- a/crates/common/src/models/provider.rs +++ b/crates/common/src/models/provider.rs @@ -27,6 +27,15 @@ pub struct Model { pub input_weight: Decimal, /// Relative output-token cost factor. pub output_weight: Decimal, + /// Cache-read input, against the input baseline. `None` ⇒ + /// `input_weight × 0.1` (see `limits::weight::Weights::resolve`). + pub cache_read_weight: Option, + /// Cache-write input (5-minute), against the input baseline. + /// `None` ⇒ `input_weight × 1.25`. + pub cache_write_weight: Option, + /// Cache-write input with a 1-hour lifetime. `None` ⇒ + /// `input_weight × 2`. + pub cache_write_1h_weight: Option, /// Per-model routing strategy override. /// `None` ⇒ inherit `gateway.default_routing_strategy`. /// One of `weighted` / `latency` / `health` / `latency_health`. diff --git a/crates/gateway/src/cost_tracker.rs b/crates/gateway/src/cost_tracker.rs index c06d1539..a19084ee 100644 --- a/crates/gateway/src/cost_tracker.rs +++ b/crates/gateway/src/cost_tracker.rs @@ -1,17 +1,21 @@ // ============================================================================ // Cost tracker // -// Translates `(model_id, prompt_tokens, completion_tokens)` into a USD -// cost for the gateway_logs audit trail. +// Translates a request's token counts into a USD cost for the +// gateway_logs audit trail. // -// cost = platform_baseline × model_weight × tokens +// cost = input_price × (input × input_weight +// + cache_read × cache_read_weight +// + cache_write × cache_write_weight) +// + output_price × output × output_weight // // where: -// * `platform_baseline` = `(input_price_per_token, output_price_per_token)` -// from the `platform_pricing` singleton table. -// * `model_weight` = per-model `(input_weight, output_weight)` from -// the `models` row (reused from the limits `WeightCache` so we -// don't double-query or double-cache). +// * `input_price` / `output_price` = `(input_price_per_token, +// output_price_per_token)` from the `platform_pricing` singleton. +// * the weights come from the `models` row (reused from the limits +// `WeightCache` so we don't double-query or double-cache). Unset +// cache weights follow the input weight; see `Weights::resolve`. +// A 1-hour cache write uses `cache_write_1h_weight`. // // The tracker owns a read-through cache of the platform baseline with a // 60-second TTL. Admins change it rarely, and a 60s lag on a brand-new @@ -30,7 +34,7 @@ use rust_decimal::Decimal; use sqlx::PgPool; use tokio::sync::RwLock; -use think_watch_common::limits::weight::WeightCache; +use think_watch_common::limits::weight::{TokenCounts, WeightCache, Weights}; /// Platform-wide per-token prices in USD as `Decimal` so the cost /// math stays precision-preserving end-to-end — stored as-is in the @@ -69,18 +73,21 @@ fn fallback_output() -> Decimal { /// than as an `impl` method because it has no state — keeping it free /// also lets the tests call it without constructing a tracker. fn compute_cost( - input_tokens: u32, - output_tokens: u32, + t: &TokenCounts, input_per_token: Decimal, output_per_token: Decimal, - w_input: f64, - w_output: f64, + w: Weights, ) -> Decimal { - let w_input = Decimal::try_from(w_input).unwrap_or(Decimal::ONE); - let w_output = Decimal::try_from(w_output).unwrap_or(Decimal::ONE); - let input_cost = Decimal::from(input_tokens) * input_per_token * w_input; - let output_cost = Decimal::from(output_tokens) * output_per_token * w_output; - input_cost + output_cost + let d = |x: f64| Decimal::try_from(x).unwrap_or(Decimal::ONE); + let n = |x: i64| Decimal::from(x.max(0)); + let write = if t.cache_write_1h { + w.cache_write_1h + } else { + w.cache_write + }; + let input_units = + n(t.input) * d(w.input) + n(t.cache_read) * d(w.cache_read) + n(t.cache_write) * d(write); + input_units * input_per_token + n(t.output) * d(w.output) * output_per_token } pub struct CostTracker { @@ -107,21 +114,14 @@ impl CostTracker { /// lift it to `Decimal` for the money multiply. Precision loss /// at the weight boundary is ~15 sig-figs which is ample for the /// 0.1–10× range weights actually live in. - pub async fn calculate_cost( - &self, - model: &str, - input_tokens: u32, - output_tokens: u32, - ) -> Decimal { + pub async fn calculate_cost(&self, model: &str, tokens: &TokenCounts) -> Decimal { let baseline = self.baseline_value().await; let w = self.weight_cache.get(&self.pool, model).await; compute_cost( - input_tokens, - output_tokens, + tokens, baseline.input_per_token, baseline.output_per_token, - w.input, - w.output, + w, ) } @@ -171,59 +171,87 @@ mod tests { Decimal::from_str(s).unwrap() } + fn plain(input: i64, output: i64) -> TokenCounts { + TokenCounts { + input, + output, + ..Default::default() + } + } + + fn w(input: f64, output: f64) -> Weights { + Weights::resolve(input, output, None, None, None) + } + #[test] fn cost_is_sum_of_input_and_output_legs() { // 1000 in * 0.000002 * 1.0 + 500 out * 0.000008 * 1.0 // = 0.002 + 0.004 = 0.006 - let cost = compute_cost(1000, 500, d("0.000002"), d("0.000008"), 1.0, 1.0); + let cost = compute_cost(&plain(1000, 500), d("0.000002"), d("0.000008"), w(1.0, 1.0)); assert_eq!(cost, d("0.006")); } #[test] fn zero_tokens_yields_zero_cost() { - let cost = compute_cost(0, 0, d("0.000002"), d("0.000008"), 1.0, 1.0); + let cost = compute_cost(&plain(0, 0), d("0.000002"), d("0.000008"), w(1.0, 1.0)); assert_eq!(cost, Decimal::ZERO); } #[test] fn weights_scale_each_leg_independently() { // Halving the input weight halves only the input leg. - let baseline_cost = compute_cost(1000, 1000, d("0.000001"), d("0.000001"), 1.0, 1.0); - let halved_input = compute_cost(1000, 1000, d("0.000001"), d("0.000001"), 0.5, 1.0); + let t = plain(1000, 1000); + let baseline_cost = compute_cost(&t, d("0.000001"), d("0.000001"), w(1.0, 1.0)); + let halved_input = compute_cost(&t, d("0.000001"), d("0.000001"), w(0.5, 1.0)); // baseline = 0.001 + 0.001 = 0.002; halved = 0.0005 + 0.001 = 0.0015 assert_eq!(baseline_cost, d("0.002")); assert_eq!(halved_input, d("0.0015")); } - #[test] - fn output_more_expensive_than_input_reflects_in_cost() { - // 1000 in @ 1e-6 + 1000 out @ 5e-6 = 0.001 + 0.005 = 0.006 - let cost = compute_cost(1000, 1000, d("0.000001"), d("0.000005"), 1.0, 1.0); - assert_eq!(cost, d("0.006")); - } - #[test] fn nan_weight_falls_back_to_one_not_panic() { // f64::NAN doesn't convert to Decimal; the fallback keeps the // request from blowing up at the cost-log boundary. - let cost = compute_cost(1000, 0, d("0.000002"), d("0.000008"), f64::NAN, 1.0); - // Falls back to 1.0 → 1000 * 0.000002 * 1.0 = 0.002. + let weights = Weights { + input: f64::NAN, + ..w(1.0, 1.0) + }; + let cost = compute_cost(&plain(1000, 0), d("0.000002"), d("0.000008"), weights); assert_eq!(cost, d("0.002")); } - #[test] - fn negative_weight_is_representable_and_yields_negative_cost() { - // -1.0 IS representable as Decimal, so this DOES become negative. - // Lock that in so we notice if a future refactor changes the - // contract (e.g. by clamping at the boundary instead). - let cost = compute_cost(1000, 0, d("0.000002"), d("0.000008"), -1.0, 1.0); - assert_eq!(cost, d("-0.002")); - } - #[test] fn fractional_weight_preserves_full_precision() { // 1.25 scales 100 tokens @ 0.0001 to 0.0125 - let cost = compute_cost(100, 0, d("0.0001"), d("0.0001"), 1.25, 1.0); + let cost = compute_cost(&plain(100, 0), d("0.0001"), d("0.0001"), w(1.25, 1.0)); assert_eq!(cost, d("0.0125")); } + + #[test] + fn cached_input_is_priced_apart_from_plain_input() { + // Anthropic-shaped: 100 fresh, 10 000 read from cache, 2 000 written. + let t = TokenCounts { + input: 100, + cache_read: 10_000, + cache_write: 2_000, + cache_write_1h: false, + output: 0, + }; + // 0.000003 × (100 + 10 000 × 0.1 + 2 000 × 1.25) = 0.000003 × 3 600 + let cost = compute_cost(&t, d("0.000003"), d("0.000015"), w(1.0, 1.0)); + assert_eq!(cost, d("0.0108")); + // At the full input price it would have been 0.000003 × 12 100. + assert!(cost < d("0.0363")); + } + + #[test] + fn a_one_hour_cache_write_costs_twice_the_input_price_by_default() { + let t = TokenCounts { + cache_write: 1_000, + cache_write_1h: true, + ..Default::default() + }; + let cost = compute_cost(&t, d("0.000003"), d("0.000015"), w(1.0, 1.0)); + assert_eq!(cost, d("0.006")); + } } diff --git a/crates/gateway/src/lib.rs b/crates/gateway/src/lib.rs index f006249e..b8249123 100644 --- a/crates/gateway/src/lib.rs +++ b/crates/gateway/src/lib.rs @@ -16,3 +16,4 @@ pub mod rate_limiter; pub mod router; pub mod strategy; pub mod tool_inspection; +pub mod usage_estimate; diff --git a/crates/gateway/src/lifecycle/mod.rs b/crates/gateway/src/lifecycle/mod.rs index 6d470b92..c630c001 100644 --- a/crates/gateway/src/lifecycle/mod.rs +++ b/crates/gateway/src/lifecycle/mod.rs @@ -32,7 +32,7 @@ use tw_dialect::ir::Dialect; use tw_types::GatewayError; use crate::pii_redactor::PiiRedactor; -use crate::proxy::generate::{Wire, tokens}; +use crate::proxy::generate::{Wire, priced, tokens}; use crate::proxy::shaper::{StreamShaper, rewrite_model}; use crate::proxy::{ GatewayRequestIdentity, GatewayState, SelectionRecord, emit_gateway_log_with_extra, @@ -52,8 +52,11 @@ pub struct Completed { /// still in place — this is also the form the cache stores, so a /// later caller can paint in their own values. pub body: Vec, - /// Read off the upstream's bytes, whatever format they were in. - pub usage: Option, + /// Read off the upstream's bytes, whatever format they were in, or + /// estimated when they carried none. + pub usage: tw_wire::Usage, + /// `usage` is at least partly an estimate (see `crate::usage_estimate`). + pub usage_estimated: bool, } /// Either the upstream's answer or a short-circuit from a pipeline stage. @@ -65,8 +68,11 @@ pub enum ChatCompletionOutcome { /// What a finished stream leaves behind for the hooks. Computed once in /// the pump's tail so the hooks read it rather than each recomputing. pub struct ChatStreamCaptured { - pub prompt_tokens: u32, - pub completion_tokens: u32, + /// What the upstream reported, completed by an estimate where it + /// reported nothing or was cut short. Zero when no answer came. + pub usage: tw_wire::Usage, + /// `usage` is at least partly an estimate. + pub usage_estimated: bool, pub cost_usd: Decimal, /// The stream assembled into a whole answer, for the cache and the /// audit row. `None` when it produced nothing or could not be @@ -94,6 +100,9 @@ pub(crate) struct ChatRequestSnapshot { /// request must not be cached. pub cache_fingerprint: Option>, pub request_started_at: std::time::Instant, + /// The request's input in tokens, estimated — billed only when the + /// upstream reports no usage. + pub input_estimate: u64, } /// Pre-flight rule + cap lists, reused by the post-flight debit. @@ -314,6 +323,7 @@ pub(crate) fn build_chat_pump( let trace_id = request.trace_id.clone(); let started_at = request.request_started_at; let mapped_model = request.mapped_model.clone(); + let input_estimate = request.input_estimate; let tail = Box::pin(async move { let outcome = done_rx.await.unwrap_or(StreamOutcome::ClientCancelled); @@ -323,21 +333,41 @@ pub(crate) fn build_chat_pump( ) .increment(1); - let (usage, assembled) = match readers_for_tail.lock() { - Ok(mut r) => ( - r.sniffer.take().and_then(|s| s.finish()), - r.collector.take().and_then(|c| c.finish().ok()), - ), - Err(_) => (None, None), + // The sniffer exists once the upstream answered. Without an + // answer there is nothing to bill. + let (answered, reported, assembled) = match readers_for_tail.lock() { + Ok(mut r) => { + let sniffer = r.sniffer.take(); + ( + sniffer.is_some(), + sniffer.and_then(|s| s.finish()), + r.collector.take().and_then(|c| c.finish().ok()), + ) + } + Err(_) => (false, None, None), + }; + // A stream that did not run to its end lost the upstream's final + // count with it: the caller left, or the upstream broke off. + let (usage, usage_estimated) = if answered { + crate::usage_estimate::complete( + reported, + outcome.is_natural(), + input_estimate, + assembled.as_deref(), + ) + } else { + (tw_wire::Usage::default(), false) }; - let (prompt_tokens, completion_tokens) = usage.as_ref().map(tokens).unwrap_or((0, 0)); + if usage_estimated { + metrics::counter!("gateway_usage_estimated_total").increment(1); + } let cost_usd = deps_state .cost_tracker - .calculate_cost(&mapped_model, prompt_tokens, completion_tokens) + .calculate_cost(&mapped_model, &priced(&usage)) .await; let captured = ChatStreamCaptured { - prompt_tokens, - completion_tokens, + usage, + usage_estimated, cost_usd, // A cache hit hands this back to a caller, so it carries the // caller's model name like everything else they receive. @@ -492,7 +522,7 @@ impl Surface for ChatCompletionSurface { // A stream reaches here only on a natural end — the stage gate // already filtered the rest — and its assembled form is exactly // what a whole answer would have stored. - let (prompt_tokens, completion_tokens) = extract_usage_tokens(&invoked.view); + let (prompt_tokens, completion_tokens) = tokens(&extract_usage(&invoked.view)); let body = match &invoked.view { CapturedView::Buffered(ChatCompletionOutcome::Success(c)) => Some(&c.body), CapturedView::Streaming { captured, .. } => captured.assembled.as_ref(), @@ -509,15 +539,13 @@ impl Surface for ChatCompletionSurface { } async fn record_usage(deps: &Self::PostInvokeDeps, invoked: &Invoked) { - let (prompt_tokens, completion_tokens) = extract_usage_tokens(&invoked.view); post_flight_account( deps.state.db.clone(), deps.state.redis.clone(), deps.state.dynamic_config.clone(), deps.state.weight_cache.clone(), deps.request.mapped_model.clone(), - prompt_tokens, - completion_tokens, + priced(&extract_usage(&invoked.view)), deps.preflight.request_rules.clone(), deps.preflight.budget_caps.clone(), deps.request.identity.user_id.clone(), @@ -530,7 +558,8 @@ impl Surface for ChatCompletionSurface { } async fn emit_audit(deps: &Self::PostInvokeDeps, invoked: &Invoked) { - let (prompt_tokens, completion_tokens) = extract_usage_tokens(&invoked.view); + let usage = extract_usage(&invoked.view); + let (prompt_tokens, completion_tokens) = tokens(&usage); let (response_body, cost, logged_status, error_detail) = match &invoked.view { CapturedView::Streaming { outcome, captured } => { let (status, detail) = outcome.logged_status_and_detail(); @@ -545,7 +574,7 @@ impl Surface for ChatCompletionSurface { let cost = deps .state .cost_tracker - .calculate_cost(&deps.request.mapped_model, prompt_tokens, completion_tokens) + .calculate_cost(&deps.request.mapped_model, &priced(&usage)) .await; (Some(c.body.as_slice()), cost, 200_i64, None) } @@ -585,23 +614,56 @@ impl Surface for ChatCompletionSurface { cost, deps.request.request_started_at.elapsed().as_millis() as i64, logged_status, - error_detail, + with_usage_detail(error_detail, &usage, usage_estimated(&invoked.view)), body_capture, ); } } -/// `(prompt, completion)` from a captured view — shared by -/// `record_usage` and `emit_audit` so the budget and the audit row can -/// never disagree. -fn extract_usage_tokens(view: &CapturedView) -> (u32, u32) { - match view { - CapturedView::Streaming { captured, .. } => { - (captured.prompt_tokens, captured.completion_tokens) - } - CapturedView::Buffered(ChatCompletionOutcome::Success(c)) => { - c.usage.as_ref().map(tokens).unwrap_or((0, 0)) +/// The audit detail, with how the input splits over the prompt cache and +/// whether the count is an estimate — `input_tokens` on the row is the +/// whole input, and the cost depends on the split. +fn with_usage_detail( + detail: Option, + usage: &tw_wire::Usage, + estimated: bool, +) -> Option { + let mut extra = serde_json::Map::new(); + if usage.cache_read > 0 { + extra.insert("cache_read_tokens".into(), usage.cache_read.into()); + } + if usage.cache_write > 0 { + extra.insert("cache_write_tokens".into(), usage.cache_write.into()); + if usage.cache_1h { + extra.insert("cache_write_1h".into(), true.into()); } - CapturedView::Buffered(ChatCompletionOutcome::ShortCircuit(_)) => (0, 0), + } + if estimated { + extra.insert("usage_estimated".into(), true.into()); + } + if extra.is_empty() { + return detail; + } + if let Some(serde_json::Value::Object(d)) = detail { + extra.extend(d); + } + Some(serde_json::Value::Object(extra)) +} + +/// The usage a captured view bills — shared by `record_usage` and +/// `emit_audit` so the budget and the audit row can never disagree. +fn extract_usage(view: &CapturedView) -> tw_wire::Usage { + match view { + CapturedView::Streaming { captured, .. } => captured.usage, + CapturedView::Buffered(ChatCompletionOutcome::Success(c)) => c.usage, + CapturedView::Buffered(ChatCompletionOutcome::ShortCircuit(_)) => tw_wire::Usage::default(), + } +} + +fn usage_estimated(view: &CapturedView) -> bool { + match view { + CapturedView::Streaming { captured, .. } => captured.usage_estimated, + CapturedView::Buffered(ChatCompletionOutcome::Success(c)) => c.usage_estimated, + CapturedView::Buffered(ChatCompletionOutcome::ShortCircuit(_)) => false, } } diff --git a/crates/gateway/src/proxy/accounting.rs b/crates/gateway/src/proxy/accounting.rs index 89e98f62..770372be 100644 --- a/crates/gateway/src/proxy/accounting.rs +++ b/crates/gateway/src/proxy/accounting.rs @@ -1,8 +1,9 @@ //! Post-flight accounting + token resolution for streaming responses. //! //! [`post_flight_account`] runs the token-metric sliding rules and -//! budget caps against the real prompt/completion token counts the -//! upstream returned. Used from BOTH the non-streaming branch (called +//! budget caps against the token counts the upstream returned — or the +//! estimate, when it returned none — with cache reads and writes +//! weighted apart from plain input. Used from BOTH the non-streaming branch (called //! inline after the upstream future resolves) and the streaming branch //! (called from the post-invoke pipeline after the SSE stream is //! drained). @@ -25,8 +26,7 @@ pub(crate) async fn post_flight_account( _dynamic_config: Arc, weight_cache: weight::WeightCache, model: String, - prompt_tokens: u32, - completion_tokens: u32, + tokens: weight::TokenCounts, request_rules: Vec, budget_caps: Vec, // Actor attribution for `budget.threshold_crossed` audit entries. @@ -43,7 +43,7 @@ pub(crate) async fn post_flight_account( audit: think_watch_common::audit::AuditLogger, ) { let mult = weight_cache.get(&db, &model).await; - let weighted = weight::weighted_tokens(prompt_tokens as i64, completion_tokens as i64, mult); + let weighted = weight::weighted_tokens(&tokens, mult); if weighted <= 0 { return; } diff --git a/crates/gateway/src/proxy/generate.rs b/crates/gateway/src/proxy/generate.rs index efdf38e3..ed0463d0 100644 --- a/crates/gateway/src/proxy/generate.rs +++ b/crates/gateway/src/proxy/generate.rs @@ -57,6 +57,7 @@ use crate::protocol::UpstreamProtocol; use crate::router::RouteEntry; use think_watch_common::audit::BodyCaptureStatus; +use think_watch_common::limits::weight::TokenCounts; /// What a client-facing endpoint speaks. #[derive(Clone, Copy)] @@ -134,6 +135,9 @@ pub(crate) struct Outbound { /// converted request leaves them behind; they mean nothing in /// another format. pub dialect_headers: Vec<(String, String)>, + /// The request's input in tokens, estimated — billed only when the + /// upstream does not report its own (see `crate::usage_estimate`). + pub input_estimate: u64, } /// The request as it goes out to one upstream, and what it takes to read @@ -201,8 +205,16 @@ impl Outbound { } } let collect = decode(&body)?.encode(&target(client)).session; + let mut bytes = serde_json::to_vec(&body).unwrap_or_default(); + // Reasoning signatures a conversion wrote earlier in this + // conversation (`tw1.`-prefixed) were not issued by this + // upstream, and Anthropic refuses the whole request over + // them. That reasoning did not come from here anyway. + if let Some(stripped) = tw_dialect::convert::strip_carried(client, &bytes) { + bytes = stripped; + } return Ok(Wire { - body: serde_json::to_vec(&body).unwrap_or_default(), + body: bytes, path: self.surface.path.to_string(), query: None, dialect: client, @@ -306,10 +318,14 @@ pub(crate) async fn send( } /// Read a whole answer and put it in the caller's format. +/// +/// When the upstream reports no usage, the count is estimated from the +/// request (`input_estimate`) and the answer. pub(crate) async fn read_whole( resp: reqwest::Response, wire: &Wire, caller_model: &str, + input_estimate: u64, ) -> Result { let upstream = resp .bytes() @@ -318,7 +334,11 @@ pub(crate) async fn read_whole( let mut sniffer = tw_wire::Sniffer::new(); sniffer.feed(&upstream); - let usage = sniffer.finish(); + let (usage, usage_estimated) = + crate::usage_estimate::complete(sniffer.finish(), true, input_estimate, Some(&upstream)); + if usage_estimated { + metrics::counter!("gateway_usage_estimated_total").increment(1); + } let body = match &wire.convert { Some(session) => session.response(&upstream).ok_or_else(|| { @@ -331,6 +351,7 @@ pub(crate) async fn read_whole( Ok(Completed { body: rewrite_model(&body, caller_model), usage, + usage_estimated, }) } @@ -581,11 +602,13 @@ async fn generate( ))) })?; + let input_estimate = crate::usage_estimate::request_tokens(&decoded.request); let outbound = Outbound { surface, body: redacted, stream: is_stream, dialect_headers: dialect_headers(&headers), + input_estimate, }; let snapshot = |route: &RouteEntry, sel_record| crate::lifecycle::ChatPostInvokeDeps { state: state.clone(), @@ -598,6 +621,7 @@ async fn generate( request_for_audit: request_for_audit.clone(), cache_fingerprint: cache_fingerprint.clone(), request_started_at, + input_estimate, }, preflight: crate::lifecycle::ChatPreflightLists { request_rules: preflight.request_rules.clone(), @@ -717,11 +741,8 @@ async fn generate( let deps = snapshot(entry, sel_record); let completed = run_buffered_post_invoke(&deps, completed).await; - let total = completed - .usage - .map(|u| tokens(&u)) - .map(|(p, c)| p + c) - .unwrap_or(0); + let (prompt, completion) = tokens(&completed.usage); + let total = prompt + completion; if total > 0 && let Err(e) = state.quota.consume("a_key, total).await { @@ -763,6 +784,19 @@ pub(crate) fn tokens(u: &tw_wire::Usage) -> (u32, u32) { ) } +/// The same usage split the way it is priced: cache reads and writes +/// apart from plain input (see `cost_tracker`). +pub(crate) fn priced(u: &tw_wire::Usage) -> TokenCounts { + let n = |x: u64| i64::try_from(x).unwrap_or(i64::MAX); + TokenCounts { + input: n(u.input), + cache_read: n(u.cache_read), + cache_write: n(u.cache_write), + cache_write_1h: u.cache_1h, + output: n(u.output), + } +} + /// The caller's `anthropic-*` headers, to go with a request forwarded in /// its own format. fn dialect_headers(headers: &HeaderMap) -> Vec<(String, String)> { diff --git a/crates/gateway/src/proxy/routing.rs b/crates/gateway/src/proxy/routing.rs index 277ac1f8..206a4244 100644 --- a/crates/gateway/src/proxy/routing.rs +++ b/crates/gateway/src/proxy/routing.rs @@ -341,7 +341,10 @@ pub(super) async fn select_route_with_failover<'a>( match super::generate::send(entry, outbound, call_ctx, &ctx.state.db, upstream_model) .await { - Ok((resp, wire)) => super::generate::read_whole(resp, &wire, caller_model).await, + Ok((resp, wire)) => { + super::generate::read_whole(resp, &wire, caller_model, outbound.input_estimate) + .await + } Err(e) => Err(e), }; diff --git a/crates/gateway/src/usage_estimate.rs b/crates/gateway/src/usage_estimate.rs new file mode 100644 index 00000000..53ccf728 --- /dev/null +++ b/crates/gateway/src/usage_estimate.rs @@ -0,0 +1,200 @@ +//! Token counts for a request the upstream did not report usage for. +//! +//! The upstream's own usage is the truth, and it is what gets billed +//! whenever it arrives. It does not always arrive: a caller that leaves +//! mid-stream takes the upstream's final usage chunk with it, and some +//! upstreams never send one. Billing such a request as zero tokens would +//! make it free — no cost, no budget debit, no rate-limit weight — so the +//! count is estimated instead, and the audit row says so +//! (`usage_estimated`). +//! +//! The estimate is about four bytes of text per token. It leans high for +//! most text, which is the side to err on for limits and budgets. Images +//! and files are not counted: their base64 would turn one screenshot into +//! hundreds of thousands of "tokens". + +use serde_json::Value; +use tw_dialect::ir::{Part, Request, ToolInput, ToolKind}; + +const BYTES_PER_TOKEN: u64 = 4; + +/// The input a request carries, in tokens. +pub fn request_tokens(r: &Request) -> u64 { + let mut bytes: usize = r.system.iter().map(String::len).sum(); + for part in r.messages.iter().flat_map(|m| &m.parts) { + bytes += part_len(part); + } + for tool in &r.tools { + bytes += tool.name.len() + tool.description.as_ref().map_or(0, String::len); + if let ToolKind::Function { schema, .. } = &tool.kind { + bytes += schema.to_string().len(); + } + } + to_tokens(bytes) +} + +fn part_len(part: &Part) -> usize { + match part { + Part::Text(t) => t.len(), + Part::Thinking(t) => t.text.len(), + Part::ToolCall(c) => { + c.name.len() + + match &c.input { + ToolInput::Json(v) => v.to_string().len(), + ToolInput::Text(t) => t.len(), + } + } + Part::ToolResult(t) => t.text().len(), + Part::Image(_) | Part::File { .. } => 0, + } +} + +/// The output a whole answer carries, in tokens — whatever its format. +/// +/// Every string in the answer counts except the bookkeeping around the +/// text: ids, names of things, and reasoning signatures, which are opaque +/// blobs rather than generated text. +pub fn answer_tokens(body: &[u8]) -> u64 { + let Ok(v) = serde_json::from_slice::(body) else { + return to_tokens(body.len()); + }; + to_tokens(text_len(&v)) +} + +fn text_len(v: &Value) -> usize { + const NOT_TEXT: &[&str] = &[ + "id", + "model", + "object", + "type", + "role", + "status", + "finish_reason", + "stop_reason", + "system_fingerprint", + "service_tier", + "call_id", + "tool_call_id", + "signature", + "encrypted_content", + ]; + match v { + Value::String(s) => s.len(), + Value::Array(a) => a.iter().map(text_len).sum(), + Value::Object(o) => o + .iter() + .filter(|(k, _)| !NOT_TEXT.contains(&k.as_str())) + .map(|(_, v)| text_len(v)) + .sum(), + _ => 0, + } +} + +fn to_tokens(bytes: usize) -> u64 { + (bytes as u64).div_ceil(BYTES_PER_TOKEN) +} + +/// Fill in what the upstream did not report. +/// +/// `reported` is what was read off the upstream's bytes, if anything. +/// `finished` says whether the answer ran to its end: an upstream reports +/// its output count at the end, so one that was cut short has at most a +/// running count, and the text that did arrive is the better measure. +/// +/// Returns the usage to bill and whether any of it is an estimate. +pub fn complete( + reported: Option, + finished: bool, + input_estimate: u64, + answer: Option<&[u8]>, +) -> (tw_wire::Usage, bool) { + let output_estimate = || answer.map(answer_tokens).unwrap_or(0); + match reported { + Some(mut u) => { + let mut estimated = false; + if u.input + u.cache_read + u.cache_write == 0 && input_estimate > 0 { + u.input = input_estimate; + estimated = true; + } + if !finished { + let out = output_estimate(); + if out > u.output { + u.output = out; + estimated = true; + } + } + (u, estimated) + } + None => ( + tw_wire::Usage { + input: input_estimate, + output: output_estimate(), + ..Default::default() + }, + true, + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn an_answer_counts_its_text_and_not_its_bookkeeping() { + let body = json!({ + "id": "chatcmpl-a-very-long-identifier-that-is-not-text", + "model": "gpt-4o-2024-08-06", + "choices": [{"index": 0, "message": {"role": "assistant", "content": "12345678"}}], + }); + assert_eq!(answer_tokens(body.to_string().as_bytes()), 2); + } + + #[test] + fn a_reasoning_signature_is_not_output() { + let body = json!({ + "content": [ + {"type": "thinking", "thinking": "abcd", "signature": "x".repeat(4000)}, + {"type": "text", "text": "efgh"}, + ], + }); + assert_eq!(answer_tokens(body.to_string().as_bytes()), 2); + } + + #[test] + fn nothing_reported_is_estimated_whole() { + let answer = json!({"choices": [{"message": {"content": "x".repeat(40)}}]}).to_string(); + let (u, estimated) = complete(None, true, 100, Some(answer.as_bytes())); + assert!(estimated); + assert_eq!((u.input, u.output), (100, 10)); + } + + #[test] + fn a_finished_answer_keeps_what_the_upstream_reported() { + let reported = tw_wire::Usage { + input: 7, + output: 3, + ..Default::default() + }; + let answer = json!({"text": "x".repeat(400)}).to_string(); + let (u, estimated) = complete(Some(reported), true, 100, Some(answer.as_bytes())); + assert!(!estimated); + assert_eq!(u, reported); + } + + #[test] + fn a_cut_short_answer_bills_the_text_that_arrived() { + // Anthropic reports input at the start and a running output + // count; a stream cut off after it has only the first count. + let reported = tw_wire::Usage { + input: 7, + output: 1, + ..Default::default() + }; + let answer = json!({"text": "x".repeat(400)}).to_string(); + let (u, estimated) = complete(Some(reported), false, 100, Some(answer.as_bytes())); + assert!(estimated); + assert_eq!((u.input, u.output), (7, 100)); + } +} diff --git a/crates/server/src/handlers/models.rs b/crates/server/src/handlers/models.rs index 2efc8d7a..e1889ca0 100644 --- a/crates/server/src/handlers/models.rs +++ b/crates/server/src/handlers/models.rs @@ -4,7 +4,8 @@ // Manages rows in the `models` table — the exposed catalog clients see // via `/v1/models`. Each row carries `input_weight` / `output_weight` // (relative factors against `platform_pricing` for cost reporting + -// weighted-token quota accounting). Routing to providers is handled by +// weighted-token quota accounting), and optional cache-read / cache-write +// weights that default from the input weight. Routing to providers is handled by // the `model_routes` table. // // Permissions: `models:read` for GET, `models:write` for POST/PATCH/DELETE. @@ -37,6 +38,13 @@ pub struct ModelRow { pub input_weight: Decimal, #[schema(value_type = f64)] pub output_weight: Decimal, + /// Cache weights as stored. `None` ⇒ derived from `input_weight`. + #[schema(value_type = Option)] + pub cache_read_weight: Option, + #[schema(value_type = Option)] + pub cache_write_weight: Option, + #[schema(value_type = Option)] + pub cache_write_1h_weight: Option, pub route_count: i64, pub enabled_route_count: i64, /// Model-level kill switch. FALSE ⇒ all routes are skipped at @@ -149,6 +157,7 @@ pub async fn list_models( let list_sql = format!( r#"SELECT m.id, m.model_id, m.display_name, m.input_weight, m.output_weight, + m.cache_read_weight, m.cache_write_weight, m.cache_write_1h_weight, COALESCE(rc.route_count, 0) AS route_count, COALESCE(rc.enabled_route_count, 0) AS enabled_route_count, m.enabled, @@ -200,6 +209,18 @@ pub struct CreateModelRequest { /// Relative output-token cost factor. Defaults to 1.0. #[schema(value_type = Option)] pub output_weight: Option, + /// Cache-read input weight. Unset ⇒ `input_weight × 0.1`. + #[serde(default)] + #[schema(value_type = Option)] + pub cache_read_weight: Option, + /// Cache-write input weight (5-minute). Unset ⇒ `input_weight × 1.25`. + #[serde(default)] + #[schema(value_type = Option)] + pub cache_write_weight: Option, + /// Cache-write input weight (1-hour). Unset ⇒ `input_weight × 2`. + #[serde(default)] + #[schema(value_type = Option)] + pub cache_write_1h_weight: Option, /// Override the gateway-wide default routing strategy. NULL ⇒ /// inherit. One of weighted/latency/health/latency_health. #[serde(default)] @@ -254,6 +275,12 @@ pub async fn create_model( "weights must be greater than zero".into(), )); } + let cache = [ + req.cache_read_weight, + req.cache_write_weight, + req.cache_write_1h_weight, + ]; + validate_cache_weights(&cache)?; validate_routing_overrides( req.routing_strategy.as_deref(), req.affinity_mode.as_deref(), @@ -268,9 +295,11 @@ pub async fn create_model( r#"INSERT INTO models (model_id, display_name, input_weight, output_weight, routing_strategy, affinity_mode, affinity_ttl_secs, tags, - output_guardrails) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + output_guardrails, + cache_read_weight, cache_write_weight, cache_write_1h_weight) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING id, model_id, display_name, input_weight, output_weight, + cache_read_weight, cache_write_weight, cache_write_1h_weight, routing_strategy, affinity_mode, affinity_ttl_secs, tags, enabled, output_guardrails"#, ) @@ -283,6 +312,9 @@ pub async fn create_model( .bind(req.affinity_ttl_secs) .bind(req.tags.as_deref()) .bind(&guardrails_json) + .bind(cache[0]) + .bind(cache[1]) + .bind(cache[2]) .fetch_one(&state.db) .await?; @@ -310,6 +342,17 @@ pub struct UpdateModelRequest { pub input_weight: Option, #[schema(value_type = Option)] pub output_weight: Option, + /// PATCH-clearable cache weights: absent = unchanged, JSON `null` = + /// clear (derive from `input_weight` again), number = set. + #[serde(default, deserialize_with = "deserialize_some")] + #[schema(value_type = Option)] + pub cache_read_weight: Option>, + #[serde(default, deserialize_with = "deserialize_some")] + #[schema(value_type = Option)] + pub cache_write_weight: Option>, + #[serde(default, deserialize_with = "deserialize_some")] + #[schema(value_type = Option)] + pub cache_write_1h_weight: Option>, /// PATCH semantics: absent = unchanged, JSON `null` = clear (revert /// to global default), string = override. #[serde(default, deserialize_with = "deserialize_some")] @@ -356,6 +399,17 @@ pub(crate) fn validate_output_guardrails(rules: &[OutputGuardrail]) -> Result<() Ok(()) } +/// Cache weights may be zero (an upstream that does not bill cache +/// reads) but not negative — the column's CHECK, as a useful 400. +fn validate_cache_weights(weights: &[Option]) -> Result<(), AppError> { + if weights.iter().flatten().any(|w| *w < Decimal::ZERO) { + return Err(AppError::BadRequest( + "cache weights must not be negative".into(), + )); + } + Ok(()) +} + /// Validate routing-strategy override values mirror the CHECK /// constraints on `models`. Both create + update use this to give a /// 400 with a useful message instead of letting the SQL CHECK fail. @@ -415,6 +469,7 @@ pub async fn update_model( .await?; let existing = sqlx::query_as::<_, Model>( r#"SELECT id, model_id, display_name, input_weight, output_weight, + cache_read_weight, cache_write_weight, cache_write_1h_weight, routing_strategy, affinity_mode, affinity_ttl_secs, tags, enabled, output_guardrails FROM models WHERE id = $1"#, @@ -433,6 +488,14 @@ pub async fn update_model( } // Resolve PATCH semantics for the nullable overrides: // absent ⇒ preserve existing; Some(None) ⇒ clear; Some(Some(v)) ⇒ overwrite. + let cache = [ + req.cache_read_weight.unwrap_or(existing.cache_read_weight), + req.cache_write_weight + .unwrap_or(existing.cache_write_weight), + req.cache_write_1h_weight + .unwrap_or(existing.cache_write_1h_weight), + ]; + validate_cache_weights(&cache)?; let new_strategy: Option = match &req.routing_strategy { None => existing.routing_strategy.clone(), Some(inner) => inner.clone(), @@ -477,9 +540,13 @@ pub async fn update_model( affinity_ttl_secs = $7, tags = $8, enabled = $9, - output_guardrails = $10 + output_guardrails = $10, + cache_read_weight = $11, + cache_write_weight = $12, + cache_write_1h_weight = $13 WHERE id = $1 RETURNING id, model_id, display_name, input_weight, output_weight, + cache_read_weight, cache_write_weight, cache_write_1h_weight, routing_strategy, affinity_mode, affinity_ttl_secs, tags, enabled, output_guardrails"#, ) @@ -497,6 +564,9 @@ pub async fn update_model( .bind(new_tags.as_deref()) .bind(req.enabled.unwrap_or(existing.enabled)) .bind(&new_guardrails_json) + .bind(cache[0]) + .bind(cache[1]) + .bind(cache[2]) .fetch_one(&state.db) .await?; diff --git a/crates/test-support/tests/analytics_clickhouse.rs b/crates/test-support/tests/analytics_clickhouse.rs index a009b8f2..96f59afa 100644 --- a/crates/test-support/tests/analytics_clickhouse.rs +++ b/crates/test-support/tests/analytics_clickhouse.rs @@ -321,3 +321,246 @@ async fn a_chat_stream_is_billed_when_the_caller_did_not_ask_for_usage() { let (_, input_tokens, output_tokens) = wait_for_gateway_log(ch, user.user.id).await; assert_eq!((input_tokens, output_tokens), (5, 2)); } + +/// The latest `gateway_logs` row for a user: status, input and output +/// tokens, cost, and the detail JSON. +async fn last_gateway_log( + ch: &clickhouse::Client, + user_id: uuid::Uuid, +) -> (i64, i64, i64, Decimal, Value) { + for _ in 0..200 { + let row: Option<(i64, i64, i64, String, String)> = ch + .query( + "SELECT ifNull(status_code, -1), ifNull(input_tokens, -1), \ + ifNull(output_tokens, -1), ifNull(toString(cost_usd), ''), \ + ifNull(detail, '') \ + FROM gateway_logs \ + WHERE user_id = ? AND cost_usd IS NOT NULL \ + ORDER BY created_at DESC LIMIT 1", + ) + .bind(user_id.to_string()) + .fetch_optional() + .await + .expect("CH select"); + if let Some((status, input, output, cost, detail)) = row + && !cost.is_empty() + { + return ( + status, + input, + output, + Decimal::from_str(&cost).unwrap(), + serde_json::from_str(&detail).unwrap_or(Value::Null), + ); + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + panic!("gateway_logs row never landed for user {user_id}"); +} + +/// One provider at `uri` serving `model`, and a key for a new user. +async fn seed_upstream( + app: &TestApp, + uri: &str, + provider_type: &str, + model: &str, +) -> (String, uuid::Uuid) { + let user = fixtures::create_random_user(&app.db).await.unwrap(); + let provider = + fixtures::create_provider(&app.db, &unique_name("bill"), provider_type, uri, None) + .await + .unwrap(); + fixtures::create_model_and_route(&app.db, provider.id, model) + .await + .unwrap(); + app.rebuild_gateway_router().await; + let key = fixtures::create_api_key( + &app.db, + user.user.id, + &unique_name("bill-key"), + &["ai_gateway"], + None, + None, + ) + .await + .unwrap(); + (key.plaintext, user.user.id) +} + +/// A stream the upstream reports no usage for — one that ignores +/// `stream_options` — is billed on an estimate, not as zero tokens, and +/// the row says it is an estimate. +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn a_stream_without_usage_is_billed_on_an_estimate() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let app = TestApp::spawn_with_clickhouse().await; + let chunk = |content: &str| { + json!({"id":"c","object":"chat.completion.chunk","created":1,"model":"gpt-nousage", + "choices":[{"index":0,"delta":{"content":content},"finish_reason":null}]}) + }; + let words = "x".repeat(400); + let sse = format!("data: {}\n\ndata: [DONE]\n\n", chunk(&words)); + let upstream = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v1/chat/completions")) + .respond_with(ResponseTemplate::new(200).set_body_raw(sse, "text/event-stream")) + .mount(&upstream) + .await; + let (key, user_id) = seed_upstream(&app, &upstream.uri(), "openai", "gpt-nousage").await; + + let gw = app.gateway_client(); + gw.set_bearer(&key); + let prompt = "y".repeat(800); + gw.post( + "/v1/chat/completions", + json!({"model": "gpt-nousage", "stream": true, + "messages": [{"role": "user", "content": prompt}]}), + ) + .await + .unwrap() + .assert_ok(); + + let ch = app.state.clickhouse.as_ref().expect("clickhouse client"); + let (status, input, output, cost, detail) = last_gateway_log(ch, user_id).await; + assert_eq!(status, 200); + // About four bytes a token: 800 bytes in, 400 out. + assert_eq!((input, output), (200, 100)); + assert!(cost > Decimal::ZERO, "an unreported stream was free"); + assert_eq!(detail["usage_estimated"], true, "{detail}"); +} + +/// A caller that leaves mid-stream takes the upstream's final usage with +/// it. The request is billed on what was sent before it left. +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn a_stream_the_caller_leaves_is_billed_on_an_estimate() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let app = TestApp::spawn_with_clickhouse().await; + // An upstream that sends one chunk and then keeps the stream open. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + while let Ok((mut sock, _)) = listener.accept().await { + tokio::spawn(async move { + let mut buf = vec![0u8; 65536]; + let _ = sock.read(&mut buf).await; + let chunk = json!({"id":"c","object":"chat.completion.chunk","created":1, + "model":"gpt-leave","choices":[{"index":0, + "delta":{"content":"z".repeat(400)},"finish_reason":null}]}); + let event = format!("data: {chunk}\n\n"); + let head = "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\ + transfer-encoding: chunked\r\n\r\n"; + let _ = sock.write_all(head.as_bytes()).await; + let _ = sock + .write_all(format!("{:x}\r\n{event}\r\n", event.len()).as_bytes()) + .await; + let _ = sock.flush().await; + tokio::time::sleep(std::time::Duration::from_secs(30)).await; + }); + } + }); + let (key, user_id) = + seed_upstream(&app, &format!("http://{addr}"), "openai", "gpt-leave").await; + + let mut resp = reqwest::Client::new() + .post(format!("{}/v1/chat/completions", app.gateway_url)) + .bearer_auth(&key) + .json(&json!({"model": "gpt-leave", "stream": true, + "messages": [{"role": "user", "content": "q".repeat(800)}]})) + .send() + .await + .unwrap(); + assert!(resp.status().is_success()); + let first = resp.chunk().await.unwrap().unwrap_or_default(); + assert!(String::from_utf8_lossy(&first).contains("zzzz")); + drop(resp); + + let ch = app.state.clickhouse.as_ref().expect("clickhouse client"); + let (status, input, output, cost, detail) = last_gateway_log(ch, user_id).await; + assert_eq!(status, 499, "{detail}"); + assert_eq!((input, output), (200, 100)); + assert!(cost > Decimal::ZERO, "a stream the caller left was free"); + assert_eq!(detail["usage_estimated"], true, "{detail}"); +} + +/// Input read from the prompt cache is billed at a tenth of the input +/// price and input written to it at 1.25×, not all at the full price — +/// and the budget counter is debited by the same weights. +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn cached_input_is_billed_at_the_cache_prices() { + use fred::interfaces::KeysInterface; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let app = TestApp::spawn_with_clickhouse().await; + let upstream = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v1/messages")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "id": "msg_cache", "type": "message", "role": "assistant", "model": "claude-cache", + "content": [{"type": "text", "text": "hi"}], "stop_reason": "end_turn", + "usage": {"input_tokens": 100, "cache_read_input_tokens": 10000, + "cache_creation_input_tokens": 2000, "output_tokens": 50} + }))) + .mount(&upstream) + .await; + let (key, user_id) = seed_upstream(&app, &upstream.uri(), "anthropic", "claude-cache").await; + fixtures::create_budget_cap(&app.db, "user", user_id, "daily", 1_000_000) + .await + .unwrap(); + + let gw = app.gateway_client(); + gw.set_bearer(&key); + let ask = || { + gw.post( + "/v1/messages", + json!({"model": "claude-cache", "max_tokens": 16, + "messages": [{"role": "user", "content": "hi"}]}), + ) + }; + ask().await.unwrap().assert_ok(); + + let ch = app.state.clickhouse.as_ref().expect("clickhouse client"); + let (_, input, output, cost, detail) = last_gateway_log(ch, user_id).await; + // The row's input is the whole input, cached or not. + assert_eq!((input, output), (12_100, 50)); + // Default baseline 0.000002 in / 0.000008 out, weights 1.0: + // 0.000002 × (100 + 10 000 × 0.1 + 2 000 × 1.25) + 0.000008 × 50 + assert_eq!(cost, Decimal::from_str("0.0076").unwrap(), "{detail}"); + assert_eq!(detail["cache_read_tokens"], 10_000); + assert_eq!(detail["cache_write_tokens"], 2_000); + + // 100 + 1 000 + 2 500 + 50 weighted tokens on the budget counter. + let budget_key = + think_watch_common::limits::budget::build_key("user", user_id, "daily", chrono::Utc::now()); + let debited: Option = app.state.redis.get(&budget_key).await.unwrap(); + assert_eq!( + debited.as_deref(), + Some("3650"), + "{budget_key} for {user_id}" + ); + + // A model's own cache price replaces the derived one. + sqlx::query("UPDATE models SET cache_read_weight = 0.5 WHERE model_id = 'claude-cache'") + .execute(&app.db) + .await + .unwrap(); + app.state.weight_cache.invalidate_all().await; + ask().await.unwrap().assert_ok(); + // The second row lands asynchronously, like the first. + let mut second = cost; + for _ in 0..200 { + second = last_gateway_log(ch, user_id).await.3; + if second != cost { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + // 0.000002 × (100 + 5 000 + 2 500) + 0.0004 + assert_eq!(second, Decimal::from_str("0.0156").unwrap()); +} diff --git a/crates/test-support/tests/console_admin.rs b/crates/test-support/tests/console_admin.rs index 5c601794..de3aae4c 100644 --- a/crates/test-support/tests/console_admin.rs +++ b/crates/test-support/tests/console_admin.rs @@ -523,3 +523,76 @@ async fn console_api_key_rejected_after_owner_deactivated() { after.status ); } + +/// A decimal as the API sends it (a string), as a number. +fn num(v: &Value) -> Option { + v.as_str().and_then(|s| s.parse().ok()) +} + +/// A model's cache weights: set on create, left alone by a PATCH that +/// does not name them, cleared back to derived by `null`, and listed. +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn model_cache_weights_round_trip() { + let app = TestApp::spawn().await; + let (con, _) = admin_session_with_user(&app).await; + let model_id = unique_name("cache-model"); + + let created: Value = con + .post( + "/api/admin/models", + json!({"model_id": model_id, "display_name": "Cache", "cache_read_weight": 0.5}), + ) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(num(&created["cache_read_weight"]), Some(0.5)); + assert_eq!(created["cache_write_weight"], Value::Null); + let id = created["id"].as_str().unwrap().to_string(); + + let updated: Value = con + .patch( + &format!("/api/admin/models/{id}"), + json!({"cache_write_weight": 1, "cache_write_1h_weight": 1.5}), + ) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(num(&updated["cache_read_weight"]), Some(0.5), "{updated}"); + assert_eq!(num(&updated["cache_write_weight"]), Some(1.0)); + assert_eq!(num(&updated["cache_write_1h_weight"]), Some(1.5)); + + let cleared: Value = con + .patch( + &format!("/api/admin/models/{id}"), + json!({"cache_read_weight": null}), + ) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!(cleared["cache_read_weight"], Value::Null, "{cleared}"); + assert_eq!(num(&cleared["cache_write_weight"]), Some(1.0)); + + con.patch( + &format!("/api/admin/models/{id}"), + json!({"cache_read_weight": -1}), + ) + .await + .unwrap() + .assert_status(400); + + let list: Value = con + .get(&format!("/api/admin/models?q={model_id}")) + .await + .unwrap() + .json() + .unwrap(); + assert_eq!( + num(&list["items"][0]["cache_write_1h_weight"]), + Some(1.5), + "{list}" + ); +} diff --git a/crates/test-support/tests/gateway_proxy.rs b/crates/test-support/tests/gateway_proxy.rs index 0161bf5d..a0246003 100644 --- a/crates/test-support/tests/gateway_proxy.rs +++ b/crates/test-support/tests/gateway_proxy.rs @@ -570,3 +570,54 @@ async fn revoked_api_key_no_longer_authorises() { .unwrap(); resp.assert_status(401); } + +/// A conversation that went through a format conversion earlier carries +/// reasoning signatures the gateway wrote (`tw1.`). When a later turn of +/// it is forwarded as sent to Anthropic, those signatures go too, and +/// Anthropic refuses the whole request over them. They are taken out; a +/// signature Anthropic issued itself stays. +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn a_passthrough_request_leaves_the_gateways_own_signatures_behind() { + let app = TestApp::spawn().await; + let upstream = MockProvider::anthropic_messages_ok("claude-carried").await; + let api_key = + seed_provider_and_key(&app, &upstream.uri(), "anthropic", "claude-carried", None).await; + + let gw = app.gateway_client(); + gw.set_bearer(&api_key); + let resp = gw + .post( + "/v1/messages", + json!({ + "model": "claude-carried", + "max_tokens": 16, + "messages": [ + {"role": "user", "content": "first"}, + {"role": "assistant", "content": [ + {"type": "thinking", "thinking": "converted", "signature": "tw1.abc"}, + {"type": "text", "text": "answer one"} + ]}, + {"role": "assistant", "content": [ + {"type": "thinking", "thinking": "native", "signature": "EqQBCkgIBx"}, + {"type": "text", "text": "answer two"} + ]}, + {"role": "user", "content": "second"} + ] + }), + ) + .await + .unwrap(); + resp.assert_ok(); + + let sent = upstream.received_requests().await; + assert_eq!(sent.len(), 1); + let text = String::from_utf8_lossy(&sent[0].body).into_owned(); + assert!( + !text.contains("tw1."), + "a carried signature was forwarded: {text}" + ); + let sent: Value = serde_json::from_str(&text).unwrap(); + assert_eq!(sent["messages"][1]["content"][0]["text"], "answer one"); + assert_eq!(sent["messages"][2]["content"][0]["signature"], "EqQBCkgIBx"); +} diff --git a/db/schema.sql b/db/schema.sql index 34b9d54c..0960b669 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -335,6 +335,14 @@ CREATE TABLE IF NOT EXISTS models ( display_name VARCHAR(255) NOT NULL, input_weight DECIMAL(8, 4) NOT NULL DEFAULT 1.0 CHECK (input_weight > 0), output_weight DECIMAL(8, 4) NOT NULL DEFAULT 1.0 CHECK (output_weight > 0), + -- Input read from / written to the upstream's prompt cache, against + -- the same input baseline. NULL ⇒ derived from input_weight: + -- read 0.1×, write 1.25×, 1-hour write 2× (Anthropic's ratios; see + -- crates/common/src/limits/weight.rs). Set them for an upstream + -- that prices its cache differently. + cache_read_weight DECIMAL(8, 4) CHECK (cache_read_weight >= 0), + cache_write_weight DECIMAL(8, 4) CHECK (cache_write_weight >= 0), + cache_write_1h_weight DECIMAL(8, 4) CHECK (cache_write_1h_weight >= 0), -- Per-model overrides. NULL ⇒ "fall through to gateway.default_*". -- Strategy semantics — see crates/gateway/src/strategy.rs: -- weighted — operator-set weight = traffic ratio (manual) @@ -372,6 +380,14 @@ CREATE TABLE IF NOT EXISTS models ( created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); +-- Added after first boot; see the note above `model_routes`'s ALTER. +ALTER TABLE models ADD COLUMN IF NOT EXISTS cache_read_weight + DECIMAL(8, 4) CHECK (cache_read_weight >= 0); +ALTER TABLE models ADD COLUMN IF NOT EXISTS cache_write_weight + DECIMAL(8, 4) CHECK (cache_write_weight >= 0); +ALTER TABLE models ADD COLUMN IF NOT EXISTS cache_write_1h_weight + DECIMAL(8, 4) CHECK (cache_write_1h_weight >= 0); + -- Platform-wide per-token pricing baseline. Single-row singleton -- (PK pinned to 1 via CHECK). `cost($) = tokens × weight × baseline`. CREATE TABLE IF NOT EXISTS platform_pricing ( diff --git a/web/src/i18n/en.json b/web/src/i18n/en.json index f3859b5f..f097aaea 100644 --- a/web/src/i18n/en.json +++ b/web/src/i18n/en.json @@ -442,7 +442,10 @@ "upstreamModel": "Upstream Model", "health": "Health", "healthHint": "Live circuit-breaker state from the rolling-window error rate. Closed = passing through, open = excluded from selection, half-open = probing.", - "p50": "EWMA latency" + "p50": "EWMA latency", + "cacheRead": "Cache read ×", + "cacheWrite": "Cache write ×", + "cacheWrite1h": "1h cache write ×" }, "status": { "all": "All models", @@ -467,7 +470,10 @@ "affinityMode": "Session affinity", "affinityTtlSecs": "Affinity TTL (seconds)", "rpmCap": "RPM cap", - "tpmCap": "TPM cap" + "tpmCap": "TPM cap", + "cacheReadWeight": "Cache read weight", + "cacheWriteWeight": "Cache write weight", + "cacheWrite1hWeight": "1-hour cache write weight" }, "useGlobalDefault": "Use global default", "unlimited": "Unlimited", @@ -519,7 +525,8 @@ "errors": { "weightMustBePositive": "Weights must be positive numbers.", "affinityTtlRange": "Affinity TTL must be between 0 and 86400 seconds.", - "capMustBePositive": "RPM/TPM caps must be positive integers (or empty for unlimited)." + "capMustBePositive": "RPM/TPM caps must be positive integers (or empty for unlimited).", + "cacheWeightNotNegative": "Cache weights must not be negative." }, "batchImportHint": "Import model entries from a provider's remote catalog into your exposed models list.", "batchImportWarning": "Imported routes go live in /v1/models right away. Tick only the models you actually want exposed.", @@ -548,7 +555,9 @@ "created": "Model added.", "updated": "Model updated.", "deleted": "Model removed." - } + }, + "cacheWeightHint": "Input read from or written to the upstream's prompt cache, priced against the input baseline. Empty = derived from the input weight: read 0.1×, write 1.25×, 1-hour write 2×.", + "derivedWeight": "{{value}} (derived)" }, "teams": { "title": "Teams", diff --git a/web/src/i18n/zh.json b/web/src/i18n/zh.json index 77d9f82e..901833e0 100644 --- a/web/src/i18n/zh.json +++ b/web/src/i18n/zh.json @@ -442,7 +442,10 @@ "upstreamModel": "上游模型", "health": "健康", "healthHint": "实时熔断器状态(基于滚动窗口错误率)。健康 = 正常路由,熔断 = 暂时排除,半开 = 探测中。", - "p50": "EWMA 延迟" + "p50": "EWMA 延迟", + "cacheRead": "缓存读 ×", + "cacheWrite": "缓存写 ×", + "cacheWrite1h": "1 小时缓存写 ×" }, "status": { "all": "全部模型", @@ -467,7 +470,10 @@ "affinityMode": "会话黏性", "affinityTtlSecs": "黏性 TTL (秒)", "rpmCap": "RPM 上限", - "tpmCap": "TPM 上限" + "tpmCap": "TPM 上限", + "cacheReadWeight": "缓存读取权重", + "cacheWriteWeight": "缓存写入权重", + "cacheWrite1hWeight": "1 小时缓存写入权重" }, "useGlobalDefault": "使用全局默认", "unlimited": "不限制", @@ -519,7 +525,8 @@ "errors": { "weightMustBePositive": "权重必须为正数。", "affinityTtlRange": "黏性 TTL 必须在 0 到 86400 秒之间。", - "capMustBePositive": "RPM/TPM 上限必须是正整数(留空表示不限制)。" + "capMustBePositive": "RPM/TPM 上限必须是正整数(留空表示不限制)。", + "cacheWeightNotNegative": "缓存权重不能为负数。" }, "batchImportHint": "从提供商远端 catalog 导入模型条目到已暴露模型列表。", "batchImportWarning": "导入后路由立即在 /v1/models 生效。只勾选你确实想暴露的模型。", @@ -548,7 +555,9 @@ "created": "模型已添加。", "updated": "模型已更新。", "deleted": "模型已删除。" - } + }, + "cacheWeightHint": "命中或写入上游提示缓存的输入,按输入基准价计。留空则按输入权重推算:读取 0.1 倍,写入 1.25 倍,1 小时写入 2 倍。", + "derivedWeight": "{{value}}(推算)" }, "teams": { "title": "团队", diff --git a/web/src/routes/gateway/models/ModelDetailSheet.tsx b/web/src/routes/gateway/models/ModelDetailSheet.tsx index ea5495a2..fba82986 100644 --- a/web/src/routes/gateway/models/ModelDetailSheet.tsx +++ b/web/src/routes/gateway/models/ModelDetailSheet.tsx @@ -17,7 +17,10 @@ import { RoutingModeSection } from '../routing/RoutingModeSection'; import { TrafficBar } from '../routing/TrafficBar'; import { CostPreview } from './CostPreview'; import { + CACHE_WEIGHTS, + derivedCacheWeight, modelStatus, + type CacheWeight, type ModelRow, type PlatformPricing, type RouteHealthEntry, @@ -25,6 +28,12 @@ import { type RoutingStrategy, } from './types'; +const CACHE_COL_LABEL: Record = { + cache_read_weight: 'models.col.cacheRead', + cache_write_weight: 'models.col.cacheWrite', + cache_write_1h_weight: 'models.col.cacheWrite1h', +}; + /// Right-side drawer with one model's basics (weights, cost preview, /// edit/delete actions) and routes list (per-route health, /// latency, bulk-enable, weight rebalance). Open state is parent- @@ -147,6 +156,19 @@ export function ModelDetailSheet({
{model.output_weight}
+
+ {CACHE_WEIGHTS.map((k) => ( +
+
{t(CACHE_COL_LABEL[k])}
+
+ {model[k] ?? + t('models.derivedWeight', { + value: derivedCacheWeight(model.input_weight, k), + })} +
+
+ ))} +
= { + cache_read_weight: 'models.field.cacheReadWeight', + cache_write_weight: 'models.field.cacheWriteWeight', + cache_write_1h_weight: 'models.field.cacheWrite1hWeight', +}; + /// Create/edit dialog for a Model catalog entry. Owns its own form /// state + saving + error UI so the parent route only manages /// `open`/`model` plus a single `onSaved` callback that fires after @@ -74,6 +83,9 @@ export function ModelEditorDialog({ display_name: model.display_name, input_weight: model.input_weight, output_weight: model.output_weight, + cache_read_weight: model.cache_read_weight ?? '', + cache_write_weight: model.cache_write_weight ?? '', + cache_write_1h_weight: model.cache_write_1h_weight ?? '', routing_strategy: (model.routing_strategy ?? '') as ModelFormState['routing_strategy'], affinity_mode: (model.affinity_mode ?? '') as ModelFormState['affinity_mode'], affinity_ttl_secs: model.affinity_ttl_secs == null ? '' : String(model.affinity_ttl_secs), @@ -94,6 +106,17 @@ export function ModelEditorDialog({ setError(t('models.errors.weightMustBePositive')); return; } + // Cache weights: empty ⇒ null ⇒ derived from the input weight. + const cacheWeights = {} as Record; + for (const k of CACHE_WEIGHTS) { + const raw = form[k].trim(); + const n = raw ? Number(raw) : null; + if (n != null && (!Number.isFinite(n) || n < 0)) { + setError(t('models.errors.cacheWeightNotNegative')); + return; + } + cacheWeights[k] = n; + } // Routing overrides: empty string in the form ⇒ JSON null on the // wire ⇒ "inherit global default" (PATCH semantics). const ttl = form.affinity_ttl_secs.trim(); @@ -117,6 +140,7 @@ export function ModelEditorDialog({ display_name: form.display_name.trim() || form.model_id.trim(), input_weight: inW, output_weight: outW, + ...cacheWeights, routing_strategy: form.routing_strategy === '' ? null : form.routing_strategy, affinity_mode: form.affinity_mode === '' ? null : form.affinity_mode, affinity_ttl_secs: ttlNum, @@ -213,6 +237,23 @@ export function ModelEditorDialog({ /> +
+

{t('models.cacheWeightHint')}

+
+ {CACHE_WEIGHTS.map((k) => ( +
+ + setForm({ ...form, [k]: e.target.value })} + placeholder={derivedCacheWeight(form.input_weight, k)} + inputMode="decimal" + /> +
+ ))} +
+
{/* Routing strategy + affinity overrides. Empty = inherit the global default from system_settings.gateway.*. Only useful when an operator wants to diverge from the diff --git a/web/src/routes/gateway/models/types.ts b/web/src/routes/gateway/models/types.ts index 2161718b..7cda7b8c 100644 --- a/web/src/routes/gateway/models/types.ts +++ b/web/src/routes/gateway/models/types.ts @@ -14,6 +14,11 @@ export interface ModelRow { /// `platform_pricing.input_price_per_token × input_weight × tokens`. input_weight: string; output_weight: string; + /// Prompt-cache weights as stored; null ⇒ derived from `input_weight` + /// (see `effectiveCacheWeight`). + cache_read_weight: string | null; + cache_write_weight: string | null; + cache_write_1h_weight: string | null; route_count: number; enabled_route_count: number; /// Model-level kill switch. FALSE ⇒ all routes are skipped at the @@ -146,6 +151,10 @@ export interface ModelFormState { display_name: string; input_weight: string; output_weight: string; + /// Empty string = derive from the input weight (stored as NULL). + cache_read_weight: string; + cache_write_weight: string; + cache_write_1h_weight: string; /// Empty string = inherit global default. Form serializes that /// to `null` on submit so the backend stores the override as NULL. routing_strategy: '' | RoutingStrategy; @@ -174,6 +183,9 @@ export const emptyModelForm: ModelFormState = { display_name: '', input_weight: '1.0', output_weight: '1.0', + cache_read_weight: '', + cache_write_weight: '', + cache_write_1h_weight: '', routing_strategy: '', affinity_mode: '', affinity_ttl_secs: '', @@ -189,3 +201,27 @@ export const emptyRouteForm: RouteFormState = { rpm_cap: '', tpm_cap: '', }; + +export type CacheWeight = 'cache_read_weight' | 'cache_write_weight' | 'cache_write_1h_weight'; + +export const CACHE_WEIGHTS: CacheWeight[] = [ + 'cache_read_weight', + 'cache_write_weight', + 'cache_write_1h_weight', +]; + +/// A cache weight left unset follows the input weight by these ratios. +/// Mirrors `CACHE_*_RATIO` in `crates/common/src/limits/weight.rs`. +export const CACHE_WEIGHT_RATIO: Record = { + cache_read_weight: 0.1, + cache_write_weight: 1.25, + cache_write_1h_weight: 2, +}; + +/// The weight derived from `inputWeight` for an unset cache weight, as +/// text for display; empty when the input weight is not a number. +export function derivedCacheWeight(inputWeight: string, which: CacheWeight): string { + const w = Number(inputWeight); + if (!Number.isFinite(w)) return ''; + return String(Number((w * CACHE_WEIGHT_RATIO[which]).toFixed(4))); +}