Skip to content
Visual explainer 2h 30m to learn 4 steps

Tokens, context windows and sampling across input types

Explain how text, image, audio and document inputs become tokens and how sampling, context size and latency shape the output.

By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 11 minutes to read.

Topic 2 of 34

In short

Models do not read characters or pixels directly. Text, images, audio and documents are turned into tokens, and the model predicts the next token one step at a time until it stops. The context window caps how many tokens fit in one request, and sampling settings such as temperature control how much the output varies between runs.

Think of it like this: The context window is a desk of fixed size: everything the model should consider, including its own reply, has to fit on the desk at once.

Explained simply

A language model reads and writes tokens. A token is a small chunk of text, often part of a word. 'Password' might be one token, while an unusual product name might split into three. In English, one token is about four characters on average, but the exact split depends on the model's tokenizer.

Other inputs are turned into tokens too. An image is split into patches and encoded, audio is encoded into short slices, and a PDF may be converted to text plus page images. Each of these uses up tokens, and images and long documents can use a lot.

Every model has a context window, the most tokens it can handle in one request. Your instructions, the user's message, any documents and the model's reply all share that space. If you fill it with input, there is no room left for the answer.

The model writes its reply one token at a time. At each step it scores every possible next token and then samples one. Temperature controls how adventurous that choice is. Low temperature picks the likeliest tokens and gives repeatable output. High temperature gives more variety, which helps brainstorming but hurts consistent labels.

Press Play on a diagram to walk through it one step at a time.

FlowOne inference request, step by step
  1. 1
    Input

    Text, image, audio or document

  2. 2
    Tokenise

    Input becomes a sequence of token IDs

  3. 3
    Fit the window

    Prompt plus reply must fit the limit

  4. 4
    Predict and sample

    Pick the next token, repeat

  5. 5
    Stop

    End token, length limit or stop sequence

MapInput types and typical generation tasks
Inputs
  • Text
    • Summarise a ticket
    • Draft a reply
    • Extract fields
  • Image
    • Describe a screenshot
    • Read text in a photo
  • Audio
    • Transcribe a call
    • Summarise a voicemail
  • Document
    • Answer from a PDF
    • Pull a table into JSON
CompareLow versus high temperature for the same prompt
Temperature 0 to 0.2
  • Picks the likeliest token almost always
  • Very similar output across runs
  • Good for labels and extraction
  • Can sound repetitive
Temperature 0.8 to 1.2
  • Samples from more candidates
  • Different wording each run
  • Good for drafts and ideas
  • More risk of drifting off task

In depth

How tokens are counted and billed

Providers bill and limit by tokens, not characters or words. Input tokens are everything you send: system instructions, examples, the user message and attached content. Output tokens are what the model writes. Many providers charge more per output token than per input token. The response from most APIs includes a usage object with the exact counts, and that is the number to log. Before a call, you can estimate with the provider's tokenizer library or the rough rule of four characters per token for English. Other languages, code and unusual names often use more tokens per character, so test with your real data before setting budgets.

  • Log the usage counts the API returns, not your estimate
  • Output tokens are often priced higher than input tokens
  • Non-English text and code usually need more tokens
  • Images and PDFs can cost many tokens each

Fitting a context window

Think of the window as a budget. Suppose a model allows 128,000 tokens. Reserve space for the reply first, for example 1,000 tokens. Then add fixed instructions and examples, maybe 800 tokens. What remains is for the user message and any documents. Large windows are tempting, but filling them has costs: every token costs money, longer prompts increase latency, and models can pay less attention to details buried in the middle of a very long input. Later modules use retrieval to pick only the most relevant passages, which keeps prompts small and focused.

LayersA context window budget, top to bottom
  1. 1
    System instructions

    Task rules, output format

  2. 2
    Few-shot examples

    Two or three worked cases

  3. 3
    Retrieved evidence

    Added in later modules

  4. 4
    User message

    The ticket or question

  5. 5
    Reserved for reply

    Set with a max output tokens limit

Sampling settings

After scoring candidate tokens, the model samples one. Temperature reshapes those scores: values near 0 make the top choice dominate, higher values flatten the distribution. Top-p, also called nucleus sampling, keeps only the smallest set of tokens whose probabilities add up to p, such as 0.9, and samples from those. A maximum output tokens setting caps reply length, and stop sequences end output when a given string appears. Usually you change temperature or top-p, not both. Some newer reasoning models fix or ignore these settings, so check the model's documentation. For classification and extraction, start with low temperature.

  • Temperature low: repeatable labels and extraction
  • Temperature higher: varied drafts and ideas
  • Top-p trims unlikely tokens
  • Max output tokens caps length and cost
  • Stop sequences end output at a marker

