Sub topic 9
Estimating what a call costs
This chapter assumes you can read basic Python, have called an LLM through a chat or completion API, and are comfortable with unit conversion. It builds on the earlier chapters about tokens, the context window, output limits, per-token pricing, and usage data. Here you combine them into a cost estimate for one call and for a whole conversation.
The core formula
Providers bill input tokens and output tokens at separate rates. Prices are quoted in dollars per million tokens, so the cost of one call is:
cost = (inputtokens × inputprice + outputtokens × outputprice) ÷ 1,000,000
Output tokens usually cost several times more than input tokens. A call with a long prompt and a short answer can therefore cost less than a call with a short prompt and a long answer.
The code below checks that a request fits the window and then computes the cost. The prices are placeholders chosen so the arithmetic is easy to follow. They are not real rates.
def fits_in_window(input_tokens, max_output_tokens, context_window):
return input_tokens + max_output_tokens <= context_window
def estimate_cost(input_tokens, output_tokens,
input_price_per_million, output_price_per_million):
return (
input_tokens * input_price_per_million
+ output_tokens * output_price_per_million
) / 1_000_000
# Placeholder prices in dollars per million tokens, not real rates.
cost = estimate_cost(2000, 500, 3.0, 15.0)
print(fits_in_window(2000, 500, 8000)) # True
print(f"${cost:.4f}") # $0.0135Work through the numbers by hand once. The input part is 2000 × 3 = 6,000. The output part is 500 × 15 = 7,500. The sum is 13,500, and dividing by 1,000,000 gives 0.0135 dollars, which is about 1.35 cents.
The check fits_in_window uses the maximum output you allow, not the output you expect. The window must hold the prompt and the full output you permit. If the check fails, the API may reject the request or cut the answer short.
Two kinds of estimate
You can estimate cost at two points in time, and they have different accuracy.
| When | Input tokens from | Output tokens from | Accuracy |
|---|---|---|---|
| Before the call | A tokenizer library | Your guess or your `max_tokens` cap | Input is close. Output is a range. |
| After the call | The `usage` field in the response | The `usage` field in the response | Exact for what was billed |
Before the call, count the input with a tokenizer. The following example uses the open-source tiktoken library. Other model families use different tokenizers, so the count is only exact for the matching one. For any other model, treat it as an approximation.
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
text = "Tokens are not the same as words."
token_ids = enc.encode(text)
print(len(text.split()), "words")
print(len(token_ids), "tokens")
print([enc.decode([t]) for t in token_ids])The word count and the token count differ, which is why estimating from words alone gives the wrong bill.
You cannot know the output length in advance. Two ways to handle it:
- Upper bound. Use
max_tokensas the output size. This is the worst case, and it is the number you also need for the window check. - Expected value. Use the average output length from past calls of the same kind. This is better for budgeting across many calls.
After the call, replace estimates with the usage numbers from the response. The billed values are the ones to log, since they include any overhead the provider adds, such as special tokens around messages.
What counts as input
A common error is to count only the latest user message. The input of a call includes everything the model receives:
- The system prompt.
- The full conversation history you resend.
- The new user message.
- Tool or function definitions, if you pass them.
- Any documents or retrieved text you paste into the prompt.
If you count only the new message, you will underestimate, sometimes by a large factor.
Estimating a whole conversation
A chat API is stateless. The model remembers nothing between calls, so your application resends the history on every turn. Each turn's input is the system prompt plus every earlier message plus the new one. Input cost therefore grows with each turn, and the total grows faster than the number of turns.
The next function simulates this. It assumes a fixed system prompt, a fixed user message size, and a fixed reply size.
def total_input_tokens(system_tokens, user_tokens, reply_tokens, turns):
total = 0
history = system_tokens
for _ in range(turns):
history += user_tokens
total += history # the whole history is sent as input on every call
history += reply_tokens
return total
print(total_input_tokens(500, 100, 300, 10)) # 24000With a 500-token system prompt, 100-token user messages, and 300-token replies, ten turns bill 24,000 input tokens. The user and model wrote only 4,000 new tokens in total (10 × 100 + 10 × 300). The remaining tokens are the same text sent again and again.
The input on turn n is 500 + 100n + 400(n − 1). That is a linear function of n, so the sum over all turns grows with the square of n. Doubling the number of turns roughly quadruples the input tokens once the history dominates.
A full conversation cost function
Combining the two pieces gives a cost for the conversation. Output tokens are billed once, because each reply is generated once. Input tokens are billed on every call.
def conversation_cost(system_tokens, user_tokens, reply_tokens, turns,
input_price_per_million, output_price_per_million):
input_total = total_input_tokens(
system_tokens, user_tokens, reply_tokens, turns
)
output_total = reply_tokens * turns
return (
input_total * input_price_per_million
+ output_total * output_price_per_million
) / 1_000_000
def total_input_tokens(system_tokens, user_tokens, reply_tokens, turns):
total = 0
history = system_tokens
for _ in range(turns):
history += user_tokens
total += history
history += reply_tokens
return total
# Placeholder prices, not real rates.
print(f"${conversation_cost(500, 100, 300, 10, 3.0, 15.0):.4f}") # $0.1170Check it by hand. Input is 24,000 × 3 = 72,000. Output is 3,000 × 15 = 45,000. The sum is 117,000, and dividing by 1,000,000 gives 0.117 dollars.
Here the input side is the larger share, even though each input token is five times cheaper than an output token. If you extend the same chat to 50 turns, input tokens grow much faster than output tokens, and input dominates the bill.
Edge cases and common errors
- Forgetting the output cap in the window check. A prompt of 7,900 tokens fits an 8,000-token window by itself, but not with a 500-token output allowance.
- Mixing units. Prices are per million tokens. Dividing by 1,000 instead of 1,000,000 inflates the estimate a thousandfold.
- Using the wrong tokenizer. A tokenizer for one model family can be off by a noticeable margin for another. Use the provider's own counter or the usage field when accuracy matters.
- Ignoring hidden output. Some models produce reasoning tokens that you do not see in the answer but that are billed as output. Your estimate should add them, and the usage data reports them.
- Assuming one price. Some providers charge different rates for cached input, for very long prompts, or for batch processing. Check the current price sheet rather than reusing numbers from memory.
- Estimating a single call from a conversation average. Early turns are cheap and late turns are expensive. An average hides the growth.
A practical workflow
- Count input tokens with the matching tokenizer, including system prompt, history, and any pasted text.
- Choose an output figure: your
max_tokensfor the worst case, or a measured average for budgeting. - Run the window check with the output cap.
- Apply the formula with the current per-million prices for input and output.
- After the call, read the usage data and compute the actual cost with the same function.
- Compare the two numbers. If they differ consistently, find out why before scaling up.
The same estimate_cost function serves both the estimate and the actual cost. Only the source of the token counts changes.
Exercises
Exercise
A call sends 4,000 input tokens and receives 1,000 output tokens. The input price is $2 per million tokens and the output price is $10 per million tokens. What does the call cost?
Show answer
Input: 4,000 × 2 = 8,000. Output: 1,000 × 10 = 10,000. The sum is 18,000, and 18,000 ÷ 1,000,000 = $0.018.
Exercise
A model has a 16,000-token context window. Your prompt is 15,200 tokens and you set maxtokens to 1,000. Does the request fit? What is the largest maxtokens that would fit?
Show answer
No. 15,200 + 1,000 = 16,200, which is more than 16,000. The largest max_tokens that fits is 16,000 − 15,200 = 800.
Exercise
Using totalinputtokens, a chat has a 200-token system prompt, 50-token user messages, and 150-token replies. How many input tokens are billed over 3 turns?
Show answer
Turn 1 input: 200 + 50 = 250. History becomes 250 + 150 = 400. Turn 2 input: 400 + 50 = 450. History becomes 600. Turn 3 input: 600 + 50 = 650. The total is 250 + 450 + 650 = 1,350 input tokens.