The Filter AI / Build

How these systems are built.

How a model is trained, how an application is assembled around it, and what the ecosystem is made of — written for the person who has to defend the result. Not a tutorial for shipping one. A machine you cannot name the parts of is a machine you cannot secure.

9 sections 6 training stages 6 primitives 4 reference architectures Links checked 31 Aug 2026
01

Why a defender reads this.

Most security material about AI starts at the chat box. That is roughly like learning web security by studying the login form: you will recognise the obvious problems and miss every structural one.

Three things change once you know how the machine is put together.

  • You stop asking the wrong question. "Can the model be tricked" has a known answer — yes, given enough attempts. "What does a successful trick actually reach" is answerable, and the answer is architecture.
  • You can locate a control. Every defence in the pattern library lives at a specific component. If you cannot point at the component, you cannot review whether the control is there.
  • You can read a design document. The engineers building this will describe their system in the vocabulary below. Speaking it is the difference between being consulted and being informed afterwards.

The one thing to carry through the whole page

Nothing in the training pipeline creates a channel that separates instructions from data, and nothing in the application stack adds one either. Every layer below is built on a component that cannot tell your rules apart from the document it was handed. The rest is engineering around that fact.

02

How a model is made.

Six stages, in order. The security-relevant point is which stage produces which behaviour, and who controls it — because you inherit the first five and only really operate the sixth.

00

Corpus collection and curation

Assembling the training data: crawled web text, books, code, licensed sets, filtered and deduplicated. The largest and least visible stage.

web crawlcode reposlicensed datafilteringdedup

You inherit: whatever was in there. Memorised secrets, licence problems, and the raw material for data poisoning. Maps to: LLM05, LLM04.

01

Pretraining

Next-token prediction across the corpus, at enormous scale. The result is a base model: a system that continues text plausibly and has no concept of a request, a rule, or a user.

next-token objectivetransformerweeks of computebase model

Where the defect is born. A base model has exactly one input: a sequence. Not a privileged sequence and a subordinate one. One. Everything downstream is an attempt to impose a hierarchy on a component that has no notion of one.

02

Supervised fine-tuning

Training on demonstrations of instruction-following — prompt and ideal response pairs — so the base model behaves like an assistant rather than an autocomplete.

instruction datademonstrationschat templaterole tokens

You inherit: the appearance of an instruction channel. Role markers like system and user are learned conventions in the token stream, not enforced boundaries — which is precisely why forging them works. Maps to: LLM01.

03

Preference tuning

Optimising against human or model judgements of which response is better — reward modelling with reinforcement learning (InstructGPT), direct methods such as DPO, or AI feedback against a written policy (Constitutional AI).

reward modelRLHF / DPOrefusal behaviourhelpfulness

You inherit: the refusal behaviour, and the tension inside it. This stage is trained to be both helpful and harmless, and a jailbreak is an argument that the helpful reading should win. Maps to: the whole jailbreak literature.

04

Instruction hierarchy and safety training

Explicitly training the model to rank sources of instruction: platform above developer, developer above user, user above tool output. OpenAI's instruction hierarchy paper is the clearest public statement of the approach.

privilege rankingadversarial trainingred team datarefusal tuning

You inherit: a real, measurable improvement and not a guarantee. It is a learned preference, so it holds probabilistically. Treat it as defence in depth, never as an authorisation boundary.

05

Adaptation and packaging

What happens after the lab ships it: fine-tunes, LoRA adapters, distillation, quantisation, serialisation into a file, publication to a hub, and versioning behind an API.

fine-tuneLoRAquantisationsafetensorsmodel version

Your first real decision point. A community adapter is executable dependency. Prefer safetensors over pickle formats, pin versions, and review provenance. Maps to: LLM04.

06

Inference-time configuration

The system prompt, tool schemas, sampling settings, context window, and any structured-output constraints. Applied per request, at run time.

system prompttool schemastemperaturecontext window

The only stage you fully control — and the weakest one, because everything here is text or configuration handed to a component that treats text as text. It is where most teams put their security policy, and it is the wrong place for it.

The consequence people skip

