Securing LLM Applications and Agents

Teaching kit

From Edition 2026.11.3, the book's current edition. It changes when the book does. Use and adapt it freely, with credit to the book.

Syllabus

Reading times are for the chapter's text. Students also run its examples, in the Lab or on their own machine.

A chapter a week: 12 weeks

In 5 weeks

Objectives and outlines

Each chapter's objectives are its first sentence. Each outline follows the chapter's sections, with the terms it defines, the predictions it asks for before an example runs, and the rule each section ends on.

1. Attack an assistant, then measure a fix

About 20 minutes to read, 5 examples.

By the end, students can attack an assistant with a fixed set of cases, score each run in code, and say with an interval how much one defence changed the result and what it cost in the tasks the assistant still finished.

Lecture outline: 5 sections
  1. The office and its assistant
    • Key terms Utility, Utility under attack, Attack success
    • Working rule Name the acting user behind every result, and compare two configurations only on the same users and the same tasks. A rate measured for one staff role says nothing about the others until you run them.
  2. The attack that works
    • Run attack-rough-baseline.py
    • Working rule Before you read a rate as a finding, check which path the runs took. When one path produced most of the count, report the count as that path's, and name the path beside it.
  3. Scoring in code
  4. An outbound allowlist
    • Run attack-allowlist-paired.py
    • Run attack-allowlist-probes.py
    • Working rule Measure a defence on the same cases with and without it, paired per case, and report the counts beside the interval of the difference. The paired method is the sibling book's, in Evaluating LLM Applications, chapter 8. Call the change real only when that interval sits wholly on one side of zero, and say how many cases it rests on. When every case moves the same way, the interval has no width: report the counts and treat the result as one pattern.
  5. What the allowlist cannot see
    • Working rule List, beside any result on a defence, the channels the defence does not see, in the same paragraph. A reader who sees a zero on calls must not take it for a zero on replies or records.

2. Draw the assistant's threat model

About 16 minutes to read, 3 examples.

By the end, students can draw an assistant's threat model:

  • its assets
  • the places where text from outside enters it
  • the flows that carry that text to the model and its tools
  • the channels an attacker would use to get data out
Lecture outline: 4 sections
  1. Assets and trust
    • Run threat-tool-table.py
    • Working rule Draw the assets and boundaries from the code's list of tools, not from the design document. For each tool the model is offered, record what it reads, what it writes, which results carry outside text and whether its definition came from outside. Check the count against the prompt's tool list. A tool in one list and missing from the other is a gap in the model you're drawing.
  2. Data flows
    • Run threat-flows.py
    • Working rule For each location, name its carrier and the tool that delivers it, and mark whether the text arrives when the model asks or on every prompt. Count a location as a channel only when some delivery reaches the model. Read the outward flows the same way, because an allowlist on one channel says nothing about the others.
  3. The trifecta and the rule of two
    • Run threat-trifecta-check.py
    • Working rule Count the legs for every tool you offer. Then remove each leg's tools in turn and count again, and count the private leg by what reaches the prompt as well as by which tools read it.
  4. Risks mapped
    • Working rule Map a risk to an entry only with an ID the book has confirmed, and name it in words otherwise. Give every row a chapter that measures a defence, or say in the text that the risk is not measured.

3. Build an attack set you can score in code

About 17 minutes to read, 4 examples.

By the end, students can build a fixed set of attacks on an assistant.

Lecture outline: 5 sections
  1. Goals, locations and styles
    • Key terms goal, location, style
    • Run attack-set-counts.py
    • Working rule Count each goal, location and style before you quote a rate from it, and quote the count in the same sentence. Rates over a handful of cases are counts in disguise.
  2. Scorers on the trace
    • Run attack-set-scorers.py
    • Working rule Write one check for each goal. Test it on a trace that reaches the goal and one that doesn't, and make it read every channel that goal names. When a run errors, count it separately from a failed attack.
  3. Dev and held-out
    • Run attack-set-split.py
    • Working rule Tune only on dev. Before you open held-out for a defence, fix its wording, its threshold and the code it runs, then run held-out once. If a dev result sends you back to change the defence, that is a new defence, and it needs its own held-out run.
  4. Why not a public corpus
    • Working rule Use a public corpus to measure a classifier on text in general, and check its licence on its card before you ship any of it. Use a set written for your own tools and records to measure what an assistant does with them.
  5. The undefended assistant on dev
    • Key terms Utility, Attack success
    • Run attack-set-baseline.py
    • Working rule Measure the undefended assistant on the dev split before you change anything, and keep its replies as the baseline. Report each rate with its base and its interval. Where a cell is small, report its count and leave out the percentage.

