{"course":{"slug":"building-with-ai","title":"Building with AI","url":"https://addaly.com/learn/building-with-ai","level":"intermediate","track":"build"},"lesson":{"slug":"tokens-and-the-context-window","title":"Tokens, language and the context budget","url":"https://addaly.com/learn/building-with-ai/tokens-and-the-context-window","position":3,"of":80,"minutes":10,"answer":"Measure the actual request with the selected model's tokenizer, then budget input, output and cost using its documented limits and rates.","keyIdea":"Measure the actual request with the selected model's tokenizer, then budget input, output and cost using its documented limits and rates."},"body":{"format":"markdown","text":"## Text becomes tokens\n\nBefore a text model processes a request, a tokenizer maps the text to token IDs. The divisions depend on its vocabulary, algorithm and preprocessing. A token may cover a word, part of a word, punctuation or whitespace. Capitalization and surrounding spaces can change the result. Different tokenizers use different methods. For example, `tiktoken` uses byte-pair encoding, while Hugging Face supports BPE, Unigram, WordPiece and other models. [Tokenizer methods](https://huggingface.co/docs/tokenizers/pipeline).\n\nFor a rough English estimate, one token is about four characters or three quarters of a word. That makes 500 words roughly 667 tokens. Actual counts vary, so measure the text that your application will send. [English estimates and counting](https://help.openai.com/en/articles/4936856-understanding-and-counting-tokens).\n\n### Measure the languages your users use\n\nThe same meaning can produce different counts across languages and encodings. This example counts two specific strings using the named `cl100k_base` encoding. Install `tiktoken` before running it. The encoding is an example for comparison. Select the tokenizer for your production model when estimating its inputs. [tiktoken documentation](https://github.com/openai/tiktoken).\n\n```python\nimport tiktoken\n\nenc = tiktoken.get_encoding(\"cl100k_base\")\nen = (\n    \"Hello, how are you? \"\n    \"I need help with my order.\"\n)\nhi = (\n    \"नमस्ते, आप कैसे हैं? \"\n    \"मुझे अपने ऑर्डर में मदद चाहिए।\"\n)\nprint(len(enc.encode(en)), len(enc.encode(hi)))\n# 13 52\n```\n\n> Figure: Two strings under cl100k_base. Bars (tokens for the printed string): English 13; Hindi in Devanagari 52. Local plain-text counts with tiktoken 0.14.0 for the exact English and Hindi strings printed above. API message formatting and generated output are excluded. The ratio describes this example and encoding.\n\nThe local measurement with `tiktoken` 0.14.0 gives 13 and 52 tokens. These are plain-text counts for those exact strings. API message formatting, tools and generated output add their own usage. This one comparison cannot establish the cost ratio for an entire Hindi support service. Measure representative messages, replies and conversation lengths in each language, then apply the chosen model's input, output and cache rates.\n\nCode, JSON, numbers and whitespace can also produce different token patterns. Inspect the actual input before estimating capacity or cost from word count. When an application transforms or retrieves text, count the final request it constructs.\n\n## Planning a context budget\n\nRead the chosen model's documented input, output and context limits. For Claude, the context includes the request and the generated output, with model-specific rules for thinking and previous turns. Gemini's model metadata exposes separate `inputTokenLimit` and `outputTokenLimit` fields. Allow room for the response and any reasoning tokens that count toward the relevant limit. [Claude context rules](https://platform.claude.com/docs/en/build-with-claude/context-windows), [Gemini model limits](https://ai.google.dev/api/models).\n\nAn illustrative request budget might contain a 1,000-token system prompt and tool definitions, 6,000 tokens of retrieved documents and 3,000 tokens of conversation history. That is 10,000 input tokens. Reserve another 500 output tokens for this example, and verify the complete request against the selected model's limits.\n\nAt illustrative rates of $3 per million input tokens and $15 per million output tokens, the example costs $0.03 + $0.0075 = $0.0375. Ten thousand such requests cost $375, before other charges. These figures assume all input uses that input rate. Cache pricing, reasoning output and other features can change the bill. Use current prices and measured usage for a real forecast.\n\n## Using a large window well\n\nIf your program resends an ever-growing history, each later request contains more input. Under a simplified model that adds the same number of tokens each turn, resends all previous turns and uses a constant uncached rate, cumulative input cost grows quadratically with the number of turns. Trimming or summarizing changes that growth. Prompt caching can change the price of repeated input while those tokens still occupy context. Measure the approach you use. [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching).\n\nEvaluate retrieval with the actual model and task. The 2023 *Lost in the Middle* study found position-sensitive performance on its question-answering and key-value retrieval tests, often with lower accuracy when relevant information was in the middle. This is a dated empirical result. Test your own documents, distractors and answer checks before deciding how much context to include. [Study and test details](https://arxiv.org/abs/2307.03172).\n\n## Count before you send\n\nUse a model-compatible local tokenizer when available. A provider's token-counting endpoint can estimate a complete request, including supported messages and tools. For example, Claude provides a token-counting API. Input counts are estimates of the request and do not predict generated output. Compare them with returned usage. [Claude token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting).\n\nCheck request size and the output allowance before generation. If the request is too large, deliberately select, split or summarize the material and verify that the necessary information remains. Report the problem clearly when the task cannot fit. Avoid silently dropping the end of a document."},"check":{"question":"A local measurement with cl100k_base gives 13 tokens for the exact English string and 52 for the exact Hindi string in this lesson. What does this establish?","options":[{"text":"The provider charges a higher per-token price for every Hindi request.","correct":false,"tempting":"A count measures the encoded text. Pricing requires the chosen model and token category."},{"text":"Those two strings have different token counts under that named encoding. A service cost estimate needs representative requests and the applicable rates.","correct":true},{"text":"Every Hindi conversation will cost exactly four times the equivalent English conversation.","correct":false,"tempting":"A ratio for two fixed strings does not include other messages, replies, cache use or a different tokenizer."},{"text":"The model must translate Hindi into English and bill a second request.","correct":false,"tempting":"This local counting example performs no model generation or translation request."}]},"prev":{"slug":"system-prompts-and-turns","title":"System prompts, user turns, and who the model listens to","url":"https://addaly.com/learn/building-with-ai/system-prompts-and-turns"},"next":{"slug":"sampling-and-determinism","title":"Temperature, sampling, and why the same input gives a different answer","url":"https://addaly.com/learn/building-with-ai/sampling-and-determinism"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Tokens, language and the context budget', in Building with AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/building-with-ai/tokens-and-the-context-window (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Tokens, language and the context budget","courseTitle":"Building with AI","module":{"index":1,"slug":"the-call-underneath-everything","title":"The call underneath everything"},"answer":null,"keyIdea":"Measure the actual request with the selected model’s tokenizer, then budget input, output and cost using its documented limits and rates.","hero":{"kind":"figure","figure":{"t":"figure","label":"Figure","figure":{"type":"bars","title":"Two strings under cl100k_base","caption":"Local plain-text counts with tiktoken 0.14.0 for the exact English and Hindi strings printed above. API message formatting and generated output are excluded. The ratio describes this example and encoding.","unit":"tokens for the printed string","series":[{"label":"English","value":13},{"label":"Hindi in Devanagari","value":52,"highlight":true}]},"alt":"Figure: Two strings under cl100k_base. Bars (tokens for the printed string): English 13; Hindi in Devanagari 52. Local plain-text counts with tiktoken 0.14.0 for the exact English and Hindi strings printed above. API message formatting and generated output are excluded. The ratio describes this example and encoding."}},"blocks":[{"t":"h2","id":"text-becomes-tokens","runs":[{"text":"Text becomes tokens"}]},{"t":"p","runs":[{"text":"Before a text model processes a request, a tokenizer maps the text to token IDs. The divisions depend on its vocabulary, algorithm and preprocessing. A token may cover a word, part of a word, punctuation or whitespace. Capitalization and surrounding spaces can change the result. Different tokenizers use different methods. For example, "},{"text":"tiktoken","code":true},{"text":" uses byte-pair encoding, while Hugging Face supports BPE, Unigram, WordPiece and other models. "},{"text":"Tokenizer methods","href":"https://huggingface.co/docs/tokenizers/pipeline"},{"text":"."}]},{"t":"p","runs":[{"text":"For a rough English estimate, one token is about four characters or three quarters of a word. That makes 500 words roughly 667 tokens. Actual counts vary, so measure the text that your application will send. "},{"text":"English estimates and counting","href":"https://help.openai.com/en/articles/4936856-understanding-and-counting-tokens"},{"text":"."}]},{"t":"h3","id":"measure-the-languages-your-users-use","runs":[{"text":"Measure the languages your users use"}]},{"t":"p","runs":[{"text":"The same meaning can produce different counts across languages and encodings. This example counts two specific strings using the named "},{"text":"cl100k_base","code":true},{"text":" encoding. Install "},{"text":"tiktoken","code":true},{"text":" before running it. The encoding is an example for comparison. Select the tokenizer for your production model when estimating its inputs. "},{"text":"tiktoken documentation","href":"https://github.com/openai/tiktoken"},{"text":"."}]},{"t":"code","lang":"python","label":"Python","text":"import tiktoken\n\nenc = tiktoken.get_encoding(\"cl100k_base\")\nen = (\n    \"Hello, how are you? \"\n    \"I need help with my order.\"\n)\nhi = (\n    \"नमस्ते, आप कैसे हैं? \"\n    \"मुझे अपने ऑर्डर में मदद चाहिए।\"\n)\nprint(len(enc.encode(en)), len(enc.encode(hi)))\n# 13 52"},{"t":"p","runs":[{"text":"The local measurement with "},{"text":"tiktoken","code":true},{"text":" 0.14.0 gives 13 and 52 tokens. These are plain-text counts for those exact strings. API message formatting, tools and generated output add their own usage. This one comparison cannot establish the cost ratio for an entire Hindi support service. Measure representative messages, replies and conversation lengths in each language, then apply the chosen model’s input, output and cache rates."}]},{"t":"p","runs":[{"text":"Code, JSON, numbers and whitespace can also produce different token patterns. Inspect the actual input before estimating capacity or cost from word count. When an application transforms or retrieves text, count the final request it constructs."}]},{"t":"h2","id":"planning-a-context-budget","runs":[{"text":"Planning a context budget"}]},{"t":"p","runs":[{"text":"Read the chosen model’s documented input, output and context limits. For Claude, the context includes the request and the generated output, with model-specific rules for thinking and previous turns. Gemini’s model metadata exposes separate "},{"text":"inputTokenLimit","code":true},{"text":" and "},{"text":"outputTokenLimit","code":true},{"text":" fields. Allow room for the response and any reasoning tokens that count toward the relevant limit. "},{"text":"Claude context rules","href":"https://platform.claude.com/docs/en/build-with-claude/context-windows"},{"text":", "},{"text":"Gemini model limits","href":"https://ai.google.dev/api/models"},{"text":"."}]},{"t":"p","runs":[{"text":"An illustrative request budget might contain a 1,000-token system prompt and tool definitions, 6,000 tokens of retrieved documents and 3,000 tokens of conversation history. That is 10,000 input tokens. Reserve another 500 output tokens for this example, and verify the complete request against the selected model’s limits."}]},{"t":"p","runs":[{"text":"At illustrative rates of $3 per million input tokens and $15 per million output tokens, the example costs $0.03 + $0.0075 = $0.0375. Ten thousand such requests cost $375, before other charges. These figures assume all input uses that input rate. Cache pricing, reasoning output and other features can change the bill. Use current prices and measured usage for a real forecast."}]},{"t":"h2","id":"using-a-large-window-well","runs":[{"text":"Using a large window well"}]},{"t":"p","runs":[{"text":"If your program resends an ever-growing history, each later request contains more input. Under a simplified model that adds the same number of tokens each turn, resends all previous turns and uses a constant uncached rate, cumulative input cost grows quadratically with the number of turns. Trimming or summarizing changes that growth. Prompt caching can change the price of repeated input while those tokens still occupy context. Measure the approach you use. "},{"text":"Prompt caching","href":"https://platform.claude.com/docs/en/build-with-claude/prompt-caching"},{"text":"."}]},{"t":"p","runs":[{"text":"Evaluate retrieval with the actual model and task. The 2023 "},{"text":"Lost in the Middle","i":true},{"text":" study found position-sensitive performance on its question-answering and key-value retrieval tests, often with lower accuracy when relevant information was in the middle. This is a dated empirical result. Test your own documents, distractors and answer checks before deciding how much context to include. "},{"text":"Study and test details","href":"https://arxiv.org/abs/2307.03172"},{"text":"."}]},{"t":"h2","id":"count-before-you-send","runs":[{"text":"Count before you send"}]},{"t":"p","runs":[{"text":"Use a model-compatible local tokenizer when available. A provider’s token-counting endpoint can estimate a complete request, including supported messages and tools. For example, Claude provides a token-counting API. Input counts are estimates of the request and do not predict generated output. Compare them with returned usage. "},{"text":"Claude token counting","href":"https://platform.claude.com/docs/en/build-with-claude/token-counting"},{"text":"."}]},{"t":"p","runs":[{"text":"Check request size and the output allowance before generation. If the request is too large, deliberately select, split or summarize the material and verify that the necessary information remains. Report the problem clearly when the task cannot fit. Avoid silently dropping the end of a document."}]}],"check":{"question":[{"text":"A local measurement with cl100k_base gives 13 tokens for the exact English string and 52 for the exact Hindi string in this lesson. What does this establish?"}],"options":[{"text":[{"text":"The provider charges a higher per-token price for every Hindi request."}],"correct":false,"tempting":[{"text":"A count measures the encoded text. Pricing requires the chosen model and token category."}]},{"text":[{"text":"Those two strings have different token counts under that named encoding. A service cost estimate needs representative requests and the applicable rates."}],"correct":true,"tempting":null},{"text":[{"text":"Every Hindi conversation will cost exactly four times the equivalent English conversation."}],"correct":false,"tempting":[{"text":"A ratio for two fixed strings does not include other messages, replies, cache use or a different tokenizer."}]},{"text":[{"text":"The model must translate Hindi into English and bill a second request."}],"correct":false,"tempting":[{"text":"This local counting example performs no model generation or translation request."}]}],"order":[0,1,2,3],"why":null},"prev":{"slug":"system-prompts-and-turns","title":"System prompts, user turns, and who the model listens to","minutes":6},"next":{"slug":"sampling-and-determinism","title":"Temperature, sampling, and why the same input gives a different answer","minutes":9}}}