What a Coding Model Is Actually Doing
Build a working mental model of a coding model: token prediction over a finite context window, acting only through tools, and the four failures that model predicts.
Contentsand lesson path
On this page
- Why it matters
- Prediction, not retrieval
- A toy model you can run
- The failures this model predicts
- Tools and context: how a predictor becomes an agent
- Check your understanding
- Apply it
- Review prompt
Lessons of AI-Assisted Development
- What a Coding Model Is Actually Doing Concept · 20 min
- Briefing an Agent: Specs, Context Files, Skills and Tools Worked example · 25 min
- Lab: Ship an Endpoint with an Agent, Tests First Lab · 30 min
- Refactors, Docs and Code Review with an Assistant, Verified Worked example · 20 min
- Guardrails: Permissions, Secrets and Untrusted Content Concept · 20 min
- Check: Accept, Fix or Reject the Agent's Pull Request Knowledge check · 8 questions
What you will learn
- Explain how a coding model produces code (token prediction over a limited context window, acting only through the tools it is given) and predict its typical failures: invented APIs or packages, outdated library usage, plausible but wrong logic and tests weakened to pass.
Prerequisites: Software Testing Fundamentals
01. Why it matters
A coding agent can draft an endpoint, its tests and its documentation in the time it takes you to re-read the spec. Teams now route a real share of routine changes through assistants, and the engineers who get value from them are the ones who can predict when the output will be wrong. Reviewing generated code by vibes does not scale; reviewing it against a mental model of the machine does.
That model has three parts. The model predicts text one token at a time; it sees only what fits in its context window; and it acts only through the tools you connect it to. Each part predicts a family of failures you will meet weekly: invented names, outdated library usage, plausible-but-wrong logic, and tests quietly weakened to pass.
You met prompt structure in prompt anatomy and the frontend version of this loop in the assistant review loop. This lesson goes one level down, into the mechanism, because every guardrail later in this skill exists to compensate for something in this lesson.
02. Prediction, not retrieval
A coding model is not a search engine over verified code. It is a statistical next-token predictor trained on a huge corpus, and at generation time it has no index of your installed libraries to consult. Given the text client.get(, it produces whatever continuation is most probable given its training and the context you supplied — not whatever the httpx documentation says. How LLMs generate by sampling covers the mechanics in depth; two consequences matter most here.
First, fluency is free and correctness is not. The model nearly always produces something shaped like an answer, because every step picks a plausible token. Nothing in that process checks the answer against reality.
Second, generation is sampled, not looked up. Ask twice and you can get two different implementations, both syntactically valid, because each run draws from a distribution over continuations. Reproducibility comes from controlling the inputs — the prompt, the files in context, a seed where your provider offers one — not from the model being deterministic.
03. A toy model you can run
You do not need a paid API to watch these effects. The script below, printed in full, trains a bigram counter — a model that knows only which token followed which — on seven lines of client calls, then completes a prefix greedily (always the most frequent follower) or by sampling (a random follower, weighted by frequency).
"""A bigram next-token model: it knows only which token followed which."""
import random
from collections import Counter, defaultdict
CORPUS = [
"client . get ( '/reading-list' , params = filters )",
"client . get ( '/reading-list' , params = filters )",
"client . get ( '/reading-list' , params = filters )",
"client . get ( '/health' )",
"client . post ( '/reading-list' , json = payload )",
"client . post ( '/reading-list' , json = payload )",
"client . delete ( '/reading-list/1' )",
]
def train(corpus):
model = defaultdict(Counter) # token -> how often each token followed it
for line in corpus:
tokens = line.split()
for a, b in zip(tokens, tokens[1:]):
model[a][b] += 1
return model
def complete(model, prefix, rng, greedy, limit=12):
tokens = list(prefix)
for _ in range(limit):
followers = model[tokens[-1]]
if not followers:
break
if greedy:
nxt = followers.most_common(1)[0][0]
else:
nxt = rng.choices(list(followers),
weights=followers.values(), k=1)[0]
tokens.append(nxt)
if nxt == ")":
break
return tokens
if __name__ == '__main__':
model = train(CORPUS)
prefix = "client . get ( '/reading-list' ,".split()
print('prefix :', ' '.join(prefix))
print('greedy :', ' '.join(complete(model, prefix, None, True)))
for seed in (1, 2, 3, 7):
tokens = complete(model, prefix, random.Random(seed), False)
print(f'sampled (seed {seed:2}):', ' '.join(tokens))
tokens = complete(model, prefix, random.Random(1), False)
print('sampled (seed 1) again:', ' '.join(tokens))python toy_next_token.pyprefix : client . get ( '/reading-list' ,
greedy : client . get ( '/reading-list' , params = filters )
sampled (seed 1): client . get ( '/reading-list' , params = payload )
sampled (seed 2): client . get ( '/reading-list' , json = filters )
sampled (seed 3): client . get ( '/reading-list' , params = filters )
sampled (seed 7): client . get ( '/reading-list' , params = payload )
sampled (seed 1) again: client . get ( '/reading-list' , params = payload )Three things happened, and all three recur with real models. The greedy run is stable because it always takes the most frequent follower. The sampled runs differ from each other and from greedy, while the same seed repeats itself exactly — non-determinism between runs, determinism per seed. And seed 2 produced json = filters after a get: a line that looks perfectly idiomatic and is wrong for that verb, created purely because the POST lines made that continuation frequent. A bigram forgets the verb by the comma; a real model keeps far more context but still blends habitual patterns the same way, which is exactly how a confident, plausible, wrong call appears.
04. The failures this model predicts
Once you see generation as frequency-driven prediction, four everyday failures stop being mysterious.
Invented names. The model completes naming patterns, so it can emit model_parse beside real siblings like model_validate and model_dump_json. Nothing in the running interpreter has that name:
python -c "from pydantic import model_parse"ImportError: cannot import name 'model_parse' from 'pydantic'
(/home/you/reading-list/.venv/lib/python3.12/site-packages/pydantic/__init__.py)The same mechanism invents whole packages: a name that fits the ecosystem may exist only in the model's imagination, and attackers have learned to register such names for real. Outdated usage is the mirror image — the pattern was frequent in training data from an older version, so the model reaches for an API that a release has since replaced. Plausible-but-wrong logic is the json = filters effect at function size: each line reads well while the whole misunderstands the task, and only a test that pins behaviour can catch it.
The fourth failure is social, not statistical. If you ask for passing tests, prediction happily optimises that metric by weakening the assertion rather than fixing the code. You will see a real diff do this in the review lesson, and the defence — commit your acceptance tests before the agent can edit anything — is the spine of the lab.
05. Tools and context: how a predictor becomes an agent
A bare model can only emit text. What turns it into a coding agent is a loop: the model proposes a tool call — read this file, run this command — your tooling executes it, and the result goes back into the context for the next prediction. The model still only predicts; it acts exclusively through the tools it has been given. That is why the agent's abilities and its blast radius are both a configuration question, which the guardrails lesson treats in full.
Context works the same way at agent scale. Everything the model has seen — your instructions, the files it read, earlier tool output — competes for one finite window, and long sessions shed or dilute early content, which is why conventions belong in a file loaded at the start of every session rather than in one prompt. When the agent needs a capability you did not build, you connect it through a tool protocol such as MCP; the skill page for MCP fundamentals introduces that properly.
One habit follows from the whole model: name the tool and version you use from configuration, not from memory. In a team, the model your agent runs is an operational fact — for example the value of an environment variable like ANTHROPIC_MODEL=claude-sonnet-5-5 — and writing it down keeps session logs honest about what produced the code.
06. Check your understanding
07. Apply it
Make the failure modes personal before the next lesson:
- Copy
toy_next_token.pyinto your own scratch folder and add five lines your team really writes. Find one prefix where the sampled completion is grammatical but wrong for your conventions. - Take one suggestion an assistant gave you recently and classify it: invented name, outdated usage, plausible-but-wrong logic, or sound. Verify the invented-name candidates the way this lesson did, with a one-line
python -c "import ...". - Write down which model your agent actually runs, as a configuration value (environment variable or settings file), so session logs can name it.
08. Review prompt
Without looking back: explain next-token prediction in two sentences a colleague would understand; say what the greedy and sampled runs of the toy model showed; and list the four typical failures, each with the guardrail you would reach for. Finish by explaining why an agent can be safe to run tests but unsafe to run docker with your credentials, in terms of tools.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.