Tokens, Cost and Rate Limits
Model APIs are priced by tokens: small pieces of text, roughly three-quarters of an English word each. Every call is charged for its input tokens (everything you send, including the system prompt and earlier messages) and its output tokens (the reply), at separate rates. Rate limits cap how many requests and tokens you can use per minute.
Knowing both lets you estimate a feature's monthly bill before you build it, and keep it working when traffic grows.
How a Bill Is Calculated
Example Prices
Providers usually sell several sizes of model: a large model that is best at hard tasks, and smaller ones that are faster and much cheaper. These are one hosted provider's prices for three sizes in November 2026, used as examples:
| Model size | Input, per million tokens | Output, per million tokens |
|---|---|---|
| Large | $4.00 | $20.00 |
| Medium | $2.00 | $10.00 |
| Small | $0.10 | $0.50 |
Prices differ between providers and change often; check your provider's pricing page before you plan a budget.
Example: Estimating a Monthly Bill
PRICES = { # US dollars per million tokens (input, output): example prices, November 2026
"large-model": (4.00, 20.00),
"medium-model": (2.00, 10.00),
"small-model": (0.10, 0.50),
}
def cost(model, input_tokens, output_tokens):
price_in, price_out = PRICES[model]
return (input_tokens * price_in + output_tokens * price_out) / 1_000_000
for model in PRICES:
one = cost(model, input_tokens=1200, output_tokens=150)
print(f"{model:13} one question ${one:.6f} | 30,000 a month ${one * 30000:,.2f}")large-model one question $0.007800 | 30,000 a month $234.00
medium-model one question $0.003900 | 30,000 a month $117.00
small-model one question $0.000195 | 30,000 a month $5.85Explanation: Each question sends about 1,200 input tokens, mostly the fee document in the system prompt, and gets about 150 output tokens back. For the large model that is 1,200 × $4 plus 150 × $20, divided by one million: $0.0078 a question, or $234 for 30,000 questions. This calculation is plain Python and its output is real; the token counts are estimates you should replace with measured ones.
Measuring Tokens Before You Send
Before you build, a quick estimate is enough: English text averages about four characters per token.
def estimate_tokens(text):
return round(len(text) / 4) # English text averages about 4 characters per token
system = "You are Campus Helper. Fees: lab $45, due September 30; field trip $30, due October 15."
question = "When is the lab fee due?"
print("Characters:", len(system) + len(question))
print("Estimated input tokens:", estimate_tokens(system) + estimate_tokens(question))Characters: 111
Estimated input tokens: 28Explanation: The estimate divides the length of the text by four. Real counts depend on each model's tokenizer, so after a real call, reply.input_tokens and reply.output_tokens report the exact numbers. Log them on every call and compare them with your estimate.
Rate Limits and Retries
| Situation | What happens | What to do |
|---|---|---|
| Too many requests | The API returns error 429 | Wait and retry, waiting longer each time |
| Server busy or failing | Errors 500 and above | Retry with a growing wait |
| Bad request | Errors 400 to 404 | Fix the request; retrying won't help |
import time
import httpx
from model_api import ModelClient
RETRY = {429, 500, 502, 503, 504}
def chat_with_retries(client, messages, attempts=4, **settings):
for attempt in range(attempts):
try:
return client.chat(messages, **settings)
except httpx.HTTPStatusError as error:
if error.response.status_code not in RETRY or attempt == attempts - 1:
raise # a bad request, or out of attempts
time.sleep(2 ** attempt) # wait 1, 2, then 4 seconds
reply = chat_with_retries(ModelClient(), [{"role": "user", "content": "When is the lab fee due?"}])Explanation: raise_for_status() in the helper turns an error response into httpx.HTTPStatusError. The function retries only 429 and server errors, doubling the wait each time, and re-raises anything else so a bad request is fixed instead of repeated. Many providers' own SDKs retry this way automatically.
Common Mistakes
Pricing only the reply. Input usually costs more in total, because it is resent every call.
Estimating once and never measuring. Log usage and check the real bill weekly.
Retrying bad requests. A 400 error won't fix itself; only retry 429 and server errors.
Interview Corner
How do you estimate the cost of an AI feature?
Measure input and output tokens per request, multiply each by its price, and multiply by expected monthly requests. Then compare models and check the estimate against real usage.
How should code handle a 429 error?
Wait and retry with a growing delay, and show a friendly message if retries run out. Don't retry 400-level request errors.
Practice
Exercise: budget Campus Helper. Suppose the fee document grows to 4,000 tokens and traffic doubles to 60,000 questions a month. Rerun the estimate for all three models. Which would you test first, and why?
Check your understanding:
- What are input tokens?
- Why can input cost more than output in total?
- Which errors should be retried?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Estimate before sending | len(text) / 4 |
| Tokens used | reply.input_tokens, reply.output_tokens |
| Retry safely | chat_with_retries(client, messages) |
| Catch an error response | except httpx.HTTPStatusError as error: |
Was this tutorial helpful?