Documentation
¶
Overview ¶
Package tokenizer 实现 token estimator 的近似版本.
比简单的 4 chars/token 估算准确得多:
- 英文按空格和标点分词,每个词约 1-1.5 token
- 代码按标识符边界分词,长标识符约 1-2 token
- CJK 字符每个约 2 token(保守估算, 宁高勿低)
- 空白和标点通常与前后合并
- JSON/结构化数据按 key-value 对估算
不需要引入外部 tokenizer 依赖,但比固定比例估算准确 2-3 倍.
Index ¶
- Variables
- func ContextWindow(model string) int
- func EstimateCost(inputTokens, outputTokens int, model string) float64
- func EstimateCostWithPricing(inputTokens, outputTokens int, ...) float64
- func EstimateMessageTokens(messages []Message) int
- func EstimateRawMessageTokens(roles []string, contents []json.RawMessage) int
- func EstimateTokens(text string) int
- type Message
- type ModelInfo
Constants ¶
This section is empty.
Variables ¶
var ModelPricing = map[string]ModelInfo{}
ModelPricing 是模型定价/上下文窗口查找表.
已清空:定价数据由 pkg/config/models.go 的 ModelRegistry 统一管理. EstimateCost() 未知模型返回 0,ContextWindow() 未知模型返回默认值 200000. 精确定价请使用 EstimateCostWithPricing() 或 config.ModelRegistry.EstimateCost().
Functions ¶
func EstimateCost ¶
EstimateCost 估算 API 调用成本(美元). 使用内部定价表查询.未知模型返回 0(与 config.EstimateCost 一致). 如果需要更精确的定价(含缓存),请使用 config.ModelRegistry.EstimateCost().
func EstimateCostWithPricing ¶
func EstimateCostWithPricing(inputTokens, outputTokens int, inputPricePerMillion, outputPricePerMillion float64) float64
EstimateCostWithPricing 使用外部提供的定价信息估算成本. 这允许消费层传入 ModelRegistry 中的定价,避免依赖内部硬编码表.
func EstimateMessageTokens ¶
EstimateMessageTokens 估算消息列表的 token 数. 每条消息包含 role 标签的开销(约 3-4 token).
func EstimateRawMessageTokens ¶
func EstimateRawMessageTokens(roles []string, contents []json.RawMessage) int
EstimateRawMessageTokens 估算带 json.RawMessage 的消息列表的 token 数. 用于兼容 compact.go 的 CompactMessage 格式.
func EstimateTokens ¶
EstimateTokens 估算文本的 token 数.
策略:
- 遍历文本,根据字符类型分段计数
- 英文单词:按空格分隔,短词(<=4字符)约 1 token,长词按 ceil(len/4) token
- CJK 字符:每个字符约 1.5 token(向上取整,即 2个CJK = 3 token)
- 数字序列:按长度/3 估算(数字编码效率较高)
- 标点符号:通常与前后合并,约 0.5 token
- 空白符:通常被合并到相邻 token,不单独计数
- 代码标识符中的 camelCase/snake_case 边界会拆分