123DevOps··7 min read

How does an LLM work? Tokens, context, temperature, and hallucination explained

A no-mystery guide to how an LLM is trained and generates answers: tokens, the context window, temperature, the system prompt, hallucination, embeddings, the knowledge cutoff, and the shape of an API request.

AI

When you type on your phone, the keyboard suggests the next word. An LLM (Large Language Model) is, in a way, that autocomplete taken to the extreme: trained on an enormous amount of text, it continues a sentence so coherently that it seems to reason. Understanding the mechanism helps you use it better, spend less, and be skeptical at the right moments. If you’re starting from scratch, first read what are AI, machine learning, and LLMs.

Training in phases

An LLM isn’t born ready to chat. Broadly speaking, it goes through three phases.

Pre-training

The model reads large volumes of text, such as web pages, books, and code, and learns a single task: predicting the next piece of text. With every mistake, its weights (millions or billions of adjustable numbers) get corrected a tiny bit. This is the most expensive phase, using many GPUs for a long time. The result knows how to continue text, but it still doesn’t follow instructions very well.

Fine-tuning

In fine-tuning, the model is trained on a smaller, carefully assembled set of question-and-answer examples. This is where it learns the assistant format: receiving a request and responding to it, instead of simply continuing the text.

Alignment

Finally, people (and sometimes other models) compare answers and indicate which ones are more helpful, honest, and safe. The model is adjusted to prefer that kind of answer. A well-known technique is RLHF (Reinforcement Learning from Human Feedback), but there are variations, and each company combines the stages in its own way.

Tokens: the pieces of text

The model doesn’t read letters or whole words: it reads tokens, which are pieces of text. A common word may be a single token; a rare or long word becomes several.

Sentence:  "Kubernetes restarted the pod."
Tokens:    ["Kube", "rnetes", " rest", "arted", " the", " pod", "."]

(illustrative split only: each model uses its own tokenizer
and cuts the same text differently)

Tokens matter for two practical reasons:

  • Cost: LLM APIs usually charge per input token (what you send) and per output token (what the model generates). Long prompts and long answers cost more. See FinOps for AI and cost per token.
  • Limits: the maximum amount the model can process is also measured in tokens.

In many models, text in languages other than English, such as Portuguese, uses more tokens than the same content in English, because tokenizers are usually built with more English text. If cost matters, measure with your model’s tokenizer instead of estimating.

Context window: working memory

The context window is everything the model “sees” when generating an answer: the system instructions, the conversation history, the documents you pasted, and the answer being built. Think of a desk: whatever is on the desk can be used; whatever isn’t doesn’t exist for the model.

The model keeps no memory between calls. The feeling that it “remembers” comes from the application, which resends the history with every message. When the conversation no longer fits in the window, older parts get cut or summarized, and details from the beginning are lost. Even within the limit, very long contexts can lower quality.

In practice: a new conversation for each task, only the relevant context, and the important facts repeated when the conversation gets long. Window size varies widely between models; check the current documentation.

Temperature and sampling

At each step, the model calculates a probability for every possible token. Then a step called sampling picks one of them. Temperature controls how much that choice ventures beyond the most likely tokens.

Temperature Behavior Good for
Low (near 0) Predictable, almost always picks the most likely token Data extraction, classification, code, factual answers
Medium Balance between consistency and variety General chat, explanations, drafts
High More varied and creative, with a higher risk of going off the rails Brainstorming, naming, creative writing

Another common parameter is top-p, which limits the choice to the group of most likely tokens whose combined probability reaches a set value. The accepted ranges differ from API to API. And note: a low temperature reduces variation, but it doesn’t guarantee identical answers across all servers, nor correct answers.

System prompt vs. user message

Chat APIs organize the conversation into messages with roles:

  • system: general instructions set by the application, such as tone, language, rules, and limits.
  • user: the person’s request.
  • assistant: the model’s previous answers, resent as history.

Models give more weight to the system prompt, but it is not a security boundary: malicious text in a document can try to override the instructions (prompt injection). Never put secrets in the system prompt thinking they’ll stay hidden. To write good prompts, see prompt engineering for tech professionals.

Hallucination: why it happens and how to reduce it

A hallucination is when the model states something false with complete confidence: a command flag that doesn’t exist, a made-up function, a fake reference. It happens because the model was trained to produce the most plausible continuation, not to check facts. If the topic was rare in training or the question is ambiguous, it fills the gap with something that “sounds right.”

How to reduce it:

  • Provide context and sources. Paste the relevant documentation, log, or code snippet. That’s the principle behind RAG, explained in what is RAG.
  • Ask for citations from the material you provided and explicitly allow “I don’t know” as an answer. Check that the citations actually exist.
  • Verify. Run tests, use --dry-run, check the official documentation.
  • Lower the temperature for factual tasks.
  • Break big tasks into smaller, verifiable steps.

Embeddings in one paragraph

An embedding turns a piece of text into a list of numbers (a vector) that represents its meaning. Texts with similar meanings produce nearby vectors, even when they use different words: “the pod won’t start” and “container in CrashLoopBackOff” end up close to each other. This is the foundation of semantic search and of RAG, which finds the right passages in your documentation before handing them to the LLM.

Knowledge cutoff

Every model has a knowledge cutoff: the point where its training data ends. It doesn’t know about versions, security flaws, or API changes released afterward, unless that information arrives through the context. Be skeptical of answers about “the latest version” of any tool.

A request from the inside

Many model servers, such as Ollama and vLLM, offer an API compatible with the chat completions format popularized by OpenAI. The example below is illustrative and points to Ollama running locally:

curl http://localhost:11434/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "<model>",
    "messages": [
      {"role": "system", "content": "You are an experienced SRE. Answer in English, briefly."},
      {"role": "user", "content": "What does CrashLoopBackOff mean in Kubernetes?"}
    ],
    "temperature": 0.2,
    "max_tokens": 300
  }'

The response (trimmed) contains the generated text and the token counts:

{
  "choices": [
    {
      "message": { "role": "assistant", "content": "It means the container starts, fails, and Kubernetes keeps trying to restart it..." },
      "finish_reason": "stop"
    }
  ],
  "usage": { "prompt_tokens": 41, "completion_tokens": 87, "total_tokens": 128 }
}

Notice the system and user roles, the low temperature for a factual question, max_tokens capping the output, and the usage field, the basis of any cost calculation. The numbers are just an example. With a hosted API, the key goes in a header read from an environment variable, such as -H "Authorization: Bearer $LLM_API_KEY", never written into the code.

Summary

  • An LLM goes through pre-training, fine-tuning, and alignment
  • Cost and limits are measured in tokens, and each model tokenizes differently
  • The context window is working memory; whatever falls outside it is forgotten
  • Low temperature for factual tasks, higher for creative ones
  • The system prompt guides the model, but it doesn’t protect secrets
  • Hallucination is reduced with context, sources, verification, and low temperature
  • The model doesn’t know what happened after its knowledge cutoff

An LLM doesn’t know the truth: it knows what’s likely. Whoever provides the context and checks the result turns probability into usefulness.

Get updates on new posts and stay in the loop!