Stages 02 to 04 all teach the model to prefer some instructions over others. None of them build a mechanism that enforces it. A preference expressed by a probability distribution can be argued with, and an attacker gets unlimited attempts while you get one deployment. That is the entire reason the pattern library builds isolation before detection.

03

The six primitives of an AI application.

Whatever framework a team has chosen, and whatever they call it, every LLM application is assembled from the same six parts. Learn these and you can read any architecture diagram in this field, including one drawn by someone using entirely different words.

PrimitiveWhat it isThe question to askLayer
01
Model
The component that predicts. A hosted endpoint or weights you run yourself. Which version, pinned how, and what did stage 05 do to it? 01
02
Context
Everything assembled into the prompt for this one turn. System text, user text, retrieved documents, tool results. Which bytes in here did we author, and which arrived from outside? 02 · 03
03
Memory
What survives between turns and between sessions. History, summaries, saved profiles, vector stores. Who can write into it, and does an injection written today fire next week? 03
04
Tools
The functions the model can invoke. Search, database reads, email, shell, another agent, an MCP server. Whose credentials, what scope, and which of these cannot be undone? 04 · 06
05
Loop
The controller that decides whether to call the model again. Turns a single completion into an agent. What stops it, who pays for it, and can retrieved content extend it? 04
06
Deploy
Where it runs and what it is attached to. Identity, network egress, logging, the surface a user sees. What can this process reach on the network, and what did we record about the decision? 05 · 06 · 07

A useful review habit: for any system someone shows you, name all six out loud before asking a single security question. Two thirds of the findings fall out of the naming exercise, because the parts nobody can describe are the parts nobody owns.

04

One request, end to end.

Here is what actually happens when someone types a sentence into an agentic assistant. Colour marks provenance: green is content you authored, red is content from outside, amber is mixed and needs a decision.

You authored itIt came from outsideMixed
1person“summarise the tickets assigned to me”2appassembles the contextsystem promptTRUSTEDuser messageSEMIretrieved docsUNTRUSTEDhistoryMIXED3ONE FLAT TOKEN STREAMprovenance no longer existsmodel4send_email(to, body)authority is spent here5tool resultUNTRUSTEDre-entersstep 36browser · renderera stranger’s string
Step 4 is the only irreversible moment, and step 5 re-opens the door on every pass — tool output returns to the context as fresh untrusted content. An agent is not one request with a filter on the front; it is a cycle.

Five things worth noticing in that trace, all of which are invisible in a product demo.

  • Step 2 is where trust is decided, and it is code you wrote. Nobody else can label provenance for you, and nothing downstream can recover a label you did not attach.
  • Step 3 flattens everything. Four sources with four different trust levels arrive as one sequence. The colour coding above exists in your application, not in the model.
  • Step 4 is the only irreversible moment. Everything before it is an opinion. This is the step worth a confirmation dialog (DP-07) and a scoped credential (DP-01).
  • Step 5 loops back. Tool output re-enters the context as new untrusted content, which is why an agent is not one request with a filter on the front but a cycle that re-opens the door on every pass.
  • Step 6 is ordinary appsec. And it is where a successful injection turns into an actual data loss (DP-02, DP-04).
05

Four reference architectures.

Almost every product in this space is one of these four, or a composition of them. Each entry gives the shape, where untrusted content enters, how far a successful injection reaches, and the minimum set of patterns worth arguing for before it ships.

A1

Plain assistant

Simplest Model + context

A system prompt, the user's message, and a response. No retrieval, no tools, no memory beyond the conversation. Support chat widgets and writing helpers usually start here.

You authored itIt came from outsideMixed
system promptTRUSTEDuser messageSEMI-TRUSTEDmodelrenderOUTPUT HANDLINGthe control that matters here
The only architecture where the user's own message is the whole untrusted surface. A successful injection makes the model say something. That is reputational, rarely a data loss — unless the prompt held a secret.
Untrusted enters at

The user's own message, and nowhere else. This is the only architecture where that statement is true.

Blast radius

Small. A successful injection gets the model to say something. Reputational and policy risk, rarely data loss — unless the system prompt held a secret.

Minimum patterns

