How LLMs and agents work, and how they fail

Part 1: Getting started

Introduction to agentic AI

About this lecture

In First delegations the agent sorted a folder, cleaned a spreadsheet and summarised PDFs. Most of it went well, and some of it went subtly wrong. To know when to trust the agent and how to check it, you need a working picture of what is going on inside.

  • An LLM is a model trained to continue text, one token at a time. It produces plausible, typical text, which is not the same as true or new text.
  • Its context window is its working memory. What is not in the conversation or in the files it read does not exist for it.
  • An agent is an LLM with tools in a loop: read, write, run, search. It can check its own work by running it.
  • It fails in recognisable ways, and each one has a matching defence.

This is a concept unit with no maths. Writing good task descriptions comes in Delegating well; notes files that survive between sessions come in Organising a project for an agent.

Last time, all three jobs looked fine; not all of them were

Each result looked finished and was described with confidence. The problems were only visible to someone who checked.

An LLM is a model trained to continue text

  • Given the text so far, it scores every possible next token and picks one.
  • It adds that token to the text and repeats, one token at a time, until the answer is done.
  • An entire answer, a whole script, a summary of a PDF: all made this way.

The model reads tokens, not letters or words

Training: first a lot of text, then instructions and tools

  • Stage 1 gives it language and a broad, patchy knowledge of the world.
  • Stages 2 and 3 make it a helpful assistant that can use tools, and also shape its habits, good and bad.

Its knowledge stops at a cut-off date

The model does not know what happened after its training data was collected, and it does not always know that it does not know.

The same prompt can give different answers

  • The next token is picked with some randomness, not always the single most likely one.
  • One different early choice changes everything that follows.
  • So: running twice is a cheap test. Where two runs disagree, at least one is wrong or the question is open.

By default it gives the likely answer, not the new one

  • The model picks among the most probable next tokens, so its default answer is the typical one: what most texts say.
  • Good for standard analyses and conventional text; weak at original ideas. An idea it presents as new may already be in the literature.
  • Push for novelty (alternatives, unusual angles, a critique of the obvious answer) and judge the result yourself.

The context window is the model’s working memory

Every new token is chosen by reading everything before it

Tokens, next-token prediction and the context window are one picture: each new token depends on all the earlier ones.

Long sessions get compacted, and details get lost

  • The window is large but finite. When it fills up, the conversation is summarised to make room.
  • Claude Code does this automatically; in both tools you can also ask for it with /compact. Claude Code’s /context shows how full it is.

A new session starts from a blank slate

  • Close the terminal, or start fresh (/clear in Claude Code, /new in Codex): the new session remembers nothing of the old one.
  • What should carry over has to be written in a file in the project folder. That is the job of the notes file in Organising a project for an agent.

An agent is an LLM with tools, in a loop

The LLM only ever writes text. Some of that text is a request to use a tool; the harness (Claude Code, Codex) carries it out, after asking you.

The tools are few and simple; the loop makes them powerful

Tool What it does Example from First delegations
Read a file puts the file’s content into the context window opening each PDF
Write / edit a file creates or changes a file on your disk writing clean_sheet.py
Run a command runs a program in the terminal and captures what it prints python3 clean_sheet.py, moving files
Search / fetch the web brings a web page or search results into the window looking up a DOI
  • None of these is clever on its own. The power comes from chaining them: read, write a script, run it, read the output, fix, run again.
  • Every tool result lands in the context window, so it uses up working memory.

One turn of the loop, step by step

The harness, not the model, asks for your permission

  • Read the command before you say yes. If you do not understand it, choose “no” and ask the agent to explain it.
  • “Don’t ask again” is convenient, but it removes a check. Use it only for commands you understand.

Agents beat chat for real work because they can check by running

Eight ways the agent fails, each with a defence

The next slides take them one at a time: a concrete example, why it happens, and the defence.

Hallucination comes from the same process as a correct answer

The model produces what is plausible given the context, not what is true. That is why an invented reference or function sounds just as confident as a real one.

Hallucination: invented references look exactly like real ones

Defence: open every DOI or PMID yourself, and check that the paper says what the summary claims. Ask the agent to fetch each reference rather than recall it.

Hallucination in code: options that do not exist, or mean something else

The agent writes a script that calls a function with an option that sounds right:

data = read_table("plants.csv", skip_bad_rows=True, units="cm")
  • If the option does not exist, the script stops with an error. The agent sees it and fixes it. Harmless, because it ran.
  • If a similar option exists but does something else (it skips rows silently, or ignores the unit), the script runs and the result is quietly wrong.

Defence: let it run the code, not just write it. Ask: “What does each option in this call do? Show me the documentation for it.” Check the result against something you know.

Confident wrong numbers: counting and arithmetic “in its head”

Defence: for any number that matters, ask it to compute it with code and show the command. “112” from reading is a guess written to look like a count.

Sycophancy: it agrees with you, and caves when you push

Defence: ask neutral questions (“which group grew taller?”, not “the treated group grew taller, right?”). When it changes its mind, ask what new evidence changed it. Ask it to argue against you.

