Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions desktop-tauri/src-tauri/server/src/server/api/chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,9 +440,14 @@ fn anthropic_models_view(body: &Value) -> Value {
///
/// Anthropic 的官方契约里这是**独立端点**(Claude Code 启动时会探它)。
/// 真正的分词只有上游知道,而本项目六家上游都没有对应的 tokenizer 接口 ——
/// 所以这里给一个**估算**并如实标注 `estimated: true`:
/// 按「字符数 ÷ 3.5」估(中英混排的经验值,与 Anthropic 官方「约 3.5 字符
/// 一个 token」的量级一致)。
/// 所以这里给一个**估算**并如实标注 `estimated: true`(口径见
/// `core::protocol::estimate`:CJK 约 1.5 字符 / token、其余约 4 字符 / token)。
///
/// ── 为什么和流式首帧共用同一个估算器 ────────────────────────
/// `/v1/messages` 流式响应的 `message_start` 也只能给估算(真实 usage 在上游
/// 收尾帧里才到,见 `core::protocol::estimate` 的模块头)。两处若各用一套
/// 系数,同一个请求在 context 预算与消息 usage 上会给出两个数 —— Claude Code
/// 会同时读这两处,读数打架比数字略粗更糟。
///
/// ── 为什么不直接 404 ────────────────────────────────────────
/// Claude Code 在网关模式下会调它做上下文预算;404 会让它按「网关不支持」
Expand All @@ -456,12 +461,11 @@ pub async fn count_tokens(State(state): State<ServerState>, body: Bytes) -> Resp
};
// 复用 Anthropic → Chat 的转换来统计:这样「工具定义 / 图片块 / system」
// 的文本都被算进去,口径与真正转发时一致(转换失败则按原始 JSON 估)
let text = match crate::server::core::protocol::anthropic::chat_from_anthropic(&payload) {
Ok(chat) => serde_json::to_string(&chat).unwrap_or_default(),
Err(_) => serde_json::to_string(&payload).unwrap_or_default(),
let chat = match crate::server::core::protocol::anthropic::chat_from_anthropic(&payload) {
Ok(chat) => chat,
Err(_) => payload.clone(),
};
let characters = text.chars().count();
let tokens = ((characters as f64) / 3.5).ceil().max(1.0) as i64;
let tokens = crate::server::core::protocol::estimate::estimate_prompt_tokens(&chat);
let _ = state;
json_response(json!({
"input_tokens": tokens,
Expand Down
12 changes: 10 additions & 2 deletions desktop-tauri/src-tauri/server/src/server/api/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use axum::response::Response;
use serde_json::{json, Value};

use crate::server::core::key_scope::KeyScope;
use crate::server::core::protocol::{anthropic, responses};
use crate::server::core::protocol::{anthropic, estimate, responses};
use crate::server::core::upstream::cancellation;
use crate::server::core::upstream::continuation::{self, Continuation};
use crate::server::core::upstream::usage::RequestTelemetry;
Expand Down Expand Up @@ -370,6 +370,14 @@ pub async fn messages_endpoint(
// 下游等级从**翻译后的 chat 体**读:Anthropic 的 thinking/output_config →
// reasoning_effort 是网关自己的映射(anthropic_effort),比通用并集链更准
let client_reasoning = pipeline::client_reasoning_of(&chat_body);
// 流式首帧(message_start)的输入 token 兜底:真实 usage 只在上游收尾帧
// 里到达,首帧只能给估算(口径见 `core::protocol::estimate` 的模块头)。
// 非流式走聚合器、能拿到真实 usage,不必估算 —— 也就不付这份遍历成本。
let input_tokens_hint = if stream {
estimate::estimate_prompt_tokens(&chat_body)
} else {
0
};
let requested_model = match pipeline::resolve_model(&state, &mut chat_body, scope.as_ref()) {
Ok(model) => model,
Err(error) => {
Expand Down Expand Up @@ -457,7 +465,7 @@ pub async fn messages_endpoint(
let model = requested_model.clone();
let context = RecordContext { status: i64::from(status.as_u16()), ..context };
if stream {
let mut machine = anthropic::AnthropicStream::new(&model);
let mut machine = anthropic::AnthropicStream::new(&model, input_tokens_hint);
let transformed = pipeline::transformed_stream(
source,
context,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,11 @@ pub fn usage_to_anthropic(usage: Option<&Value>) -> Value {
})
}

/// usage 对象里的一个计数字段(缺失 / 非数值按 0)。
fn usage_number(usage: &Value, key: &str) -> i64 {
usage.get(key).and_then(Value::as_i64).unwrap_or(0)
}

// ─── 流式:Chat SSE → Anthropic SSE ─────────────────────────

/// Chat 的 SSE 字节流 → Anthropic 的 SSE 字节流(状态机)。
Expand Down Expand Up @@ -726,10 +731,20 @@ pub struct AnthropicStream {
has_tool: bool,
stop_reason: Option<String>,
usage: Option<Value>,
/// 请求体估算的输入 token(口径见 `super::estimate`)。
///
/// `message_start` 必须带 `input_tokens`,而上游的真实 usage 通常只出现在
/// 最后一帧 —— 首帧用它兜底;上游整轮没报输入时,收尾的 `message_delta`
/// 也沿用它(否则客户端会把锚点合并回 0,见 `reported_usage`)。
input_tokens_hint: i64,
}

impl AnthropicStream {
pub fn new(model: &str) -> Self {
/// `input_tokens_hint`:本次请求的输入 token 估算(`super::estimate`)。
///
/// 上游的真实 usage 只出现在最后一帧,首帧拿不到 —— 传 0 就退回改造前
/// 「`message_start` 恒 0」的行为(issue #1)。生产路径必须传估算值。
pub fn new(model: &str, input_tokens_hint: i64) -> Self {
Self {
buffer: SseLineBuffer::new(),
message_id: random_id("msg"),
Expand All @@ -747,6 +762,7 @@ impl AnthropicStream {
has_tool: false,
stop_reason: None,
usage: None,
input_tokens_hint: input_tokens_hint.max(0),
}
}

Expand Down Expand Up @@ -792,7 +808,7 @@ impl AnthropicStream {
json!({
"delta": { "stop_reason": stop_reason, "stop_sequence": Value::Null },
// Chat 的 usage 可能末尾才到;message_delta 允许补发累计输入与缓存用量。
"usage": usage_to_anthropic(self.usage.as_ref()),
"usage": self.reported_usage(),
}),
));
out.push(self.event("message_stop", json!({})));
Expand Down Expand Up @@ -995,12 +1011,58 @@ impl AnthropicStream {
out
}

/// 本次请求对外的 usage(首帧与收尾帧共用)。
///
/// 上游给了输入就照抄(`usage_to_anthropic` 的口径:`input_tokens` 不含
/// 缓存命中);上游**整轮都没报输入**时回落到 `input_tokens_hint`。
///
/// 为什么收尾帧也要这一层:客户端(Claude Agent SDK / Claude Code)会把
/// `message_delta` 的 usage **按字段**合并进最终消息,收尾再发一次 0 等于
/// 把 `message_start` 的锚点覆盖回去 —— 那正是 issue #1 的另一半。
///
/// 判据是「输入与缓存命中都为 0」而不是只看 `input_tokens`:全部命中缓存
/// 的请求(prompt = cached)本来就该是 `input_tokens: 0` +
/// `cache_read_input_tokens: N`,那是真实读数,不能被估算值顶掉。
fn reported_usage(&self) -> Value {
let mut usage = match self.usage.as_ref() {
Some(usage) => usage_to_anthropic(Some(usage)),
// 上游还没报 usage:键要补齐。Anthropic 的客户端按字段读缓存计数,
// 缺键与 0 在部分客户端(Hermes,上游 issue #424)里表现不同。
None => json!({
"input_tokens": 0,
"output_tokens": 0,
"cache_read_input_tokens": 0,
}),
};
let cache_read = usage
.get("cache_read_input_tokens")
.and_then(Value::as_i64)
.unwrap_or(0);
if usage_number(&usage, "input_tokens") <= 0 && cache_read <= 0 && self.input_tokens_hint > 0 {
usage["input_tokens"] = json!(self.input_tokens_hint);
}
usage
}

/// 首帧 `message_start`。
///
/// ── usage 为什么不是上游的原样值 ────────────────────────────
/// 上游的真实 usage 只出现在最后一帧(Chat 系在收尾的 usage 帧,Anthropic
/// 系在 `message_delta` —— 它自己的 `message_start` 也只给 0 占位,见
/// `anthropic_outbound::ChatFromAnthropicStream::absorb_usage`),首帧时
/// `self.usage` 往往还是 None。改造前这里直接发 0,于是 Claude Code 这类
/// 客户端拿不到输入量、退回本地估算把每轮输入累加,`/context` 显示成
/// 2.6M / 1M(issue #1)。现在:
/// · 首帧已带 usage(少数上游会在开头补一帧)→ 用上游的真值;
/// · 没有 → 用请求体的估算值(`input_tokens_hint`),量级正确即可;
/// 真实值仍由收尾的 `message_delta` 给出,客户端在流结束时校正。
fn emit_start(&mut self) -> Vec<bytes::Bytes> {
if self.started {
return Vec::new();
}
self.started = true;
let mut usage = usage_to_anthropic(self.usage.as_ref());
let mut usage = self.reported_usage();
// 首帧时还没有任何输出:output_tokens 恒 0(Anthropic 的语义)
usage["output_tokens"] = json!(0);
vec![self.event(
"message_start",
Expand Down
145 changes: 145 additions & 0 deletions desktop-tauri/src-tauri/server/src/server/core/protocol/estimate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
//! 输入 token 的**量级估算**(请求体 → token 数;不是精确分词)。
//!
//! ── 为什么网关要自己估 ──────────────────────────────────────
//! Anthropic 协议的流式响应必须以 `message_start` 开头,而这一帧里的
//! `usage.input_tokens` 是 Claude Code / Claude Desktop / Hermes 这类客户端
//! 判断「这一轮上下文用了多少」的锚点。但本网关的上游全是 Chat 系:
//! **真实的 prompt_tokens 只在上游的最后一帧 usage 里出现** ——
//! · OpenAI 兼容上游:`stream_options.include_usage` 的收尾帧(空 choices);
//! · Anthropic 系上游:`message_start` 里是 0 占位,真值在收尾前的
//! `message_delta`(见 `anthropic_outbound::ChatFromAnthropicStream::absorb_usage`)。
//! 也就是说流式首帧到达时,精确值**不可能**已经存在:网关没有上游的分词器,
//! 六家上游也都不提供 tokenizer 接口(`api::chat::count_tokens` 里记着同一件事)。
//!
//! 于是首帧只能给「量级正确的估算」:客户端拿到 5 万左右的锚点,就不会退回
//! 本地估算、把每轮输入一路累加成 2.6M(issue #1)。真实用量仍由收尾的
//! `message_delta` 给出,客户端在流结束时校正。
//!
//! ── 估算值不进请求统计 ──────────────────────────────────────
//! 只用于首帧的协议字段。请求日志/报表的 `prompt_tokens` 口径是「上游计费的
//! 读数」,只认上游 usage(`core::upstream::usage::report_usage`)——
//! 把估算值写进那一列会让统计与计费脱钩。
//!
//! ── 口径 ────────────────────────────────────────────────────
//! 按文本逐字符加权(与 Anthropic 官方「约 3.5 字符 / token」的量级一致):
//! · 中日韩字符(汉字、假名、谚文、全角标点):约 1.5 字符 / token。
//! 主流分词器对 CJK 大多一字一 token 上下,按 ASCII 的 4 字符 / token 折
//! 会把中文请求低估 3 倍,正是 issue 里「估算不可用」的那一侧;
//! · 其余字符(ASCII 字母数字、标点、空白):约 4 字符 / token;
//! · 内联图片(`data:…;base64,…`):整段按一张图估固定值 —— base64 的长度
//! 与图片的 token 成本无关,按字符数折会把一张截图算成几万 token。
//! JSON 的键名同样计入(每个键在真实分词里也占 token)。
//!
//! 估算误差在两倍以内即可满足用途(给客户端一个量级锚点);它**不是**计费值,
//! 也不承诺与上游的 prompt_tokens 逐 token 对齐。
//!
//! 用例在 `server/tests/anthropic_message_start.rs`(与流式帧的回归用例同居,
//! 理由见那里的注释:本基线的 lib 测试目标编译不过,单元测试跑不起来)。

use serde_json::Value;

/// 中日韩字符每个 token 覆盖的字符数(约 1.5 字符 / token)。
const WIDE_CHARS_PER_TOKEN: f64 = 1.5;
/// 其余字符每个 token 覆盖的字符数(约 4 字符 / token)。
const NARROW_CHARS_PER_TOKEN: f64 = 4.0;
/// 一张内联图片(base64 data URL)的估算 token 数。
///
/// Anthropic 的图片计费约为 `宽 × 高 / 750`(1024×768 的截图 ≈ 1050),
/// Claude Code 常见的 1568×800 截图 ≈ 1670 —— 取 1600 作代表值。
/// 精确值取决于上游的分词与缩放策略,这里只需要量级正确。
const INLINE_IMAGE_TOKENS: f64 = 1600.0;

/// 估算一个 Chat 形态请求体的输入 token 数(下限 1)。
///
/// 入参用 **Chat 形态**而不是 Anthropic 原始体:`/v1/messages` 的转发体就是
/// `chat_from_anthropic` 的结果,`count_tokens` 端点也用同一份,两处的读数因此
/// 同源(同一个请求在 context 预算与首帧 usage 上看到的数字一致)。
pub fn estimate_prompt_tokens(body: &Value) -> i64 {
let mut score = 0.0f64;
accumulate(body, &mut score);
// 下限 1:空请求也至少算 1 —— 0 在客户端眼里是「没有输入」,
// 而真实请求不可能真的没有 token
(score.ceil() as i64).max(1)
}

/// 递归累加:字符串按字符加权,容器逐层下钻,数字/布尔忽略。
fn accumulate(value: &Value, score: &mut f64) {
match value {
Value::String(text) => *score += text_tokens(text),
Value::Array(items) => {
for item in items {
accumulate(item, score);
}
}
Value::Object(map) => {
for (key, item) in map {
// 键名本身也占 token(`"role"` / `"content"` 各 1~2 个)
*score += text_tokens(key);
accumulate(item, score);
}
}
_ => {}
}
}

/// 一段文本的估算 token 数。
fn text_tokens(text: &str) -> f64 {
if is_inline_media(text) {
return INLINE_IMAGE_TOKENS;
}
let mut wide = 0usize;
let mut narrow = 0usize;
for ch in text.chars() {
if is_wide_script(ch) {
wide += 1;
} else {
narrow += 1;
}
}
wide as f64 / WIDE_CHARS_PER_TOKEN + narrow as f64 / NARROW_CHARS_PER_TOKEN
}

/// 是否是内联媒体(`data:` URL 且带 base64 载荷)。
///
/// 只认前缀形态,不解析内容:图片、音频、PDF 一律按固定值估。真正的图片
/// token 成本取决于尺寸,与 base64 的字符数无关。
fn is_inline_media(text: &str) -> bool {
// `find` 返回的是字符边界上的字节下标,按它比较不会切坏多字节字符
text.starts_with("data:")
&& text
.find(";base64,")
.is_some_and(|offset| offset < 64)
&& text.len() > 32
}

/// 是否是「宽字符脚本」:汉字、假名、谚文、全角标点等(约 1.5 字符 / token)。
///
/// 区间取 Unicode 的常用块,不追求完备(生僻字少一个多一个对估算没有意义):
/// · 1100–11FF 谚文字母
/// · 2E80–2FFF CJK 部首 / 康熙部首
/// · 3000–30FF CJK 标点、平假名、片假名
/// · 3400–4DBF CJK 扩展 A
/// · 4E00–9FFF CJK 基本区
/// · A960–A97F 谚文字母扩展 A
/// · AC00–D7FF 谚文音节
/// · F900–FAFF CJK 兼容汉字
/// · FE30–FE4F CJK 兼容形式(竖排标点)
/// · FF00–FFEF 全角 / 半角形式
/// · 20000–2FA1F CJK 扩展 B 及以后
fn is_wide_script(ch: char) -> bool {
matches!(
u32::from(ch),
0x1100..=0x11FF
| 0x2E80..=0x2FFF
| 0x3000..=0x30FF
| 0x3400..=0x4DBF
| 0x4E00..=0x9FFF
| 0xA960..=0xA97F
| 0xAC00..=0xD7FF
| 0xF900..=0xFAFF
| 0xFE30..=0xFE4F
| 0xFF00..=0xFFEF
| 0x20000..=0x2FA1F
)
}

Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ pub mod antigravity_signature_cache;
pub mod antigravity_stream;
pub mod chatglm_stream;
pub mod ai_sdk_ndjson;
pub mod estimate;
pub mod freeform;
pub mod history;
pub mod native_tool;
Expand Down
Loading
Loading