Latency and run-to-run variation

Latency has two parts you can measure. Time to first token is how long until output starts; it grows with prompt length and server load. Generation time grows with the number of output tokens. Streaming shows tokens as they arrive, which improves how fast it feels but not the total time. Variation is the other thing to measure. Send the same prompt ten times and count how many distinct answers you get. Even at temperature 0, hosted models can differ slightly between runs because of how requests are batched on shared hardware, and model updates can change answers overnight. Record both numbers so you can compare models fairly.

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Map input types to generation tasks~40m
  2. 2
    Count tokens and fit a context window~40m
  3. 3
    Tune temperature and other sampling settings~40m
  4. 4
    Measure latency and run-to-run variation~40m

Key points

  • A token is a chunk of text, often part of a word; in English one token is roughly four characters.
  • Input tokens and output tokens both count against the context window and usually both cost money.
  • Temperature near 0 makes output more repeatable; higher values make it more varied.
  • Latency grows with output length because tokens are generated one after another.
  • Even at low temperature, run-to-run variation can remain, so measure it instead of assuming it is zero.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
import time

def rough_tokens(text: str) -> int:
    # Rule of thumb for English; use the provider's tokenizer for real counts.
    return max(1, len(text) // 4)

prompt = "Customer cannot reset password after the update."
print("approx tokens:", rough_tokens(prompt))

start = time.perf_counter()
# reply = model.generate(prompt)  # any model call
elapsed_ms = (time.perf_counter() - start) * 1000
print(f"latency: {elapsed_ms:.1f} ms")

Estimate tokens and time a call. Replace the estimate with the provider's tokenizer before trusting cost numbers.

Budgeting a ticket summary request

You want a 100-word summary of a support thread. Step 1: estimate the thread. It is 6,000 characters, so roughly 1,500 tokens. Step 2: add instructions of 200 tokens and two examples of 300 tokens each, giving about 2,300 input tokens. Step 3: 100 words is roughly 130 to 150 output tokens; set max output tokens to 200 for safety. Step 4: confirm the total of about 2,500 tokens is well inside the window. Step 5: after the call, log the real usage counts and compare them to your estimate.

Measuring variation with a repeat test

Send one prompt several times and count distinct outputs. With the deterministic fake this prints 1. Point it at a real model at different temperatures to see the effect.

python
import time
from collections import Counter

def repeat_test(model, prompt: str, runs: int = 10) -> None:
    outputs, times = [], []
    for _ in range(runs):
        start = time.perf_counter()
        outputs.append(model.generate(prompt).text)
        times.append(time.perf_counter() - start)
    counts = Counter(outputs)
    print("distinct outputs:", len(counts))
    print("most common:", counts.most_common(1))
    print(f"median latency: {sorted(times)[runs // 2] * 1000:.1f} ms")

Quick reference

  • English rule of thumb: about 4 characters per token; use the real tokenizer for budgets
  • Context window = input tokens + output tokens in one request
  • Reserve reply space first with a max output tokens limit
  • Low temperature for labels and extraction; higher for drafts
  • Change temperature or top-p, not both at once
  • Latency = time to first token + time to generate the output tokens
  • Measure variation: same prompt, several runs, count distinct outputs

Common mistakes

  • Filling the window with input and leaving no room for the reply, so output is cut off.
  • Assuming temperature 0 guarantees identical output on every run and every model version.
  • Estimating cost from characters instead of the token usage the API returns.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What counts against a model's context window?

Question 2

2You need the same category label each time for the same ticket. Which setting helps most?

Question 3

3Why does a 2,000-token reply take longer than a 50-token reply?

Question 4

4Which number should you log for cost tracking?

Question 5

5Is output at temperature 0 always identical across runs on a hosted model?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Estimate the tokens in a 2,400-character English ticket and decide a max output tokens value for a 60-word summary.

  2. Exercise 2medium

    Write a function that checks whether a prompt fits a window, given an estimated prompt size, a reserved reply size and the window limit.

  3. Exercise 3hard

    Extend the repeat test to run at two temperatures with a model whose generate method accepts temperature. Report distinct outputs for each and explain what you expect.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is a token the same as a word?
No. A token is often part of a word, and punctuation and spaces can be tokens too. Short common words are often a single token.
Should I always use the model with the largest context window?
Not by default. Bigger prompts cost more and run slower, and models can miss details in very long inputs. Send only what the task needs.
Why does this path keep the labs text-based if models accept images and audio?
Text keeps the labs cheap, fast and easy to check. The same ideas of tokens, windows and sampling apply to other input types.

Go deeper

ShareXLinkedInWhatsApp