Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(adaptive-sizer): char bigrams for spaceless CJK items (#1748)
Zhenjia ZHOU8879c50dbe92
diff --git a/crates/headroom-core/src/transforms/adaptive_sizer.rs b/crates/headroom-core/src/transforms/adaptive_sizer.rsindex 63c7beb90..cb8ecca75 100644--- a/crates/headroom-core/src/transforms/adaptive_sizer.rs+++ b/crates/headroom-core/src/transforms/adaptive_sizer.rs@@ -148,12 +148,23 @@ pub fn find_knee(curve: &[usize]) -> Option<usize> {knee_idx.map(|i| i + 1)}+/// True for CJK ideographs, kana, and Hangul. Code-point ranges kept+/// byte-identical with the Python `_is_cjk_char` for adaptive-sizer parity.+fn is_cjk_char(c: char) -> bool {+ matches!(+ c as u32,+ 0x3040..=0x30FF | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xAC00..=0xD7AF | 0xF900..=0xFAFF+ )+}+/// Cumulative unique-bigram coverage curve.////// Direct port of `compute_unique_bigram_curve` (Python/// `adaptive_sizer.py:157-182`). Each item contributes its word-level-/// bigrams; single-word items contribute `(word, "")`. The curve at-/// index `k` is the running count of unique bigrams after seeing+/// bigrams; single-word items contribute `(word, "")`. A spaceless CJK item+/// (no whitespace to split on) uses character bigrams instead, so CJK lists+/// produce a real coverage curve rather than one pseudo-bigram per item. The+/// curve at index `k` is the running count of unique bigrams after seeing/// `items[0..=k]`.pub fn compute_unique_bigram_curve(items: &[&str]) -> Vec<usize> {let mut seen: HashSet<(String, String)> = HashSet::new();@@ -162,14 +173,23 @@ pub fn compute_unique_bigram_curve(items: &[&str]) -> Vec<usize> {for item in items {let lower = item.to_lowercase();let words: Vec<&str> = lower.split_whitespace().collect();- if words.len() < 2 {- // Single word or empty: synthesize a unigram-bigram.- let first = words.first().copied().unwrap_or("");- seen.insert((first.to_string(), String::new()));- } else {+ if words.len() >= 2 {for j in 0..words.len() - 1 {seen.insert((words[j].to_string(), words[j + 1].to_string()));}+ } else if let Some(w) = words.first() {+ let chars: Vec<char> = w.chars().collect();+ if chars.len() >= 2 && chars.iter().any(|&c| is_cjk_char(c)) {+ // Spaceless CJK item: synthesize character bigrams.+ for j in 0..chars.len() - 1 {+ seen.insert((chars[j].to_string(), chars[j + 1].to_string()));+ }+ } else {+ seen.insert((w.to_string(), String::new()));+ }+ } else {+ // Empty item.+ seen.insert((String::new(), String::new()));}curve.push(seen.len());}@@ -469,6 +489,22 @@ mod tests {assert_eq!(compute_unique_bigram_curve(&items), vec![1, 1]);}+ #[test]+ fn bigram_curve_cjk_uses_char_bigrams() {+ // Spaceless CJK: char bigrams give a real coverage curve (was 1 per item).+ // "数据库连接失败" -> 数据,据库,库连,连接,接失,失败 = 6+ // "数据库连接成功" -> shares 4, adds 接成,成功 -> 6+2 = 8+ let items = ["数据库连接失败", "数据库连接成功"];+ assert_eq!(compute_unique_bigram_curve(&items), vec![6, 8]);+ }++ #[test]+ fn bigram_curve_cjk_single_char_is_unigram() {+ // a 1-char CJK item has no bigram -> (char, "")+ let items = ["中", "文"];+ assert_eq!(compute_unique_bigram_curve(&items), vec![1, 2]);+ }+// ---------- find_knee ----------#[test]diff --git a/headroom/transforms/adaptive_sizer.py b/headroom/transforms/adaptive_sizer.pyindex d8228e163..9a867d60a 100644--- a/headroom/transforms/adaptive_sizer.py+++ b/headroom/transforms/adaptive_sizer.py@@ -154,11 +154,26 @@ def find_knee(curve: list[int]) -> int | None:return knee_idx + 1 if knee_idx is not None else None+def _is_cjk_char(c: str) -> bool:+ """True for CJK ideographs, kana, and Hangul. Code-point ranges kept+ byte-identical with the Rust port for adaptive-sizer parity."""+ o = ord(c)+ return (+ 0x3040 <= o <= 0x30FF+ or 0x3400 <= o <= 0x4DBF+ or 0x4E00 <= o <= 0x9FFF+ or 0xAC00 <= o <= 0xD7AF+ or 0xF900 <= o <= 0xFAFF+ )++def compute_unique_bigram_curve(items: Sequence[str]) -> list[int]:"""Build cumulative unique bigram coverage curve.For each item (in order), extracts word-level bigrams, adds them to a- running set, and records the total unique count.+ running set, and records the total unique count. A spaceless CJK item+ (no whitespace to word-split on) uses character bigrams instead, so CJK+ lists produce a real coverage curve rather than one pseudo-bigram per item.Args:items: Sequence of string items in importance order.@@ -171,12 +186,18 @@ def compute_unique_bigram_curve(items: Sequence[str]) -> list[int]:for item in items:words = item.lower().split()- if len(words) < 2:- # For single-word items, use the word itself as a "unigram bigram"- seen_bigrams.add((words[0] if words else "", ""))- else:+ if len(words) >= 2:for j in range(len(words) - 1):seen_bigrams.add((words[j], words[j + 1]))+ elif words and len(words[0]) >= 2 and any(_is_cjk_char(c) for c in words[0]):+ # Spaceless CJK item: word-split yields one giant token with no+ # coverage signal, so use character bigrams instead.+ w = words[0]+ for j in range(len(w) - 1):+ seen_bigrams.add((w[j], w[j + 1]))+ else:+ # Single ASCII word (or empty): a "unigram bigram".+ seen_bigrams.add((words[0] if words else "", ""))curve.append(len(seen_bigrams))return curvediff --git a/tests/test_adaptive_sizer.py b/tests/test_adaptive_sizer.pyindex ca242c619..f20746d56 100644--- a/tests/test_adaptive_sizer.py+++ b/tests/test_adaptive_sizer.py@@ -4,7 +4,31 @@ from __future__ import annotationsimport json-from headroom.transforms.adaptive_sizer import compute_optimal_k+from headroom.transforms.adaptive_sizer import (+ compute_optimal_k,+ compute_unique_bigram_curve,+)+++def test_bigram_curve_cjk_uses_char_bigrams():+ # Spaceless CJK: char bigrams give a real coverage curve (was 1 per item).+ # Same input + expected as the Rust reference test -> proves byte-exact parity.+ assert compute_unique_bigram_curve(["数据库连接失败", "数据库连接成功"]) == [6, 8]+++def test_bigram_curve_cjk_single_char_is_unigram():+ assert compute_unique_bigram_curve(["中", "文"]) == [1, 2]+++def test_bigram_curve_ascii_unchanged():+ # non-CJK behavior is byte-identical to before the CJK branch+ assert compute_unique_bigram_curve(["the cat", "the dog", "a fish"]) == [1, 2, 3]+ assert compute_unique_bigram_curve(["hello", "world", "hello"]) == [1, 2, 2]+++def test_bigram_curve_empty_string_contributes_one():+ # mirrors the Rust reference test for the empty-item ("", "") path+ assert compute_unique_bigram_curve(["", "a", "a b"]) == [1, 2, 3]def _make_unique_items(n: int) -> list[str]: