Cybersecurity

What Are Tokens?

Python LLMs GPT RAG Prompt Engineering AI Agents Transformers Embeddings Vector Search LLaMA HTTPS
1,643 words Includes Code
Tokens and context windows tutorial showing tokenization pipeline, context window comparison across models, context budget breakdown, and the tradeoff between more and focused context
📌 Key Takeaway

Every LLM interaction has a finite context window — a fixed budget of tokens for both input and output. More context is not automatically better: it increases cost, latency, and hallucination risk. The skill is choosing the right context, not the most context.

You type a prompt and get a response. But before the model processes anything, your text is split into tokens — the atomic units of LLM processing. Every token counts against a fixed budget called the context window. Understanding tokens and context windows is essential for anyone building AI applications.

Table of Contents


1. What Are Tokens?

A token is a piece of text that the model processes as a unit. Tokens are NOT the same as words:

TOKENIZATION EXAMPLES:

"Hello, world!" → ["Hello", ",", " world", "!"] → 4 tokens
"unhappiness" → ["un", "happiness"] → 2 tokens
"GPT-4" → ["GPT", "-", "4"] → 3 tokens
"def calc_avg(n):" → ["def", " calc", "_avg", "(", "n", ")", ":"] → 7 tokens
"I can't" → ["I", " can", "'", "t"] → 4 tokens

Rule of thumb for English: 1 token ≈ 4 characters ≈ 0.75 words

Code is tokenized differently than prose. Indentation, symbols, and keywords each become separate tokens. A 200-line Python file might be 800–1,200 tokens.


2. How Tokenization Works

Most modern LLMs use Byte Pair Encoding (BPE) — a subword tokenization algorithm that learns the most common character patterns from training data.

TextTokensCount
"Hello, world!"Hello | , | world | !4
"https://example.com/path?q=search"https | : | / | / | example | . | com | / | path | ? | q | = | search13
"def calculate_average(numbers):"def | calculate | _ | average | ( | numbers | ) | :8
"price = $19.99"price | = | $ | 19 | . | 996

Key insight: URLs, code symbols, and punctuation are token-expensive. A URL like https://example.com/path?q=search is 13 tokens — more than the entire sentence "The cat sat on the mat" (7 tokens).


3. Token Counting

Quick estimation rules for English:

RULES OF THUMB:

1 token ≈ 4 characters (including spaces)
1 token ≈ 0.75 words
1,000 tokens ≈ 750 words ≈ 1 page
100,000 tokens ≈ a 300-page book

Code tokens: ~3–4 characters per token (more symbols = more tokens)
Document TypeTypical SizeEst. Tokens
Short email200 words~270 tokens
Blog post1,500 words~2,000 tokens
Python file (200 lines)~4,000 chars~800 tokens
Python file (2,000 lines)~40,000 chars~8,000 tokens
Research paper8,000 words~10,700 tokens
Entire novel80,000 words~107,000 tokens

4. The Context Window

