From Neurons
to Agents
How large language models work, and how to put coding agents to work.
Predict the next token. Then run it in a loop.
What happens between pressing Enter and the answer appearing?
tokens generated: 0 · each one is a full pass through the network
How the machine works
Neurons, learning, attention, scale, and the step from assistant to agent.
How to put it to work
Workflow, context, caching, skills, MCP, and keeping it safe.
How we got here
From a model of a single brain cell in 1943 to agents that fix your failing tests.
A neuron is a weighted vote
Multiply each input by its weight, add them up with a bias, and fire if the total clears zero.
output = fire( Σ w·x + b )
Learning means adjusting the weights, based on how past Saturdays turned out.
1943: McCulloch & Pitts show that networks of these units can compute logic.
1958: a machine that learns its own weights
Frank Rosenblatt's Mark I Perceptron was physical hardware: a 20 × 20 grid of photocells as its "retina", with its weights stored in motor-driven dials.
Show it a shape. Right? Do nothing. Wrong? Nudge each weight towards the answer that would have been right. Repeat thousands of times.
Press reports at the time said the US Navy expected the machine to eventually walk, talk, see, write, reproduce itself and be conscious of its own existence.
One layer can only draw one straight line
1969: Minsky & Papert prove a single layer can't learn XOR.
Stacking layers would solve it, but nobody knew how to train the hidden layers.
Result: funding dries up. The first AI winter.
Learning is walking downhill in the fog
Loss
One number for how wrong the model is. The height of the landscape.
Gradient
The slope under your feet: which way is down, for every weight at once.
Learning rate
Your step size. Too big and you overshoot; too small and you're there next year.
Worked example: one weight, three steps
prediction = w × 2 · correct answer = 10 · learning rate = 0.1 · start at w = 3
| Step | w | Prediction | Loss | Gradient | New w |
|---|---|---|---|---|---|
| 1 | 3.00 | 6.00 | 16.00 | −16.00 | 4.60 |
| 2 | 4.60 | 9.20 | 0.64 | −3.20 | 4.92 |
| 3 | 4.92 | 9.84 | 0.026 | −0.64 | 4.984 |
Nobody told the model the answer was 5. It found it by following the slope.
w = 3 → 11 (loss 144) → −13 → … It overshoots further every step and diverges.
Backpropagation: assigning blame, backwards
Run the inputs through every layer and make a prediction.
The chain rule, applied from the end, tells every weight its share of the blame.
Move every weight a little downhill. Then repeat, billions of times.
One backward pass costs about 2× a forward pass, whether there are a thousand weights or a trillion.
1970 Linnainmaa · 1974 Werbos · 1986 Rumelhart, Hinton & Williams
Five lines that built modern AI
for batch in training_data: predictions = model(batch.inputs) # forward pass loss = loss_fn(predictions, batch.targets) # how wrong? loss.backward() # backprop optimizer.step() # nudge downhill optimizer.zero_grad() # go again
step 0 · loss —
Run this loop over trillions of tokens of text, on thousands of GPUs, for months, and you get a large language model.
Nobody writes backprop by hand any more: PyTorch and JAX derive the backward pass automatically. A batch is a random handful of examples, and an epoch is one pass over all the data.
2012: old ideas meet big data and gaming GPUs
ImageNet, 2009
Over 14 million hand-labelled images.
GPUs
Built for video games, perfect for multiply-adds. CUDA (2007) made them programmable.
ReLU, dropout
Plus better initialisation: deeper networks became trainable.
IMAGENET 2012 · TOP-5 ERROR · LOWER IS BETTER
Krizhevsky, Sutskever & Hinton. Trained on two consumer gaming GPUs.
General methods that make use of more computation eventually beat hand-built cleverness. (Rich Sutton, 2019, paraphrased)
Turing Award 2018: Hinton, LeCun, Bengio · Nobel Prize in Physics 2024: Hopfield, Hinton
First, text becomes tokens
≈ ¾ word
per token in English, about 4 characters.
Everything is counted in tokens
Pricing, rate limits, and the size of the context window.
Not all text is equal
Code, numbers and many non-English languages need more tokens per word.
Splits shown are illustrative; every tokenizer differs. Vocabularies hold roughly 100,000–200,000 entries.
Then each token becomes a point in "meaning space"
Each token maps to a list of thousands of numbers: its embedding.
Those numbers are learned by backprop, not designed. Words used in similar ways end up close together.
Directions carry meaning: king − man + woman ≈ queen (word2vec, 2013)
The same idea powers semantic search and RAG: finding text by meaning, not keywords.
A 2-D sketch. Real embeddings have thousands of dimensions, and they rarely map onto tidy human concepts.
The training objective: predict the next token
The model outputs a probability for every token in its vocabulary. One gets picked and appended, and the model runs again.
To predict the next line of a proof, a program or a detective novel ("…and the murderer is"), the model has to pick up a lot about the world.
Temperature controls the picking. Low always takes the top token; higher samples more freely. That's why the same prompt can give different answers.
Before 2017: reading through a keyhole
at a time
HIDDEN STATE: FIXED SIZE
it → which noun? "animal" has nearly faded.
It forgets
Early words fade as the memory is overwritten. LSTMs (1997) added gates: better, but still limited.
It's slow
Word 50 has to wait for word 49, which wastes the GPU's parallelism.
It's a bottleneck
Translation squeezed the whole sentence into one fixed-size vector (seq2seq, 2014).
2014: let the model look back at every word
For each French word it writes, the model decides which English words to look at.
"European Economic Area" becomes "zone économique européenne". The order flips, and so does the attention.
Nobody programmed this alignment. It was learned.
Bahdanau, Cho & Bengio, 2014. Pattern redrawn from the paper; brighter = more attention.
Google · 2017 · eight authors
"Attention Is All
You Need"
No more recurrence
Every token attends to every other token directly, all at once.
Faster and better
Better translations; the big model trained in 3.5 days on 8 GPUs.
The T in GPT
The foundation of essentially every modern LLM.
Self-attention is a fuzzy dictionary lookup
A PYTHON DICT
memory = {"animal": v1, "street": v2, ...}memory["animal"] # → v1# exact match, one value
| Query | "What am I looking for?" |
| Key | "What can I be matched on?" |
| Value | "What I pass along if you pick me" |
ATTENTION, FOR THE TOKEN "IT": COMPARE THE QUERY WITH EVERY KEY
NEW VECTOR FOR "IT" = A BLEND OF ALL THE VALUES
Attention(Q, K, V) = softmax( Q·Kᵀ / √dₖ ) · V
What does "it" refer to? Attention works it out
With tired, most of the weight goes to animal.
Illustrative weights for one attention head. Shown encoder-style, where every word sees the whole sentence; in GPT-style models, which only look backwards, the same link forms once "tired" or "wide" has been read.
Many heads, each looking for something different
Real models run dozens of heads in every layer. Researchers have found heads that track patterns like these; simplified here.
The Transformer block, stacked N times
Attention
Where tokens talk to each other.
Feed-forward
Where each token thinks on its own. Much of the model's knowledge seems to live here.
Residual connections
Each layer adds to its input: a highway for the gradient, so 100+ layers can be trained.
Position
Attention alone ignores order, so position is mixed in (today usually "RoPE").
From text to the next token, again and again
Causal mask: each token sees only the tokens before it. In training, every position is a prediction, all computed in parallel.
Why answers stream in: every new token is another full pass through the network.
The model only ever predicts one token. The loop around it (red) produces the whole answer.
Two facts to remember for Part 2
① Cost grows with length²
② The KV cache
Keys and values for earlier tokens don't change, so they're stored, not recomputed. In Part 2: prompt caching is this idea, across requests.
Then people made it bigger. Much bigger.
PARAMETERS (LOG SCALE)
GPT-3's surprise was in-context learning: show it a few examples in the prompt and it does the task, without retraining.
Scaling laws, 2020
Loss falls predictably with size, data and compute, so you can forecast a model before paying for it.
Chinchilla, 2022
About 20 training tokens per parameter is compute-optimal: a 70B model beat a 280B one.
Feel the scale
Training compute ≈ 6 × parameters × tokens. GPT-3 ≈ 3 × 10²³ operations: about a century for one good gaming GPU.
A pre-trained model isn't an assistant yet
On the internet, questions like that often come in quiz-shaped lists. A base model continues the document; it isn't trying to help you.
From text predictor to reasoning assistant
Read the whole library
Next-token prediction on vast amounts of text and code.
Adds: knowledge, fluency
An apprenticeship
Curated examples of instruction → ideal response.
Adds: format, manners
A coach's feedback
"This answer was better than that one", from people or from AI guided by principles.
Adds: judgement
Exams with an answer key
Maths with known answers, code with tests that pass or fail.
Adds: problem-solving
InstructGPT (2022): people preferred a 1.3B model tuned this way over the 175B GPT-3.
30 November 2022: ChatGPT = a GPT-3.5 model + this recipe + a chat box.
Reasoning models: try, check, backtrack
Trained with reinforcement learning on problems that can be checked automatically (o1 in 2024, DeepSeek-R1 in 2025, now standard).
A new scaling axis, test-time compute: thinking longer gives better answers on hard problems.
Why coding got so good, so fast: code compiles or it doesn't, and the tests pass or they don't.
Hint for Part 2: agents do their best work when they can check their own work.
Tool use: the model asks, the harness acts
Why is the auth test failing?
{ "tool": "run_tests",
"input": {
"path": "tests/auth" } }$ pytest tests/auth
1 failed: test_plus_address
AssertionError: …The email normaliser drops everything after "+". I'll fix…
The model only ever produces text. The program around it, the harness, runs the tool and feeds the result back in as more text.
An agent is a model using tools in a loop
It decides for itself what to do next, until the goal is met.
messages = [system, tools, goal] while True: reply = model(messages) messages.append(reply) if not reply.tool_calls: break # done for call in reply.tool_calls: result = run_tool(call) messages.append(result)
The model is stateless. Every lap sends the whole context again.
CONTEXT, RESENT EVERY LAP
0 tokens
How fast this moved
2% → ~80%
SWE-bench: real GitHub issues resolved by the best system, 2023 → late 2025.
2023 figure on the full set; 2025 on the human-validated "Verified" subset.
~7 months
Doubling time of the length of tasks AI agents can complete on their own.
METR, 2025.
Five ideas to carry into Part 2
- Neurons are weighted votes. Stacked in layers, they can represent almost anything.
- Learning is gradient descent: measure the error, and backprop nudges every weight downhill.
- Attention lets every token look at every other. The Transformer is built from it, and it scales.
- Scale + post-training turn a next-token predictor into a reasoning assistant.
- Agent = model + tools + loop. The context, resent every lap, is everything it knows.
Break
10 minutes
Back with Part 2: agents at work.
Agents at work
An agent is a model using tools in a loop, and its context is everything it knows. Most of the skill lies in what you put into that context, and how the agent checks its own work.
What's inside a coding agent
Goals, judgement, review. Accountable for the result.
The loop · system prompt · context management · permissions · UI
Read, edit, search files · run shell commands · fetch the web · start sub-agents
Your repo, terminal, git, test suite, dev server
Permission prompts · allow / deny lists · sandbox · hooks
Same model, different harness: very different results. The harness decides what the model sees and can do.
What a task actually looks like
Reads before it writes
Finds the test, the function and the source first.
Runs the tests itself
No copy-paste between chat and terminal.
Sees the failure, corrects itself
Only possible because it could verify.
Checks the whole suite
Then summarises what changed and why.
A spectrum of autonomy
Most teams use several points on this line, depending on the task.
Treat the agent like a fast, well-read new team member with zero context about your project, no memory between sessions, who will confidently do exactly what you asked, including the wrong thing.
Everything that follows comes from taking that seriously.
Explore → Plan → Implement → Verify → Review
Read the code and explain it. No changes yet.
Plan mode. The cheapest place to catch a mistake.
Small steps you can review.
Tests, types, lint, build, run it. The #1 lever.
You own every line. Fresh eyes review.
An agent that can run the tests can find and fix its own mistakes before you ever see them.
Prompting: say what "done" looks like
WEAK
Fix the login bug.
STRONG
jo+test@example.com) get "invalid credentials" at login.
The failing test is tests/auth/test_login.py::test_plus_address.
Email normalisation is probably in src/auth/normalize.py.
Fix the root cause rather than special-casing "+".
Add a regression test, and run the full auth test suite before you finish.
Don't modify existing tests.
Thirty extra seconds of typing saves many wasted turns, and many wasted tokens.
Habits that pay off
Failing tests, then code
Write (or review) tests that describe the behaviour, then let it implement until green. Say: "don't modify the tests."
Interrupt and rewind
Esc stops it the moment it heads the wrong way. /rewind (or Esc Esc) rolls back code and conversation.
Then start over
Corrected it twice on the same issue? /clear and a better prompt beats a context full of failed attempts.
Ask it to interview you
"Ask me questions until you understand what I want, then write a spec."
Where agents shine, and where they struggle
- Exploring and explaining an unfamiliar codebase
- Writing tests, especially for existing code
- Mechanical changes: migrations, renames, upgrades
- Bug fixing when there's a reproducible failure
- Boilerplate, scripts, internal tools, docs
- First drafts of almost anything
- Vague or contradictory requirements
- Novel architecture and matters of taste
- Big cross-cutting changes in code with no tests
- Subtle concurrency, performance and security issues
- Your unwritten business rules
- Knowing it's wrong without a way to check
What fills the context window
Context is a budget,
not a bucket.
Cost
The whole context is resent on every turn.
Speed
More context, slower answers. Remember n².
Quality
"Lost in the middle" (2023), "context rot" (2025): long inputs are used less reliably.
With million-token windows you rarely run out. Manage context for focus, quality and cost, not space.
Eight habits that keep an agent sharp
/clearOne task per sessionOld context distracts, and costs on every turn./contextLook before you guessSee what's actually using the budget./compact focus on…Compact at natural breaksA lossy summary, so steer what it keeps.sub-agentsDelegate explorationIt reads 50 files; you get one page back.PLAN.md · git commitWrite things downFresh sessions reload only what matters.tail · grepDon't flood itA 5,000-line log crowds out the signal.@src/auth/session.tsPoint preciselyFewer exploratory reads.CLAUDE.md · MCPKeep always-on parts leanThey cost tokens every turn of every session.Sub-agents: the reading happens somewhere else
MAIN SESSION
"Find every place we parse dates, and summarise the patterns."
12.4k tokens
SUB-AGENT · EXPLORE · OWN CONTEXT
0 tokens
Sub-agents aren't smarter: their value is a clean context and parallelism. They do cost tokens of their own.
Memory files: how the agent "remembers"
# Orders service ## Commands - Install: `pnpm install` (not npm) - Test: `pnpm test`; one file: `pnpm test path/to/file` - Lint + types: `pnpm check`. Run before saying you're done. ## Architecture - src/routes → src/services → src/db (Drizzle) - Route handlers never call the DB directly. ## Gotchas - src/generated/ comes from `pnpm codegen`. Never edit. - Money is integer cents. Never floats. - Integration tests need: `docker compose up -d db`
CLAUDE.md (Claude Code) or AGENTS.md (many other agents) is loaded at the start of every session.
Put in
- Build, test, lint commands
- A few lines of architecture
- Conventions you can't infer
- Gotchas
Leave out
- What the code already says
- Style guides (use a linter)
- Anything stale
Keep it short (docs suggest under ~200 lines). If a line wouldn't change behaviour, delete it. Same mistake twice? Add a line.
Start with /init, then edit it down. Mixed-tool team? Keep AGENTS.md and have CLAUDE.md import it with @AGENTS.md.
How you pay: by the token, every turn
| Model | Input | Output | Cache read |
|---|---|---|---|
| Claude Haiku 5.5* | $0.10 | $0.50 | ≈ $0.01 |
| Claude Sonnet 5.5 | $2.00 | $10.00 | $0.10 |
| Claude Opus 5.5 | $4.00 | $20.00 | $0.20 |
Per million tokens, Anthropic API, November 2026. *Up to 100K-token prompts. Check current prices before presenting.
5×
Output costs about five times input, per token…
…but in an agent session input dominates by volume, because the whole context is resent on every turn.
~$13
per developer per active day, enterprise average (Claude Code docs)
Prompt caching: the KV cache, across requests
A 60-turn session on Sonnet 5.5
−85%
Caching is what makes agents affordable. Without it, every turn re-buys the whole context at full price.
| Input processed | 4.2M tokens |
| Without caching | ≈ $9.00 |
| With caching | ≈ $1.31 |
Assumes context grows from 20k to 120k tokens and ~1k output tokens per turn. Hover the chart for per-turn totals.
Caching is a prefix match. Don't fight it.
Breaks the cache
- Switching model mid-session (caches are per model)
- Changing effort level, or toggling fast mode
- Adding or removing MCP servers or plugins (when tools load upfront)
- Compaction (a deliberate rebuild)
- Idling past the cache lifetime: your coffee break
Keeps it
- Editing your code files
- Invoking skills, spawning sub-agents
/rewind, changing permission mode- Editing CLAUDE.md mid-session (it reloads on /clear, /compact or restart)
Practical rule: choose your model, effort level and MCP servers at the start of a task, and change them at task boundaries, right after /clear.
Token-efficiency checklist
- Right model for the job. Big for planning and hard debugging; smaller and faster for mechanical work. Switch at task boundaries.
- Right effort level. More effort = more thinking tokens. High for hard problems, lower for routine (
/effort). /clearbetween tasks, and compact at natural breaks.- Sub-agents for noisy work, but they aren't free: many agents in parallel can multiply token use.
- Precise prompts. Fewer wasted turns is the biggest saving. Measure cost per completed task, not per request.
- Trim always-on context. Disable unused MCP servers; tool search loads tool names first, full definitions on demand.
- Keep junk out: lockfiles, minified bundles, giant logs, generated code.
Six ways to extend an agent
| Mechanism | Gives the agent | Loaded | Context cost | Like |
|---|---|---|---|---|
| Memory files | Always-on project knowledge | Every session start | Full text, every turn | Onboarding notes on the desk |
| Skills | Know-how: procedures, scripts, templates | Name + description at start; body when relevant | Tiny until used | Runbooks on the shelf |
| MCP servers | Access to external systems and data | Tool names at start; definitions on demand | Small to large | An access badge |
| Hooks | Guaranteed automation at lifecycle events | Run by the harness, not the model | None, unless they print | CI checks, git hooks |
| Sub-agents | Delegated work in an isolated context | On demand | Only the summary | A colleague who reports back |
| Plugins | A shareable bundle of all of the above | When installed | Depends on contents | An app-store package |
Memory is what it always knows. Skills are what it knows how to do. MCP is what it can reach. Hooks are what always happens.
Skills: loaded only when they're needed
At startup: 6 skills × ~40 tokens ≈ 240 tokens
--- name: add-api-endpoint description: Use when adding a new REST endpoint to the orders service. Covers routing, validation, OpenAPI, tests. --- 1. Add the route in src/routes/<resource>.ts 2. Validate input with a Zod schema in src/schemas/ 3. Update openapi.yaml, then run `pnpm spec:check` 4. Add an integration test using the testServer fixture 5. Run scripts/check-endpoint.sh and fix what it reports
.claude/skills/add-api-endpoint/
├── SKILL.md loaded now
├── reference/error-codes.md read only if needed
└── scripts/check-endpoint.sh run, never read into context
MCP: one protocol instead of a tangle
Introduced by Anthropic (Nov 2024), adopted across the industry in 2025, now hosted by the Linux Foundation's Agentic AI Foundation.
Using MCP well
# Local server (stdio): a browser the agent can drive claude mcp add playwright -- npx @playwright/mcp@latest # Remote server (HTTP), shared with the team via .mcp.json claude mcp add --transport http --scope project \ tracker https://mcp.example.com/mcp # Inside a session: status and sign-in /mcp
Scopes
local: just you, this project · project: .mcp.json, committed · user: all your projects
Typical servers
GitHub, Jira/Linear, Sentry, databases (read-only!), Playwright, Figma, docs
Mind the cost
Tool definitions take up context. Tool search loads names first and definitions on demand. Enable only what a project needs.
CLI or MCP?
If a good CLI exists (gh, aws, kubectl), the agent can just use it. Use MCP when there's no CLI, you need OAuth, or you want a curated set of actions.
MCP + skills
MCP is can access; skills are knows how. A "triage-bug" skill can say how to use Sentry and GitHub your team's way.
Hooks: things that always happen
{ "hooks": { "PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{ "type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" }]
}]}}
.claude/settings.json: format every file the agent edits
Instructions in CLAUDE.md are requests. Hooks are guarantees.
Your own sub-agents, shared as a plugin
--- name: code-reviewer description: Reviews the current git diff for bugs, missing tests and security issues. Use after a change. tools: Read, Grep, Glob, Bash model: sonnet --- You are a meticulous senior reviewer. Review only the current git diff. Report concrete problems with file:line references. Do not edit files.
.claude/agents/code-reviewer.md · built-in examples: Explore, Plan, general-purpose
PLUGIN · OUR-TEAM-TOOLKIT
A plugin bundles skills, sub-agents, hooks and MCP servers into one installable package, shared through a marketplace (often just a git repo). /plugin browses and installs.
This is how a team standardises.
It runs real commands, with your credentials
planRead-only exploration and planningdefaultAsks before actingacceptEditsEdits files freely, asks for commandsautoA classifier reviews each action. Fewer prompts; not a safety guaranteebypassPermissionsOnly inside a disposable container or VMCLAUDE CODE PERMISSION MODES · LESS → MORE AUTONOMY
- Allow-list the safe, repetitive commands (tests, lint, build); deny the dangerous ones.
- Sandbox file writes and network access (
/sandbox; on Windows, use WSL2).
- Never give an agent production credentials or write access to production data.
- Use read-only database users for MCP servers.
Prompt injection and the "lethal trifecta"
Anything the agent reads can contain instructions: web pages, issues, PR comments, a dependency's README, MCP tool output.
With all three at once, data can be stolen. Remove at least one leg. (Simon Willison, 2025)
- No network access while working with secrets
- No secrets when browsing untrusted content
- Install MCP servers and plugins only from sources you trust
- Verify new dependencies: attackers register package names LLMs invent ("slopsquatting")
You still own every line you merge
Quality and accountability
- Git is your safety net: branches, frequent commits, CI that must pass. One worktree per parallel agent.
- Review standards don't drop because an AI wrote it. Watch for plausible-but-wrong code, invented APIs, weakened tests, quiet scope creep.
- Don't merge code you don't understand. Ask the agent to explain it: cheap learning, and it keeps your own skills sharp.
Team adoption
- Commit the shared setup: CLAUDE.md / AGENTS.md, skills, agents,
.mcp.json, hook and permission settings. - Start where risk is low and value is high: tests, docs, migrations, internal tools.
- Share what works. Measure outcomes (cycle time, escaped defects), not lines generated.
- Check your AI and data policies: which code may go to which provider, on which terms.
Let's watch it work
- StartOpen the repo, show CLAUDE.md0:30
- Explore"Explain the structure and how tests run. Don't change anything."1:30
- PlanPlan mode: "Add an optional due date to tasks; reject past dates; include tests."2:00
- Implement + verifyLet it run. Watch it test, fail, fix.3:00
- Context
/context: where the budget went1:00 - ExtendA skill ("write the PR description") or an MCP server1:30
- Reset
/clear: new task, new context0:30
If it goes wrong
Say so, and narrate it: "this is where I'd interrupt." Esc to stop, /rewind to roll back, or switch to the recording.
Audiences learn as much from a recovered failure as from a clean run.
What to try on Monday
- Set up one repo. Run
/init, then cut the memory file down to what really matters. - Pick one well-tested, low-risk task and work through Explore → Plan → Implement → Verify → Review.
- Glance at
/contextonce a day for a week, to build intuition for what fills it. - Write one skill for something you've explained to the agent more than twice.
- Add one MCP server or CLI that removes a copy-paste step from your day.
Given tools, a loop and the right context, they become real engineering collaborators.
They don't replace the engineering. They make it faster, for those who learn to steer them.
Questions?
Thank you.