Say a team adds a 10,000-token product manual to every request in their customer support assistant, so the model can answer from it. The answers get better. Then the monthly bill arrives, and nearly all of it is the same manual, sent and paid for thousands of times a day.
Language model APIs charge by the token, for what you send and for what the model writes back. To use fewer LLM tokens, measure where they go first, then cut in this order: cache the parts of the prompt that repeat, keep outputs short and structured, trim the context you send, batch work that is not urgent, and send simple tasks to cheaper models. This guide explains what tokens are, shows real token counts you can reproduce, and walks through each method with an example.
Key Takeaways
- A token is a chunk of text, often a word or part of a word, that a model reads and writes. APIs bill input and output tokens separately.
- Different models use different tokenizers, so the same text can be a different number of tokens. Count with the tokenizer or counting endpoint for the model you use.
- Prompt caching is usually the biggest saving when many requests share a long prefix, such as a system prompt, a manual or a set of examples.
- Output tokens cost more than input tokens on major APIs. On Anthropic’s current price list, output costs five times as much as input for every model listed.
- Batch APIs trade speed for price. Anthropic’s Message Batches API costs 50% less for work that can wait up to 24 hours.
What Are LLM Tokens?
A token is the unit of text a language model works with. Before a model sees your prompt, a tokenizer splits the text into tokens and turns each one into a number. Common words are often a single token. Rare words, names, numbers and code are often split into several.
You can see this with tiktoken, OpenAI’s open-source tokenizer library, which runs locally. The example below uses r50k_base, the tokenizer of GPT-2 and the original GPT-3. Newer models use larger vocabularies (GPT-4o uses o200k_base), so their counts differ, but the way text gets split is the same idea.
import json
import tiktoken
enc = tiktoken.get_encoding("r50k_base") # the GPT-2 / original GPT-3 tokenizer
def count(text: str) -> int:
return len(enc.encode(text))
sentence = "Tokenization splits text into pieces."
ids = enc.encode(sentence)
print(len(ids), [enc.decode([i]) for i in ids])
verbose = (
"I would really appreciate it if you could please take a careful look at the "
"customer review below and then let me know, in your own words, whether the "
"overall sentiment expressed by the customer is positive, negative or neutral."
)
concise = "Classify the review's sentiment as positive, negative or neutral."
print("verbose instruction:", count(verbose))
print("concise instruction:", count(concise))
record = {"order_id": "A-1001", "customer_name": "Dana", "status": "delivered"}
print("pretty JSON:", count(json.dumps(record, indent=4)))
print("compact JSON:", count(json.dumps(record, separators=(",", ":")))) Output:
7 ['Token', 'ization', ' splits', ' text', ' into', ' pieces', '.']
verbose instruction: 44
concise instruction: 13
pretty JSON: 42
compact JSON: 22 Three things stand out. “Tokenization” is two tokens, while short common words are one each. The polite, wordy instruction costs more than three times as many tokens as the direct one and asks for the same thing. And pretty-printed JSON nearly doubles the token count of the same data, because spaces and line breaks are tokens too.
Count Tokens for the Model You Actually Use
A tokenizer from one model family gives only an estimate for another. Anthropic’s pricing page, for example, notes that Claude 4.7 and later models use a newer tokenizer that produces roughly 30% more tokens for the same text than earlier Claude models. Count with the right tool before you estimate costs.
For Claude models, the Messages API has a token counting endpoint that returns the input token count for a request without running it. According to the documentation it is free to use, with its own rate limits.
import anthropic
client = anthropic.Anthropic()
count = client.messages.count_tokens(
model="claude-opus-5-5",
system="Classify the review's sentiment as positive, negative or neutral.",
messages=[{"role": "user", "content": "The lamp arrived broken."}],
)
print(count.input_tokens) Better still, log the token usage that every API response already reports, and add it up per feature. You cannot cut what you have not measured, and the biggest cost is often not where you expect.
Cache the Parts That Repeat
Prompt caching lets the API store the processed form of a prompt prefix, such as a system prompt, a long document or a set of examples, and reuse it on later requests that start with the same text. Reused tokens are billed at a steep discount and processed faster.
On the Claude API, prompt caching works like this, according to Anthropic’s documentation and pricing page:
- Writing to the cache costs 1.25 times the normal input price for the default 5-minute lifetime, or 2 times for a 1-hour lifetime.
- Reading from the cache costs 0.1 times the normal input price on most models, and less on some of the newest ones.
- The 5-minute lifetime is refreshed at no extra cost each time the cached content is used.
- Prompts below a minimum length, which depends on the model, are not cached, and no error is returned. Check the cache fields in the response to confirm it worked.
Here is the support assistant from the opening, with the manual marked for caching:
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
with open("product_manual.txt") as f:
manual = f.read() # the long text every request shares
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=300,
system=[
{"type": "text", "text": "Answer questions using only the manual below."},
{"type": "text", "text": manual, "cache_control": {"type": "ephemeral"}},
],
messages=[{"role": "user", "content": "How do I reset the device?"}],
)
usage = response.usage
print("written to cache:", usage.cache_creation_input_tokens)
print("read from cache:", usage.cache_read_input_tokens)
print("uncached input:", usage.input_tokens) A worked example with those multipliers: send the 10,000-token manual 100 times within the cache lifetime. Without caching you pay for 1,000,000 input tokens. With caching you pay for one write (10,000 × 1.25 = 12,500 token-equivalents) and 99 reads (99 × 10,000 × 0.1 = 99,000), or 111,500 in total. That is about 11% of the uncached cost for the manual.
The rule that makes caching work: put the parts that never change first and the parts that change last. A timestamp or user name at the top of the system prompt breaks the cache on every request. Other providers, including OpenAI and Google, offer their own forms of prompt caching with different rules and prices, so check their documentation. DeepSeek takes a different approach: its API caches automatically. According to DeepSeek’s context caching documentation, caching is on by default for every account with no code change, and when a request shares a prefix with an earlier one, the shared part is read from the cache and counted as a cache hit. The same rule applies: keep the shared part at the front.
Ask for Shorter Outputs
Output tokens are the expensive ones. On Anthropic’s current price list, each model’s output price is five times its input price, so a reply that is twice as long as it needs to be costs much more than an extra paragraph of instructions.
- Say the length. “Answer in at most three sentences” or “Return only the category name” works better than hoping for brevity.
- Use structure. Ask for JSON with named fields, or use the API’s structured output or tool calling features, so the model does not wrap the answer in an introduction and a summary.
- Set
max_tokens. It is a hard cap, not a target, so set it a little above the longest output you expect. A response that hits the cap is cut off mid-sentence, so treat that as an error to fix in the prompt. - Watch reasoning tokens. Models with a thinking or reasoning mode produce extra output tokens while they work. Use that mode for hard problems, not for simple classification.
Send Less Context
Most input tokens in real applications are context, not instructions. Three places usually have the most to trim:
- Retrieved documents. In a retrieval-augmented generation (RAG) app, sending the top 3 relevant passages instead of the top 20 can cut input sharply. Better retrieval lets you send fewer passages with the same answer quality; see our guide to hybrid search for RAG retrieval.
- Conversation history. Every turn of a chat resends the whole conversation. Summarize or drop older turns once a conversation gets long.
- Tool results. An agent that calls an API and gets back a 5,000-token JSON response pays for it on every later step. Return only the fields the model needs.
Batch Work That Can Wait
Not every request needs an answer in seconds. Nightly report generation, tagging a backlog of support tickets or running an evaluation set can all wait. Anthropic’s Message Batches API processes such work asynchronously at a 50% discount on input and output tokens. Most batches finish within an hour, and a batch that is not done within 24 hours expires. The discount stacks with prompt caching. OpenAI offers a similar Batch API; check its documentation for current terms.
Use the Right Model for Each Task
A cheaper, faster model is often good enough for classification, extraction and routing. A common pattern is to send every request to an inexpensive model first and pass only the hard ones to a more capable model. Test this on your own examples: if the cheaper model gets the same answer on 95% of your test set, the savings on that 95% are real.
A Checklist for Your Next Bill
- Log input, output and cached tokens per feature for a week.
- Move every fixed part of the prompt to the front and turn on prompt caching.
- Set an explicit output format and length, and a sensible
max_tokens. - Cut retrieved passages, old chat turns and tool output to what the model needs.
- Move anything that can wait an hour or more to a batch API.
- Test a cheaper model on the simplest tasks.
Back to the Product Manual
The support team from the opening did not have to remove the manual. They moved it to the front of the prompt and marked it for caching, set a three-sentence limit on answers, and moved their nightly ticket tagging to the batch API. The manual still goes with every request, but it is now billed at a fraction of the original price most of the time.
Frequently Asked Questions
How Many Words Is a Token?
It depends on the tokenizer and the text. Common English words are often one token, while rare words, numbers, code and many non-English languages take more tokens per word. Count your own text with the tokenizer or counting endpoint for your model rather than relying on a rule of thumb.
Do Input and Output Tokens Cost the Same?
No. On major APIs, output tokens cost more than input tokens. That is why limiting output length and asking for structured answers is one of the quickest ways to lower cost.
Does Prompt Caching Change the Model’s Answers?
No. Caching stores the processed prompt prefix so it does not have to be processed again. The model receives the same input either way, so caching changes cost and speed, not the content of the reply.
Why Does the Same Prompt Use Different Token Counts on Different Models?
Each model family has its own tokenizer with its own vocabulary, so the same text splits into a different number of pieces. Even models from the same provider can differ, as Anthropic notes for its newer tokenizer. Always count against the model you plan to use.




