Sub topic 3
Estimating What a Call Costs
Assume you can read basic Python, call an LLM API, and do simple arithmetic. A provider usually charges separately for input tokens and output tokens:
\[ \text{cost} = \frac{(\text{input tokens} \times \text{input price}) +(\text{output tokens} \times \text{output price})}{1{,}000{,}000} \]
Prices below are dollars per million tokens.
| Usage | Tokens | Price per million | Cost |
|---|---|---|---|
| Input | 2,000 | $3 | $0.006 |
| Output | 500 | $15 | $0.0075 |
| Total | 2,500 | — | $0.0135 |
def estimate_cost(input_tokens, output_tokens,
input_price, output_price):
return (
input_tokens * input_price
+ output_tokens * output_price
) / 1_000_000
cost = estimate_cost(2_000, 500, 3.0, 15.0)
print(f"${cost:.4f}") # $0.0135Reasoning Tokens and Hidden Output
Some models use internal reasoning tokens before producing visible output. The API may report these separately, or include them in output-token usage. They can affect both cost and the context budget even when the user cannot see them.
Use the provider's usage fields as the billing record. Do not estimate cost from visible response length alone.
Keeping Context Within Budget
A context window is the maximum token capacity for a request. It usually includes the input, requested output, and sometimes hidden reasoning:
def fits(input_tokens, max_output_tokens, context_window):
return input_tokens + max_output_tokens <= context_window
print(fits(2_000, 500, 8_000)) # TrueManage context by trimming old messages, summarizing them, or retrieving only relevant documents. A smaller request reduces both failure risk and input cost.
Prompt Caching
Prompt caching stores repeated input, such as system instructions or stable reference documents. Later requests can reuse that prefix at a lower rate or with lower latency, depending on the provider. Keep stable content together and changing user data after it so the cache can match the prefix.
Practical Ways to Lower Cost
- Use a smaller model for classification, extraction, and routine drafts.
- Limit maximum output tokens.
- Remove irrelevant history and duplicate instructions.
- Summarize long conversations before they exceed the window.
- Cache stable prompts when the provider supports it.
- Record input, output, cached, and reasoning usage from every API response.
Exercise
A request uses 4,000 input tokens at $2 per million and 1,000 output tokens at $8 per million. What is its estimated cost?
Show answer
(4,000 × 2 + 1,000 × 8) ÷ 1,000,000 = $0.016.