726 字
约 2 分钟
1
估算、百分比与严格阈值
无标签

Grok Build · 上下文容量 估算、百分比与严格阈值 xai-token-estimation 提供共享算术原语。它既有 bytes/4 的本地粗估,也有对调用方传入 used 与 total 的使用率和阈值判断。 一句话速览 区分 Token 估算、使用率计算和 exceeds_threshold 的严格比较语义

课程目标 区分本地估算与服务端 usage 观测,读懂 usage_percentage 、 exceeds_threshold 、 exceeds_threshold_with_headroom ,并准确判断 85% 的等号边界。

核心视觉 · 85% 边界

context_window = 1,000

85% = 850 0 1,000 used = 849 false used = 850 true,等号触发

阈值采用整数交叉相乘: used × 100 >= window × percent 。

三个核心函数

usage_percentage total == 0 时返回 0,其他情况计算百分比,并把结果上限限制为 100。 (used / total × 100).min(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 会把触发点进一步前移。

估算、百分比与严格阈值
http://www.clxhxhhr.top/posts/4000/
作者
clxstart
发布于
2026-09-25
许可协议
CC BY-NC-SA 4.0
评论
0 条
还没有评论,先写一条吧。