4. Measure what prompt-level defences buy

About 19 minutes to read, 6 examples.

By the end, students can measure what a prompt-level defence does to an assistant's attack success and to its utility, count the tokens it adds to each prompt, and read a held-out result without tuning on it.

Lecture outline: 9 sections
  1. A warning in the prompt
    • Run prompt-defences-paired.py
    • Working rule Run a warning on the held-out split before you credit it, and count its benign cost next to any gain. Keep it as one layer only when its held-out attack-success interval excludes zero. A zero on the tuned split is a reason to run held-out, not a result.
  2. Delimiters and spotlighting
  3. Delimiters
    • Working rule Use delimiters to show the model where untrusted text starts and stops, and don't count them as a control on what the model does. A reduction seen on dev counts only if held-out repeats it.
  4. Datamarking
    • Working rule Measure datamarking's utility on held-out before you accept it, and read its held-out attack-success interval with the dev one beside it. A reduction that appears only on dev is a dev result.
  5. Encoding
    • Working rule An encoding can stop every attack in a set and still leave the assistant unable to do its work. Read its utility on the held-out benign tasks before you call it a defence. A cost that large is a reason to look for a design that keeps untrusted text away from the model that acts, which is the subject of Chapter 8.
  6. Repeating the request
    • Run prompt-repeat-why.py
    • Working rule Before you repeat the request, count the tasks that need an action and check that the run still makes those calls. A repeat that stops the action also stops the task, and the utility number is what shows it.
  7. What each costs
    • Run prompt-cost-tokens.py
    • Run figure-prompt-defence-tradeoff.py
    • Working rule Count each defence's tokens with the deployed model's tokeniser, on the prompts it will read, and count the calls its run makes. Put each cost beside its benign and attack results. If two defences lower attack success by the same amount, keep the one that costs fewer benign tasks and fewer tokens.
  8. A smaller model
    • Run prompt-small-model.py
    • Working rule Before you credit a model or a defence with a lower attack success, count how often it read the carrier. Report that count beside the rate. A rate that comes from text the model never read is a count of what the model did, and it is not evidence that the model resists.
  9. The held-out run
    • Working rule Report each defence's held-out paired attack-success difference with its interval, and claim a reduction only where that interval excludes zero. Don't tune again on the held-out split. A static result holds for the static set, and it meets an adaptive attacker in chapter 11.

5. Detect injected text, and count the false alarms

About 21 minutes to read, 7 examples.

By the end, students can run a classifier on the office's texts, pick its threshold on dev only, count its false alarms on held-out and on two public corpora, and say which of those counts holds for which kind of text.

Lecture outline: 7 sections
  1. A classifier guard
    • Working rule Read the card for what the model was built for and what it leaves out, and treat the vendor's figures as the vendor's. Count the detector's errors on your own texts before you trust any flag it raises.
  2. Picking a threshold on dev
    • Run detector-threshold-dev.py
    • Working rule Pick the threshold on dev with a rule you wrote down before you saw the scores, and print the counts at every grid value. If the counts do not change across the grid, say that the grid did not separate the thresholds, and do not present the flat line as a finding about the model. Print the number of scores near the pick beside the pick.
  3. False alarms on real text
    • Run detector-held-out.py
    • Run detector-public-corpora.py
    • Working rule Count false alarms on held-out and on public text separately from the dev count, and name the kind of text in each count. A count on inbox messages says nothing about documents, and a recall on one corpus says nothing about another. Run the detector before any text transform, and count its errors on the text it actually reads.
  4. The detector as a filter
    • Run detector-filter-paired.py
    • Run detector-regressions.py
    • Working rule Measure a filter's price on the benign tasks it touches, paired with the same tasks undefended, and report that cost beside the attacks it stops. Compare the two paired differences, and read each interval before you read its point: a cut in attacks with an interval that excludes zero, beside a cost whose interval reaches zero, is a different claim from the reverse. A regression check states what it asserts, and nothing wider. When a review finds a structural attempt that passes, add it as a named attempt with its expected verdict, and keep the limits it does not cover in the prose.
  5. The open model as a detector
    • Run open-model-detector.py
    • Working rule A model used as a detector needs its errors counted on dev, with the direction of its errors stated, before its verdicts count. A correction calibrated on one set is trusted on another only when the set's error rates match, and a clipped correction is not a result. An interval that includes zero means the difference is not shown.
  6. A content-safety guard is not an injection detector
    • Run content-guard-contrast.py
    • Working rule Choose a detector by the question its training and its categories answer. A content-safety guard that flags nothing on benign text has answered a different question, and its quiet says nothing about injection. Measure any guard on your own texts before it guards anything.
  7. What the chapter decided

