Learning path: Build Your First LLM App with Claude · Step 1 of 4
LLM Tokens, Context Windows and Cost: What One Question Really Costs
Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.
What you will learn
- Explain why a model reads far more input tokens than the words in the question
- Describe how the prompt, the chat history and the reply share one context window
- Use max_tokens and the stop reason to spot a cut-off answer
- Work out the cost of a call from input and output token prices
Before you start
- Basic Python
A customer types four words into a help desk: Where is order 1002? The token meter under the answer says the model read 911 input tokens. Where did the other 907 come from?
That number is the whole lesson. Once you can explain it, you know what a token is, what the context window holds, why chats get more expensive every turn, and how to work out the bill. We'll follow that one question through a small FastAPI help desk app.
Four words in, 911 tokens read
Here's the question going through the app, with the meter it prints:
def ask(question="Where is order 1002?"):
"""Send one question through the app, like the page does."""
from app.main import app
data = TestClient(app).post("/api/ask", json={"text": question}).json()
print(f"You: {question}\nModel: {data['answer']}")
print(f"({data['model']}: in {data['input_tokens']}, out {data['output_tokens']}, ${data['dollars']:.6f})")
You: Where is order 1002?
Model: Order 1002, the standing desk, is being packed and ships tomorrow morning.
(test-model: in 911, out 12, $0.000097)
The model didn't read just the question. Before it, the app sends the shop policy (891 words of rules) and a short brief of 16 words. Only then come the 4 words of the question. 891 + 16 + 4 = 911. The answer counts too: 12 output tokens.
A note on the numbers. This run uses a stand-in test model that counts one token per word, so you can run the app without an API key. A real tokenizer cuts text into smaller pieces and usually counts a few more. With a key in the .env file, the same code calls the real model. You'll see real counts further down.
So the first rule: the model reads everything you send, not just the question.
The context window is a small desk
Picture the model reading at a small desk. Only so many pages fit on it.
- On every call you put pages on the desk: the policy, the brief and the question.
- In a chat, the earlier turns go on the desk as well.
- When the desk is full, the oldest page has to go. It falls off the edge and the model can't see it any more.
- You also keep a strip free, because the reply is written on the same desk.
That desk is the context window. Every model has a fixed size for it, measured in tokens. The input and the reply share it.
Who fills the window: build_messages
In the app, one function in llm.py decides what lands on the desk:
def build_messages(history: list, question: str,
settings: Settings) -> list:
shots = example_messages() if settings.examples else []
# one turn = 2 messages: keep the last few, oldest first
kept = history[-2 * settings.remember:] if settings.remember else []
# the long fixed policy FIRST (a cache reuses the beginning of a
# prompt), then the brief, the examples, the turns, the question
system = settings.policy + "\n\n" + settings.system
return [{"role": "system", "content": system},
*shots,
*kept,
{"role": "user", "content": question}]
kepttakes only the last few turns of the history, two messages per turn. Theremembersetting decides how many.- The system message is the long policy first, then the brief.
- The list starts with that system message, then the earlier turns we kept, and the new question goes last.
This list is exactly what the model reads, every single call.
Chat memory fills the desk
The API keeps nothing between calls, so a chat with memory sends the earlier turns again each time. Here's a three-turn chat with remember set to 5:
-- remember last 5 turns
You: Where is order 1002?
Model: Order 1002, the standing desk, is being packed and ships tomorrow morning.
(messages sent 2, in 911 tokens)
You: and when will it arrive?
Model: Order 1002, the standing desk, is being packed and ships tomorrow morning.
(messages sent 4, in 928 tokens)
You: How do returns work?
Model: You can return any item within 30 days. Start the return from My Orders and print the free label.
(messages sent 6, in 944 tokens)
Every earlier turn goes along again, so every turn reads more tokens than the one before: 911, then 928, then 944.
The oldest turn slides off
Keep chatting for seven turns. By turn 6 the app sends 12 messages and 1,005 input tokens. At turn 7 it's still 12 messages, at 1,010 tokens. Why not 14?
Look at the oldest question sent. Until turn 6 it was "Where is order 1002?". At turn 7 it's "and when will it arrive?". Turn one slid off the desk, because remember is 5. That setting keeps the window from overflowing, and the price is that the oldest turn is forgotten.
max_tokens caps the answer
The strip kept for the reply is set in the Settings class:
@dataclass
class Settings:
system: str = SYSTEM # who the model is, how it answers
temperature: float = 0.2 # 0 = same words, higher = more varied
max_tokens: int = 200 # the longest answer we allow
remember: int = 5 # earlier turns we send along
examples: bool = False # send two worked examples first
The settings demo runs the same question with different settings. Here are the default run and the run with max_tokens set to 4 (the other runs are left out):
default settings Order 1002, the standing desk, is being packed and ships tomorrow morning. [stop, out 12]
max tokens 4 Order 1002, the standing [length, out 4]
With the default, the answer is complete and the stop reason is stop. With 4, the answer is cut mid-sentence and the stop reason is length. Keep enough room for the reply, and always check the stop reason before you show an answer to a user.
Pricing a call
Providers price tokens per one million, with one price for input and another for output. The help desk keeps them in prices.py, copied from the provider's pricing page:
@dataclass(frozen=True)
class Price:
input_price: float # dollars per 1 million input tokens
output_price: float # dollars per 1 million output tokens
PRICES = {
"gpt-6-luna": Price(0.10, 0.50),
"gpt-6.1-sol": Price(2.00, 10.00),
}
def cost(model, input_tokens, output_tokens):
p = PRICES[model]
return (input_tokens * p.input_price + output_tokens * p.output_price) / 1_000_000
These were the prices on OpenAI's official pricing page when the lecture was recorded. The same page has a context-length switch: "long" means more than 272K input tokens, and for gpt-6-luna the long-context price rises to $0.20 in and $0.75 out. A very full window costs more for every token. Prices change, so always check the provider's page before you rely on them.
One question, priced
| Part | Tokens | Price per 1M | Dollars |
|---|---|---|---|
| Input | 911 | $0.10 | 0.0000911 |
| Output | 12 | $0.50 | 0.0000060 |
| Total | 923 | 0.0000971 |
That's the meter's $0.000097. About 94% of this bill is input, and most of the input is the policy.
A real model's meter
The stand-in counts words. To see a real tokenizer, the lecture's project has a small script that sends one question to a real model and reads the usage from the response:
# Token meter: ask one question, see how many tokens it used.
# pip install -r requirements.txt
import os
from openai import OpenAI
API_KEY = os.getenv("OPENAI_API_KEY", "") # never put a key in code
MODEL = "gpt-6.1-sol"
client = OpenAI(api_key=API_KEY)
question = input("Ask the model: ")
response = client.responses.create(model=MODEL, input=question)
usage = response.usage
print()
print("Answer:", response.output_text)
print()
print("Input tokens: ", usage.input_tokens)
print("Output tokens: ", usage.output_tokens)
print("Reasoning tokens:", usage.output_tokens_details.reasoning_tokens)
print("Total tokens: ", usage.total_tokens)
The question was "hi, who are you, what's your context window?", eight words. The counts it printed (the answer text is left out here):
Input tokens: 17
Output tokens: 104
Reasoning tokens: 33
Total tokens: 121
Eight words became 17 input tokens, so a real tokenizer counts more tokens than words. Of the 104 output tokens, 33 are reasoning tokens: the model thinking before it writes. You pay for those as output too. The total is 17 + 104 = 121.
What moves the bill
One question is tiny. Four things make the bill grow:
- The number of calls. A thousand questions like this one cost about $0.097.
- The model. The same question on
gpt-6.1-solcosts 20 times more ($2.00 vs $0.10 in, $10.00 vs $0.50 out). - The history. Turn 7 read 99 more tokens than turn 1.
- The fixed prompt. 891 of the 911 tokens are the policy, read again on every call.
Common mistakes
- Counting only the user's words. The system prompt, examples and history are all input tokens, on every call.
- Forgetting the reply needs room. If the input fills the window, there's nothing left for the answer.
- Ignoring the stop reason. A reply that stopped on
lengthis cut off, even if it looks fine at a glance. - Hard-coding prices and never checking them. Copy them from the pricing page, note the source, and check again.
- Forgetting reasoning tokens. They don't appear in the answer, but they're billed as output.
Quick recap
| Step | What to do | Help desk example |
|---|---|---|
| Count it | Everything you send, plus the reply | 4 words asked, 911 tokens read, 12 written |
| Fit it | Policy, kept turns and question, with room left to reply | remember=5, max_tokens=200 |
| Price it | tokens × price ÷ 1,000,000, for input and output | $0.0000971, 94% of it input |
Try it yourself
The memory demo also runs the same three questions with remember set to 0. Before you run it, predict: how many messages does each turn send, how many input tokens does turn two read, and what happens to the answer to "and when will it arrive?" Then run it and check.
Next, see the same ideas from the Claude side in The Claude Messages API: your first call, where max_tokens is a required field and the usage comes back on every Message.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
The AI Stack in One Picture: Six Layers Every AI Product Is Built From
Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.
Tokenization: What an LLM Actually Sees When You Type
A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.
What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.
Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
An LLM replies with a string. Pydantic turns that string into a typed object or a clear error. Validate a User, generate its JSON Schema, then follow one customer e-mail through a Ticket model where the first reply says refund, fails the check, and the retry fits.