DP-02 on the render surface, and nothing confidential in the prompt. That is genuinely most of it.

A2

Retrieval-augmented application

Most common + memory

The user's question is embedded, similar chunks are fetched from a vector store, and those chunks are pasted into the context. The original RAG paper is from 2020; the pattern is now the default shape of an enterprise AI product.

You authored itIt came from outsideMixed
ingestWHO CAN WRITE HERE?docs · wiki · uploads · ticketssupport mail · crawled webvector storechunks · still untrustedquestionsystem promptmodelanswerauthorise at retrieval, not in the promptpre-filter by identity · re-check ownership afterone poisoned chunk reaches everyone who asks
The ingest path is an input to your prompt, and it is usually the widest door in the building. Anywhere a customer, partner or crawler can write, they are writing into the model's context — persistently, until someone cleans the index.
Untrusted enters at

The ingest path, which is usually wide open — anywhere a customer, partner or crawler can write is an input to your prompt. Also the retrieval path, if tenancy filtering is done in the prompt rather than in the query.

Blast radius

Everyone who asks a question that retrieves the poisoned chunk. One insertion, persistent, and it survives until someone cleans the index.

Minimum patterns

DP-03 authorise at retrieval, DP-05 fence the chunks, DP-02 on output. Watch per-chunk retrieval frequency.

A3

Single agent with tools

Where it gets serious + tools + loop

The model is offered a set of functions and a loop runs it repeatedly: think, call a tool, read the result, decide again. ReAct is the canonical description of the pattern.

You authored itIt came from outsideMixed
requestmodeltool calltoolRUNS AS WHOM?result · untrustedevery pass re-opens the doorfinal answerTHE LOOP · needs a ceiling you enforce, not one you ask for
This is where injection stops being a content problem and becomes remote control. The blast radius is everything the agent's credentials reach, and a search tool means the open web is an input on every pass.
Untrusted enters at

Every tool result, on every pass of the loop. A search tool means the open web is an input. The door does not close after the first turn.

Blast radius

Everything the agent's credentials can reach. This is the architecture where injection stops being a content problem and becomes remote control of a process holding your tokens.

Minimum patterns

DP-01 scoped tools, DP-04 egress control, DP-08 loop ceilings, DP-07 on anything irreversible. All four, not a subset.

A4

Multi-agent and connected systems

Largest surface + delegation + protocol

Several agents delegating to each other, and tools supplied by third parties over a protocol such as MCP. The tool catalogue becomes a dependency graph you did not write.

You authored itFrom outsideThird-party surface
orchestratorHOLDS THE TOOLSdelegatessub-agentREADS THE WEBsummary returns with no provenance labeland is read as internal outputMCP serversTHIRD PARTYtool descriptions are text in your prompt,written by someone else, changeable after reviewreview a manifest like a dependency with commit access
The blast radius is the union of every agent's permissions, and nobody has written that number down. Provenance is lost at the delegation hop, and the tool catalogue is a dependency graph you did not author.
Untrusted enters at

Tool results, tool descriptions from third-party servers, and every sub-agent summary — which arrives looking like internal output because the provenance label was dropped at the hop.

Blast radius

The union of every agent's permissions, which nobody has written down. Compromise one hop and you inherit the authority of whatever trusts its output.

Minimum patterns

Everything from A3, plus DP-06 so provenance survives a hop, and seriously consider DP-11 — separating the component that reads from the component that acts.

How products actually move

Almost nobody designs A4. They ship A1, add retrieval because answers were thin, add a tool because users asked, then connect a second agent because one was slow. The architecture changes category without anyone declaring a new design. The useful review question is not "what is this" but "which of the four was it last quarter", because the controls were sized for that one.

06

The ecosystem map.

The layers a team assembles, what each one is for, and — the column that matters here — what adding it does to your attack surface. Names are representative examples, not recommendations, and this part of the market changes faster than any other section on this site.