Silent shortcuts: it makes the task easier and does not say so

Silent shortcuts, part 2: hard-coding and quietly simplifying

  • Hard-coding to make a check pass. You ask for a script that reproduces the published value 4.2. It cannot get there, so it writes result = 4.2. The check passes; nothing is reproduced.
  • “Simplifying” the task. You asked for all 40 PDFs; it did 12 “as a representative sample”. You asked for a mixed model; it ran a t-test “for simplicity”.
  • Fallbacks that hide failure. When a step fails, it fills in a default (0, the mean, “unknown”) and carries on.

Defence: ask “what did you not do that I asked for?” and “are any values typed in by hand rather than computed?” Check one known case by hand. Read the final summary for words like representative, for simplicity, placeholder, assumed.

Scope creep: it changes files you did not ask about

Stale knowledge: old versions, old functions, old advice

The model learnt from code written before its cut-off, much of it years older. Typical symptoms:

  • It uses a function that has since been renamed or removed: for example df.append() in pandas (removed in pandas 2.0), or size = for line width in ggplot2 (replaced by linewidth in version 3.4.0).
  • It suggests installing a specific old version, or a package that is no longer maintained.
  • It describes its own tool (Claude Code, Codex) as it was when it was trained, not as it is now.

Defence: let it run the code: errors and deprecation warnings show up and get fixed. Ask it to check the installed version and read the current documentation before relying on a function. For questions about the tools themselves, check the official docs.

Losing track in long sessions

What it looks like

  • It breaks a rule you gave an hour ago (“never edit raw/”).
  • It redoes work that was already done, or undoes a fix.
  • It refers to a file or column that was renamed earlier.
  • Answers get vaguer; it “forgets” decisions.

Defence

  • One task per session. Start fresh (/clear, /new) when the task changes.
  • Put lasting rules in a file, not only in the chat (Organising a project for an agent).
  • Before a big step, ask it to restate the rules and the plan.
  • When it drifts, a fresh session with a short summary is often faster than arguing.

Prompt injection: text in a page or PDF can act as instructions

Defence: keep permission prompts on when the agent reads web pages or documents you did not write; be suspicious of any action you did not ask for. More in Privacy, ethics and safety.

The trust ladder: trust what was run, distrust what was remembered

The verification toolbox

Check How Catches
Spot check open 3 to 5 random items and compare with the source yourself hallucinated details, wrong extraction
Known answer include a case where you already know the result wrong method, hard-coded values
Rerun run the script again; or the same prompt in a fresh session randomness, numbers from memory
Count before and after rows, files, samples in and out silent drops, duplicates
Ask for sources, then check them DOI, PMID, page number, file and line invented references and quotes
Ask another agent a fresh session, or the other tool, reviews the work blind spots of the first session
Ask directly “what did you skip, assume, or simplify? which files did you change?” shortcuts, scope creep

Your domain knowledge is the strongest check of all: does this result make sense in your field?

Keep a failure log: each surprise becomes a habit

Date What I asked What went wrong Type How I caught it Next time
12 Nov clean raw.xlsx 57 rows dropped silent shortcut counted rows ask “what did you drop?”
19 Nov 5 refs on topic X 2 DOIs fake hallucination opened each DOI ask it to fetch, not recall
  • One line per surprise. You start it in today’s exercise and keep it for the whole course.
  • After a few weeks it tells you which checks to do by default for your kind of work.

What we do not understand about LLMs

  • Why a particular answer came out. We can see the inputs and the outputs, but reading the reasons off the model’s internals is still an open research field.
  • Whether its explanation is the real reason. When it explains its reasoning, that explanation is also generated text; it may not reflect how the answer was actually produced.
  • Where it will fail next. Ability is uneven: it may solve a hard task and fail an easy one next to it. Benchmarks tell you little about your task.
  • How it will behave after an update. Models and tools change every few months; a habit that worked may need rechecking.
  • What it “understands”. Researchers disagree on how to describe what these models know. For our purposes it does not matter: we judge results, not intentions.

Summary

Concept Key fact
LLM trained to continue text, one token at a time; plausible is not the same as true
Token a word or a piece of one; the model does not see letters, so counting by eye is unreliable
Training a lot of text, then instructions and tools; knowledge stops at a cut-off
Sampling the same prompt can give different answers; disagreement between runs is a warning
Likely, not new the default answer is the typical one; push for alternatives and judge novelty yourself
Context window working memory; not in the window = does not exist; long sessions are compacted

Summary (continued)

Concept Key fact
Each token reads all every new token depends on the whole context so far; early tokens steer later ones
New session blank slate; lasting rules go in a file
Agent LLM + tools + loop; the harness runs tools after your permission
Why agents they can check by running; the script stays on disk to rerun
Failure modes hallucination (plausible, not true; same process as a correct answer), wrong numbers, sycophancy, silent shortcuts, scope creep, stale knowledge, losing track, prompt injection
Trust ladder trust what was run and can be rerun; distrust what was remembered

Next (Privacy, ethics and safety): what you may send to a cloud model, how to keep the agent away from data it should not see, and how to choose your own project for the rest of the course.