Tokens, context windows and cost
Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.
What you will be able to do
#- Estimate token counts with a clearly labeled characters-per-token approximation and state when it is unsafe to trust.
- Compute the token budget remaining for a reply from window size, system prompt, history and user input.
- Calculate request cost in exact integer micro-USD from hypothetical per-million prices.
Overview
#Tokens are the unit everything is measured in
Models do not read characters; they read tokens, subword pieces produced by a tokenizer. Two facts follow. First, token counts are not character counts: "hello" is one token, while an unusual identifier or non-English text can be several. Second, pricing, context limits and rate limits are all denominated in tokens, so every AI feature needs a token budget.
A widely used planning heuristic is that English text averages roughly four characters per token. It is an approximation, not a tokenizer: real counts vary by language, casing, code and punctuation. Use it for estimates and UI hints, and use the provider's tokenizer or the response's usage block for accounting.
function estimateTokens(text) {
return Math.ceil(text.length / 4);
}
// estimateTokens("Reset password guide") -> 5 (20 chars / 4)
// estimateTokens("") -> 0
The context window is a budget you allocate
The context window is the maximum number of tokens a request may occupy. Everything competes for the same space:
| Allocation | Example |
|---|---|
| System instructions | 20 tokens |
| Conversation history | grows every turn |
| Retrieved documents | lesson 9's chunks |
| Current user input | varies |
| Reserved space for the reply | your maxOutputTokens |
function remainingReplyTokens(windowTokens, systemTokens, historySizes, userInputTokens) {
const used = systemTokens
+ historySizes.reduce((a, b) => a + b, 0)
+ userInputTokens;
return windowTokens - used;
}
// remainingReplyTokens(60, 20, [8, 12], 10) -> 10
If the remaining space drops below your reserved reply size, you must shrink something before sending: drop or summarize the oldest turns, retrieve fewer or smaller chunks, or shorten the system prompt. Silent overflow is not an option; providers reject or truncate over-limit requests.
Cost is arithmetic you can audit
Providers price input and output tokens separately, and output is usually more expensive. The numbers below are hypothetical mock prices chosen for clean arithmetic; substitute your provider's real prices when you build a real budget.
const MOCK_PRICES = { inputUsdPerMillion: 3, outputUsdPerMillion: 15 };
function estimateCostMicroUsd(inputTokens, outputTokens) {
// 1 USD per million tokens = 1 micro-USD per token.
return inputTokens * MOCK_PRICES.inputUsdPerMillion
+ outputTokens * MOCK_PRICES.outputUsdPerMillion;
}
// estimateCostMicroUsd(1200, 300) -> 8100 micro-USD, i.e. 0.0081 USD
Working in integer micro-USD avoids floating-point drift and makes cost tests exact. Two cost behaviors surprise teams: chat history re-bills every turn (a 20-turn conversation sends turn one's tokens twenty times), and retrieved documents are billed as input even when they do not help the answer, which is a direct reason to keep retrieval precise.
Truncation is a product decision
When content exceeds the budget you have three honest options, and choosing among them is product design:
- Drop: remove the oldest turns or lowest-ranked chunks. Cheap, loses detail.
- Summarize: replace old turns with a compressed version. Keeps gist, costs one extra call and can drop specifics.
- Refuse or defer: tell the user the input is too large. Honest, sometimes correct.
All three beat the fourth option, silently truncating the middle of the user's data and hoping the model does not notice. If you truncate, do it at a boundary you chose, and say so in the UI.
Why bigger windows are not automatically better
A larger context window raises per-request cost and latency, and quality does not necessarily improve with more text: relevant material can get lost among irrelevant material, and models tend to attend unevenly across very long contexts. Retrieval (lesson 9) exists precisely because "stuff everything into the prompt" scales badly. The engineering habit is to measure: track token usage per feature, set budgets per request type, and treat context growth like any other resource leak.
Continue with ai-engineering-structured-output, where hitting maxOutputTokens mid-JSON becomes a parsing bug you must handle.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement estimateTokens(text) using the four-characters-per-token heuristic: ceiling of text length divided by 4. An empty string must return 0.
starter.javascriptfunction estimateTokens(text) { // Ceiling of text.length / 4; empty string returns 0. }Reveal the reference answer
reference.javascriptfunction estimateTokens(text) { return Math.ceil(text.length / 4); } console.log(String(estimateTokens("Reset password guide")));Authored expected output: 5
estimateTokens("Reset password guide") is ceil(20 / 4) = 5. The heuristic is for planning and UI hints only; real accounting must use the provider tokenizer or the response usage block.
Exercise 2Implement
Implement remainingReplyTokens(windowTokens, systemTokens, historySizes, userInputTokens). historySizes is an array of per-message token counts. Return windowTokens minus system, minus all history, minus user input.
starter.javascriptfunction remainingReplyTokens(windowTokens, systemTokens, historySizes, userInputTokens) { // windowTokens minus systemTokens, minus every entry in historySizes, // minus userInputTokens. }Reveal the reference answer
reference.javascriptfunction remainingReplyTokens(windowTokens, systemTokens, historySizes, userInputTokens) { const used = systemTokens + historySizes.reduce((a, b) => a + b, 0) + userInputTokens; return windowTokens - used; } console.log(String(remainingReplyTokens(60, 20, [8, 12], 10)));Authored expected output: 10
remainingReplyTokens(60, 20, [8, 12], 10) = 60 - 20 - 20 - 10 = 10. If this number falls below your reserved reply size, you must drop, summarize or refuse before sending.
Exercise 3Predict
Using MOCK_PRICES (input 3 USD per million tokens, output 15 USD per million tokens) and the micro-USD rule (1 USD per million = 1 micro-USD per token), predict the logged value of estimateCostMicroUsd(1200, 300) and state the dollar amount it represents.
starter.javascriptconst MOCK_PRICES = { inputUsdPerMillion: 3, outputUsdPerMillion: 15 }; function estimateCostMicroUsd(inputTokens, outputTokens) { return inputTokens * MOCK_PRICES.inputUsdPerMillion + outputTokens * MOCK_PRICES.outputUsdPerMillion; } console.log(String(estimateCostMicroUsd(1200, 300)));Reveal the reference answer
reference.javascript// Predicted output: // // 8100 // // Trace: 1200 * 3 = 3600 micro-USD of input; 300 * 15 = 4500 micro-USD of // output; total 8100 micro-USD = 0.0081 USD. The prices are hypothetical // mock values for clean arithmetic, not a real provider's price list.Authored expected output: 8100
1200 input tokens cost 1200 * 3 = 3600 micro-USD; 300 output tokens cost 300 * 15 = 4500; total 8100 micro-USD, which is 0.0081 USD. Integer micro-USD keeps the arithmetic exact for tests.
Exercise 4Explain
Knowledge check: what does a response look like when generation hits maxOutputTokens before the model finishes?
starter.text// Choose the correct option.Reveal the reference answer
reference.textThe response returns successfully with truncated text and a finish reason such as length rather than stop. Callers must check the finish reason, because silently truncated output, especially JSON, breaks downstream parsing.Authored expected output: Truncated text with finish reason length
Length truncation is a normal outcome, not an exception. Checking finishReason belongs in every response handler.
Common misconceptions
#- Myth: one token equals one word. Fact: tokens are subword pieces; English averages roughly four characters per token, and code or non-English text can differ a lot.
- Myth: conversation cost grows only with new content. Fact: stateless APIs resend and re-bill the entire history every turn.
- Myth: the largest available context window is always the best choice. Fact: larger windows raise cost and latency, and quality can drop when relevant text drowns in irrelevant text.
Follow-up practice
#- ai-engineering-structured-output
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.