AI Token Counter

Count tokens locally for OpenAI, Claude, Gemini, DeepSeek, and other AI workflows. Your text stays in your browser.

Input type
133 characters20 source words

Tokens across models

Exact BPE counts for supported OpenAI encodings; proxy estimates for other providers.

ModelTokensContext usedInput estimateMethod

GPT-5.4

OpenAI

26
0.01%
<$0.0001Estimate

GPT-4o

OpenAI

26
0.02%
<$0.0001Exact BPE

GPT-4o mini

OpenAI

26
0.02%
<$0.0001Exact BPE

GPT-4 / GPT-3.5

OpenAI

27
0.02%
<$0.0001Exact BPE

Claude Sonnet

Anthropic

26
0.01%
<$0.0001Estimate

Gemini 2.5 Pro

Google

26
0.00%
<$0.0001Estimate

DeepSeek V3

DeepSeek

26
0.02%
<$0.0001Estimate

What is counted?

The counter includes exactly the text in the editor. HTML mode first removes scripts, styles, navigation, footers, and templates, then estimates the cleaned Markdown.

Why counts differ?

Tokenization depends on the model vocabulary. OpenAI encodings are calculated locally; unsupported provider vocabularies use a clearly labeled proxy estimate.

LLM Engineering & Token Economics Guide

LLM Token Calculation & Estimation Architecture

Definitive engineering solutions for calculating API tokens, understanding Byte-Pair Encoding (BPE) across code vs. natural language, estimating 250 GB+ dataset volumes, and avoiding truncation in mixed-language payloads.

Interactive File Size & Dataset Token Estimator
Rule-of-Thumb Engine

Estimated Tokens

325,059

Based on 1 MB (~1.00 MB raw bytes)

GPT-4o Input

$0.81

$2.50/M
Claude Sonnet

$0.98

$3.00/M
DeepSeek V3

$0.09

$0.27/M
Cost & API CalculationPricing Formula

How can I calculate how many tokens a given piece of text will use for LLM APIs and estimate the API cost per request?

Billing Formula & Key Takeaway:

To calculate token usage for a given text, execute a local Byte-Pair Encoding (BPE) tokenization pass using the model family's specific vocabulary: OpenAI uses o200k_base (for GPT-4o, GPT-4o mini, o1, o3) and cl100k_base (for GPT-4 and GPT-3.5); Anthropic uses Claude Byte BPE; and DeepSeek uses a 128k BPE vocabulary. To estimate the total cost per API request, use the standard billing formula:
Total Cost = (Prompt Tokens × Input Rate / 1,000,000) + (Completion Tokens × Output Rate / 1,000,000) + (Cached Tokens × Cache Rate / 1,000,000)For pre-flight checks, use client-side WASM libraries (like gpt-tokenizer) to count tokens locally without API latency, and verify actual billable usage from the response.usage.prompt_tokens payload.

1. Input (Prompt) Tokens

Encompasses system instructions, few-shot examples, injected web/document context, and user query. Billed at standard input rates ($2.50/M on GPT-4o, $0.27/M on DeepSeek).

2. Prompt Caching Discount

Static prompts >1,024 tokens that repeat across requests qualify for prompt caching, slashing input costs by 75% to 90% (OpenAI charges $1.25/M; Anthropic charges 10% of base rate).

3. Output (Completion) Tokens

Generated response tokens are typically 3x to 4x more expensive per token ($10.00/M on GPT-4o, $1.10/M on DeepSeek) due to sequential autoregressive generation overhead.

Tokenization ArchitectureBPE Vocabulary Evolution

How do different tokenization methods affect token counts for code versus natural language, and which approach typically yields fewer tokens?

Token Density Comparison:

Tokenization algorithms assign token IDs based on pre-compiled subword frequency dictionaries. For natural English prose, words condense efficiently into whole words or common stems at a high density of ~4.0 characters per token (~0.75 words per token). In source code, however, older tokenizers (cl100k_base with 100k vocab) severely fragmented syntax—splitting leading indentation spaces, camelCase variable names, and syntax punctuation (::, ->, ===) into 2 to 4 separate tokens, resulting in a low density of 2.3 to 2.8 characters per token. Modern expanded-vocabulary tokenizers (such as o200k_base with 200,000 tokens, Gemini with 256,000 tokens, and DeepSeek with 128,000 tokens) feature dedicated multi-space tokens (2, 4, 8 spaces) and language keywords, yielding 15% to 30% fewer tokens for code than older BPE methods.

Content Domain / SyntaxOlder BPE (cl100k)Modern BPE (o200k / DeepSeek)Token Density (Chars/Token)Token Reduction
Natural English Prose1,000 tokens / 4,000 chars960 tokens / 4,000 chars~4.0 – 4.2~4% savings
Python Code (with 4-space tabs)1,550 tokens / 4,000 chars1,210 tokens / 4,000 chars~3.1 – 3.422% fewer tokens
TypeScript / JavaScript Code1,480 tokens / 4,000 chars1,190 tokens / 4,000 chars~3.2 – 3.520% fewer tokens
Raw HTML & Inline CSS2,100 tokens / 4,000 chars1,750 tokens / 4,000 chars~2.2 – 2.4Heavy syntactic waste
Clean Markdown (Converted)1,080 tokens / 4,000 chars1,020 tokens / 4,000 chars~3.8 – 4.0Optimal AI density
Big Data Estimation Pipeline250 GB Source Code Benchmark

What is the best method to estimate total tokens and expected cost for a very large dataset (for example, 250 GB of source code) before sending it to an LLM?

Large-Scale Estimation Framework:

For massive multi-gigabyte corpora like 250 GB of source code, attempting to stream or tokenize the entire dataset upfront is prohibitively slow and expensive. The industry-standard approach is the Stratified Representative Sampling Method: (1) Deduplicate & Filter: Strip non-code binaries (.git, lockfiles, compiled binaries, minified bundles), which typically reduces raw disk size by 40%–60%; (2) Stratified 1% Sampling: Extract a 1% random sample (~1 GB to 2.5 GB) partitioned proportionally across major file extensions (.py, .ts, .java, .md); (3) Local Multithreaded Tokenization: Pass the sample through a high-performance local tokenizer (Python tiktoken with multiprocessing or Rust tiktoken-rs) processing at 15–30 MB/sec/core; (4) Extrapolate Volume: Multiply the category token densities against total corpus size. For 250 GB of clean code, the expected volume is approximately 75 to 85 Billion tokens; and (5) Batch Pricing: Apply 50% Batch API discounts (reducing OpenAI or Anthropic costs from ~$200,000 to ~$100,000, or DeepSeek V3 to ~$21,600).

Mathematical Extrapolation for 250 GB Dataset:

Raw Codebase Size

250 GB

~268.4 Billion Bytes
Average Code Density

~0.31 Tokens / Byte

~3.22 characters per token
Total Token Estimate

~83.2 Billion Tokens

± 4% sample error margin
# Python Stratified Sample Tokenizer Script
import os, random, tiktoken
from pathlib import Path

enc = tiktoken.get_encoding("o200k_base")

def sample_and_estimate(dir_path: str, sample_ratio=0.01):
    total_bytes, sample_bytes, sample_tokens = 0, 0, 0
    all_files = [p for p in Path(dir_path).rglob('*') if p.is_file() and not p.name.startswith('.')]
    
    for f in all_files:
        size = f.stat().st_size
        total_bytes += size
        if random.random() < sample_ratio:
            try:
                text = f.read_text(errors='ignore')
                sample_bytes += size
                sample_tokens += len(enc.encode(text))
            except Exception:
                pass
                
    tokens_per_byte = sample_tokens / max(sample_bytes, 1)
    estimated_total_tokens = int(total_bytes * tokens_per_byte)
    print(f"Total Tokens: {estimated_total_tokens:,} (Density: {tokens_per_byte:.3f} tokens/byte)")
