- 新增 tokenizer 包(tiktoken-go)按模型估算 token, 未知模型回退 cl100k_base - passthrough 提取请求输入文本 + SSE 已生成内容, 客户端断开时记 canceled - usage 计费范围扩展: canceled(流式中断)按已生成部分收费 Co-Authored-By: Claude <noreply@anthropic.com>
25 lines
590 B
Go
25 lines
590 B
Go
// Package tokenizer 按模型估算 token 数(tiktoken-go)。
|
|
// 用于流式中断时对已生成内容做近似计费;未知模型回退 cl100k_base。
|
|
package tokenizer
|
|
|
|
import "github.com/tiktoken-go/tokenizer"
|
|
|
|
// Count 估算文本 token 数;空文本返回 0。
|
|
func Count(text, model string) int {
|
|
if text == "" {
|
|
return 0
|
|
}
|
|
enc, err := tokenizer.ForModel(tokenizer.Model(model))
|
|
if err != nil {
|
|
enc, err = tokenizer.Get(tokenizer.Cl100kBase)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
}
|
|
toks, _, err := enc.Encode(text)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return len(toks)
|
|
}
|