You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

tiktoken与Vertex AI count_tokens计数差异过大问题求助

排查Vertex AI 400状态码:Token计数差异问题

今日排查Vertex AI返回的400状态码问题时,遇到了提示词Token计数的矛盾情况:

  • 初期用tiktoken的cl100k_base编码统计提示词Token数,结果约1.87M,完全在Gemini 1.5 Pro的2M限制范围内
  • 改用Gemini官方的count_tokens方法统计,结果却达到2.07M,超出限制触发400错误(要是能直接返回‘over token limit’的错误提示就好了!)

无法想象cl100k_base与Gemini实际使用的Tokenizer之间会有近200k的差异,怀疑是自己错误使用了tiktoken工具。

相关代码如下:

import tiktoken
from vertexai.generative_models import GenerativeModel

# ---------------------------------------------------

def num_tokens_from_string(string: str, encoding_name: str) -> int:
    """Returns the number of tokens in a text string."""
    encoding = tiktoken.get_encoding(encoding_name)
    num_tokens = len(encoding.encode(string))
    return num_tokens

# Trust I have auth and blob client setup here...

user_prompt = await download_blob_as_text(blob_client)

num_tokens = num_tokens_from_string(user_prompt, "cl100k_base")
logging.info(f'### Number of Tokens in user_prompt: {num_tokens}') # ~1.87M

# Trust I have all the vertex auth, project init, etc. here...

model = GenerativeModel("gemini-1.5-pro-001")
response = model.count_tokens(user_prompt)
logging.info(f'### Number of Tokens in user_prompt: {num_tokens}') # ~2.07M

内容的提问来源于stack exchange,提问作者SeaDude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 19:57:07