---
title: "Token Counting Utilities and Accurate Usage Estimation in Google ADK"
date: "2026-12-05T08:10:00+07:00"
description: "Master pre-flight token counting, multimodal token calculation, and exact cost estimation using the google-genai SDK and Google ADK utilities."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-token-counting-utilities-accurate-usage-estimation.jpg"
alt: "Token Counting Utilities in Google ADK"
tags: ['google-adk', 'gemini', 'tokens', 'cost-optimization', 'python']
---

Estimating token usage before invoking an LLM is a prerequisite for robust enterprise AI engineering. Without pre-flight counting, agents risk breaching context limits, blowing past per-turn token budgets, or triggering unexpected billing costs on massive multimodal inputs.

While informal heuristics (like `words * 1.3` or `chars / 4`) work for rough estimates in plain English, they fail dramatically on code, structured JSON, non-Latin scripts (such as Thai, Arabic, or Japanese), and multimodal inputs (images, audio, PDF pages).

In this tutorial, we explore exact token counting utilities provided by the `google-genai` SDK and Google Agent Development Kit (ADK).

---

### The Tokenizer Difference: Why Heuristics Fail

Gemini models utilize a byte-level Byte-Pair Encoding (BPE) tokenizer with a 256,000-token vocabulary optimized for code and multilingual fidelity.

```
Heuristic Estimation vs. Real Gemini Tokenization:
Text: '{"order_id": 98412, "status": "APPROVED"}'
- Heuristic (chars / 4): 43 / 4 ≈ 10 tokens
- Real Gemini Tokenizer: 17 tokens (+70% difference!)

Text (Thai): 'ระบบเอเจนต์ทำงานอัตโนมัติ'
- Heuristic (chars / 4): 26 / 4 ≈ 6 tokens
- Real Gemini Tokenizer: 22 tokens (+266% difference!)
```

Relying on string heuristics for budget gatekeeping will cause unexpected runtime exceptions or silent context truncation.

---

### Using `client.models.count_tokens`

The official `google-genai` SDK provides direct access to Gemini's tokenization engine without incurring inference generation charges:

```python
import asyncio
from google.genai import Client

async def measure_prompt_tokens():
    client = Client()

    # 1. Plain text count
    text_content = "Analyze the annual balance sheet and compute EBITDA margin."
    response = await client.models.count_tokens(
        model="gemini-3.8-flash",
        contents=text_content
    )
    print(f"Text Token Count: {response.total_tokens}")

    # 2. Multi-part structured message
    complex_contents = [
        "System: You are an expert code reviewer.",
        "User: Review the following Python function:",
        "def compute_hash(data: bytes) -> str:\n    return hashlib.sha256(data).hexdigest()"
    ]
    multi_response = await client.models.count_tokens(
        model="gemini-3.8-pro",
        contents=complex_contents
    )
    print(f"Multi-part Token Count: {multi_response.total_tokens}")

if __name__ == "__main__":
    asyncio.run(measure_prompt_tokens())
```

---

### Multimodal Token Counting (Images, Audio, Video, PDF)

Token calculation for multimodal inputs does not depend on file size in bytes, but on media resolution and duration:

- **Images**: Fixed tile calculation (typically 258 tokens per 768x768 tile).
- **Audio**: Approximately 32 tokens per second of audio.
- **Video**: Sampled at 1 frame per second (approx. 258 tokens/sec).
- **PDF Documents**: 258 tokens per rendered page plus embedded text tokens.

```python
from google.genai.types import Part

async def count_multimodal_tokens(client: Client, image_path: str, audio_path: str):
    image_part = Part.from_bytes(
        data=open(image_path, "rb").read(),
        mime_type="image/jpeg"
    )
    
    result = await client.models.count_tokens(
        model="gemini-3.8-flash",
        contents=[image_part, "Describe the technical architecture shown in this diagram."]
    )
    
    print(f"Multimodal Total Tokens: {result.total_tokens}")
```

---

### Building a Pre-Flight Budget Guard in ADK

Wrap your agent calls with a `ContextGuard` that aborts or compresses prompts that exceed safety limits:

```python
class PreFlightContextGuard:
    def __init__(self, max_allowed_tokens: int = 100000):
        self.client = Client()
        self.max_tokens = max_allowed_tokens

    async def validate_turn(self, model: str, prompt_parts: list) -> int:
        token_info = await self.client.models.count_tokens(
            model=model,
            contents=prompt_parts
        )
        
        count = token_info.total_tokens
        if count > self.max_tokens:
            raise ValueError(
                f"Context budget exceeded! Prompt contains {count} tokens "
                f"(Hard limit is {self.max_tokens}). Triggering compaction."
            )
            
        return count
```

---

### Exact Cost Estimation Utility

Combine token counts with published pricing to compute exact costs per turn:

```python
from decimal import Decimal

# Gemini 3.8 Flash Pricing (Per Million Tokens)
INPUT_COST_PER_M = Decimal("0.10")    # $0.10 per 1M input tokens
OUTPUT_COST_PER_M = Decimal("0.40")   # $0.40 per 1M output tokens
CACHED_INPUT_PER_M = Decimal("0.025") # $0.025 per 1M cached tokens

def calculate_turn_cost(prompt_tokens: int, completion_tokens: int, cached_tokens: int = 0) -> Decimal:
    regular_input = prompt_tokens - cached_tokens
    
    cost = (
        (Decimal(regular_input) / Decimal("1000000")) * INPUT_COST_PER_M +
        (Decimal(cached_tokens) / Decimal("1000000")) * CACHED_INPUT_PER_M +
        (Decimal(completion_tokens) / Decimal("1000000")) * OUTPUT_COST_PER_M
    )
    return cost.quantize(Decimal("0.000001"))

# Example: 150k input (100k cached), 2k completion
cost = calculate_turn_cost(prompt_tokens=150000, completion_tokens=2000, cached_tokens=100000)
print(f"Turn Cost: ${cost:.6f} USD")
```

---

### Key Takeaways

1. **Never use heuristic char/word counts** for multi-lingual or code-heavy prompts; use `count_tokens`.
2. **Account for multimodal tile fixed costs**: PDFs and high-res images contribute substantial token counts.
3. **Run pre-flight checks before expensive runs** to eliminate `400 InvalidArgument (Context window exceeded)` errors in long-running autonomous loops.
