deepstrike_core/context/
token_engine.rs1use std::sync::Arc;
2
3use crate::types::message::{Content, ContentPart, Message};
4
5pub trait TokenCounter: Send + Sync {
8 fn count(&self, text: &str) -> u32;
10
11 fn truncate<'a>(&self, text: &'a str, max_tokens: u32) -> &'a str;
14}
15
16pub struct CharApproxCounter;
20
21impl TokenCounter for CharApproxCounter {
22 fn count(&self, text: &str) -> u32 {
23 (text.chars().count() as u32 / 4).max(1)
24 }
25
26 fn truncate<'a>(&self, text: &'a str, max_tokens: u32) -> &'a str {
27 let max_chars = (max_tokens as usize).saturating_mul(4);
28 let mut byte_end = text.len(); let mut seen = 0usize;
30 for (byte_idx, _) in text.char_indices() {
31 if seen >= max_chars {
32 byte_end = byte_idx;
33 break;
34 }
35 seen += 1;
36 }
37 &text[..byte_end]
38 }
39}
40
41pub struct FallbackEstimator {
51 tokenizer: deepstrike_tokenizer::Tokenizer,
52 safety_margin: f64,
55}
56
57impl FallbackEstimator {
58 pub fn new(backend: deepstrike_tokenizer::TokenizerBackend, safety_margin: f64) -> Self {
59 Self {
60 tokenizer: deepstrike_tokenizer::Tokenizer::new(backend),
61 safety_margin,
62 }
63 }
64}
65
66impl Default for FallbackEstimator {
67 fn default() -> Self {
68 Self::new(deepstrike_tokenizer::TokenizerBackend::Cl100k, 1.1)
69 }
70}
71
72impl TokenCounter for FallbackEstimator {
73 fn count(&self, text: &str) -> u32 {
74 let raw = self.tokenizer.count(text) as f64;
75 ((raw * self.safety_margin).ceil() as u32).max(1)
76 }
77
78 fn truncate<'a>(&self, text: &'a str, max_tokens: u32) -> &'a str {
79 let raw_budget = ((max_tokens as f64) / self.safety_margin).floor() as u32;
82 self.tokenizer.truncate(text, raw_budget)
83 }
84}
85
86#[derive(Clone)]
90pub struct ContextTokenEngine(Arc<dyn TokenCounter>);
91
92impl ContextTokenEngine {
93 pub fn char_approx() -> Self {
97 Self(Arc::new(CharApproxCounter))
98 }
99
100 pub fn fallback_estimator() -> Self {
104 Self(Arc::new(FallbackEstimator::default()))
105 }
106
107 pub fn count(&self, text: &str) -> u32 {
108 self.0.count(text)
109 }
110
111 pub fn truncate<'a>(&self, text: &'a str, max_tokens: u32) -> &'a str {
112 self.0.truncate(text, max_tokens)
113 }
114
115 pub fn token_budget_to_bytes(&self, tokens: u32) -> usize {
116 (tokens as usize).saturating_mul(4)
117 }
118
119 pub fn count_message(&self, msg: &Message) -> u32 {
120 match &msg.content {
121 Content::Text(t) => self.count(t),
122 Content::Parts(parts) => parts.iter().map(|p| self.count_part(p)).sum(),
123 }
124 }
125
126 fn count_part(&self, part: &ContentPart) -> u32 {
127 match part {
128 ContentPart::Text { text } => self.count(text),
129 ContentPart::ToolResult { output, .. } => self.count(output),
130 ContentPart::Image { .. } | ContentPart::Audio { .. } => {
133 part.estimate_tokens().unwrap_or(1)
134 }
135 }
136 }
137
138 pub fn truncate_message(&self, msg: &Message, max_tokens: u32) -> Message {
142 match &msg.content {
143 Content::Text(t) => {
144 let kept = self.0.truncate(t, max_tokens);
145 if kept.len() < t.len() {
146 let mut m = msg.clone();
147 m.content = Content::Text(format!("{}… [truncated]", kept));
148 m.token_count = Some(max_tokens);
149 m
150 } else {
151 msg.clone()
152 }
153 }
154 Content::Parts(_) => msg.clone(),
155 }
156 }
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162 use crate::types::message::{ContentPart, Message};
163
164 fn engine() -> ContextTokenEngine {
165 ContextTokenEngine::char_approx()
166 }
167
168 #[test]
169 fn count_nonzero_for_nonempty_text() {
170 assert!(engine().count("hello") > 0);
171 }
172
173 #[test]
174 fn count_is_char_based_not_byte_based() {
175 let e = engine();
176 let cjk_count = e.count("你好世界"); let ascii_count = e.count("abcd"); assert_eq!(cjk_count, ascii_count);
182 }
183
184 #[test]
185 fn truncate_stays_within_budget() {
186 let e = engine();
187 let text = "a".repeat(1000);
188 let kept = e.0.truncate(&text, 10);
189 assert!(e.count(kept) <= 10);
190 }
191
192 #[test]
193 fn truncate_cjk_valid_utf8() {
194 let e = engine();
195 let text = "你好世界".repeat(100);
196 let kept = e.0.truncate(&text, 5);
197 assert!(std::str::from_utf8(kept.as_bytes()).is_ok());
198 }
199
200 #[test]
201 fn truncate_count_le_budget() {
202 let e = engine();
203 for max in [1u32, 5, 20, 100] {
204 let kept =
205 e.0.truncate("The quick brown fox jumps over the lazy dog.", max);
206 assert!(
207 e.count(kept) <= max,
208 "max={max} kept_count={}",
209 e.count(kept)
210 );
211 }
212 }
213
214 #[test]
215 fn truncate_message_appends_suffix_on_cut() {
216 let e = engine();
217 let msg = Message::user("a".repeat(200));
218 let truncated = e.truncate_message(&msg, 5);
219 let text = truncated.content.as_text().unwrap();
220 assert!(text.ends_with("… [truncated]"), "got: {text}");
221 }
222
223 #[test]
224 fn truncate_message_unchanged_when_fits() {
225 let e = engine();
226 let msg = Message::user("hi");
227 let out = e.truncate_message(&msg, 1000);
228 assert_eq!(out.content.as_text().unwrap(), "hi");
229 }
230
231 #[test]
232 fn count_image_uses_detail_heuristic_not_one() {
233 let e = engine();
234 let low = Message::user_multimodal(vec![ContentPart::image_base64_with_detail(
235 "abc",
236 "image/png",
237 "low",
238 )]);
239 let auto = Message::user_multimodal(vec![ContentPart::image_base64("abc", "image/png")]);
240 let high = Message::user_multimodal(vec![ContentPart::image_base64_with_detail(
241 "abc",
242 "image/png",
243 "high",
244 )]);
245 assert_eq!(e.count_message(&low), 85);
246 assert_eq!(e.count_message(&auto), 255);
247 assert_eq!(e.count_message(&high), 680);
248 }
249
250 #[test]
256 fn char_approx_severely_underestimates_cjk_heavy_text_vs_real_bpe() {
257 let sample = "核实 `ContextTokenEngine` 默认使用 `CharApproxCounter`(4 字符≈1 token),\
258而 `ContextManager::new()` 明确默认初始化 `ContextTokenEngine::char_approx()`。这就能解释实际观察到的 \
25920%~30% 少算问题。这个值直接进入 Context ρ → Snip → Micro → Collapse → Auto → Renewal 决策链路,\
260低估会导致压缩没有按时触发,继续 append 下去最终造成 Provider context overflow。";
261
262 let approx = CharApproxCounter.count(sample);
263 let real =
264 deepstrike_tokenizer::Tokenizer::new(deepstrike_tokenizer::TokenizerBackend::Cl100k)
265 .count(sample);
266
267 let underestimate_pct = 1.0 - (approx as f64 / real as f64);
268 assert!(
269 underestimate_pct > 0.30,
270 "expected char_approx to underestimate real BPE count by >30% on CJK-heavy text, \
271 got approx={approx} real={real} ({:.1}%)",
272 underestimate_pct * 100.0
273 );
274 }
275
276 #[test]
279 fn fallback_estimator_does_not_underestimate_cjk_heavy_text() {
280 let sample = "核实 `ContextTokenEngine` 默认使用 `CharApproxCounter`(4 字符≈1 token),\
281而 `ContextManager::new()` 明确默认初始化 `ContextTokenEngine::char_approx()`。这就能解释实际观察到的 \
28220%~30% 少算问题。";
283
284 let e = ContextTokenEngine::fallback_estimator();
285 let estimated = e.count(sample);
286 let real =
287 deepstrike_tokenizer::Tokenizer::new(deepstrike_tokenizer::TokenizerBackend::Cl100k)
288 .count(sample);
289
290 assert!(
291 estimated >= real,
292 "fallback_estimator margin must stay above its cl100k base \
293 (estimated={estimated} real={real})"
294 );
295 }
296
297 #[test]
301 fn context_manager_new_does_not_default_to_char_approx() {
302 let cjk = "这是一段包含中文的示例文本,用来验证生产路径默认引擎不再是字符近似计数器。";
303 let mgr = crate::context::manager::ContextManager::new(100_000);
304 let default_engine_count = mgr.engine.count(cjk);
305 let char_approx_count = ContextTokenEngine::char_approx().count(cjk);
306 assert_ne!(
307 default_engine_count, char_approx_count,
308 "ContextManager::new() must not use char_approx as its token engine"
309 );
310 }
311
312 #[test]
313 fn count_audio_uses_decoded_byte_heuristic_not_base64_text() {
314 let e = engine();
315 let audio =
317 Message::user_multimodal(vec![ContentPart::audio("A".repeat(6400), "audio/wav")]);
318 assert_eq!(e.count_message(&audio), 3);
319 assert!(e.count_message(&audio) < 100);
321 }
322}