Skip to content

Commit 63e7c04

Browse files
改进token计算精度并修复类型错误
- 在 openai_to_claude.ts 中使用 tiktoken 精确计算 token 数量,替代简单的长度估算 - 修复 tiktoken.ts 中的 TypeScript 类型错误,添加类型断言以支持模型参数
1 parent 81df3e9 commit 63e7c04

2 files changed

Lines changed: 7 additions & 5 deletions

File tree

deno-proxy/src/openai_to_claude.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { ParsedInvokeCall, ParserEvent } from "./types.ts";
22
import { SSEWriter } from "./sse.ts";
33
import { TextAggregator } from "./aggregator.ts";
44
import { ProxyConfig } from "./config.ts";
5+
import { countTokensWithTiktoken } from "./tiktoken.ts";
56

67
function 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",

deno-proxy/src/tiktoken.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ function getEncoderForModel(model: string): any {
2121
let encoder;
2222
try {
2323
// 尝试根据模型获取对应的编码器
24-
encoder = encodingForModel(model);
24+
// 使用类型断言来告诉 TypeScript 这是一个有效的 TiktokenModel
25+
encoder = encodingForModel(model as any);
2526
} catch (error) {
2627
// 如果模型不支持,回退到 cl100k_base (GPT-4 的编码器)
2728
console.warn(`Model ${model} not found in tiktoken, falling back to cl100k_base`);

0 commit comments

Comments
 (0)