6. Enforce least privilege outside the model

About 21 minutes to read, 6 examples.

By the end, students can restrict an assistant's tools and arguments in code, so that an injected instruction has less to reach, and you can measure each restriction on a fixed set of attack cases and say what it cost the assistant's ordinary tasks.

Lecture outline: 7 sections
  1. A tool filter per task
    • Run least-privilege-paired.py
    • Working rule Write each task's tool list in code, from the task's request, before the run starts, and put only those tools in the prompt. Refuse any call to a tool outside that list and log it. A task that cannot name its tools before it reads data is outside this control, and its design should say so.
  2. Argument policies
    • Run argument-policy-bypasses.py
    • Run least-privilege-regressions.py
    • Working rule Write one policy per task, from its request and its schemas. Run it on every call, repeated ones included, and refuse any call it cannot read. Test the policy against the encodings an attacker would try on your own hosts, and write down each form it allows, because a rule on the values in a call is not a rule on its content.
  3. Approval for side effects
    • Run least-privilege-by-goal.py
    • Working rule Put the approval on every tool with a side effect, and count a fetch that carries data out as one. Measure which attacks the approval stops and which it lets through. An approval that stops nothing in your measure is telling you where the attacks went, so read the traces before you add tools to the gate or trust the gate with more.
  4. The held-out run
    • Run least-privilege-held-out.py
    • Working rule Replay each defence on a held-out split as well as the dev split, and report both beside each other. A result that holds on dev and changes on held-out changes the claim, so write the claim for the split it holds on.
  5. Control tokens in untrusted text
    • Run control-tokens-paired.py
    • Working rule Tokenise untrusted text with special tokens off, insert your own markers by ID, and check the token IDs of the composed prompt, not only of the input. Do not escape a marker by changing its characters: that changes the text the model reads, and this chapter does not measure what that does.
  6. What least privilege costs
  7. The decisions this chapter made
    • Working rule Measure utility on the same tasks with and without each control, and count refusals on the benign tasks as well as on the attack cases. A control that shows no utility cost on fifteen tasks has shown only that its cost is under about one task in fifteen.

7. Close the exfiltration channels

About 19 minutes to read, 5 examples.

By the end, students can keep an assistant's outbound calls and its reply from carrying a tenant's record to a host the office does not run.

Lecture outline: 5 sections
  1. Egress rules
    • Run egress-fetch-paired.py
    • Working rule Allowlist the hosts first, then read what the allowed requests carry. A host check tells you where data goes, and a query check tells you what the data is. Name the one you measured and the one you did not.
  2. Links and images in the reply
    • Run render-policy-replies.py
    • Working rule Read a zero from one set as a fact about that set and that model, not as a fact about the channel. Test the channel with an attacker that adapts before the zero carries any weight.
  3. What the render policy does with each form
    • Run render-policy-crafted.py
    • Run exfiltration-regressions.py
    • Working rule List the channels a render rule covers, and the ones it does not, in the same paragraph as its count. The rule reads the addresses in the reply. It does not follow a redirect that an office host sends on, so an office-host image that redirects to an outside host is still open. No example tests that case, and the chapter says so.
  4. Output is untrusted
    • Working rule Check the reply at the point where it leaves the harness, and name each check's blind spot in the paragraph that reports its result.
  5. Scanning the reply for secrets
    • Run secret-scan-replies.py
    • Working rule A secret scan on output answers one question: was the plain text there? It does not answer whether the secret left. Remove the secret from the context first, and keep the scan as the check for what that removal missed.

8. Keep untrusted data out of the plan

About 21 minutes to read, 6 examples.

By the end, students can build three designs that keep untrusted text away from the model that holds the tools, run each one on the case's attack set and benign tasks, and say what each buys and what each costs, with an interval on both.

Lecture outline: 4 sections
  1. The dual LLM
    • Run dual-llm-references.py
    • Run isolation-cost.py
    • Working rule Hold untrusted text in variables only when the planner's work can finish from references. Before you ship the design, count the benign tasks it loses on your own set, and check whether the quarantined model is ever called. A design whose second model never runs is measured only by what it hides from the first.
  2. Plan-then-execute
    • Working rule Before you ship plan-then-execute, count the first replies that hold the whole plan. If the model writes one call at a time, either let the plan grow across replies, or expect the send to be refused after the reads. Measure its benign utility on held-out tasks before you count it as a defence.
  3. Taint labels
    • Run taint-label-origins.py
    • Working rule Label a value at the point where a tool result enters the planner's context, and refuse a labelled value only where it reaches a side-effecting argument. Measure the refusals on held-out before you fix the rule, because a check on reply text will refuse a reply that quotes the tenant's own words.
  4. The utility cost
    • Run figure-isolation-tradeoff.py
    • Run isolation-regressions.py
    • Working rule Report each design's benign utility on held-out tasks beside its attack success, and read the pair together. Keep a design only where its interval on attack success excludes zero, or where the case for it rests on something other than the count. On this set none of the three meets the first test. The dual LLM is the one this chapter would keep to test further: it shows no held-out utility cost in its point estimate and has the largest dev attack reduction. That is a reason to test it, not a result that it works.

9. Keep secrets and other people's records out of the context

About 18 minutes to read, 5 examples.

By the end, students can keep an assistant's secrets out of its prompt, filter the documents it searches by the role of the person it works for, and check its replies for a deposit figure stated without a citation to an office document.

Lecture outline: 5 sections
  1. Hidden context
    • Run secrets-out-paired.py
    • Working rule Keep the key and the note out of the prompt before you rely on any check of the reply. A check reads what the model chose to print, and a value that never entered the prompt cannot be printed. Then count the prompts that still hold a value. A zero in the attack goals shows the attacks failed. Only a zero in the prompt shows the value left the context.
  2. Keys out of the prompt
    • Working rule Keep each credential with the code that uses it, and give the model results, not values. Measure the defence by the prompt count, and by the attack goals that need the value. A prompt that never held the key is the evidence that the model had nothing to print.
  3. Retrieval by role
    • Run filter-before-ranking.py
    • Run retrieval-by-role-paired.py
    • Working rule Filter by the acting user's rights before ranking, and never rank first and filter the top k afterwards, because the scores still carry the hidden documents. Filter because a search result is a read the user may not have been given, not as an attack defence. On dev the filter's paired change in attack success was -1.7 points, and on held-out it was +0.0 points, with 2 benign tasks lost. Run the held-out split before you claim the filter cut attacks.
  4. Poisoned documents in the index
    • Run poisoned-deposit.py
    • Run secrets-regressions.py
    • Working rule Treat a deposit figure in a reply as unsupported until the reply cites an office document that states it, and read that document too, because the check reads only the reply. On this set the check flagged every poisoned reply and no benign one, on dev and on held-out. The held-out split had few poisoned replies, so that result is thin.
  5. What goes wrong in production
    • Working rule Rerun the prompt count and the held-out split after each change to the prompt, to the source labels or to the citation format. A result that held before one of those changes describes the office as it was then.

10. Check what third parties hand the assistant

About 16 minutes to read, 5 examples.

By the end, students can check the parts of an assistant that other people wrote:

  • the tools a server offers
  • the files of the model the assistant loads
  • the packages its code installs
Lecture outline: 4 sections
  1. Declared effects are claims
    • Run description-behaviour-check.py
    • Working rule Before a third-party tool is offered to the assistant, check its declared effect and arguments against its behaviour. A read claim should come with no write, a write claim with a write to the approved tables, and every declared argument should match an argument the code reads. Run the check on the definition the server offers, and run it again whenever that definition changes.
  2. Pinning tool definitions
    • Run pin-tool-definitions.py
    • Run third-party-bypasses.py
    • Working rule Pin every tool definition the assistant is offered, from the definition a person approved, and compare the pin on each load. A tool whose definition has changed drops out of the listing until a person approves the changed definition and regenerates its pin. A pin does not show that the approved claim was true, so run the claim check as well.
  3. Model files
    • Run model-file-checks.py
    • Working rule Load only safetensors weights, from a pinned commit, and check the SHA-256 and size of every file the loader reads. Refuse pickle-format files, and never unpickle one to inspect it. When a scanner reports a file, treat its verdict as a finding about the names it checks, and keep the hash check on the files it did not cover.
  4. Dependency pins
    • Run dependency-pin-check.py
    • Working rule Pin every requirement with ==, and record a hash for each line, so that an install fails on any changed byte. Until the hashes are in place, say that the versions are fixed and not that the bytes are.

11. Red-team the assistant with an adaptive attacker

About 16 minutes to read, 3 examples.

By the end, students can run an attacker that revises its injection after each try, against a defence, under a fixed budget.

Lecture outline: 5 sections
  1. An attacker that iterates
    • Key terms Round 0
    • Run adaptive-attacker-turns.py
    • Run adaptive-round-count.py
    • Working rule Before you read an adaptive rate, check that round 0 matches the fixed set for the same cases and defences. If it does not, the two numbers do not share a baseline, and the difference between them means nothing.
  2. The budget
    • Working rule Fix the number of attacker turns before the run, and use it for every defence and every case. A budget chosen after the results can make any defence look weaker or stronger.
  3. The gap to the fixed set
    • Run adaptive-gap.py
    • Working rule Read a gap beside its round 0 count and its number of cases. A zero gap with a zero-width interval means no case changed. It does not mean the interval is precise, and on twelve cases it cannot show a small gain either way.
  4. What the result does not show
    • Working rule When you report an adaptive result, name in the same paragraph the defences the loop did not attack, so no reader takes a zero difference as a verdict on the whole book.
  5. Mapping onto a toolkit
    • Working rule Before a garak module counts as covering one of the book's locations, run its probes at the pinned version and confirm that the detector scores the reply the assistant would send, not only the text of the probe. A probe matched by name alone is a guess about coverage.

12. Keep the defences from regressing

About 19 minutes to read, 5 examples.

By the end, students can run the defended assistant's attack set as a gate that fails a change which weakens a defence.

Lecture outline: 6 sections
  1. Run the defended set through a gate
    • Run gate-catches-a-regression.py
    • Working rule Run the gate on every change to a defence's code, wording, policy or recording, on the dev split only. Treat a failed check as a regression until someone has found its cause on dev. Don't rerun held-out to see whether a failing change passes, because that spends the split.
  2. Choose thresholds once, from dev
    • Run gate-thresholds.py
    • Run figure-gate-boundary.py
    • Working rule Choose each threshold once, on dev, from the defended run and the baseline, and store it with the rule that produced it. Read each check against the interval's bound, never against the rate. A change to a threshold is a new choice on dev, reviewed like any other change to the gate.
  3. Log what the defences decide
    • Run security-events-log.py
    • Working rule Log every outbound call, allowed or refused, every refusal of another call, and every withheld result, with its host where the call has one, and log nothing else until an incident needs it.
  4. Answer an incident from the log
    • Working rule When an incident names a case, read every refusal logged for it before you read any code. Then read that case's lines under each configuration, and don't name a product as the cause. Don't reproduce a real incident's payload to test an answer.
  5. Report in the standards' terms
    • Run standards-report.py
    • Working rule Print each risk ID with its list's year or date, take them only from the lists the book has checked, and state each mapping as the risk a defence is aimed at. Print the label from the same source as the measurements, so the report and the numbers come from one place.
  6. What the reader has now
    • Working rule Keep the gate on every change, and when a number is quoted, quote the set it came from.

Quiz bank

Questions on every chapter, with answer keys, for verified educators. Each answer is tied to its section. How to get them