Skip to content

修复:处理TokenCounterProcessor中tiktoken特殊标记编码错误导致请求失败的问题#45

Merged
mirrorange merged 1 commit intomirrorange:mainfrom
Huan-zhaojun:pr/fix/tiktoken-special-token-encoding
Feb 22, 2026
Merged

修复:处理TokenCounterProcessor中tiktoken特殊标记编码错误导致请求失败的问题#45
mirrorange merged 1 commit intomirrorange:mainfrom
Huan-zhaojun:pr/fix/tiktoken-special-token-encoding

Conversation

@Huan-zhaojun
Copy link
Copy Markdown
Contributor

概要

  • 修复用户消息包含 OpenAI 特殊 token(如 <|endofprompt|>)时请求崩溃的问题
  • 添加 disallowed_special=() 将特殊 token 当作普通文本编码
  • 添加 try-except 兜底,确保 token 计数永远不会中断主请求流程

问题描述

当用户消息中包含 tiktoken cl100k_base 的特殊 token(如 <|endofprompt|>)时,
encoder.encode() 抛出 ValueError,该异常通过 lazy generator 在流式传输过程中冒泡,
导致整个请求失败(流式/非流式均受影响)。

Token 计数仅用于使用量估算,属于非关键功能,应遵循 fail-open 设计原则。

修改内容

app/processors/claude_ai/token_counter_processor.py

  • _calculate_input_tokens:使用 disallowed_special=() 编码 + 异常降级估算
  • _calculate_output_tokens:同上

预期

  • 发送包含 <|endofprompt|> 的流式请求 — 正常返回~

用户消息包含 <|endofprompt|> 等 OpenAI 特殊 token 时,
tiktoken encoder.encode() 抛出 ValueError 导致整个流式响应中断。
添加 disallowed_special=() 参数将特殊 token 当作普通文本编码,
并增加 try-except 兜底确保 token 计数不会影响主流程。

(cherry picked from commit 460b97f)
@mirrorange mirrorange merged commit 51502c0 into mirrorange:main Feb 22, 2026
1 check passed
@Huan-zhaojun Huan-zhaojun deleted the pr/fix/tiktoken-special-token-encoding branch February 23, 2026 15:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants