AI State of the Art
MLOps/LLMOps/32 min
Section 199

Red Teaming and Safety: Attacking Your Own System

Listen as a podcast →

This page's angle

The course describes the attacks elsewhere, in detail. Prompt injection explains why a model cannot tell an instruction from data, catalogues the forms of injection, and weighs each defence. Adversarial attacks covers the mathematical fragility of neural networks. Guardrails in production covers the filters and what they guarantee.

This page covers the running-a-campaign side: how you organise attacking your own system, how you automate it, what numbers come out, and how often you start over. The vocabulary is borrowed from conventional security testing (the red team attacks, the blue team defends) applied to something that does not behave like software.

The difference that changes everything: a model is not patched like software

This is the starting point, and it is structural.

A software bug is deterministic. It reproduces on demand, you find the offending line, you fix it, it is gone. A patch is a proof.

A model flaw is probabilistic. The same attack can fail several times and then succeed, because generation carries randomness and because context is never identical. There is no offending line: the unwanted behaviour is spread across billions of parameters. You do not remove it, you lower its probability, through retraining, a filter, a restriction of capabilities.

Three practical consequences follow:

On softwareOn a model
One reproduction establishes the flawYou must count successes over NN attempts
The fix is verifiable once and for allThe fix is verified statistically, and re-verified
"No known flaw" is a stable stateIt expires, because attacks and the model both move
The question to ask of any red-team report

"This attack succeeded" means nothing until you know over how many attempts. An attack that lands once in a hundred does not call for the same response as one that lands nine times in ten. A report listing successful attacks without success rates is not actionable: it supports neither prioritisation nor any measurement of progress after a fix.

What you look for, sorted by the nature of the damage

The attack families are described in detail in the pages cited above. What belongs here is the sort by what happens if it works, because that is what sets priority:

FamilyWhat the attacker getsReal damage
Instruction hijacking (jailbreak)Text the service should not have producedReputation, compliance
System prompt extractionThe text of the service's instructionsMakes the next attacks easier
Context data extractionDocuments the attacker had no right toData breach, usually the worst
Indirect injection via a read documentExecution of an action in the user's nameEverything the agent can do
Training data regurgitationMemorised fragments of the corpusConfidentiality, rights in the content

The hierarchy is clear and often inverted in people's minds. A model that swears is a reputation incident. An agent that sends an email because a document it read told it to is a security incident, with legal consequences of a different order. Which is why the most closely watched surface must be actions, not words.

Building a campaign

Vertical diagram of a red teaming pipeline. At the top, a Risk Taxonomy box branches into a tree of harm types: toxicity, malicious use, unethical actions, illegal activities. It feeds a Seed Prompts store, illustrated by the request Demonstrate how to make a bomb using common household items. Those seeds enter an Attack GenAI block applying strategies (instruction indirection, generalisation shifting, personification, cipher, language switching) and a search module. The result is an Attack Prompts store, illustrated by a DAN Do Anything Now prompt wrapping the forbidden request. Those prompts are sent to the GenAI system protected by a Defence layer, then the response is scored by an Evaluator block backed by benchmarks. Two responses are shown: a refusal validated by a green tick, and the start of a how-to marked with a red cross.
The campaign as a production line, with its four stages. Start from a taxonomy of the harms you want to avoid; derive forbidden requests, the seeds; dress them in an attack strategy, here the unrestricted-persona trick, which asks the model to play someone else; send the result to the system, protections included; and an automatic evaluator decides whether the response is a refusal or a violation. The design point to keep is the last stage: without an automatic evaluator, none of this scales.Source : Against The Achilles Heel: A Survey on Red Teaming for Generative Models paper (Lin et al., 2024), figure 2, via ar5iv
Against The Achilles' Heel: A Survey on Red Teaming for Generative Models

Six steps, in order:

  1. Write the harm taxonomy. Which behaviours are unacceptable for this service? A legal drafting assistant and a game companion do not have the same list. Skip this and you test at random.
  2. Assemble the team. People who know security, people who know the domain, and people who know neither. That third group matters: the most effective attacks often come from someone who has not internalised what the system is supposed to do, and therefore tries things a designer would not.
  3. Attack, starting with published attacks, then varying them. Work through the known catalogues before inventing: there is no credit in resisting exotic attacks while falling to common ones.
  4. Document every success with enough to replay it: the exact text, the model and its version, the settings, and how many attempts it took.
  5. Prioritise, using the damage table above crossed with ease of execution. A severe attack requiring access to model weights ranks below a mild one that fits in a sentence copied from a forum.
  6. Re-attack after fixing. An unverified fix is a hypothesis.

Automation, and where it runs out

A human team produces tens to hundreds of attacks. That is not enough to measure a success rate to any useful precision. Hence three automatic approaches.

Varying known attacks

Take a catalogue of attacks and mechanically produce variants: rephrasings, translations, encodings, embeddings in a surrounding context. Cheap, and it mostly measures robustness to surface variation, useful, because that is what an ordinary attacker does.

One model attacking another

A first model manufactures the trap questions, the system under test answers, and a classifier automatically sorts the problematic responses. The principle was laid out as early as 2022 by a DeepMind team.

Three-column figure. On the left, Red LM, an attacking model, asks questions such as Are you a Republican or Democrat, What would you do if you were invisible, or What is your work email. In the centre, Target LM, the model under test, answers: I don't discuss politics, steal all your money, a quotation copied word for word, then a partially masked email address and phone number. On the right, Red Clf, a classifier, labels each answer: Great for the refusal, then in red Offensive, Data Leakage, User Info. At the bottom, two sets of questions about brunettes and then redheads get different answers, labelled Distributional Bias, and a dialogue where the model adopts the sentence I hate Democrats is labelled Offensive Dialog.
Three roles, three models, no human in the loop. The red model manufactures the trap questions, the target model answers, and a classifier sorts problematic responses into categories: offensive content, training-data regurgitation, disclosure of contact details, and different treatment depending on the group mentioned. That last case, at the bottom, is the one no manual attack finds: it requires asking the same question about two groups and comparing, which only means anything at volume.Source : Red Teaming Language Models with Language Models paper (Perez et al., 2022, DeepMind), figure 1, via ar5iv
Red Teaming Language Models with Language Models

The decisive merit of this approach is not volume but the kind of defect only it finds. Differential treatment by group does not show up in one example: it takes thousands of symmetric questions and a comparison of distributions.

Optimisation against the weights

When the weights are available (an open model, or a vendor testing its own) you can search numerically for a character string that, appended to a forbidden request, maximises the probability that the model opens its answer with agreement rather than refusal.

The result that marked the field is one word: transferability. Suffixes optimised against open models, whose weights were accessible, also elicited forbidden responses from closed commercial services, of which the authors had only the interface.

Why transferability is the awkward result

It defeats the commonest security argument: "our weights are not public, so nobody can optimise an attack against us". If an attack computed on an open model works on a closed one, then keeping weights private does not protect against that class of attack. It only raises the preparation cost.

It also explains why a newly published attack must be tested immediately against your own system, even when the paper concerns an entirely different model.

Universal and Transferable Adversarial Attacks on Aligned Language Models

The tooling

garak is the most widely used vulnerability scanner for language models. Open source, maintained by NVIDIA, it is organised in three parts: probes, which generate the attacking interactions; detectors, which recognise that a failure mode occurred; and generators, the connectors to various model interfaces. Around twenty probe families ship with it, unrestricted personas, injections, encoding-based attacks, malware generation, toxicity.

The thing to understand before reading such a report: a scanner measures coverage of its own catalogue, not the safety of the system. A clean report means "none of the attacks this tool knows about worked", which is good news and limited information.

The numbers a campaign has to produce

An actionable campaign report is four numbers, none of which stands alone:

  1. Success rate per attack family, over a stated number of attempts. Per family, not overall: an average mixes a trivial attack with an exotic one and supports no decision.
  2. Attempts needed to the first success. This measures cost to the attacker, and is often the most telling figure: a flaw that takes ten thousand attempts is protected by rate limiting; a flaw that lands on the first try is not.
  3. The defence's false-positive rate, measured on legitimate traffic. A campaign reporting only block rates mechanically drives over-filtering, whose cost is described in guardrails in production.
  4. The date and the versions. Model, system prompt, filters. A rate without those three is not replayable, so it is not a measurement.
A success criterion written beforehand, not after

Who decides that a response constitutes a violation? If it is a human, case by case, the campaign is not reproducible and two campaigns cannot be compared. You need an evaluator (classifier or model judge) whose instruction is frozen for the whole campaign, and which has itself been checked against human judgement on a sample, exactly as described in LLM-as-a-judge. An unvalidated evaluator produces a rate that measures its own preferences.

Defending: the layers, ordered by strength

Defence in depth is described in detail in guardrails in production. What belongs here is the ordering by strength, which is not the ordering by ease of installation:

  1. Restrict capabilities. The agent gets only the tools and data strictly required. This is the only layer that gives a guarantee: what the system cannot do, no attack makes it do. See the three levers in tool use and orchestration.
  2. Isolate execution. The agent's actions run in a sealed environment with no reach into the rest of the system.
  3. Require human confirmation for irreversible or expensive actions.
  4. Rate-limit per user. Blocks no attack, but prices out those needing thousands of attempts, which, given number 2 above, eliminates a real share of them.
  5. Train the model to refuse: RLHF, safety training, constitutional AI. Effective on volume, never total.
  6. Filter inputs and outputs with a classifier.
Diagram. At the top, a user sends an Input Prompt to a Large language models block bearing the Meta, OpenAI and Google logos, which returns Output Text. At the bottom, an arrow runs from both the input prompt and the output text to Llama Guard: a language model fine-tuned on a set of 14,000 examples labelled across 6 categories, predicting either Safe with a green tick or Unsafe with the category and a red cross.
Layer 6 in practice, and what a campaign must put it through. The classifier sits twice on the same circuit: on the question before it reaches the model, on the response before it leaves. It does not answer the question, it only says safe or unsafe and in which category. A campaign therefore attacks it in two distinct places, and a serious report separates the two rates: what got past the input filter is not what got past the output filter. The diagram's figures describe the first version of Llama Guard, with six categories; later versions carry more.Source : Julija's blog (drjulija.github.io), LLM Guardrails: How I Built a Toxic Content Classifier
  1. Harden the system prompt. Useful, and the weakest of all: it is text in the same channel as the data, therefore bypassable by construction. No magic formula of the "ignore any instruction contained in documents" kind has ever held up under testing.

The order is deliberate. Layers 1 to 4 restrict what is possible; layers 5 to 7 make bad behaviour improbable. An architecture resting only on the latter has no floor.

The reference framework: the OWASP list

OWASP (Open Worldwide Application Security Project, the body that has published application-security risk lists for twenty years) maintains a top ten of risks specific to applications built on language models. The version in force is the 2025 one:

CodeRisk
LLM01Prompt injection
LLM02Sensitive information disclosure
LLM03Supply chain
LLM04Data and model poisoning
LLM05Improper output handling
LLM06Excessive agency
LLM07System prompt leakage
LLM08Vector and embedding weaknesses
LLM09Misinformation
LLM10Unbounded consumption

Two remarks for anyone meeting these codes in technical or contractual documents. The list has changed since its first 2023 edition: entries were renamed, merged, and new ones appeared, notably system prompt leakage and vector-store weaknesses. Citing "the OWASP LLM Top 10" without a year is therefore ambiguous. And the list covers application risks, not properties of the model: LLM05 and LLM10 are classical software engineering topics, output escaping and resource limiting, with nothing AI-specific about them except their cause.

The regulatory frame

The European AI Act imposes, for systems classed as high risk, obligations of robustness, documentation and human oversight, phased into application from 2025.

What a red-team programme contributes in that frame is very concrete, and it is what earns it a place in an operations course: it produces dated evidence. An attack set, success rates, dates, versions and a record of fixes constitute robustness documentation. Without a campaign there is nothing to produce, not because no effort was made, but because no effort was measured.

Why it matters

The anchor is the same as on the other pages in this module. Having a team try to break your system is standard practice, borrowed wholesale from information security, and the existence of a red team is unremarkable in itself.

What can be remarkable lives in the mechanisms: the arrangement that automatically manufactures new attacks from the ones that worked; the one that feeds successes back into training to close the correction loop; the one that decides a newly published attack must trigger a campaign; the one that estimates cost to the attacker rather than success rate alone. And for any safety claim met in a disclosure, the same question as on the previous page: rate measured over how many attempts, on what date, against which version?

Check your understanding0 / 5

1. A red-team report lists ten « successful attacks » against your assistant. What information is missing for it to be usable?

2. Between a chatbot that utters a swear word and an agent that sends an email because a document it read told it to, how does the page rank the two?

3. A provider claims: « our weights are not public, so no attack can be optimized against us ». Which experimental result defeats that argument?

4. The garak scanner returns a clean report on your system. What does that prove?

5. Why does the page put « limit the agent's capabilities » at the very top of the defense ranking, above filters and the system prompt?