---
title: How LLMs work, for builders
summary: Tokens, the context window, sampling and hallucination, the handful of facts that explain most surprising agent behavior.
section: ai
phase: any
order: 1
last_reviewed: 2026-11-20
---

# How LLMs work, for builders

You don't need the math. You need a mental model that predicts when a model will be sharp, when it will drift, and when it will confidently make something up.

## You'll be able to

- Explain why an agent forgot an instruction, repeated itself, or invented an API
- Estimate what fits in a prompt, and why "just paste the whole repo" backfires
- Set the right expectations about repeatability: same prompt, different answer
- Write prompts that make hallucinations less likely and easier to catch

## The mental model

Think of a very well-read colleague with a notepad of fixed size. They have read an enormous amount, they answer fluently whether or not they actually know, and they can only work from what is on the notepad right now: your messages, the files and tool results in the conversation, and the answer they are writing.

A useful simplification: the model produces its answer one small chunk (a **token**) at a time, each chunk chosen from what is most plausible given everything on the notepad so far. Plausible is not the same as true, which is why fluent output can still be wrong.

> **Note:** "One token at a time" is a simplification for building intuition, not a full description of how a model is trained or how a harness works. It is enough to predict the failure modes below.

## Key concepts

- **Token:** The unit a model reads and writes. It can be a whole word, part of a word, punctuation or a few characters. Providers measure limits and billing in tokens, and the number of tokens for the same text varies by model and by language. Use the provider's token-counting tool when you need an exact number.
- **Context window:** Everything the model can reference when it generates a response, including the response itself. It is working memory, not training data. It holds the system prompt, every message in the conversation, tool definitions and tool results, plus the output being written. On the API, an input that is too large for the window fails with an error.
- **Context rot:** Accuracy and recall can degrade as the amount of text in the window grows. A bigger window is not a license to fill it. What you leave out matters as much as what you put in.
- **Caching changes cost, not capacity:** Reusing a cached prompt prefix can make requests cheaper and faster, but those tokens still take up space in the window.
- **Temperature (sampling):** A setting that controls how much randomness goes into picking each token. Lower values give more conservative output, higher values more varied output. Even at the lowest setting, identical inputs are not guaranteed to produce identical outputs.
- **Hallucination:** Output that is factually wrong or inconsistent with the context you gave. It comes from the same mechanism as correct output, so the model sounds equally sure either way.
- **Grounding:** Anchoring the answer in text you supplied (quotes, documents, the actual file) rather than in what the model remembers from training.

## Decisions you make (not the agent)

| Decision | Sensible default | Choose otherwise when… |
|---|---|---|
| What goes in the prompt | The goal, constraints, and paths to the relevant files | The task truly spans many files: point to them by path and let the agent read what it needs |
| When to start a new session | One session per task; start fresh when the topic changes or the thread gets long and muddled | A follow-up depends on decisions made earlier in the thread |
| How much to trust a factual claim | Verify anything you will ship (run it, read the docs, check the package exists) | The output is throwaway or easy to test immediately |
| Relying on repeatable output | Don't. Make correctness testable instead (tests, types, linters) | You need identical output every time: store the result instead of regenerating it |
| Asking for quotes and sources | Yes, when the answer must come from documents you provide | Brainstorming or exploring, where there is no ground truth to quote |
| Letting the model say "I don't know" | Always allow it, explicitly | Never; a forced answer is a guess |

## What good output looks like

- It refers to things that actually exist in your repo and dependencies (real files, real function names, real versions)
- When the answer depends on your docs, it quotes or points to the relevant passage
- It states assumptions and says plainly when it lacks information instead of filling the gap
- It stays consistent with the constraints you set at the start, even late in a long task

## Red flags

- **An import or function that isn't in the codebase** → search for it, and run the type checker. Invented names are the classic hallucination.
- **A package you've never heard of, or one that isn't in `package.json`** → check that it exists and is what you expect before installing anything.
- **Early instructions quietly ignored late in a long session** → context has grown and muddied; summarize the decisions and start a fresh session.
- **"As we discussed" about something you never said** → the model is filling gaps. Restate the facts.
- **Confident explanation with no evidence** → ask for the exact lines, file paths or doc passages that support it.
- **Different answers to the same prompt** → expected. Treat it as a reason to check with tests, not as a bug in the tool.

## Worked example

**Task:** Add rate limiting to a Next.js API route that creates bookings.

You send a short prompt: *"Add rate limiting to the bookings endpoint."* The agent replies with a tidy diff that imports `rateLimit` from a package, calls it with an options object, and says the work is done. It reads well and it sounds sure.

**What a good result contains:** a limiter that uses a dependency already in the project, or one new dependency the agent named and justified; the limit chosen and why; behavior when the limit is hit (an HTTP 429 response); and a test.

**The wrong turn:** the package named in the import isn't in `package.json`, and the options object uses fields you can't find in any documentation. The model produced a plausible-looking call from patterns it has seen, not from the library you have.

