Skip to content
Part 1 14 min read

LLM Fundamentals

from an engineer's lens

Learn how LLMs work in practice: tokens, model families, sampling, structured output, tool use, embeddings, reasoning, and how to choose the right model for production.

Go to quiz
On this page

Section 1 of 10

Tokens, tokenization & context cost

Everything a model does — attention, generation, cost — is denominated in tokens, not characters or words. If your prompt shrinks from 800 to 200 tokens, you just cut cost by 75% and latency by a meaningful fraction. This is the single biggest engineering lever you have.

What is a token?

A token is one element in the model's vocabulary. Modern LLMs don't read characters; they read the output of a subword tokenizer — most commonly Byte-Pair Encoding (BPE), which iteratively merges the most frequent adjacent pairs in a corpus until a target vocabulary size (often 32k–200k) is reached.[15] For multilingual and code workloads, SentencePiece is the dominant alternative — it operates directly on raw Unicode bytes or whitespace, treating language as a configuration parameter.[16]

raw input unbelievable . _tokenization _ helps _compression . BPE merges (low→high freq) token IDs (vocab index) un believ able . _token ization _ helps _comp → 11 subword pieces (vs 33 raw chars). Frequent runs = single tokens; rare substrings split into 2–3. → The model never sees characters — only these integer IDs feed the embedding table.
BPE tokenization in practice: English byte-runs merge into common pieces; punctuation and whitespace often become standalone tokens.
এই ডায়াগ্রামে দেখানো হয়েছে র ইনপুট টেক্সট কীভাবে BPE মার্জের মাধ্যমে সাবওয়ার্ড পিসে ভাগ হয় এবং প্রতিটি পিস একটি টোকেন ID পায়। উপর থেকে নিচে পড়ুন: মডেল কখনো ক্যারেক্টার দেখে না, শুধু এই ইন্টিজার ID-ই এমবেডিং টেবিলে যায়।

Why this matters: the cost equation

APIs charge per token, not per character. A useful mnemonic: ~1 token ≈ 4 characters in English for most modern tokenizers, but this varies wildly by language — Chinese runs ~1 char ≈ 1.5 tokens, code ~1 token ≈ 3.5 chars, numbers are split digit-by-digit in early tokenizers but consolidated in newer ones.

# Counting tokens with tiktoken (OpenAI) or transformers
import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o")
text = "Tokenization is the silent tax on every LLM call."
print(len(enc.encode(text)))   # → 11 tokens, not 8 words

# Concrete cost (input, gpt-4o-mini, Jul 2025 pricing)
tokens        = 11
price_per_m   = 0.15      # USD per 1M input tokens
cost_per_call = tokens / 1_000_000 * price_per_m   # → $0.00000165

Context windows — what they actually are

The context window is the maximum total tokens (input + output) the model can attend to in a single call. It has grown dramatically: GPT-3's 2K window in 2020 → 8K (GPT-3.5) → 128K (GPT-4o) → 1M+ (Gemini 1.5).[1][11]

GPT-3 (2020)
2,048 tokens
GPT-4 Turbo
128K tokens
Claude 4 Sonnet
200K (1M β)
Gemini 1.5 Pro
1M–2M tokens
Llama 3.1 405B
128K tokens
Qwen3
32K native, 1M w/ YaRN

Long context ≠ free performance. Even with 1M-token windows, retrieval-augmented generation, summarisation, or hierarchical attention beats dumping 800K tokens in. Needle-in-a-haystack benchmarks improve, but multi-hop reasoning across long contexts degrades sharply. Measure on your own workloads.

How tokens map to cost & latency

ComponentCost driverWhat dominates
Prefill (prompt processing)Tokens in × input $/MQuadratic attention compute; ~100 ms–2 s on modern APIs for 10K tokens
Decode (generation)Tokens out × output $/MSequential (one per step); output tokens are 3–5× more expensive than input on most APIs
CachingCache hits vs missesPrompt caching (Anthropic, OpenAI, Gemini) cuts repeated-prefix cost by ~80–90%
Long contextQuadratic attentionA 1M-token call isn't 125× a 8K call — closer to 5–8× due to attention scaling and chunked prefill

Practice · 1 task

Open any free AI chat: ChatGPT · Claude · Gemini

How practice works
  • A new chat is a fresh conversation with no history. In ChatGPT, Claude, or Gemini, click New chat. It is usually at the top left.
  • Same chat means: keep typing in the chat that is already open. The AI remembers what you sent before.
  • To use a prompt: click Copy, click in the message box of the chat, paste it (Ctrl+V, or press and hold on a phone), and press Enter.
  • AI answers are a little different every time. Your answer does not need to match the example word for word. Look for the same idea.
  • Use made-up data only. Do not paste private information into a chat.

Task 1

Cut the prompt, keep the answer

Why this matters

When a support bot reads millions of tickets a month, every extra word in the prompt is paid for again on every call. A shorter prompt can save real money.

  1. Step 1
    New chat

    Copy this long prompt, paste it, and press Enter. Write down the answer.

    Prompt
    Hello! I hope you are having a wonderful day. I am working on a customer support system and I would really appreciate your kind help with a small task. Below you will find a customer ticket. Could you please read the ticket very carefully and then tell me which one of the following categories it belongs to? The categories are: billing, shipping, defect, account. Please choose only one category. When you answer, please do not write any explanation, any greeting, or any extra sentence. Just write the single category word. Thank you so much for your help!
    
    Ticket: My order #48213 arrived yesterday and the screen is cracked. I want my money back.

    You should see: One word, most likely defect.

    Example answer
    defect

    Your answer will be worded differently.

  2. Step 2
    New chat

    Copy this short prompt, paste it, and press Enter. Write down the answer.

    Prompt
    Classify the ticket as one of: billing, shipping, defect, account. Reply with the category only.
    
    Ticket: My order #48213 arrived yesterday and the screen is cracked. I want my money back.

    You should see: The same word, defect, from a prompt that is more than 3 times shorter.

    Example answer
    defect

    Your answer will be worded differently.

  3. Step 3
    New chat

    Copy this prompt, paste it, and press Enter. Check the numbers with a calculator.

    Prompt
    A support bot sends 800 input tokens per call. A shorter prompt sends 200 input tokens per call. The price is $0.50 per 1 million input tokens. The bot makes 2 million calls per month. Calculate the monthly input cost for each prompt, and the percentage saved. Show each step.

    You should see: $800 per month for the long prompt, $200 for the short one, and 75% saved.

    Example answer
    Long prompt: 800 tokens x 2,000,000 calls = 1,600,000,000 tokens (1,600 million). 1,600 x $0.50 = $800 per month.
    Short prompt: 200 tokens x 2,000,000 calls = 400,000,000 tokens (400 million). 400 x $0.50 = $200 per month.
    Saved: $800 - $200 = $600 per month.
    Percentage saved: $600 / $800 = 75%.

    Your answer will be worded differently.

What just happened

The AI reads your text as tokens (small pieces of words). You pay for every token you send, on every call. The polite extra words in the long prompt did not change the answer, but they were extra tokens. With 2 million calls a month, 600 fewer tokens per call saves $600.

You are done when You have the same one-word answer from both prompts, and the numbers $800, $200, and 75%.

Check yourselfWhy does a shorter prompt save money when the answer stays the same?Show answer

APIs charge per token, and the model reads every input token on every call. A prompt with 75% fewer tokens costs 75% less for input, and it also has less to read, so it can answer faster.

Try a harder version

Make the short prompt even shorter without changing the answer. Then ask the AI: Does the same sentence use more tokens in Bangla than in English?

Watch · 3 videos