Documentation
¶
Overview ¶
本文件复刻官方 token-meter/src/estimate.ts:固定密度启发式 token 估算。 在真正分词之前,用"每 4 字符 1 token + 每块结构开销 + 每条消息 role 开销"的 统一口径,让计量服务与上下文投影对同一份内容算出相同数字。
Package tokenmeter 提供 Token 计量与预算(Token Meter)。
对齐上游:packages/util/token-meter
本文件对应任务 M31:Token Meter 计量与预算。
设计要点:
- 计量每次模型请求的 prompt/completion token,按会话累计;
- session-level budget cap:一旦累计超过预算上限,在下一轮请求开始前以 budget deny 拒绝,且不产生真实的 LLM 调用(拦在请求层);
- 表面节点定价:可对派生节点(如 assistant/message、tool/result 快照)按 token 计费, 供 UI/SDK 展示成本。
Index ¶
Constants ¶
View Source
const BudgetDeniedError = "token-meter: session budget exceeded; request rejected before LLM call"
BudgetDeniedError 是预算拒绝错误(稳定文案,便于上层审计)。
View Source
const (
// RoleOverhead 每条消息 role 字段框架开销。
RoleOverhead = 4
)
Variables ¶
This section is empty.
Functions ¶
func EstimateContent ¶
func EstimateContent(blocks []llm.ContentBlock) int
EstimateContent 按固定密度估算一组内容块的 token(含每块结构开销)。
func EstimateMessage ¶
EstimateMessage 估算一条模型可见消息(内容 + role 框架)。
Types ¶
type Meter ¶
type Meter struct {
// contains filtered or unexported fields
}
Meter 是会话级 token 计量器。
type RequestRecord ¶
type RequestRecord struct {
Seq int `json:"seq"`
Usage TokenUsage `json:"usage"`
}
RequestRecord 是一次计量记录。
type SurfaceNode ¶
type SurfaceNode struct {
// Kind 节点类型(如 "assistant/message")。
Kind string
// Count 出现次数。
Count int
}
SurfaceNode 描述某类派生节点出现的次数。
type SurfacePricing ¶
SurfacePricing 是表面节点(派生节点)的定价映射。 每种节点类型给出每节点的 token 权重;成本 = weight * count。
func (SurfacePricing) CostOf ¶
func (p SurfacePricing) CostOf(entries []SurfaceNode) int
CostOf 计算一批表面节点的估算 token 成本。未知节点类型 → 无成本。
type TokenUsage ¶
type TokenUsage struct {
// PromptTokens 输入 token。
PromptTokens int `json:"promptTokens"`
// CompletionTokens 输出 token。
CompletionTokens int `json:"completionTokens"`
}
TokenUsage 是一次模型请求的 token 用量。
Click to show internal directories.
Click to hide internal directories.