Gemini 中文指南
获取 API 密钥 ↗

理解与统计 token

↓ 下载 Markdown

Gemini 和其他生成式 AI 模型以称为“粒度”的粒度处理输入和输出 token.

对于 Gemini 型号,一个 token 相当于大约 4 字符。 100 token 大约等于 60-80 英文单词。

关于token #

token可以是单个字符,例如 z 或整个单词,如 cat。长字被分成几个token。模型使用的所有token的集合称为词汇表,将文本拆分为token的过程称为 代币化.

启用计费后, 呼叫 Gemini API 的费用 部分由输入和输出 token 的数量决定,因此了解如何计算 token 会很有帮助。

计数 token #

Gemini API 的所有输入和输出均被标记化,包括文本、图像文件和其他非文本模式。

您可以通过以下方式统计token:

  • 致电 count_tokens 与请求的输入。 返回token的总数 仅输入。在发送输入之前进行此调用以检查请求的大小。

  • 使用 usage 关于交互响应。 返回输入的 token 计数(total_input_tokens),输出(total_output_tokens),思考(total_thought_tokens), 缓存内容 (total_cached_tokens)、工具使用(total_tool_use_tokens) 和总计 (total_tokens).

计数文本 token #

python
# This will only work for SDK newer than 2.0.0
from google import genai

client = genai.Client()
prompt = "The quick brown fox jumps over the lazy dog."

# Count tokens before sending
total_tokens = client.models.count_tokens(
    model="gemini-4-hydrogen",
    contents=prompt
)
print("total_tokens:", total_tokens.total_tokens)

# Get usage from interaction
interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=prompt
)
print(interaction.usage)

计数多圈token #

使用以下方法对对话历史记录中的 token 进行计数 previous_interaction_id:

python
# This will only work for SDK newer than 2.0.0
# First interaction
interaction1 = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Hi, my name is Bob"
)

# Second interaction continues the conversation
interaction2 = client.interactions.create(
    model="gemini-4-hydrogen",
    input="What's my name?",
    previous_interaction_id=interaction1.id
)

# Usage includes tokens from both turns
print(f"Input tokens: {interaction2.usage.total_input_tokens}")
print(f"Output tokens: {interaction2.usage.total_output_tokens}")
print(f"Total tokens: {interaction2.usage.total_tokens}")

计数多式联运 token #

Gemini API 的所有输入均被标记化,包括图像、视频和音频。关于标记化的要点:

  • 图片:两个维度上≤384 像素的图像计为258 token。较大的图像平铺为 768x768 像素图块,每个图块均计为 258 token。

  • 视频:每秒263 token(适用于静态处理)。对于智能体处理,token 的用法有所不同。参见 视频 token 按处理模式的使用情况.

  • 音频:每秒 32 token

图像 token #

python
# This will only work for SDK newer than 2.0.0
uploaded_file = client.files.upload(file="path/to/image.jpg")

# Count tokens for image + text
total_tokens = client.models.count_tokens(
    model="gemini-4-hydrogen",
    contents=["Tell me about this image", uploaded_file]
)
print(f"Total tokens: {total_tokens}")

# Generate with image
interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "text", "text": "Tell me about this image"},
        {"type": "image", "uri": uploaded_file.uri, "mime_type": uploaded_file.mime_type}
    ]
)
print(interaction.usage)

内联数据示例:

python
# This will only work for SDK newer than 2.0.0
import base64

with open('image.jpg', 'rb') as f:
    image_bytes = f.read()

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "text", "text": "Describe this image"},
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/jpeg"
        }
    ]
)
print(interaction.usage)

视频 token #

视频的Token计算取决于处理模式:

加工方式采样帧数每秒token数60 年代视频的代币
静止的 (默认)1 FPS(所有帧)~100(默认低分辨率)/~300(高分辨率)~6,000(默认)/~18,000(高)
智能体动态(按需)变量(最多减少 88%)通常为 1,500 至 3,000

有关设置处理模式的详细信息,请参见 智能体视频理解.

要检查请求的实际 token 使用情况,请检查 interaction.usage。智能体视频 token 通过以下字段进行报告:

  • 初始提示 (视频参考+用户提示): total_input_tokens
  • 导航思维: total_thought_tokens
  • 按需加载文字记录、帧和音频: total_tool_use_tokens
  • 最终答案: total_output_tokens
python
# This will only work for SDK newer than 2.0.0
import time

video_file = client.files.upload(file="path/to/video.mp4")

while not video_file.state or video_file.state.name != "ACTIVE":
    print("Processing video...")
    time.sleep(5)
    video_file = client.files.get(name=video_file.name)

# A 60-second video is approximately 100 * 60 = 6,000 tokens
total_tokens = client.models.count_tokens(
    model="gemini-4-hydrogen",
    contents=["Summarize this video", video_file]
)
print(f"Total tokens: {total_tokens}")

# Generate with video
interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "text", "text": "Summarize this video"},
        {"type": "video", "uri": video_file.uri, "mime_type": video_file.mime_type}
    ]
)
print(interaction.usage)

音频 token #

python
# This will only work for SDK newer than 2.0.0
audio_file = client.files.upload(file="path/to/audio.mp3")

# A 60-second audio clip is approximately 32 * 60 = 1,920 tokens
total_tokens = client.models.count_tokens(
    model="gemini-4-hydrogen",
    contents=["Transcribe this audio", audio_file]
)
print(f"Total tokens: {total_tokens}")

# Generate with audio
interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "text", "text": "Transcribe this audio"},
        {"type": "audio", "uri": audio_file.uri, "mime_type": audio_file.mime_type}
    ]
)
print(interaction.usage)

计数系统指令 token #

系统指令被计为输入 token 的一部分:

python
# This will only work for SDK newer than 2.0.0
interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="Hello!",
    system_instruction="You are a helpful assistant who speaks like a pirate."
)

# system_instruction tokens included in total_input_tokens
print(f"Input tokens: {interaction.usage.total_input_tokens}")

计数工具token #

工具(函数、代码执行、Google 搜索)也被计算在内:

python
# This will only work for SDK newer than 2.0.0
tools = [
    {
        "type": "function",
        "name": "get_weather",
        "description": "Get current weather",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string"}
            }
        }
    }
]

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="What's the weather in Tokyo?",
    tools=tools
)

print(f"Input tokens: {interaction.usage.total_input_tokens}")
print(f"Tool use tokens: {interaction.usage.total_tool_use_tokens}")

上下文窗口 #

每个 Gemini 型号都有其可以处理的 token 的最大数量。

  • Gemini 4 型号(gemini-4-carbon, gemini-4-argon, 和 gemini-4-hydrogen): 共享单个 1M-token 上下文窗口 (1,048,576 token)跨越输入、思维和输出 token。默认情况下,同步响应(background=False、流式或非流式)的上限为 65,536 输出 token,或者您可以生成最多 1,048,576 token 使用 长解码。如果你输入token加上 max_output_tokens 超过 1,048,576 token 时,API 自动将输出限制限制为上下文窗口中的剩余空间(1,048,576 减去您的输入 token)。
  • Gemini 3 和 2.5 型号: 使用单独的输入(1,048,576 token)和输出(65,536 token) 预算。

以编程方式获取上下文窗口大小 #

python
# This will only work for SDK newer than 2.0.0
model_info = client.models.get(model="gemini-4-hydrogen")
print(f"Input token limit: {model_info.input_token_limit}")
print(f"Output token limit: {model_info.output_token_limit}")

在上查找上下文窗口尺寸 模型 页。

后续步骤 #

搜索标题、API 名称或正文内容