tokenizer

package
v0.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 26, 2026 License: None detected not legal advice Imports: 0 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
var ModelPricing = map[string]ModelInfo{}

ModelPricing 是模型定价/上下文窗口查找表.

已清空:定价数据由 pkg/config/models.go 的 ModelRegistry 统一管理. EstimateCost() 未知模型返回 0,ContextWindow() 未知模型返回默认值 200000. 精确定价请使用 EstimateCostWithPricing() 或 config.ModelRegistry.EstimateCost().

Functions

func ContextWindow

func ContextWindow(model string) int

ContextWindow 返回指定模型的上下文窗口大小.

func EstimateCost

func EstimateCost(inputTokens, outputTokens int, model string) float64

EstimateCost 估算 API 调用成本(美元). 使用内部定价表查询.未知模型返回 0(与 config.EstimateCost 一致). 如果需要更精确的定价(含缓存),请使用 config.ModelRegistry.EstimateCost().

func EstimateCostWithPricing

func EstimateCostWithPricing(inputTokens, outputTokens int, inputPricePerMillion, outputPricePerMillion float64) float64

EstimateCostWithPricing 使用外部提供的定价信息估算成本. 这允许消费层传入 ModelRegistry 中的定价,避免依赖内部硬编码表.

func EstimateMessageTokens

func EstimateMessageTokens(messages []Message) int

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

func EstimateTokens(text string) int

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 边界会拆分

Types

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

Message 是用于估算 token 的消息格式. 与 api.RequestMessage 解耦,避免循环依赖.

type ModelInfo

type ModelInfo struct {
	// ContextWindow 上下文窗口大小(token 数)
	ContextWindow int
	// InputPricePerMillion 每百万 input token 的价格(美元)
	InputPricePerMillion float64
	// OutputPricePerMillion 每百万 output token 的价格(美元)
	OutputPricePerMillion float64
}

各模型的上下文窗口和定价信息.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL