Tool overview
What is an LLM Token Counter?
An LLM token counter estimates how many tokens a prompt uses under common BPE encodings and visualizes token boundaries.
Why use this LLM Token Counter?
Budget context windows and compare encodings locally before paying for API calls or truncating production prompts.
Key Features
Tiktoken-style encodings, boundary map, cost/context cues, and private in-browser tokenization.
How to Use
Follow these steps to get accurate results from the tool interface above.
- Paste the exact text you will send to the model: system prompt, user message, tool JSON, or a concatenated RAG context block.
- Compare the three encoding cards — o200k_base for GPT-4o, cl100k_base for GPT-4 / Claude approximation, p50k_base for legacy Codex.
- Open the Token Boundary Map and hover spans to inspect Token IDs; switch map encoding when you change target models.
- Click Minify JSON for schemas and tool payloads, or Strip Spaces for padded prose, then re-check the counts.
- Enter estimated monthly volume to project input cost for GPT-4o, GPT-4o mini, and Claude 3.5 Sonnet on this payload.
- Copy multi-encoding metrics into your design doc, ticket, or PR so the team shares one budget number.
- Iterate: remove the most expensive few-shot or schema section first, re-count, and keep a 10–20% safety margin for chat wrappers.
- For agent stacks, jump to AI Agent Builder to assemble tools + MCP + prompt and re-check the combined budget there.
LLM Token Counter — Complete Guide & Use Cases
Authoritative walkthrough: encodings, step-by-step budgeting, real use cases, overflow fixes, boundary map, and pricing notes — all runnable against the cockpit above.
LLM Token Counter guide — start here
This page is the canonical guide to counting LLM tokens in the browser with DevUtilities. Use the interactive Prompt Budget Cockpit above while you read, or jump to a topic below. Everything runs client-side via js-tiktoken — prompts never leave your machine.
What the Prompt Budget Cockpit does
The LLM Token Counter (Prompt Budget Cockpit) tokenizes text with the same BPE tables OpenAI ships in tiktoken. It compares three encodings side-by-side, visualizes token boundaries, estimates input cost for GPT-4o, GPT-4o mini, and Claude 3.5 Sonnet, and helps you shrink prompts before they hit a production API.
What you get
- Concurrent counts for o200k_base (GPT-4o), cl100k_base (GPT-4 / Claude approximation), and p50k_base (legacy Codex)
- Color-coded Token Boundary Map with hoverable Token IDs
- Minify JSON and Strip Spaces actions to reduce prompt weight
- Per-query and monthly cost extrapolations from static published input rates
- Copyable multi-encoding metrics for design docs and budget reviews
Use this tool when
- You need to know whether a system prompt + tools + user message fits a context window
- You are comparing GPT-4o vs Claude-ish token budgets before picking a model
- You want a local, privacy-safe count without calling OpenAI or Anthropic APIs
- You are trimming RAG chunks, few-shot examples, or JSON schemas that inflate cost
Do not expect
- Byte-identical Claude billing — Anthropic uses a different production tokenizer; cl100k_base is a useful English approximation
- Chat wrapper overhead (role tags, tool envelopes) that APIs add around raw text
- Live market prices — the cost panel uses static published rates that can drift
o200k vs cl100k vs p50k — pick the right encoding
Token IDs are encoding-specific. The same English sentence can produce different lengths and different IDs under o200k_base vs cl100k_base. Always budget with the encoding your target model actually uses.
Encodings compared in this workspace
| Encoding | Typical models | When to use it here |
|---|---|---|
| o200k_base | GPT-4o, GPT-4o mini | Default for modern OpenAI chat and the cost cards for GPT-4o family |
| cl100k_base | GPT-4, GPT-4 Turbo, GPT-3.5 Turbo; Claude approximation | Legacy OpenAI chat budgets and rough Claude English estimates |
| p50k_base | Legacy Codex / older completion models | Historical comparisons and older completion pipelines |
Switch the Token Boundary Map encoding independently of the comparison cards when you need to inspect merges for a specific model family.
Step-by-step: count, optimize, and copy a budget
Follow this walkthrough the first time you open the cockpit. After that, most sessions are paste → compare → optimize → copy.
- Paste the full prompt payload you care about: system message, user turn, tool JSON, or a concatenated RAG context block.
- Read the three comparison cards. Note which encoding is highest — that is your conservative budget if you still need to pick a model.
- Open the Token Boundary Map and hover spans that look surprisingly long (URLs, emoji, indented JSON) to see concrete Token IDs.
- If the input is JSON-heavy, click Minify JSON. If it is prose with double spaces or padded newlines, click Strip Spaces.
- Enter your estimated monthly call volume to project GPT-4o, GPT-4o mini, and Claude 3.5 Sonnet input spend.
- Copy the metrics summary into a design doc, ticket, or PR description so the team shares one number.
What “good” looks like
- System + tools + average user turn leave headroom for the model’s reply inside the chosen context window
- JSON schemas are minified in production prompts even if humans edit pretty-printed copies
- Cost extrapolations use the encoding that matches the billed model
Use case: stop system-prompt context overflow
Problem: a support agent prompt keeps truncating mid-conversation after you add policies, tone rules, and three few-shot examples.
How this tool solves it
- Paste the current system prompt alone and record the o200k_base (or cl100k_base) count.
- Append each few-shot example one at a time and note the delta — drop the least valuable example first.
- Paste a representative user message and the tools JSON you send on every call; sum the pieces against your model’s context window.
- Use Strip Spaces on prose and Minify JSON on schemas, then re-count to quantify savings.
- Copy the final budget into your agent runbook so future prompt edits stay under the same ceiling.
Outcome: you know exactly which section blew the budget and how many tokens each optimization recovered — before another production truncation.
Use case: cut token waste in OpenAI tool schemas
Problem: OpenAI function-calling schemas are authored with indentation for readability, then pasted into live requests. Token spend climbs even though the logical schema did not change.
How this tool solves it
- Paste the pretty-printed tools array or parameters object into the input panel.
- Note the token count on the encoding your API model uses (usually o200k_base for GPT-4o).
- Click Minify JSON and compare the new count — the difference is pure whitespace tax.
- Inspect the boundary map: repeated keys and long enum lists often dominate; shorten descriptions before cutting fields.
- Ship the minified schema in API calls; keep the pretty copy only in source control or the Agent Builder editor.
Outcome: lower input cost on every tool-enabled call without changing tool behavior.
Use case: forecast monthly LLM input spend
Problem: finance asks for a monthly LLM spend estimate before you launch a feature that will call the model thousands of times.
How this tool solves it
- Build a realistic average payload (system + tools + typical user text) and paste it here.
- Confirm the comparison card for the encoding that matches your production model.
- Set Estimated monthly volume to your projected call count.
- Read the GPT-4o, GPT-4o mini, and Claude 3.5 Sonnet monthly columns to compare vendors on the same payload.
- Document that rates are static published input prices — refresh the estimate when vendors change pricing pages.
Outcome: a defensible, payload-specific forecast instead of a vague “tokens are cheap” guess.
Use case: size RAG chunks to a hard token budget
Problem: a RAG pipeline retrieves five chunks per query. Some chunks are mostly whitespace or boilerplate headers, and the model still misses the answer because useful text was truncated.
How this tool solves it
- Paste each candidate chunk separately and record token counts under your retrieval model’s encoding.
- Prefer denser chunks: Strip Spaces, remove repeated navigation headers, and drop near-duplicate paragraphs.
- Concatenate the top-k set you plan to send and verify the total still leaves room for the question and the answer.
- Use the boundary map to spot tokenizer-expensive sequences (long URLs, tables, emoji) that look short to humans.
- Set a hard token budget per query in your retriever using the measured totals from this tool.
Outcome: retrieval packs more signal per token and fails less often from silent context truncation.
Fix: context_length_exceeded and silent truncation
Symptoms: API 400 context_length_exceeded, truncated completions, or agents that “forget” early instructions mid-session.
Why it happens
The combined system prompt, tools, history, and user turn exceed the model’s context window. Pretty-printed JSON and long few-shot banks are common silent offenders.
Diagnose
Paste the exact payload your client sends (or reconstruct it). Compare the token total to the context window listed for your model. Identify the largest sections by counting them in isolation.
Fixes
- Minify JSON tool schemas and strip excess whitespace from prose.
- Move rarely used policies into on-demand retrieval instead of the always-on system prompt.
- Cap chat history (summarize or drop oldest turns) before each call.
- Switch to a larger-context model only after measuring — do not guess.
Re-count after every change. A 10% whitespace cut on a 8k-token tools blob often recovers more headroom than deleting a short policy paragraph.
Fix: local counts disagree with API usage
Symptoms: local counts look fine, but OpenAI usage dashboards disagree — or Claude bills differently than your spreadsheet.
Why it happens
You budgeted with the wrong encoding, or you compared raw text to an API that wraps messages with role and tool envelopes.
Diagnose
Confirm the model’s documented tokenizer. For GPT-4o family use o200k_base; for GPT-4 / 3.5 use cl100k_base. Treat Claude figures here as approximations only.
Fixes
- Switch the comparison focus and boundary map to the matching encoding.
- Count the serialized messages your SDK actually sends, not just the human-readable prompt draft.
- Add a small overhead buffer (often a few dozen to a few hundred tokens) for chat formatting when planning hard limits.
- For Anthropic billing, validate critical prompts against Anthropic’s own counter before locking SLAs.
Fix: pretty JSON and blank lines inflate tokens
Symptoms: token count drops dramatically after Minify JSON or Strip Spaces with no semantic change to the prompt.
Why it happens
BPE encodings charge for indentation newlines, alignment spaces, and repeated blank lines. Humans ignore them; tokenizers do not.
Diagnose
Paste the pretty payload, note the count, run Minify JSON / Strip Spaces, and compare. Large deltas mean whitespace was a primary cost driver.
Fixes
- Store human-editable pretty JSON in git; minify at request time.
- Avoid padding ASCII diagrams or huge indented logs inside system prompts.
- Collapse multi-blank-line section separators in long policy docs.
The boundary map makes whitespace tokens visible as separate colored spans — useful when teaching teammates why minify matters.
How to read the Token Boundary Map
The Token Boundary Map paints each BPE merge as a colored span. Colors cycle for visual separation only — they do not encode token categories.
How to read it
- Hover a span to reveal its numeric Token ID for the selected map encoding
- Long unbroken spans on URLs or base64 often mean expensive single-token or few-token chunks worth shortening
- Emoji and CJK text may use more tokens than Latin prose of the same visual length
- Change map encoding when comparing how GPT-4o vs GPT-4 would segment the same string
How the cost extrapolator works
Cost cards multiply local token counts by static published input rates: GPT-4o $5 / 1M, GPT-4o mini $0.15 / 1M, Claude 3.5 Sonnet $3 / 1M. Monthly volume scales the per-query cost.
Caveats
- Output tokens are not included — add completion estimates separately for full TCO
- Cached-input or batch discounts are not modeled
- Vendor list prices change; treat figures as planning aids, not invoices
Token budgeting best practices
- Budget with the encoding that matches production, then keep a 10–20% safety margin for chat wrappers and retries
- Count the full request shape (system + tools + history + user), not only the system prompt
- Minify machine-consumed JSON; keep pretty copies for humans
- Re-run counts whenever you add few-shot examples, MCP configs, or long policy appendices
- Use monthly volume projections in design reviews so cost is visible before launch
- Prefer local counting for proprietary prompts — this tool never uploads your text
Tokenizer & special-token reference
Boundary colors map to tiktoken byte-pair encodings. Special tokens like <|endoftext|> are counted when present as literal text.
Tokenizer & special-token reference
| Field type | Sample payload | Structural rule |
|---|---|---|
| cl100k_base | GPT-4, GPT-4 Turbo, Claude 3 | Default OpenAI chat encoding; ~4 characters per token for English prose; merges whitespace across word boundaries. |
| o200k_base | GPT-4o, GPT-4o mini | Expanded vocabulary encoding for omni models; token IDs differ from cl100k_base for identical strings. |
| <|endoftext|> | <|endoftext|> | Reserved control token marking document boundaries in GPT training corpora; counts as a single token when literal. |
| Unicode emoji | 🚀 | Often 1–3 tokens depending on encoding; multi-codepoint graphemes may split across multiple BPE merges. |
| JSON whitespace | {\n "key": "value"\n} | Indentation newlines and spaces consume tokens — minify JSON payloads before counting context usage. |
Frequently Asked Questions
Expandable answers for common debugging bottlenecks and data privacy questions.
Related tools
Explore other related utilities that complement this tool.
Official Documentation & References
Authoritative specifications and platform documentation for this utility.