LayerWhat it doesRepresentative namesWhat it adds to your surface
Model providers Train and serve frontier models behind an API. Anthropic, OpenAI, Google, Meta, Mistral A dependency whose behaviour changes on their schedule. Pin versions and read the deprecation notes.
Self-hosted serving Run open weights on your own hardware. vLLM, Ollama, TGI, llama.cpp You now own the supply chain: weight provenance, serialisation format, and the inference server's own CVEs.
Orchestration Frameworks that assemble context, run the loop and call tools. LangChain, LlamaIndex, agent SDKs The prompt-assembly layer becomes someone else's code. Know where it interpolates untrusted text, because it will not tell you.
Protocols Standard interfaces between models and external tools. MCP, function calling schemas Tool descriptions written by third parties, injected into your context. Review manifests like dependencies.
Retrieval and stores Embedding, indexing and similarity search. pgvector, Pinecone, Weaviate, Elastic A writable input to your prompt, plus a tenancy boundary that is usually enforced by a query filter you have not audited.
Gateways and proxies One egress point for model traffic: keys, routing, quotas, logging. LiteLLM, cloud AI gateways Mostly reduces surface — it is the natural home for budgets, logging and egress rules. Also a single point of failure holding every key.
Guardrails Classify input and output, enforce topic and format rules. Llama Guard, NeMo Guardrails, LLM Guard, managed shields Latency, spend, and a false positive rate that scales with traffic. Useful. Not an authorisation boundary — see DP-09.
Evaluation Measure task quality and security regressions before shipping. AgentDojo, promptfoo, in-house suites Reduces surface, and is the only way you will notice a defence degrading after a model version bump.
Observability Trace prompts, tool calls, costs and guardrail decisions. OpenTelemetry-based tracing, LLM-specific tools Reduces surface, with one caveat: traces contain prompts, and prompts contain customer data. Treat the trace store like the database.

Reading the column that matters

Six of those nine layers add attack surface, and three reduce it. Notice which three: the gateway, the evals and the tracing — the unglamorous operational layers, the ones cut first when a launch date moves. That is not a coincidence, and it is worth saying out loud in a planning meeting.

07

What you actually control.

Having walked the whole stack, here is the honest division. It is shorter than people expect on one side and longer on the other.

You inherit

Training data. Model behaviour. Refusal tuning. How well the instruction hierarchy holds. Detection quality in each language. When the vendor deprecates a version.

You influence

Model and version choice. System prompt. Which tools exist. Whether output is structured. Which guardrail runs and at what threshold.

You own outright

Provenance labelling. Credential scope. Tenancy filtering. Egress rules. Loop ceilings. Output encoding. What gets logged. Which actions need a human. Whether a wrongly blocked user can appeal.

Every item in the third column is engineering you can do this quarter without a model vendor's cooperation, and every one of them holds when the injection works. That is the argument this whole page has been building toward, and it is why the pattern library is ordered the way it is.

08

Questions.

Do I need to understand the maths to use this?

No. Nothing on this page requires you to read a loss function. What it requires is that you can name the six primitives in a system someone shows you, and say which of the four architectures it currently is. That is a vocabulary skill, not a mathematics one.

Is this page teaching me to build AI systems?

Only incidentally. It is the mental model a defender needs to review one, threat model it, and argue for controls in the right place. If you want to actually ship an agent, the frameworks in the ecosystem table have their own documentation and it is better than anything I would write here.

Why does the training section matter if I only run hosted models?

Because it tells you what you are allowed to rely on. Knowing that the instruction hierarchy is trained preference rather than enforced boundary is the difference between putting your authorisation rules in a prompt and putting them in code. That single distinction is worth the whole section.

The ecosystem table will be out of date in six months.

The names will. The layers will not, and the surface column will not either — a retrieval store has been a writable input to your prompt since 2020 and will be in 2030. Read the table by column, not by row.

Which architecture is my system?

Whichever one has the most components you can actually name. If retrieval exists, it is at least A2. If anything the model emits causes a side effect, it is A3, regardless of what the team calls it. If a third party supplies a tool description, it is A4.

09

Where to go next.

You now have the machine. The rest of the site is about defending it.

You can name the parts. Now sit in the seat.

The Filter AI puts you on the receiving end of the architectures above: 35 exercises, seven units, every one scored on both numbers — the attacks you missed and the real people you blocked. Unit one is free.