Sub topic 1
What a token is and why counts differ by model
Prerequisites
Assume you can read basic Python, use an AI coding assistant, and read JSON usage data. A large language model (LLM) processes text as tokens, not as whole words.
Tokens and model-dependent counts
A token is a small text unit. It may be a word, part of a word, punctuation, or whitespace. For example, unhappiness might be split into several tokens. Each model has its own tokenizer, so the same prompt can produce different token counts.
Token count also depends on the language, formatting, and repeated text. Code often uses more tokens than expected because punctuation and indentation carry meaning.
The context window as a shared budget
A context window is the maximum number of tokens a model can consider in one request. It includes instructions, conversation history, tool results, and the new prompt. The model's response must fit within the remaining space.
How token pricing works
Providers usually price input and output tokens separately, often per million tokens. Output tokens commonly cost more because generating them requires more computation. Cached input tokens may use a discounted rate when a stable prompt prefix is reused.
| Token type | Meaning | Typical billing |
|---|---|---|
| Input | Text sent to the model | Standard input rate |
| Output | Text generated by the model | Often higher rate |
| Cached input | Reused input prefix | Discounted provider rate |
def request_cost(usage, price):
"""Prices are USD per million tokens."""
return (
usage["input_tokens"] * price["input"]
+ usage["output_tokens"] * price["output"]
) / 1_000_000
price = {"input": 3.0, "output": 15.0} # placeholder rates
usage = {"input_tokens": 20_000, "output_tokens": 1_000}
print(request_cost(usage, price)) # 0.075Why an agent loop costs more
A coding agent usually makes multiple requests. Each turn may resend the growing history, tool calls, and tool results. Therefore, twenty turns can bill far more than twenty times the initial prompt. Scoped file reads, truncation, compaction, and caching limit this growth.
Exercise
Why can a short final context still produce a large input-token bill?
Show answer
Earlier turns may have resent the full context repeatedly, so the total billed input is the sum of every turn's context.