Multilingual & Edge CasesUTF-8 Explosion & Truncation

My input contains mixed languages, emojis, and HTML/markdown — how can I accurately count tokens, avoid unexpected truncation, and map token limits to character/file-size limits?

Safeguards & Buffer Strategy:

Mixed-syntax inputs create severe token density imbalances because Byte-Pair Encoders operate on underlying UTF-8 byte sequences. While ASCII English consumes 1 token per 4 characters, non-Latin scripts (CJK ideographs, Arabic, Cyrillic) split into 0.8 to 1.5 tokens per single character. Compound emojis (like family or skin-tone variations joined by Zero Width Joiners \u200D) trigger massive token explosion—consuming up to 4 to 7 tokens per visible emoji. Furthermore, raw HTML introduces a 300% token tax in structural tags. To prevent unexpected model truncation: (1) Pre-clean HTML to Markdown to eliminate tag noise; (2) Enforce a 15% safety buffer (e.g., restrict prompts to 105k tokens on a 128k context window to reserve generation space); and (3) Use token-aware splitters (such as tiktoken chunking) rather than character-count slicing to avoid severing multi-byte UTF-8 sequences.

🌐CJK & Non-Latin Scripts

Chinese, Japanese, and Korean characters consist of 3 UTF-8 bytes. In older BPEs, one ideograph consumed 2–3 tokens. In o200k and DeepSeek, density is improved to ~0.7–1.2 tokens/char.

👨‍👩‍👧‍👦Emoji ZWJ Explosion

Complex emojis combine multiple unicode codepoints via Zero Width Joiners (U+200D). A single family emoji can register as 5 to 7 distinct BPE tokens.

The 15% Context Buffer

Never fill context to 100%. Providers enforce strict request payload caps; exceeding limits truncates generation or triggers a fatal context_length_exceeded API error.

Rules of Thumb & MultipliersEmpirical Estimation Benchmarks

Is there a reliable formula or rule of thumb to convert file size or number of characters into an estimated number of tokens (e.g., tokens per character or tokens per word) for planning API usage?

Universal Rule of Thumb:

Yes. While exact token counts depend on tokenizer vocabulary, AI infrastructure engineers rely on four proven empirical conversion rules:
• Natural English Text: Tokens ≈ Words × 1.33 or Tokens ≈ Characters ÷ 4.0 (0.25 tokens/char).
• Source Code (Python, TS, Go): Tokens ≈ Characters ÷ 3.2 (0.31 tokens/char).
• Clean Markdown: Tokens ≈ Characters ÷ 3.8 (0.26 tokens/char).
• Raw Plain Text File Size Rule: 1 KB ≈ 250–320 tokens; 1 MB text ≈ 250,000–320,000 tokens; and 1 GB text ≈ 250–320 Million tokens.
Use the universal baseline formula Tokens = Raw Bytes × 0.28 for fast ±5% budget estimations across mixed technical repositories.

Content TypeTokens per WordTokens per CharacterTokens per 1 MB FilePlanning Rule of Thumb
English Articles / Prose~1.30 – 1.350.24 – 0.26~260,000 tokensChars ÷ 4
Clean Markdown (GFM)~1.35 – 1.450.25 – 0.28~275,000 tokensChars ÷ 3.8
Source Code (Indented)~1.60 – 1.850.30 – 0.33~315,000 tokensChars ÷ 3.2
JSON / XML API Payloads~1.80 – 2.400.38 – 0.44~410,000 tokensChars ÷ 2.4
CJK (Chinese / Japanese)N/A (character-based)0.80 – 1.20~850,000 tokensChars × 1.0

Need webpage extraction first? Open the Website converter or use the URL to Markdown converter.