@@ -2,6 +2,7 @@ import { ParsedInvokeCall, ParserEvent } from "./types.ts";
22import { SSEWriter } from "./sse.ts" ;
33import { TextAggregator } from "./aggregator.ts" ;
44import { ProxyConfig } from "./config.ts" ;
5+ import { countTokensWithTiktoken } from "./tiktoken.ts" ;
56
67function generateToolId ( ) : string {
78 // 生成随机 ID:toolu_ + 12位随机字符
@@ -116,8 +117,8 @@ export class ClaudeStream {
116117 private async flushText ( text : string ) {
117118 if ( ! text ) return ;
118119 await this . ensureTextBlock ( ) ;
119- // 使用 tiktoken 估算 token,然后应用倍数
120- const estimatedTokens = Math . ceil ( text . length * 0.25 ) ; // 简单估算
120+ // 使用 tiktoken 精确计算 token,然后应用倍数
121+ const estimatedTokens = countTokensWithTiktoken ( text , "cl100k_base" ) ;
121122 this . context . totalOutputTokens += estimatedTokens ;
122123 await this . writer . send ( {
123124 event : "content_block_delta" ,
@@ -167,8 +168,8 @@ export class ClaudeStream {
167168 private async emitThinking ( content : string ) {
168169 if ( ! content ) return ;
169170 await this . ensureThinkingBlock ( ) ;
170- // 使用 tiktoken 估算 token,然后应用倍数
171- const estimatedTokens = Math . ceil ( content . length * 0.25 ) ; // 简单估算
171+ // 使用 tiktoken 精确计算 token,然后应用倍数
172+ const estimatedTokens = countTokensWithTiktoken ( content , "cl100k_base" ) ;
172173 this . context . totalOutputTokens += estimatedTokens ;
173174 await this . writer . send ( {
174175 event : "content_block_delta" ,
0 commit comments