Sub topic 14
Estimating Cost and Latency from Token Usage
This chapter assumes you can already send a chat request and read the usage object from the response. It also assumes you know what a token is and how a conversation is resent on each call. You will turn those token counts into money and seconds, before and after a request is sent.
What you pay for
Hosted LLM APIs usually bill per token, with separate prices for input and output. Prices are quoted per million tokens. Output tokens normally cost several times more than input tokens, because the model generates them one at a time.
- Input tokens (
prompt_tokens) cover everything you send: system message, history, the new user message, and any tool definitions. - Output tokens (
completion_tokens) cover everything the model generates. Some providers also count hidden reasoning tokens here. - Some providers discount input tokens that were served from a prompt cache. They report this in a sub-field of
usage. The field name and the discount vary by provider.
The formula is:
cost = input_tokens / 1,000,000 * input_price
+ output_tokens / 1,000,000 * output_priceThe prices in this chapter are made-up round numbers ($2 per million input, $8 per million output). Look up your provider's current price list and your model's name before relying on any figure.
Computing the cost of one call
The response already contains exact counts, so computing cost after the fact needs no guessing. This script sends one request, measures wall-clock time, and prints cost and speed. It reads prices from environment variables so they never live in source code.
import os
import time
import requests
URL = "https://api.openai.com/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
}
INPUT_PRICE_PER_M = float(os.environ["INPUT_PRICE_PER_M"])
OUTPUT_PRICE_PER_M = float(os.environ["OUTPUT_PRICE_PER_M"])
def request_cost(usage):
return (
usage["prompt_tokens"] / 1_000_000 * INPUT_PRICE_PER_M
+ usage["completion_tokens"] / 1_000_000 * OUTPUT_PRICE_PER_M
)
payload = {
"model": os.environ["LLM_MODEL"],
"messages": [
{"role": "user", "content": "Explain what a token is in two sentences."}
],
}
start = time.perf_counter()
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=60)
elapsed = time.perf_counter() - start
resp.raise_for_status()
usage = resp.json()["usage"]
print("input tokens:", usage["prompt_tokens"])
print("output tokens:", usage["completion_tokens"])
print(f"cost: ${request_cost(usage):.6f}")
print(f"latency: {elapsed:.2f} s")
print(f"overall speed: {usage['completion_tokens'] / elapsed:.1f} output tokens/s")Run it with the prices set, for example INPUT_PRICE_PER_M=2 OUTPUT_PRICE_PER_M=8. The "overall speed" figure includes network and queueing time, so it is lower than the model's true generation speed.
Estimating before you send
Sometimes you need a number before the call: to reject an oversized request, to budget a batch job, or to pick a cheaper model. You have three options.
- Count with the model's own tokenizer. For OpenAI-style models, the
tiktokenlibrary does this locally. Other providers publish tokenizers or a token-counting endpoint. - Use a rule of thumb. For English prose, one token is roughly four characters, or three-quarters of a word. Code, numbers, and non-English text often take more tokens per character.
- Send a small sample, read the real
usage, and scale it up.
Whichever method you use, the output side is harder to predict, because the model decides how long to talk. Your max_tokens setting (or its equivalent) is the upper bound. Use it for a worst-case cost:
worst-case cost = estimated input cost + max_tokens / 1,000,000 * output_priceBudget with the worst case and report with the actual usage. Chat requests also add a few tokens of formatting per message, so a local count of only your text slightly undercounts.
Why conversations get expensive
The API is stateless, so every turn resends the full history. Input tokens therefore grow with each turn, and the total input over a conversation grows roughly with the square of the number of turns.
This script simulates a chat with no network calls. It assumes a 100-token system message, 50-token user messages, and 150-token replies.
SYSTEM = 100
USER = 50
REPLY = 150
INPUT_PRICE_PER_M = 2.0
OUTPUT_PRICE_PER_M = 8.0
def conversation_cost(turns):
total_in = 0
total_out = 0
for k in range(1, turns + 1):
history = (k - 1) * (USER + REPLY)
total_in += SYSTEM + history + USER
total_out += REPLY
cost = (
total_in / 1_000_000 * INPUT_PRICE_PER_M
+ total_out / 1_000_000 * OUTPUT_PRICE_PER_M
)
return total_in, total_out, cost
for turns in (10, 20):
tin, tout, cost = conversation_cost(turns)
print(f"{turns} turns: {tin} in, {tout} out, ${cost:.3f}")The output is:
10 turns: 10500 in, 1500 out, $0.033
20 turns: 41000 in, 3000 out, $0.106Doubling the turns multiplies input tokens by almost 4 and total cost by about 3.2. Output tokens only double. Long chats are expensive mainly because of the repeated history, not the new text.
Ways to slow the growth:
- Trim or summarize old turns once the history passes a token budget.
- Keep the system message short, since it is resent every time.
- Use prompt caching if your provider offers it. It usually requires a long, identical prefix, so put stable content (instructions, reference text) first and changing content last.
Estimating latency
A response takes time in three parts:
latency ≈ overhead + prefill time + output_tokens / generation_speed- Overhead is the network round trip, queueing, and authentication. It is often a few hundred milliseconds.
- Prefill is the model reading your input. It grows with input size but is fast compared to generation.
- Generation is the model producing tokens one after another at a steady rate, such as 50 tokens per second for some models.
The time until the first token arrives is called time to first token (TTFT). It is overhead plus prefill. Suppose TTFT is 0.6 s and generation runs at 50 tokens per second:
| Output tokens | Generation time | Total latency |
|---|---|---|
| 100 | 2.0 s | 2.6 s |
| 400 | 8.0 s | 8.6 s |
| 1,600 | 32.0 s | 32.6 s |
For most requests, output length dominates latency. A shorter answer is both cheaper and faster, so max_tokens, a concise system message, and instructions like "answer in one sentence" help on both fronts.
Streaming does not shorten total latency. It lets the user see the first words after TTFT instead of waiting for the whole reply. For interactive apps, TTFT is the number that determines how fast the app feels.
Common errors
- Using one price for all tokens. Output tokens are priced higher, so a single blended rate misleads you for long replies.
- Ignoring hidden tokens. Reasoning tokens, tool definitions, and per-message formatting all appear in
usageand on the bill, but not in your visible text. - Estimating from the visible reply only. A 20-word answer can follow a 3,000-token prompt.
- Treating the context window as a budget. A request that fits the window can still cost more than you intend.
- Averaging latency. Latency has a long tail, caused by retries, queueing, and long replies. Track the 95th percentile, not just the mean.
- Hard-coding prices. They change by model and over time. Keep them in configuration, and record the model name with each logged cost.
Putting it together
Before shipping a feature, run a short checklist:
- Measure typical and worst-case input tokens for the feature.
- Set
max_tokensto the longest reply you can accept. - Compute cost per request and multiply by expected daily volume.
- Compute latency from TTFT and generation speed, then check it against your user-facing target.
- If either number is too high, shorten the prompt, cap the reply, trim history, or switch to a smaller model, then measure again.
Estimates give you a plan. Logged usage data tells you whether the plan matches reality.
Exercise
A request uses 3,000 input tokens and 500 output tokens. Input costs $2 per million tokens and output costs $8 per million tokens. What is the cost of the request?
Show answer
Input: 3,000 / 1,000,000 $2 = $0.006. Output: 500 / 1,000,000 $8 = $0.004. Total: $0.010, or one cent.
Exercise
Using the formula latency ≈ TTFT + outputtokens / generationspeed, with TTFT of 0.8 s and a speed of 40 tokens per second, how long does a 600-token reply take? How long until the user sees the first word if you stream?
Show answer
Generation takes 600 / 40 = 15 s, so the total is 0.8 + 15 = 15.8 s. With streaming, the total stays about 15.8 s, but the first word appears after about 0.8 s.
Exercise
A chatbot averages 10 turns per conversation and costs $0.033 each. The team lets conversations run to 20 turns, and expects the cost per conversation to double. Why is that estimate wrong, and what is a better one?
Show answer
The API is stateless, so each turn resends the whole history and input tokens grow with the square of the turn count. In the chapter's simulation, 20 turns cost about $0.106, which is roughly 3.2 times the 10-turn cost. A better estimate sums the input tokens over every turn. Trimming or summarizing old turns, or caching a stable prefix, reduces the growth.