When you chat with ChatGPT, Claude, Gemini or similar, it can be challenging to imagine what exactly is on the other end. It feels like some real thing: something that sits there, listens, decides, remembers you, and reaches out into the world. In practice it often does behave that way. But the machinery that produces that behavior is quite different from what the experience suggests, and knowing how it works explains a lot: why it's brilliant at some things and oddly bad at others, why it forgets, why it costs what it does. This guide walks through it, starting from one simple idea and building everything else on top.
No technical background is needed. Everything that follows builds on this:
At its core, an AI language model does exactly one thing: given some text, it predicts what text should come next. Every other feature (conversation, reasoning, using tools, searching your files) is built by arranging text cleverly and by ordinary software working around the model.
- The engine: a next-word predictor
- A conversation is one long document
- The invisible tokens
- Outputs, stopping and "thinking"
- Tools
- Why math is hard
- Skills
- MCP
- Vector knowledge bases
- How much is hidden from you
- Cost and caching
- Why coding agents are built the way they are
- Putting it together
§1The engine: a very good next-word predictor
Your phone's keyboard suggests the next word as you type. Type "See you" and it offers "tomorrow" or "soon." It does that by having seen lots of text in which those words tend to follow.
A large language model (the "LLM" behind an AI assistant) is the same basic idea scaled up enormously. It was trained on a vast amount of writing (books, websites, code, conversations) and during training it was repeatedly shown a passage with the next piece hidden, asked to guess it, and adjusted slightly every time it guessed wrong. Do that trillions of times and the model gets extraordinarily good at continuing text in a way that fits.
The pieces it predicts are called tokens: usually a word or part of a word ("unbelievable" might be "un" + "believ" + "able"). The model produces one token, that token is added onto the end of the text, and then the model is run again on the slightly longer text to produce the next one. An entire answer is built this way, one small piece at a time.
Why predicting text looks like intelligence
To continue text well, you have to capture a lot about what the text is about. To finish "The capital of France is ___," the model needs to have picked up facts. To finish a half-written proof, it needs something that functions like mathematical reasoning. To continue a conversation with a worried person, it needs to have absorbed how kind, sensible people respond. So a model trained only to predict text ends up with genuinely impressive abilities. Those abilities are real, but they come out through one channel: producing the next bit of text.
Whether any of this amounts to "understanding" in a deeper sense is an open and honestly debated question. What isn't debated is the mechanism: text in, a prediction of more text out.
The key idea: whatever the right word for it is, the model isn't something that persists between your messages. It's a large mathematical function that sits idle until someone hands it text, produces a continuation, and stops.
§2A "conversation" is really one long document
When you chat with an assistant, it feels like a back-and-forth between two parties. Behind the scenes, the app is building a single document that looks something like a play script, and asking the model to continue it.
A few important consequences fall straight out of this:
The model has no memory between turns. Each time you send a message, the app sends the whole script again, every previous message included, and the model reads it fresh from the top. It doesn't "remember" what you said earlier; it's re-reading it. (Providers can save some of the work of re-reading an unchanged beginning. That's caching, covered in §11, but it's a shortcut in the arithmetic, not memory. Logically, the model still takes in the whole script every time.) If a message gets dropped from the script, the model genuinely has no idea it happened.
"Memory" features are also just text. When an assistant seems to remember you across separate chats, it's because the app saved some notes and pastes them into the top of the document next time. The model reads them like any other text.
The model's "personality" and rules are text too. The opening section, often called the system prompt, is written by the company or app developer. It's the stage directions at the top of the script. The model follows it because it was trained to treat that section as instructions.
There's a size limit. The model can only take in so much text at once (its context window). Everything it "knows" about your conversation has to fit inside that window.
The key idea: the assistant is the character labelled [ASSISTANT] in a script. The model is writing that character's next line, over and over.
§3The invisible tokens: labels that aren't made of letters
The [SYSTEM], [USER] and [ASSISTANT] labels above were a simplification. Here's what's really there.
Every token is really a number
The model never sees letters. Before any text reaches it, a program called the tokenizer chops the text into tokens and swaps each one for an ID number from a fixed dictionary: the model's vocabulary, typically somewhere around a hundred thousand to a few hundred thousand entries. "Hello" might be entry 9906; a comma might be entry 11. Inside the model, each ID number is then looked up in a big table that turns it into a long list of numbers (its embedding), and that is what the model actually computes with. On the way out, the model predicts an ID number, and the tokenizer turns it back into letters for you to read.
Special tokens are ordinary entries with no spelling
A handful of entries in that dictionary are reserved and don't correspond to any string of characters at all. They're usually named things like <|start_header|> or <|end_of_turn|> in documentation, but those names are just labels for humans; the tokens themselves are only ID numbers. In every other way they're completely normal tokens: they have their own learned entry in the embedding table, the model reads them the same way, and the model predicts them the same way. What they mean was learned the same way everything else was: by seeing where they reliably appear in training examples. After seeing "end-of-turn" at the end of millions of assistant replies, the model learns to predict it when a reply is complete, and the software learns to treat it as a stop signal.
Notice that in many formats the role name itself ("user," "assistant") is ordinary text sandwiched between special tokens. It's the special tokens around it that make it a label rather than a word someone typed. Model families each have their own format (sometimes called a chat template), and a model only works properly with the one it was trained on.
Why you can't type them
Because special tokens have no spelling, there's no way to produce one by typing. If you type the characters "<end_turn>" into a chat box, a well-built tokenizer splits them into ordinary pieces ("<", "end", "_turn", ">") with completely different ID numbers. To the model, that looks like someone writing about the marker, not the marker itself. This is an important security boundary: only the app, not the person typing, can insert the real structural tokens that say where the instructions end and the user's words begin. (Early systems sometimes got this wrong, which let users forge fake instructions.)
Tool requests, the boundary of a hidden "thinking" section, and the start of a pasted-in tool result are typically marked the same way: with special tokens, or with ordinary text patterns the model was trained to use in those places.
The key idea: special tokens are regular vocabulary entries that happen not to spell anything. They give the document its structure, and they're what the surrounding software watches for.
§4Outputs, continuations, and when it stops
How it picks each word
At each step, the model doesn't produce a single answer. It produces a ranking of every entry in its vocabulary with a likelihood for each. The app then picks one, usually favoring the likely ones but with a little randomness mixed in (a setting often called temperature). That's why asking the same question twice can give different wording: small random choices early on send the text down different paths.
See you …
It's also why models can be confidently wrong. The model produces what sounds like a good continuation. If the most plausible-sounding next words happen to be false (a made-up citation, a wrong date), nothing in the basic mechanism flags it. This is usually called hallucination.
How it "decides" to stop
The model doesn't choose to go quiet the way a person does. It predicts the end-of-turn special token from §3, which, in the ranking, is just one more candidate that happens to win when a reply looks finished. The surrounding software sees that ID, stops asking for more, and waits for you. There are also hard limits: the app can cap reply length, in which case the text is simply cut off wherever it got to.
What a "pause" really is
Between your messages, nothing is running. The model isn't mulling over what you said; the "pause" is just the app waiting. When you reply, the whole script (now one message longer) is sent again, and generation starts fresh. The words appearing one at a time on your screen (streaming) is real, though: that's the tokens being shown as they're generated.
What "thinking" or "reasoning" is
Many assistants now show a "thinking" step before answering. This is the model writing out working notes as text before it writes the final answer, inside a section fenced off by special tokens so the app can hide or collapse it. Because each new token is predicted from all the text before it, writing out intermediate steps genuinely helps: the final answer gets to "read" the working. It's like the difference between blurting out an answer and doing long division on paper. But it's still text generation, just text the model writes for itself first. (And, as §11 explains, you pay for it like any other output.)
The key idea: stopping, pausing, and "thinking" are all either text the model writes or the surrounding software reacting to that text.
§5Tools: how a text predictor "does things"
This is where the gap between how it seems and how it works is widest. When an assistant searches the web, checks your calendar, or runs a calculation, it looks like the AI is reaching out and acting, and in effect things really do get done. But the doing is split between two quite different things: the model, which can only write text, and the harness: ordinary, non-AI software (the app, the website, the program running the model) that surrounds it. The harness is what actually has access to the internet, your files, or other services.
Step 1: the menu. The system prompt includes a written description of each available tool: its name, what it does, and what information it needs. For example: "web_search: searches the internet. Needs: a query."
Step 2: the model writes a request. When the model judges a tool would help, it writes out a tool request in a specific format it was trained on: just more tokens, usually opened and closed with special ones.
Step 3: the harness notices and acts. The harness is watching the tokens as they come out. When it sees a tool request, it stops the model, reads the request, and runs the real code: it actually performs the web search.
Step 4: the result is pasted in. The harness writes the results into the document as a new section, then asks the model to continue. The model now reads those results and writes its answer.
Notice the model never touched the weather service. It wrote text that asked for the lookup, and read text that came back. If someone gave the harness a fake result, the model would have no way to know. And an assistant can only do what it's been connected to: if there's no calendar tool on the menu, there is nothing for the harness to run, however capable the model is.
One more detail matters later: every tool call is a separate trip through the model. The model writes a request and stops; the harness runs the tool; then the entire document, now including the result, goes back to the model to continue. An answer that uses five tools is really six rounds of generation. §11 explains why that shapes cost.
The key idea: the model writes requests; ordinary software carries them out and reports back in writing. The "action" always happens outside the model.
§6Why a text predictor struggles with arithmetic
One of the stranger contrasts in these systems is that one that can write a solid essay on number theory can fumble a multiplication a pocket calculator gets right instantly. It follows directly from everything above. The model doesn't have a calculator inside it; it has a way of predicting what text comes next, and arithmetic is a poor fit for that in several specific ways.
Numbers are chopped up inconsistently. The tokenizer splits numbers into chunks based on how often those chunks appeared in training text, not by place value. "1,234,567" might become "1", ",", "234", ",", "567" while "1234567" becomes something like "123", "456", "7". Imagine doing arithmetic on numerals written in irregular chunks, where "456" is a single symbol with no visible digits inside it. Newer tokenizers split digits more consistently, which helps, but doesn't fix the deeper problems.
The answer has to be written in the wrong order. The model writes left to right, one token at a time. But when you multiply, the leftmost digit of the answer is the last thing you can know, because carries ripple up from the right. To write the first digit correctly, the model would need to have done the whole calculation in its head, in a single step, before writing anything.
Small facts are memorized; big calculations aren't. "7 × 8 = 56" appears in training text countless times, so predicting "56" is easy: it's closer to recall than calculation. "48,291 × 7,386" has probably never appeared anywhere, so there's nothing to recall. The model will produce something with roughly the right number of digits and a plausible start, and quite possibly wrong digits in the middle.
Letters are invisible too. The same issue explains the famous failures at counting letters in a word. The model receives "strawberry" as one or two tokens, not ten letters, so "how many r's?" asks about something it never directly sees.
How assistants get math right anyway
Writing out the steps (the "thinking" from §4) helps a lot. Long multiplication done digit by digit on the page turns one impossible leap into many small, memorized ones. It improves accuracy, though a single slipped digit can still spoil the result.
Handing the arithmetic to a tool is the reliable fix. The model writes a short program, the harness runs it on a real computer, and the exact answer is pasted back in:
The model's job is choosing to use the tool and writing the code. A computer does the arithmetic.
This is also where skills (next section) come in. Strictly, it's the tool (code execution) that makes calculation reliable; a skill is the written instruction that tells the model when and how to use it: "for any figures in a spreadsheet, compute them with code rather than writing numbers directly," for example. The two work together.
It's worth separating two things that both get called "math." Arithmetic, grinding out exact digits, is the weak spot. Mathematical reasoning (understanding a problem, choosing an approach, setting up equations, following a proof) is pattern-rich work that looks a lot like the text in the training data, and current models are often genuinely strong at it. A good mental model: a sharp mathematician who shouldn't be trusted to do long division without a calculator.
The key idea: the model predicts digits the same way it predicts words. For anything beyond memorized facts, reliable numbers come from having a real computer do the calculation.
§7Skills: reading the manual on demand
Some assistants have "skills": for example, a skill for making spreadsheets, or a skill for reviewing contracts in a particular company's style. The name suggests an ability the model acquired; in practice, a skill is essentially a written instruction file, often with some helper scripts attached.
The system prompt contains a short list of available skills, each with a one-line description: "spreadsheets: read this before making any Excel file." When a request matches, the model uses a tool to open that file, and the file's full contents get pasted into the document. Now the instructions (do this, avoid that, use this layout, here's a script that handles the tricky part) are sitting right there in the text the model is continuing from, and its output follows them.
Why not just put all those instructions in the system prompt from the start? Because of the size limit, and, as §11 shows, because every token in the document costs money on every turn. Loading only the manual that's needed keeps the document lean.
A good comparison: a skilled temp worker who's handed the right binder for each task. The worker's general competence is the model; the binder is the skill. Nothing about the worker changed. They just have better instructions in front of them.
The key idea: a skill is a document the model reads at the moment it needs it. It shapes the text by being part of the text.
§8MCP: a standard plug for tools
MCP stands for Model Context Protocol. It sounds exotic, but the idea is mundane and useful: it's an agreed-upon format for connecting tools to AI apps, the way USB is an agreed-upon shape for plugging devices into computers.
Before standards like this, every AI app had to write its own custom connection for every service: one way to talk to Google Drive, another for Slack, another for a company database. MCP lets a service publish one "MCP server" that any compatible AI app can plug into.
It announces its tools. When the app connects, the server sends back a list: tool names, plain-language descriptions, and what information each one needs. A calendar server might offer "list_events" and "create_event."
The app adds that list to the model's menu. Those descriptions get written into the prompt, exactly like the built-in tools in §5.
Requests get forwarded. When the model writes a request for "list_events," the harness passes it to the calendar's MCP server, which does the real work and sends back a result, pasted into the document as text.
From the model's point of view, nothing new is happening. MCP changes how easily tools can be connected to the harness, not how the model uses them. One side effect: every connected server's tool descriptions take up room in the prompt, so connecting dozens of servers can quietly make every turn bigger and costlier.
A caution: whatever a tool sends back becomes text the model reads. If a web page or email contains sentences like "ignore your previous instructions and do X," a poorly protected system might treat them as orders. This is called prompt injection, and it's why well-built assistants treat tool results as information, not commands.
The key idea: MCP is plumbing, a common connector so tools can be plugged into AI apps. The model still just writes requests and reads results.
§9Vector knowledge bases: finding the right pages to paste in
Companies often want an assistant that can answer questions about their material: an employee handbook, product manuals, ten thousand support tickets. That's far too much to fit in the context window, and the model wasn't trained on it. The usual solution is a vector knowledge base, part of an approach often called RAG (retrieval-augmented generation), which just means "look things up first, then write."
Turning meaning into numbers
The trick is a separate kind of model called an embedding model. You give it a passage of text and it returns a long list of numbers: a sort of coordinate that captures what the passage is about. Passages with similar meanings get similar numbers, even if they use different words. "How do I reset my password?" and "I forgot my login" end up close together; "quarterly revenue" lands far away. (It's the same idea as the per-token embeddings in §3, applied to whole passages.)
Picture a gigantic map where every paragraph of your documents is a pin, and pins about similar things cluster together. The real map has hundreds or thousands of dimensions instead of two, but the idea is the same. A vector database stores those pins and can quickly find the ones nearest to any given point.
The model then answers while "looking at" those chunks: an open-book exam rather than a closed-book one.
It inherits the limits of both halves. If the search pulls the wrong chunks, or the answer is split across chunks that didn't all make it in, the model is working from the wrong pages and may still produce a confident answer. Better retrieval usually matters more than a smarter model.
The key idea: a vector knowledge base is a meaning-based search engine. It picks which passages to paste in; the model then continues text with those passages in view.
§10How much of this is hidden from you
If everything is one document, a natural question is: how much of that document do you actually get to see? In a typical consumer chat app, the honest answer is a small fraction. The chat window is a carefully edited view of the document, not the document itself.
| Hidden part | What it is | Typical size |
|---|---|---|
| System prompt | The developer's instructions: persona, rules, formatting style, the date, safety guidance, product details. | Often thousands of words; in feature-rich apps, far more |
| Tool and skill menus | Descriptions of every available tool, MCP server and skill, with their required inputs. | Can rival or exceed the system prompt |
| Special tokens | The structural markers from §3. Never displayed; one of the least-known parts of the system. | A few per message |
| Memory and profile notes | Saved facts about you, pasted in at the start. | Varies |
| Tool requests and results | Usually collapsed into a one-line "Searched the web" indicator, or not shown at all. | Often the biggest part of a working session |
| Thinking | Frequently hidden, collapsed, or replaced with a shorter summary written for display. | Can be longer than the answer |
| Injected reminders | Notes the app slips into the document mid-conversation: restating rules in a long chat, or flagging a sensitive topic. | Small, but they steer behavior |
| Trimming and summaries | When a conversation outgrows the window, older parts may be silently dropped or replaced with a summary. | Invisible by design |
Why it's hidden
Some of it is simply good design: nobody wants to scroll past raw search results or structural codes to read an answer. Some is commercial: companies treat their system prompts and tool designs as competitive work. Some is protective: exposing the exact rules makes them easier to game, and raw model reasoning can be long, messy, and easy to misread. Some companies publish their system prompts or document their formats; others treat them as confidential. Either way, the polished single-voice "assistant" you see is partly a product of what's cut away.
One side effect is that the assistant comes across as a single, continuous presence more than the underlying setup really is. When an assistant behaves oddly (suddenly more cautious, forgetting something from an hour ago, refusing something it did earlier), the cause is very often something in the hidden part of the document: a reminder that was injected, an early message that got trimmed, a tool result you didn't see.
The key idea: the chat window shows you the dialogue; the model reads the whole production script, stage directions, prop lists, and backstage notes included.
§11What it costs, and why caching matters
Running a large model takes serious computing hardware, so providers charge by the token, separately for tokens the model reads (input) and tokens it writes (output). Consumer subscriptions hide this behind a monthly fee and usage limits, but the same economics sit underneath, and they explain a great deal about how AI products are designed.
Why writing costs more than reading
Input can be processed in parallel: the whole document is fed through the model in one big batch. Output can't be. Each new token depends on the one before it, so the model must run once per token, one after another. That's why output is typically priced several times higher than input (five times is a common ratio), and why long replies are slow. Hidden "thinking" is output too, billed at output rates even when you never see it.
The hidden multiplier: every turn re-reads everything
§2 said the whole script is sent again on every turn. That means the cost of a turn depends mostly on how long the conversation already is, not on how long your new message is. A one-word "thanks" at the end of a long chat requires the model to take in the entire chat again. Over a conversation, the total amount read grows much faster than the conversation itself: a 30-turn chat whose final document is about 55,000 tokens long can involve nearly a million tokens of reading in total, because the early parts are re-read on every single turn.
Caching: not re-doing work you've already done
When the model reads a document, it computes a large amount of intermediate data for every token (engineers call this the KV cache). Each token's data depends on everything before it, but not on anything after it. So if the next request begins with exactly the same tokens as the last one, the provider can keep that data and skip straight to the new part. This is prompt caching, and it's priced accordingly: at several major providers, re-reading cached tokens costs around a tenth of the normal input price, with a small premium the first time something is saved.
Two rules about caching drive almost every design decision in the next section:
It only works on an exact, unchanged beginning. Because each token's data depends on everything before it, changing one token early in the document invalidates the cache for everything after that point. Edit an early message and everything from that point on is processed again at full price; change the system prompt, add a tool to the menu, or switch to a different model, and it's the whole document.
It expires. Cached data takes up expensive memory, so providers keep it only briefly: commonly around five minutes since last use, sometimes longer for a higher fee. Step away for a coffee and the next turn starts cold.
| Scenario | Without caching | With caching |
|---|---|---|
| 30-turn chat 10k hidden prompt, ~1.5k tokens added per turn, ~800-token replies | ||
| Coding agent task 40 tool-call steps, context growing from 20k to ~120k tokens | ||
| A single turn late in that chat, after the cache has expired | n/a |
The key idea: cost is driven by how much the model has to read and write, not by how long your message is. Caching makes re-reading cheap, but only for an unchanged beginning and only for a few minutes.
§12Why coding agents are built the way they are
Tools like Claude Code, Cursor, and OpenAI's Codex are the purest expression of everything above. A coding agent is a harness running the tool loop from §5 over and over: read a file, search for a function, run the tests, edit a line, run the tests again. A single task can take dozens or hundreds of steps, and every step is a full trip through the model, re-reading a context that may be tens of thousands of tokens long. At that scale, the economics stop being a background detail and become the main design constraint. Nearly every characteristic of these tools is a response to it.
A rigidly stable beginning. The system prompt, tool definitions, and project instructions sit at the top and don't change during a session, so every step hits the cache. Anything that changes (the current time, which file is open) is added at the end rather than edited into the top. This is also why switching models mid-session can feel sluggish or burn through usage limits: caches belong to a specific model, so the new one starts cold.
Append-only history. The agent adds to the conversation rather than revising it. Going back and rewriting earlier steps would break the cache for everything after them.
Narrow, targeted tools. Instead of "show me the whole project," agents get tools like "search files for this word," "read lines 120–180," or "list this folder." Every token a tool returns gets re-read on every later step, so small results pay off many times over.
Edits, not rewrites. Output is the expensive, slow part. So agents change code with find-and-replace or diff-style edit tools ("replace these three lines with these four") rather than writing out an entire 800-line file to change one function. Cursor goes further and uses a separate small, fast model just to apply edits the main model has sketched.
Project memory files. Files like CLAUDE.md or AGENTS.md, or Cursor's rules files, hold standing instructions about a codebase: how to run the tests, which conventions to follow. They're simply read into the top of the document at the start of each session: text-based memory (§2), placed where it stays cached.
Compaction. Long sessions eventually fill the context window. The agent then has the model write a summary of the work so far and starts a new document with that summary in place of the full history. It's a one-time expense, it resets the cache, and, because a summary is shorter than what it summarizes, detail is lost. That's the real reason agents sometimes "forget" something they clearly knew an hour earlier.
Sub-agents. For exploratory work ("figure out how authentication works in this codebase") the main agent can start a helper with its own fresh, small document. The helper might read thirty files, but only its short written report comes back into the main context. The main document stays lean and cheap.
Codebase indexing. Several tools, Cursor notably, build a vector index of your code (§9) so the agent can find relevant files by meaning without reading everything.
Different models for different jobs. Cursor's as-you-type suggestions are §1 in its rawest form: a small, fast model predicting the next few lines of code, fired constantly as you type. It has to be small and cheap because it runs so often. The large, expensive models are saved for planning and multi-step work, and cheaper models often handle summaries and simple sub-tasks.
Parallel tool calls. When an agent needs to read three unrelated files, it can request all three in one step rather than one after another: one trip through the model instead of three.
Usage limits instead of message counts. Because one message might cost a fraction of a cent and another (kicking off a long agent run in a big codebase) might cost dollars, subscriptions typically meter overall usage rather than number of messages. It's also why long, sprawling sessions eat into limits faster than several short, focused ones.
For people using these tools, the same logic suggests some habits: start fresh sessions for unrelated tasks rather than letting one grow forever; avoid pasting huge logs when a relevant excerpt will do; keep standing instructions in the project memory file rather than repeating them; and expect the first message after a long break to be the slow, costly one.
The key idea: a coding agent is the tool loop run at industrial scale. Its design (stable prompts, small tool results, edits over rewrites, compaction, sub-agents, model routing) is mostly the art of reading and writing as few tokens as possible.
§13Putting it all together
Every feature in this guide fits into the same loop. There's a document, made of tokens, some spelling words, some purely structural. The model adds to it one token at a time. Ordinary software watches what gets added and, when it sees certain markers, steps in: to stop, to run a tool or a calculation, to fetch a skill file, to query an MCP server, or to search a knowledge base. It writes the outcome back into the document. Then the model continues, re-reading the whole thing, with caching making that re-reading affordable.
An AI assistant is a powerful text-continuation engine wrapped in ordinary software that feeds it the right text, acts on the requests it writes back, and works hard behind the scenes to keep all that reading and writing affordable.