The context window is the maximum number of tokens an LLM can process in a single request — including BOTH input (your prompt + any retrieved context) AND output (the model's response).

CONTEXT WINDOW = INPUT TOKENS + OUTPUT TOKENS

Example: 8K context window
- System prompt: 500 tokens
- User message: 200 tokens
- Retrieved docs: 5,000 tokens
- Available output: 2,300 tokens

If your input uses 7,000 tokens, you can only generate 1,000 output tokens.

What happens when you exceed the context window? The model cannot see tokens beyond the limit. Earlier tokens may be truncated, or the API may return an error. Information is lost — like trying to remember a conversation from last week.


5. Context Budget

Every token in the context window must be allocated. Here is a realistic budget breakdown for a 128K context model:

ComponentTokens% of 128KPurpose
System prompt2,0001.6%Instructions, rules, persona
Conversation10,0007.8%Chat history
Retrieved context80,00062.5%Documents, code, data
Output reserve4,0963.2%Model response space
Remaining31,90424.9%Buffer / flexibility

6. Model Comparison

ModelContext Window~WordsBest For
GPT-3.5 Turbo4,096~3KShort prompts, simple tasks
GPT-48,192~6KModerate documents, code review
GPT-4 Turbo128,000~96KLong documents, full codebases
Claude 3.5 Sonnet200,000~150KVery long documents, analysis
Llama 3.1128,000~96KLocal deployment, privacy
Gemini 1.5 Pro1,000,000+~750KEntire books, massive datasets

7. Why More Context Is Not Better

This is the most misunderstood aspect of context windows. Research shows several problems with very long contexts:

The "Lost in the Middle" Problem

Research Finding: LLMs attend more to information at the beginning and end of the context window, and less to information in the middle. This is called the "lost in the middle" effect.

If you put the most important information in the middle of a long document, the model may miss it.

Practical Tradeoffs

More Context ✓More Context ✗
More information availableHigher API cost (potentially $1–5+ per call)
Better full-document understandingSlower processing (more tokens = more compute)
Fewer truncation issues"Lost in the middle" — model ignores middle content
Better RAG retrieval qualityMore hallucination risk with irrelevant context
Handles complex, multi-file tasksDiluted attention — model spreads focus too thin
💡 THE RIGHT QUESTION: Not "How much context can I fit?" but "What context does the model actually need for this task?"

8. Tokens in Coding

Code is token-expensive because of symbols, indentation, and keywords:

CODING SCENARIOS:

Single function (50 lines): ~400 tokens → fits in 4K easily
One file (200 lines): ~800 tokens → fits in 4K
Large file (2,000 lines): ~8,000 tokens → needs 32K context
Project (10 files): ~20,000 tokens → needs 32K+ context
Full codebase (50 files): ~80,000 tokens → needs 128K context

AI coding agents (Claude Code, Cursor) manage this automatically.

Practical tip: When asking an AI to review code, provide only the relevant files — not the entire codebase. This reduces cost, improves focus, and avoids the "lost in the middle" problem.

See How AI Coding Agents Actually Work for how agents manage context.


9. Tokens with Documents

Document length directly impacts what models can process:

Document~TokensFits in 8K?Fits in 128K?
README.md~500✅ Yes✅ Yes
API documentation~3,000✅ Yes✅ Yes
Research paper~10,000❌ No✅ Yes
Legal contract~8,000⚠️ Tight✅ Yes
Book chapter~15,000❌ No✅ Yes
Entire novel~100,000❌ No⚠️ Tight

10. Tokens in RAG

RAG (Retrieval-Augmented Generation) solves the context window problem by retrieving only relevant chunks instead of loading entire documents.

WITHOUT RAG:
User query → Load entire 100K document → 95K tokens wasted on irrelevant content

WITH RAG:
User query → Embed query → Find top 5 relevant chunks → Load only 5K tokens
→ Model sees exactly what it needs → Better answer, lower cost

RAG is the standard approach when your knowledge base exceeds the context window. It retrieves the most relevant chunks and sends only those to the model.

Learn more in RAG Architecture Explained.


11. Tokens in AI Agents

AI coding agents face unique token challenges because they manage multiple tool calls, file reads, and code edits in a single session:

Agent ActionTypical TokensImpact
Read a file500–5,000Consumes input budget
Run a command100–1,000Output tokens count
Edit a file200–2,000Both input and output
Run tests500–3,000Test output is token-heavy
Full agent session50,000–200,000Accumulates across turns

Agents must strategically manage context — reading only necessary files, summarizing old outputs, and avoiding unnecessary back-and-forth.

See Context Engineering Explained for how developers control what the model sees.


12. Context Management Strategies

StrategyHow It WorksBest For
TruncationKeep first N tokensSimple, but loses end context
Sliding WindowKeep recent N tokensLong conversations
RAGRetrieve relevant chunksLarge knowledge bases
SummarizationSummarize old contextReducing conversation history
ChunkingSplit into pieces, process separatelyParallel processing
HierarchicalSummary + on-demand detailsOverview + drill-down

13. Cost Implications

Tokens directly determine API costs. Here are illustrative costs per 1M tokens:

ScenarioInput TokensOutput TokensGPT-4 Cost
Short prompt500200~$0.01
Document analysis10,0002,000~$0.16
Long document100,0005,000~$1.15
Full codebase500,00010,000~$5.30

Key insight: Using RAG to send 5K relevant tokens instead of 100K full-document tokens can reduce cost by 95% while improving answer quality.


14. FAQ

Are tokens the same as words?
No. Tokens are subword units. In English, 1 token ≈ 0.75 words. "Unhappiness" might be 2 tokens (un + happiness) but is 1 word. Code is tokenized differently — symbols and keywords become separate tokens.
How do I count tokens before sending a request?
Use the model's tokenizer (e.g., tiktoken for OpenAI models) or estimate: tokens ≈ characters / 4. Most APIs return token counts in their response headers.
What happens if I exceed the context window?
The API will either truncate earlier tokens (losing information) or return an error. Neither is ideal. Always check token counts before sending.
Why is more context not always better?
Three reasons: (1) "Lost in the middle" — models attend less to middle content, (2) higher cost and latency, (3) irrelevant context can confuse the model and increase hallucination. The right context is better than more context.
What is the "lost in the middle" problem?
Research shows LLMs attend more to tokens at the beginning and end of the context window, and less to tokens in the middle. If your most important information is in the middle of a long document, the model may overlook it.
Should I always use the largest context window available?
No. Use the smallest context window that fits your task. A 4K context for a simple question is faster and cheaper than 128K. Use larger contexts only when you genuinely need to process more information.
How does RAG help with context limits?
RAG retrieves only the most relevant chunks from your knowledge base, rather than sending entire documents. This keeps context usage focused and affordable. A 100K document can be reduced to 5K relevant tokens. See RAG Architecture Explained.

Try These BestWordz Tools

Continue Learning

Try the JSON Formatter

Put what you've learned into practice with this free BestWordz tool.

Open Tool →

Continue Learning: Prompt Engineering

Master the art of communicating with AI

  1. Free-Form vs Structured Output
  2. What Are Tokens? (this article)
  3. The Sequence Modeling Problem
  4. AI → Machine Learning → Deep Learning
  5. The 10-Stage CS Learning Roadmap

💬 Discuss on BestWordz Community

Join the conversation about Python, LLMs, GPT on the BestWordz Community forum.

Visit Forum →