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. You will turn token counts into a cost figure and a latency estimate before you ship anything.
What you are billed for
Providers charge per token, and they usually charge different rates for input and output. Input tokens are everything you send: system prompt, history and the new question. Output tokens are what the model generates. Output tokens usually cost more than input tokens. Prices are quoted per million tokens, so check your provider's pricing page for the current numbers.
The response already reports what you used. In the chat-completions shape, usage contains prompt_tokens and completion_tokens. Some providers also report cached or reasoning tokens, which may be billed at other rates.
Computing cost per request
Keep prices in configuration, not in code, because they change.
import os
# Dollars per one million tokens, copied from your provider's pricing page.
INPUT_PRICE = float(os.environ["INPUT_PRICE_PER_M"])
OUTPUT_PRICE = float(os.environ["OUTPUT_PRICE_PER_M"])
def request_cost(usage):
"""Return the cost in dollars of one request, given its usage object."""
return (
usage["prompt_tokens"] * INPUT_PRICE
+ usage["completion_tokens"] * OUTPUT_PRICE
) / 1_000_000
def estimate_latency(output_tokens, first_token_s=0.6, tokens_per_s=60):
"""Rough seconds for a non-streamed reply."""
return first_token_s + output_tokens / tokens_per_s
usage = {"prompt_tokens": 1200, "completion_tokens": 300}
print(f"cost: ${request_cost(usage):.4f}")
print(f"latency: {estimate_latency(usage['completion_tokens']):.1f} s")With example prices of $2 per million input tokens and $8 per million output tokens, this request costs 1,200 × 2 / 1,000,000 = $0.0024 for input and 300 × 8 / 1,000,000 = $0.0024 for output. The total is $0.0048. At 100,000 requests a day that is $480 a day.
Estimating latency
Latency has two parts. The first is time to first token, which covers network time, queueing and processing your input. The second is generation time, which grows with the number of output tokens. A simple model is:
latency ≈ time to first token + output tokens / tokens per second
Output length dominates for long replies. Cutting max_tokens or asking for shorter answers saves more time than shortening the prompt. Measure the time to first token and the tokens per second on your own traffic, because they vary by model and by load. With streaming, users see text after about the first-token time, even though total time is unchanged.
Why conversations get expensive
The API is stateless, so every turn resends the whole history. Input tokens per turn grow with each turn, and the total over a conversation grows roughly with the square of the number of turns. Long chats, large system prompts and retrieved documents all push the input side up.
Ways to reduce cost and latency:
- Trim or summarize old turns.
- Keep the system prompt short.
- Set
max_tokensto a sensible cap. - Use a smaller model for easy tasks.
- Use prompt caching, if your provider offers it, for a large prefix that repeats.
Practice
Exercise
Input costs $1 per million tokens and output costs $4 per million. A request uses 2,000 prompt tokens and 500 completion tokens. Time to first token is 0.4 s and generation runs at 50 tokens per second. What are the cost and the estimated latency?
Show answer
Cost is 2,000 × 1 / 1,000,000 + 500 × 4 / 1,000,000 = $0.002 + $0.002 = $0.004. Latency is 0.4 + 500 / 50 = 10.4 seconds.