**How review catches it:** run the type checker and the tests (the import fails or the types don't match). Then ask the agent to list every external import in the diff and where each one is defined. Open the real docs for the package you decide on, and give the agent the relevant section so the next attempt is grounded in text rather than recall.

## Sample prompts

### Weak vs strong
```compare
## Weak
Add rate limiting to the bookings endpoint.
## Why it fails
No stack, no limits, no constraint on dependencies, no way to verify. The model fills every gap with a guess.
## Strong
Goal: add rate limiting to POST /api/bookings.
Stack: Next.js (App Router), TypeScript, Postgres via Drizzle.
Constraints: max 10 requests per minute per IP; respond with 429 and a Retry-After header when exceeded; keep existing response shapes; use only packages already in package.json. If you think a new package is needed, stop and propose it with the reason before installing.
Non-goals: no changes to the UI, no changes to other routes.
Verify: add a test that sends 11 requests and expects the 11th to return 429; run lint, typecheck and tests, and show me the output.
## Why it works
It states the goal, limits, stack, boundaries and the proof. The "only packages already in package.json" rule turns an invented dependency into an explicit decision point.
## What changed
- **Goal, stack and limits** are stated
- **A dependency rule** turns an invented package into an explicit decision
- **Non-goals** keep the change inside one route
- **Verification** names the test, the commands and the output to show
```

### Ground an answer in your own docs
```text
Using only the document at <path/to/doc>, answer: <question>.
First, extract the exact sentences that are relevant and list them. Then answer using only those sentences. If the document does not cover the question, say "not covered" instead of guessing.
```
*Why it works:* It gives the model permission to say it doesn't know, and makes it ground each claim in a quote, two techniques Anthropic's guidance recommends for reducing hallucinations.

### Audit for invented names
```text
Review this diff for anything that might not exist. List every import, function call, config key and CLI flag it introduces. For each one, tell me where it is defined (file and line in this repo, or the dependency and version in package.json). Mark anything you cannot point to as "unverified".
```
*Why it works:* It turns a vague worry into a checklist the agent can complete and you can spot-check.

### Ask it to show its assumptions
```text
Before I accept this, list the assumptions you made that I did not tell you, and the parts of your answer you are least sure about. For each, say what I could run or read to confirm it.
```
*Why it works:* It surfaces gaps and gives you a verification step. Treat the answer as a lead to check, not as proof, since the model can be wrong about its own certainty.

### Hand off to a fresh session
```text
Summarize this session so I can start a new one: the goal, decisions made and why, files changed, what is done, what is left, and any open questions. Keep it under 15 bullets.
```
*Why it works:* A short, curated summary carries forward what matters without dragging along a long, noisy context.

## Check your understanding

```quiz
Q: Which of these count toward the context window?
- [x] Your messages and the system prompt
- [x] Tool results the agent has read
- [x] The answer the model is currently writing
- [ ] The model's training data
> Why: The window is the model's working memory: everything it can reference, including its own output. Training data is not in it.

---

Q: You set temperature to its lowest setting. What can you rely on?
- [ ] Identical output on every run
- [x] More conservative output, but not guaranteed to be identical
- [ ] No hallucinations
> Why: Lower temperature reduces randomness, but identical inputs are still not guaranteed to give identical outputs, and hallucinations come from the same mechanism as correct answers.

---

Q: An answer must come only from your documents. Which prompt change helps most?
- [ ] Add "be accurate" to the prompt
- [x] Ask for the supporting quotes first, and allow "not covered" as an answer
- [ ] Paste the whole repository into the prompt
> Why: Grounding the answer in quotes and giving the model permission to say it doesn't know both reduce hallucination. Extra, unrelated context can make results worse (context rot).
```

## Checklist

- [ ] Every import, function and package in the diff exists (type check and tests pass)
- [ ] Claims that matter are backed by a doc, a quote or a test
- [ ] The prompt allowed the model to say "I don't know"
- [ ] Long session? Summarized the decisions and started fresh if quality dropped
- [ ] Correctness is checked by tests, not by regenerating until it looks right

## Go deeper

- [Context windows (Claude docs)](https://platform.claude.com/docs/en/build-with-claude/context-windows): what counts toward the window, context rot, and strategies for long conversations
- [Glossary (Claude docs)](https://platform.claude.com/docs/en/about-claude/glossary): tokens, context window and temperature, including why temperature 0 is still not fully deterministic
- [Reduce hallucinations (Claude docs)](https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/reduce-hallucinations): letting the model say "I don't know", quote-based grounding and citations; reduces, but does not eliminate, hallucinations
- [Working with coding agents](/docs/start-here/working-with-coding-agents.md): the agent loop and how harnesses use these limits
- [Anatomy of a good prompt](/docs/start-here/anatomy-of-a-good-prompt.md): the six parts of a strong prompt
