Sub topic 7
Estimating cost from token prices
This chapter assumes you have called an LLM API before, can read short Python programs, and know what a token and a context window are. It covers how hosted APIs charge, how to turn token counts into a monthly estimate, and where estimates usually go wrong.
How hosted APIs charge
Most hosted model APIs bill by tokens, not by request or by time. A token is a chunk of text, often a short word or part of a word. Providers publish two prices, usually per million tokens:
- The input price applies to every token you send: the system prompt, instructions, examples, retrieved documents, conversation history, and the user's message.
- The output price applies to every token the model generates. It is usually several times higher than the input price.
The output price is higher because generating tokens is slower and more expensive for the provider than reading them. A request that sends a long document and gets back a one-line label is mostly input cost. A request that sends a short question and gets back an essay is mostly output cost.
Prices in this chapter are placeholders. Always read the current price page of the provider you are evaluating, because prices change and differ between model sizes.
The basic formula
The cost of one request is:
cost = (inputtokens / 1,000,000) × inputprice + (outputtokens / 1,000,000) × outputprice
The first code example turns this into a function and projects a monthly bill.
def request_cost(input_tokens: int, output_tokens: int,
price_in_per_million: float, price_out_per_million: float) -> float:
return (input_tokens / 1_000_000) * price_in_per_million + \
(output_tokens / 1_000_000) * price_out_per_million
# Example with made-up prices: $1.00 per million input tokens, $4.00 per million output tokens
per_request = request_cost(2_000, 300, 1.00, 4.00)
monthly = per_request * 50_000 # 50,000 requests per month
print(f"per request: ${per_request:.4f}, per month: ${monthly:.2f}")
# per request: $0.0032, per month: $160.00Here the input side costs $0.0020 and the output side costs $0.0012. Even though the request sends almost seven times more tokens than it receives, the output is 37.5% of the cost. That is the effect of the higher output price.
Where the token counts come from
You need three numbers: tokens in, tokens out, and request volume. Guessing them is the most common source of bad estimates, so measure them.
- Collect 20 to 50 realistic requests, ideally from logs or from your evaluation set.
- Run them through the provider's tokenizer or read the usage fields the API returns with each response.
- Record the average and the 95th percentile for input and output tokens, not only the average.
Most APIs return the counts in the response, so you can log them from day one. Different model families use different tokenizers, so the same text can produce different token counts on different models. A price per token is only comparable between models after you account for this. Compare cost per task, not cost per token.
What inflates the input side
The user's message is often the smallest part of the input. These items add up:
- The system prompt, sent on every request.
- Few-shot examples, which repeat on every request.
- Retrieved documents, if you use retrieval.
- Conversation history. In a chat, each turn resends all earlier turns, so input tokens grow with every turn and the total cost of a conversation grows faster than linearly.
- Tool definitions and tool results, in applications where the model calls functions.
This connects to the context window. A larger window lets you send more, and you pay for everything you send. A model that accepts 200,000 tokens does not make a 200,000-token request cheap.
What inflates the output side
- Long answers where a short one would do. Ask for the format you need, such as a label or a JSON object, and set a maximum output length.
- Reasoning or "thinking" tokens. Some models produce hidden intermediate reasoning that is billed as output even though you never see it. Check how your provider counts these.
- Retries. If a response fails validation and you call again, you pay twice.
Ways to lower the bill
| Technique | What it changes | Trade-off |
|---|---|---|
| Shorter prompts | Fewer input tokens | May reduce quality if you cut useful context |
| Prompt caching | Lower price on repeated prefixes | Only helps when the start of the prompt is identical across requests |
| Batch processing | Discounted price for non-urgent jobs | Results arrive later, not in real time |
| Output limits | Caps output tokens | Answers may be cut off |
| Smaller model | Lower price per token | May fail more of your cases |
Not every provider offers caching or batch pricing, and the discounts differ. Treat them as options to check, not guarantees.
Hosted cost compared with self-hosting
Token pricing scales with usage. Doubling your traffic doubles your bill, and zero traffic costs nothing. Self-hosting is the opposite: you pay for hardware or rented GPU time whether or not it is busy. A server costs a fixed amount per hour, so the cost per token falls as utilization rises.
This gives a break-even point. To estimate it, divide the monthly cost of the server by your monthly hosted bill. If the server costs more than your hosted bill, hosting yourself will not save money at your current volume. Remember to add the staff time for setup, monitoring, and updates, which does not show up in the server price. The later chapter on hosted versus self-hosted trade-offs puts this together with privacy and control.
A planning script with a safety margin
Single-point estimates hide risk. The script below computes a base estimate and a high estimate, using the 95th percentile of tokens and a traffic growth factor. It also compares two models.
def request_cost(input_tokens, output_tokens, price_in, price_out):
return (input_tokens / 1_000_000) * price_in + \
(output_tokens / 1_000_000) * price_out
# Placeholder prices in dollars per million tokens: (input, output)
models = {
"small": (0.20, 0.80),
"large": (3.00, 12.00),
}
avg_in, avg_out = 1_800, 250 # measured averages
p95_in, p95_out = 4_000, 600 # measured 95th percentile
requests_per_month = 50_000
growth_factor = 1.5 # allow for traffic growth
for name, (p_in, p_out) in models.items():
base = request_cost(avg_in, avg_out, p_in, p_out) * requests_per_month
high = request_cost(p95_in, p95_out, p_in, p_out) * requests_per_month * growth_factor
print(f"{name}: base ${base:,.2f}/month, high ${high:,.2f}/month")With these inputs the small model comes out at $28.00 per month in the base case and $120.00 in the high case. The large model comes out at $420.00 and $1,800.00. The ratio between the two models is what matters here. If the small model passes your evaluation, the large model costs about 15 times more for the same traffic. If it does not pass, the saving is irrelevant.
Common errors
- Counting only the user's message and ignoring the system prompt, examples, and history.
- Using average tokens for a budget. Long requests cost more, and a few of them can dominate the bill.
- Comparing price per token across different model families without checking tokenizer differences.
- Forgetting retries, failed validations, and evaluation runs, which all consume tokens.
- Treating a placeholder or old price as current.
- Assuming the cheapest model is the cheapest solution. A model that fails 20% of the time and needs retries or human review can cost more overall.
Cost in the decision process
Cost is one criterion among several. Estimate it after you know which models pass your quality bar, because only then does the comparison mean something. The decision rule from the plan is to pick the smallest model that meets your requirements. Token pricing gives you the number that shows how much that choice saves.
Exercise
A request sends 3,000 input tokens and receives 500 output tokens. The input price is $2.00 per million tokens and the output price is $8.00 per million tokens. The application handles 20,000 requests per month. What is the cost per request and the monthly cost? Then explain which side, input or output, contributes more to the bill.
Show answer
Input cost is 3,000 / 1,000,000 × 2.00 = $0.006. Output cost is 500 / 1,000,000 × 8.00 = $0.004. The cost per request is $0.010. The monthly cost is 0.010 × 20,000 = $200.00. Input contributes more ($0.006 versus $0.004, or 60%) even though the output price per token is four times higher, because there are six times as many input tokens.
Exercise
Your chat assistant resends the full conversation on every turn. Each turn adds 200 tokens to the history, and the system prompt is 500 tokens. Ignoring output, how many input tokens are sent in total across a 5-turn conversation? Why does this matter for budgeting?
Show answer
Input on turn n is 500 + 200 × n tokens if the first turn's message is included in the 200. Turns 1 to 5 send 700, 900, 1,100, 1,300, and 1,500 tokens, for a total of 5,500. Input per turn grows with every turn, so total cost grows faster than linearly with conversation length. A budget based on the average single message would underestimate the bill; you should estimate from whole conversations.