Sub topic 1
How tokens turn into cost
Prerequisites
This chapter assumes you can read basic Python and have called an LLM chat or completion API before. You should know what a prompt, a system message, and a sampling setting such as temperature are. You should also be comfortable with HTTP APIs and JSON, because usage numbers come back in JSON response bodies.
Why tokens, not words or requests
LLM providers bill by tokens, not by request count, word count, or character count. A token is a chunk of text that the model's tokenizer produces. A tokenizer is the component that splits text into a fixed vocabulary of pieces before the model sees it. A token can be a whole common word, part of a rare word, a single punctuation mark, or a few bytes of a non-Latin character.
Two consequences follow. First, the same message can have different token counts under different models, because each model family has its own tokenizer. Second, cost scales with how much text you send and receive, so a long prompt costs more than a short one even when both are one request.
As a rough guide for English prose, one token is about four characters, or about three quarters of a word. Code, JSON, and non-English text often use more tokens per character. Treat the rule of thumb as a starting estimate and count real tokens before you make decisions.
The cost formula
Every request has an input side and an output side, and providers price them separately. Input tokens are the tokens in everything you send: the system message, the conversation history, retrieved documents, tool definitions, and the user's question. Output tokens are the tokens the model generates. Output tokens usually cost several times more than input tokens, because each one requires a separate generation step.
Prices are quoted per million tokens. The cost of one request is:
cost = (input_tokens * input_price + output_tokens * output_price) / 1,000,000A worked example with placeholder prices of $1.00 per million input tokens and $4.00 per million output tokens:
| Part | Tokens | Price per million | Cost |
|---|---|---|---|
| Input | 3,000 | $1.00 | $0.0030 |
| Output | 500 | $4.00 | $0.0020 |
| Total | 3,500 | $0.0050 |
Half a cent looks small. At 200,000 requests a day it is $1,000 a day. The unit price matters less than the product of price, tokens per request, and request volume. Changing any one of those three multiplies through to the bill.
In this example the input is six times larger than the output, yet it contributes only 60% of the cost. A prompt-heavy workload such as summarizing long documents is dominated by input cost. A generation-heavy workload such as drafting long reports is dominated by output cost. Knowing which one you have tells you where to look first.
Counting tokens before you send
You can count tokens locally with the tokenizer your model uses. The tiktoken library provides tokenizers for OpenAI models. Other providers publish their own tokenizers or offer a token-counting endpoint. The following function estimates cost from the prompt and an expected output size. Install the library first with pip install tiktoken.
import tiktoken
# Placeholder prices in USD per million tokens. Replace with your provider's current prices.
PRICE_PER_MTOK = {"input": 1.00, "output": 4.00}
def estimate_cost(prompt: str, expected_output_tokens: int) -> float:
enc = tiktoken.get_encoding("cl100k_base")
input_tokens = len(enc.encode(prompt))
return (
input_tokens * PRICE_PER_MTOK["input"]
+ expected_output_tokens * PRICE_PER_MTOK["output"]
) / 1_000_000
print(estimate_cost("Summarize this paragraph in two sentences.", 120))The output side is an estimate, because you do not know in advance how many tokens the model will generate. Use a typical value from past traffic, or the max_tokens limit as a worst case.
A local count can differ from the billed count. The encoding you pick may not match the model's real tokenizer, and chat requests add a few tokens of formatting overhead per message. For billing accuracy, read the usage field the API returns with each response. Local counts are best for planning and for checking a prompt before you send it.
Hidden sources of input tokens
Most surprises on the invoice come from input you did not think of as part of the prompt.
- Conversation history. In a chat, you resend earlier turns with every request. The input grows with each turn, so the total tokens billed over a conversation grow faster than the number of turns.
- Tool and function definitions. JSON schemas for tools are serialized into the prompt on every call, even when the model does not use them.
- Retrieved context. Retrieval-augmented systems paste document chunks into the prompt. Five chunks of 800 tokens add 4,000 tokens to every request.
- System messages. A long instruction block is cheap once and expensive at volume, because it is billed on every request.
The conversation case deserves a closer look. If each turn adds 300 tokens of new text and the model answers with 200, then turn n sends roughly 500 × (n − 1) + 300 input tokens. By turn 10 the request carries about 4,800 input tokens, most of them old history.
Hidden sources of output tokens
Output also includes more than the visible answer. Some models produce reasoning tokens, which are internal thinking steps generated before the final answer. Providers generally bill them as output tokens even when you do not see them. A request that shows a 50-token answer can still bill hundreds or thousands of output tokens. Check the usage field for a reasoning token count, and check your provider's documentation for how it is reported.
Formatting also affects count. Verbose JSON with long key names, markdown decoration, and polite preambles all spend output tokens that carry little information.
How tokens also drive latency
Tokens affect time as well as money. The model reads all input tokens before it produces the first output token, so a longer prompt delays the start of the response. It then generates output tokens one after another, so a longer answer takes proportionally longer to finish. The next chapter covers this in detail. For now, remember that cutting tokens usually reduces cost and latency together, which makes tokens the main unit to track.
Reading the usage field
Every major provider returns token counts with each response. Field names differ, but the shape is similar. A typical response includes something like this:
{
"usage": {
"prompt_tokens": 3000,
"completion_tokens": 500,
"total_tokens": 3500
}
}Log these three numbers for every request, along with the model name and a label for the feature that made the call. This is the raw material for the baseline you will build in a later chapter. Billing dashboards show totals by day, but only your own logs can tell you which feature or prompt caused a spike.
Common errors
- Using one price for all tokens. Applying the input price to output tokens underestimates cost by a factor of several.
- Forgetting to multiply by volume. A cost that looks trivial per request can dominate a budget at scale.
- Trusting word counts. Words, characters, and tokens differ, and the ratio varies by language and content type.
- Ignoring history growth. Cost per turn rises through a conversation, so measure the whole conversation, not a single turn.
- Using stale prices. Prices change and differ by model. Keep them in one configuration place, not scattered through code.
- Counting with the wrong tokenizer. A count from one model family can be off by 10% or more for another, especially on code and non-English text.
Summary of what to carry forward
Cost is tokens multiplied by price, with input and output priced separately. The numbers that move the bill are input tokens per request, output tokens per request, and request volume. Count tokens locally to plan, and read the usage field to know what you were actually charged for.
Exercise
A request has 8,000 input tokens and 400 output tokens. Input costs $2.00 per million tokens and output costs $10.00 per million. What does one request cost, and which side contributes more?
Show answer
Input cost is 8,000 × 2.00 / 1,000,000 = $0.016. Output cost is 400 × 10.00 / 1,000,000 = $0.004. The total is $0.020 per request. Input contributes more, 80% of the cost, even though output has a five times higher unit price.
Exercise
A chat assistant adds 250 tokens of user text and 150 tokens of answer per turn, and resends the full history each turn. Ignoring the system message, roughly how many input tokens does turn 6 send?
Show answer
Turns 1 to 5 each added 250 + 150 = 400 tokens of history, so 5 × 400 = 2,000 tokens. Turn 6 also sends its own 250-token question, for about 2,250 input tokens.
Exercise
A response shows a 40-token visible answer, but the bill shows 900 output tokens. Name one likely cause and where you would look to confirm it.
Show answer
The model likely produced reasoning tokens that are billed as output but not shown. Confirm it in the response's usage field, which often reports a reasoning token count, and in the provider's documentation on how reasoning tokens are billed.