Grok Build · 上下文容量
估算、百分比與嚴格閾值
xai-token-estimation 提供共享算術原語。它既有 bytes/4 的本地粗估,也有對調用方傳入 used 與 total 的使用率和閾值判斷。
課程目標區分本地估算與服務端 usage 觀測,讀懂
usage_percentage、exceeds_threshold、exceeds_threshold_with_headroom,並準確判斷 85% 的等號邊界。
核心視覺 · 85% 邊界
閾值採用整數交叉相乘:
used × 100 >= window × percent。三個核心函式
usage_percentagetotal == 0 時返回 0,其他情況計算百分比,並把結果上限限制為 100。
exceeds_threshold使用整數飽和乘法,避免浮點舍入改變觸發邊界。預設自動壓縮比例在配置中常見為 85。
used × 100 >= window × pct...with_headroom在百分比閾值前預留固定 token 空間。減法使用 saturating_sub,窗口為 0 時仍返回 false。
used × 100 >= window × pct - headroom × 100估算值與服務端 usage
本地估算
estimate_tokens(s) 使用 UTF-8 字節長度除以 4。它可在請求前、工具輸出加入後提供快速預測;單張低分辨率圖片的固定估值為 765 token。
服務端 usage 觀測
服務端 usage 描述已完成請求的實際計量。百分比函式不會取得或判斷數據來源,它只處理調用方傳入的數值。調用鏈可在不同階段使用估算總量或已更新的 usage。
邊界例:
exceeds_threshold(850, 1000, 85) 為 true,849 為 false。若窗口 100,000、閾值 85%、headroom 4,000,則提前到 81,000 觸發。真實源碼證據
crates/codegen/xai-token-estimation/src/lib.rs · 第 38 至 104 行節選
pub fn usage_percentage(used: u64, total: u64) -> f64 {
if total == 0 { 0.0 }
else { ((used as f64) / (total as f64) * 100.0).min(100.0) }
}
pub fn exceeds_threshold(
used: u64, context_window: u64, threshold_percent: u8
) -> bool {
if context_window == 0 { return false; }
used.saturating_mul(100)
>= context_window.saturating_mul(threshold_percent as u64)
}
pub fn exceeds_threshold_with_headroom(
used: u64, context_window: u64, threshold_percent: u8, headroom: u64,
) -> bool {
if context_window == 0 { return false; }
used.saturating_mul(100) >=
context_window.saturating_mul(threshold_percent as u64)
.saturating_sub(headroom.saturating_mul(100))
}
源碼快照説明:依據本地倉庫
grok-build-main 的 crates/codegen/xai-token-estimation/src/lib.rs,並核對 compaction 調用點,核對日期 2026-07-17。頁面沒有采用按中英文、程式碼類型分別計價的虛構公式。課堂練習
05
手算兩個觸發點
上下文窗口為 128,000,閾值為 85%。先算無 headroom 的最早觸發 used,再算 headroom 為 4,000 時的最早觸發 used。兩題都要保留等號。
Takeaway:本地 bytes/4 估算服務於及時預測,服務端 usage 提供已完成請求的觀測。共享函式負責統一算術。85% 邊界採用
>=,等於閾值時立即為 true,headroom 會把觸發點進一步前移。