AISim: AI System Design Simulator

A free, interactive simulator for learning AI system design. Build RAG pipelines, agents and LLM apps from parts, push realistic traffic through them, and learn to fix rate limits, hallucinations, latency, cost and more. 33 scenarios, 34 lessons and a 129-term glossary in plain English.

The point isn't memorising components. It's learning to name the binding pressure: the one limit hurting your system right now. AI systems fail in two ways at once: load (rate limits, latency, cost, context windows) and quality (hallucinations, retrieval misses, prompt injection, runaway agents). AISim models both.

This interactive simulator needs JavaScript. Source code on GitHub.

Built by (cybernerdie).

Frequently asked questions

What is AISim?

AISim is a free, browser-based simulator for learning how to design AI systems. You build an AI app from parts (models, vector databases, rerankers, guardrails, caches, agents), send realistic traffic through it, and see which part breaks first. No real models are called, and nothing to install.

What is binding pressure in AI system design?

Binding pressure is the single limit hurting your system right now: a rate limit, retrieval misses, prompt injection, latency, cost, a full context window, or GPU capacity. Fixing anything else doesn't help until that limit is relieved. AISim shows the binding pressure live and explains it in plain language.

Who is AISim for?

Software engineers moving into AI engineering, product managers and founders who want to understand how LLM apps behave in production, and anyone preparing for AI system design interviews. The lessons start from zero and build up to inference, agents and production reliability.

What topics does AISim cover?

Retrieval-augmented generation (RAG), chunking and hybrid search, reranking, conversation memory, rate limits and scaling, streaming and latency, caching, model routing, prompt injection (direct and indirect) and guardrails, agent permissions, temperature and sampling, evals and LLM-as-judge, self-hosted inference on GPUs, provider outages and failover, multi-agent systems, reasoning budgets, structured outputs, fine-tuning versus RAG, model version drift, privacy and PII, voice pipelines and per-user abuse limits.

When should I fine-tune a model instead of using RAG?

Use RAG for knowledge: facts and documents that change. Use fine-tuning for behaviour: your labels, output format, tone, or a narrow task repeated many times. A fine-tuned small model often beats a large general model on a narrow task at a fraction of the cost, but it should still get its facts from retrieval.

Why does my RAG chatbot give confidently wrong answers?

Usually retrieval is returning the wrong chunks: chunks that are too large or small, too few results (top-K), or pure vector search missing exact identifiers like product codes. Hybrid search (vector plus keyword/BM25), a reranker and better chunking fix most of it. AISim scenario 2, "Confidently wrong RAG", lets you try each fix.

How does the game work?

There are 33 levels in six chapters, and each chapter ends with a boss level that mixes everything it taught. Every level hands you a broken AI system; clear it to unlock the next and earn up to three stars for staying within budget and building lean. There is also a daily challenge (the same remixed level for everyone, every day), an endless incident mode where outages, traffic spikes and attacks hit your system, a sandbox where you can build anything and turn it into a level to share, and achievements with a certificate for clearing every level.

Is AISim free and open source?

Yes. AISim is free to use in the browser and open source on GitHub. It was built by Joshua Paul (cybernerdie), a Senior Fullstack and Applied AI Engineer. Your progress is saved in your browser, and you can share any design you build as a link.

Scenarios (33)

  1. 1 · The store chatbot

    It sounds confident. It's making things up. Your online store launched a chatbot to answer customers' questions. It's just a prompt and an LLM. Complaints are piling up: customers got confident, wrong answers about returns, delivery and warranties.

    Level: Intro. Concepts: RAG, Grounding.

    What you learn: You built retrieval-augmented generation (RAG). A model can only be as right as the information it's given — when the answer lives in private data, the fix is retrieval, not a bigger model. Notice recall: it's not 100%, and every miss is still a potential hallucination. That's the next wall.

  2. 2 · The wrong error code

    Retrieval is on. Answers are still wrong. You added RAG and things got better — but not good enough. Half the questions mention exact product codes and error numbers ("what does E1043 mean on my coffee machine?"). Someone also set huge chunks and Top-K 2 to "save tokens".

    Level: Core. Concepts: Hybrid search, Chunking, Reranking.

    What you learn: Retrieval quality is usually the real bottleneck in RAG, not the model. Hybrid search (keywords + vectors) covers both exact identifiers and paraphrases, chunk size trades precision against completeness, and a reranker lets you retrieve wide while still handing the model a short, clean context.

  3. 3 · The holiday rush

    It works. Now 40× more people want it. Quality is great — you're running the large model on everything. Then you hit the front page: traffic jumps to 60 req/s. The provider starts returning 429s and finance asks why the bill looks like a phone number. Lots of these questions are repeats, and most are easy.

    Level: Core. Concepts: Semantic cache, Model routing, Rate limits.

    What you learn: At scale, the expensive part of an AI system is tokens through your biggest model. A semantic cache removes repeats entirely, and a router sends easy traffic to a model that's ~100× cheaper with its own rate limit. You kept the large model — just for the requests that need it.

  4. 4 · Where's my order?

    Users want things done, not explained. Most support requests are actions: "where is my order?", "cancel my subscription". Your bot can only talk, so it invents an order status. Leadership wants an agent that actually uses tools — without a surprise bill.

    Level: Core. Concepts: Agents, Step budgets, Cost.

    What you learn: Agents turn one LLM call into many. Real tasks here need 2–5 steps, but ~10% of runs get stuck repeating themselves — and a stuck agent spends its entire step budget. The step cap is a cost control, not just a safety net: set it just above what real work needs.

  5. 5 · The refund trick

    "Ignore previous instructions and…" Your assistant is public. 15% of traffic is now people trying to make it leak the system prompt, insult customers, or promise refunds it can't give. A screenshot is already on social media.

    Level: Core. Concepts: Prompt injection, Guardrails.

    What you learn: Safety is layered. An input classifier catches most attacks cheaply, an output judge catches what slips through (and many hallucinations too) — but each layer has false positives, and the judge must see the full answer, which breaks streaming. Defense in depth is a trade-off, not a checkbox.

  6. 6 · The contract reviewer

    Every answer is buried in a 90-page PDF. Legal wants a bot that answers questions about long contracts. To "not miss anything", someone set retrieval to grab 12 huge chunks per question and pinned the cheap small model to save money. Now every request fails.

    Level: Advanced. Concepts: Context windows, Reranking, Cost.

    What you learn: Context windows are a budget, not a bucket. Stuffing more into the prompt costs money, adds latency and drowns the answer ("lost in the middle"). Retrieving wide and reranking down to a few precise chunks fits a small, cheap model, and is usually more accurate than a huge prompt on a big one.

  7. 7 · "It feels slow"

    Users stare at a spinner for eight seconds. Answers are good, but users bounce before they arrive. You run the large model on everything and an Output Judge checks every answer before it ships. Product wants the first words on screen in under a second, without letting hallucinations climb.

    Level: Advanced. Concepts: Streaming, Time to first token.

    What you learn: Perceived speed is time to first token, and streaming is the biggest lever. But anything that must read the full answer first, like an output judge, silently cancels streaming. Here better retrieval protects quality up front, so the model can stream straight to the user.

  8. 8 · The chat that never ends

    Memory optimization: it either forgets what you said, or costs a fortune. Customers love planning whole kitchens with your shopping assistant, in chats that run 20, 40, 80 messages. They refer back all the time ("like I said earlier, my budget is…"). The prototype resends the entire conversation with every message. The bill grows every week, answers get worse as chats get longer, and the longest chats have started failing.

    Level: Advanced. Concepts: Memory optimization, Stateless models, Cost.

    What you learn: Models are stateless: they remember nothing between calls, so "memory" is whatever you choose to resend. Resending everything is accurate at first, then gets expensive, slow and noisy, and eventually overflows. A sliding window is cheap but forgets. A summary keeps the gist but loses specifics. Storing the conversation as long-term memory and retrieving only what each message needs keeps prompts small and the important facts in view.

  9. 9 · Flying blind

    Costs are down 95%. Is anything else down? A contractor "optimised" your help bot: the small model, one huge chunk per question. The dashboard looks fantastic (fast, cheap, zero errors) and they've already invoiced. Support says answers have got worse, but nobody can prove it, because nothing measures whether answers are right.

    Level: Core. Concepts: Evals, LLM-as-judge, Observability.

    What you learn: You can't improve what you can't see. Speed, cost and errors are easy to measure, so teams optimise them and quietly wreck quality. An eval harness (a test set with known answers, plus an LLM judge scoring a sample of real traffic) turns "I think it's worse" into a number, and tells you whether each change actually helped.

  10. 10 · Bring it in-house

    We moved off the API to save money. Now everything times out. The API bill was about $10 per 1,000 requests, so the team moved to an open 70B model on rented GPUs: 4 GPUs, one request at a time, full precision. The bill dropped to almost nothing, because almost nothing gets answered. Find a setup that is cheap, fast enough and still as good as the API.

    Level: Advanced. Concepts: Self-hosting, Batching, Quantization, GPU capacity.

    What you learn: Self-hosting turns a per-token bill into a capacity-planning problem. Batching is the biggest lever (one GPU serves many requests at once), quantization makes each GPU faster for a small quality cost, and the GPU count sets your bill whether the GPUs are busy or not. The sweet spot is busy but not saturated: too few GPUs and requests queue and time out, too many and you pay for idle silicon.

  11. 11 · The provider is down

    503, 503, 503. Your status page is getting traffic. Your model provider is having a bad day: 70% of calls fail with 503 errors. Your whole product depends on that one provider, so your users see errors too. Keep the product up without wrecking speed or quality.

    Level: Core. Concepts: Outages, Retries, Failover.

    What you learn: Retries help with brief blips, but during a real outage they pile more load onto a struggling provider and make things worse (a retry storm). Resilience means having somewhere else to go: a second provider or a self-hosted model, with automatic failover, timeouts and a cap on retries. The backup doesn't need to be identical, just good enough to keep you up.

  12. 12 · The research assistant

    One agent, twenty tabs open, forty seconds per answer. Analysts ask your assistant multi-part research questions: compare three vendors, summarise five competitors, build a briefing. A single agent works through every sub-question one after another, its prompt growing with each search result. Answers are slow and keep missing things. Leadership heard "multi-agent" on a podcast.

    Level: Advanced. Concepts: Multi-agent, Orchestration, Hand-offs.

    What you learn: Multi-agent systems trade money for speed and focus. Parallel workers with small, focused contexts beat one agent drowning in its own history, but every agent is more calls, every hand-off loses detail, and agents can loop. Good teams are small (about one worker per sub-task), have a reviewer to catch what the hand-offs dropped, and have a hard cap on rounds.

  13. 13 · Think harder?

    The hard questions keep coming back wrong. Your tutoring assistant handles a lot of genuinely hard questions: multi-step maths, tricky logic, "explain why this proof is wrong". The medium model gets too many of them wrong. One engineer wants the large model for everything, another wants the new reasoning mode turned all the way up.

    Level: Core. Concepts: Reasoning models, Thinking budgets, Model routing.

    What you learn: Reasoning ("thinking") lets a model work through a problem before answering, which buys real accuracy on hard questions. But the hidden thinking tokens are paid for, and they're written before the first visible word, so more thinking is slower too. A modest budget usually captures most of the gain. Spend it only where questions are hard, for example by routing easy ones to a small model.

  14. 14 · It broke the parser

    One in nine responses crashes your code. Your invoice-extraction API asks the model to return JSON (vendor, date, line items), and your code parses it. It works in the demo. In production, every so often the model adds a friendly sentence, forgets a bracket or invents a field, and your parser throws. The customer sees a 500 error.

    Level: Intro. Concepts: Structured outputs, JSON mode, Validation.

    What you learn: Asking nicely for JSON isn't a contract. Models occasionally break format, and at scale "occasionally" means constant crashes. Structured output (JSON mode or schema-constrained decoding) makes the model produce valid output by construction. A validator that checks and retries is the safety net, not the fix.

  15. 15 · Yesterday's answers

    The price changed on Monday. The bot still quotes the old one. Your retrieval setup is solid (hybrid search, reranking), but the docs it searches change daily: prices, policies, release notes. The index was built once, by hand, from text scraped out of PDFs. Customers get confident answers that were true last month, and anything inside a table seems invisible.

    Level: Core. Concepts: Data ingestion, Index freshness, Document parsing.

    What you learn: Most RAG problems start before retrieval: in ingestion. Content that changes needs a pipeline that re-indexes on a schedule or on every change, or the model will confidently quote old facts that your judge can't catch, because the sources agree. And how you parse documents matters: plain text extraction turns tables and multi-column PDFs into word soup.

  16. 16 · The 20-page system prompt

    Every request re-reads the whole manual. Your compliance assistant sends a 12,000-token system prompt with every request: the full policy manual, tone guide and twenty worked examples. Quality is excellent. The bill is not: almost all of it pays for reading the same text over and over. The small model can't even fit it.

    Level: Intro. Concepts: Prompt caching, Cost, Latency.

    What you learn: When every request starts with the same long prefix (system prompt, documents, examples), prompt caching lets the provider reuse its work: cached tokens cost roughly a tenth and are read almost instantly. Put the stable content first and the changing content last, so as much as possible can be cached.

  17. 17 · The nightly job ate the day

    A million tickets to summarise, and live users get 429s. Someone kicked off a job to summarise and tag every support ticket from the last year. It runs through the same real-time API as your live chat. Now 60% of your traffic is a background job nobody is waiting on, it's eating your rate limit, and live customers are getting errors.

    Level: Core. Concepts: Batch APIs, Async workloads, Rate limits.

    What you learn: Separate work that someone is waiting on from work that can wait. Providers offer batch APIs at roughly half price with results within hours, and batch jobs don't compete with your live traffic for rate limits. Real-time capacity is precious: keep it for real-time users.

  18. 18 · Fine-tune it?

    Your labels, your format, your 40 categories. Your support triage system sorts tickets into your company's 40 internal categories, in your exact format, and also answers questions from the help centre. Off-the-shelf models keep inventing categories. The large model does a bit better and costs five times as much. Someone says "just fine-tune it". Someone else says "fine-tuning will teach it our docs too".

    Level: Core. Concepts: Fine-tuning, RAG vs fine-tuning, Cost.

    What you learn: Prompting, RAG and fine-tuning solve different problems. Fine-tuning teaches behaviour: your labels, your format, your tone. A fine-tuned small model often beats a general large one on a narrow task, at a fraction of the price. But it doesn't reliably teach facts, and facts change, so knowledge still comes from retrieval. Most real systems use both.

  19. 19 · Nothing changed. Everything broke.

    No deploy, no code change, and quality fell off a cliff. Nobody touched the code for two weeks, yet support complaints doubled and a few JSON responses started breaking. Your app calls the provider's "latest" model alias, and there's nothing measuring answer quality, so all you have is a feeling.

    Level: Core. Concepts: Model versions, Regressions, Evals.

    What you learn: The model is a dependency, and "latest" is an unpinned dependency. Providers update models behind aliases, and prompts tuned for one version can quietly regress on the next. Pin versions, run your evals against a new version before switching, and upgrade on purpose. Evals are what let you notice at all.

  20. 20 · Compliance is calling

    Half your prompts contain someone's medical history. Your insurance assistant works well, and every claim question that customers paste in (names, policy numbers, diagnoses) goes straight to a third-party model provider. The compliance team has found out. They want personal data to stop leaving your systems without killing the product.

    Level: Intro. Concepts: Privacy, PII redaction, Compliance.

    What you learn: Anything in a prompt is data you're sending to whoever runs the model. Redact personal details before they leave (swap them for placeholders and put them back in the answer), or keep sensitive traffic on models you host yourself. Detection is never perfect, so combine it with provider agreements, retention settings and data minimisation.

  21. 21 · The walkie-talkie

    Talk. Wait seven seconds. Hear a reply. Your new voice assistant answers well, but conversations feel like a walkie-talkie: you finish speaking, then silence for seven seconds, then the whole reply at once. People talk over it or hang up. A natural conversation needs the reply to start in about a second.

    Level: Core. Concepts: Voice, Speech-to-text, Streaming.

    What you learn: Voice is a pipeline (speech-to-text, the model, text-to-speech) with a latency budget of about a second. If each stage waits for the previous one to finish, the delays stack up. Stream every stage: transcribe while the user speaks, stream tokens from the model, and start speaking the first sentence immediately. Images and audio as input work similarly: they become tokens the model has to read, and they cost time and money too.

  22. 22 · One user, half your bill

    A few scripted accounts are eating everyone's capacity. You launched a free tier. Within a week, a handful of accounts started hammering your API from scripts, with huge prompts, hundreds of times a minute. Half your traffic is now them. Real users are getting 429 errors, and your cost per real request has nearly tripled.

    Level: Intro. Concepts: Abuse, Per-user limits, Cost control.

    What you learn: Your provider's rate limits protect them, not you. Anything that's free, or billed per seat while you pay per token, needs per-user limits on requests, on tokens per day and on spend, so a single script can't burn your capacity or your budget. Set them generously for people and tightly for machines.

  23. 23 · Same question, different answers

    Upload the same invoice twice, get two different totals. Your accounting tool reads invoices and returns the total, VAT and due date as JSON. Customers have noticed that uploading the same invoice twice can give two different totals. It also writes the odd product description. Someone suggests a bigger model.

    Level: Intro. Concepts: Temperature, Sampling, Determinism.

    What you learn: Temperature controls randomness, not intelligence. For extraction, classification and anything with one right answer, run near 0 so the same input gives the same output. Keep some temperature for writing where variety helps. A bigger model doesn't fix sampling; it just costs more.

  24. 24 · The evals say it's fine

    The dashboard says 98%. Support says otherwise. Your docs assistant's eval dashboard has been green since launch: nearly every answer passes. Meanwhile support tickets keep arriving about wrong part numbers and made-up steps. Your goals are measured on real outcomes (tickets, refunds, follow-up questions), not on the dashboard.

    Level: Advanced. Concepts: Evals, LLM-as-judge, Test sets.

    What you learn: Evals are only as good as their test set and their judge. Test on samples of real traffic, refreshed regularly, not the 50 examples you wrote at launch. If an LLM judges, check it against human ratings so you know how often it's fooled. Exact match is cheap but punishes correct answers worded differently. Honest evals first, then fix what they show.

  25. 25 · The email that hijacked the agent

    Nobody attacked the chat. They emailed the agent. Your inbox assistant reads customers' emails, sorts them, looks things up and sends replies on its own. This morning it forwarded a batch of invoices to an outside address. No user typed anything suspicious: the instructions were hidden in white text inside an incoming email. Customers still want replies sent for them.

    Level: Advanced. Concepts: Indirect prompt injection, Least privilege, Human approval.

    What you learn: Anything your system reads can carry instructions: emails, web pages, documents, tool results. Models can't reliably tell data from commands, so assume some will get through. Limit the damage instead: mark external content as untrusted, give agents the fewest permissions the job needs, and require approval for actions that send, pay or delete. No single layer is enough.

  26. 26 · Right answer, wrong question

    Fast and cheap, and sometimes answering something else. Your docs assistant is quick and costs almost nothing, thanks to a cache. But some customers asking about the Pro plan are getting answers about the Basic plan, and people asking how to cancel are told how to upgrade. Everything is already in place. Something in it is set wrong.

    Level: Core. Concepts: Debugging, Semantic cache, Similarity threshold.

    What you learn: A semantic cache matches questions by meaning, so its threshold decides how similar is similar enough. Set it too loose and "how do I cancel?" gets the cached answer to "how do I upgrade?". Too strict and nothing ever hits. Tune it on real pairs of questions, and keep exact facts like prices and plan names out of loose matches.

  27. 27 · The goldfish

    "As I said two minutes ago..." Your coaching chatbot has long conversations with its users, and the bill is under control. The complaint is that it keeps forgetting things: the user's goal, the injury they mentioned, the plan you agreed on ten messages back. They have to repeat themselves constantly.

    Level: Core. Concepts: Debugging, Conversation memory.

    What you learn: Whatever isn't in the prompt doesn't exist for the model. A tight window keeps costs flat but drops everything older than a few turns. Rolling summaries keep the gist cheaply, and long-term memory brings back the specific earlier turns a new message needs.

  28. 28 · Safe and useless

    No jailbreak has got through. Neither have many customers. After last month's jailbreak scare, security turned the protection up. No attack has got through since. But support is flooded: customers asking ordinary questions are being told their message "can't be processed", and sign-ups are down.

    Level: Intro. Concepts: Debugging, Guardrails, False positives.

    What you learn: Every guardrail has two error rates: attacks it lets through and real users it blocks. Turning it all the way up trades one for the other, and blocked customers are a failure too, just a quieter one. Measure both, and layer defences instead of maxing out one.

  29. 29 · It found it, then threw it away

    Recall looks fine. The answers don't. Your search pipeline has everything: vector search, keyword search and a reranker. The logs show the right document is almost always retrieved. Yet the assistant still says "I couldn't find that" or guesses, especially on questions that need two pieces of information.

    Level: Core. Concepts: Debugging, Reranking, Context.

    What you learn: A reranker is a filter: it decides what the model gets to read. Keep too few and you throw away the second fact a question needs, or the right chunk when the reranker's top pick is wrong. Keep too many and you're back to noise and cost. A handful usually works best.

  30. 30 · Overthinking "hello"

    The bill went up sevenfold after someone made it smarter. Your support assistant used to be cheap and snappy. Last sprint someone changed a setting to make it "smarter" on tricky questions. Quality barely moved, but every reply now takes many seconds and the monthly bill is seven times what it was. Most questions are simple.

    Level: Core. Concepts: Debugging, Reasoning budget, Cost.

    What you learn: Reasoning tokens are billed and waited for like any other output. Spending them on every request makes easy questions slow and expensive for no gain. Turn thinking off by default, and use it (or a router) only where the problem needs it.

  31. 31 · The key was in the app

    Per-user limits are on. The bill doubled anyway. Your mobile app calls the AI endpoint directly, with the key built into the app. Someone pulled it out, and now scripts all over the world use your endpoint as a free AI. They rotate thousands of accounts and addresses, so your per-user limits barely notice. Nearly half your traffic isn't your users.

    Level: Core. Concepts: Authentication, API keys, Cost control.

    What you learn: Anything shipped to a user's device or browser is public, including keys. Put auth in front of your own endpoint so every call needs valid credentials, keep provider keys on your server, and use per-user limits for the users you do let in. Limits and auth answer different questions: how much, and who.

  32. 32 · Why did it say that?

    A customer has a screenshot. You have nothing. A customer sent a screenshot of your assistant confidently quoting the wrong refund policy. Engineering wants to know what the model was sent and what retrieval found, but nothing was recorded. Every complaint like this takes two days of guessing. Be able to answer "why" within a few hours, without a huge storage bill.

    Level: Core. Concepts: Tracing, Observability, Sampling.

    What you learn: Wrong answers don't throw errors, so you need traces: the prompt, what was retrieved, each model call. Keeping every request is expensive and mostly useless; random samples miss the rare failure you're hunting. Keep every failure plus a small sample of the rest, store the text (with personal data redacted first), and you can answer "why did it say that?" in minutes.

  33. 33 · The average looks fine

    Fine on average. Not for everyone. Your help assistant scores well, and the dashboard is green. But a third of your customers write in Spanish or Portuguese, and they keep escalating to human support. Nobody has checked whether quality is the same for them. Find out, and close the gap.

    Level: Advanced. Concepts: Fairness, Cohort evals, Multilingual.

    What you learn: An average hides who is being served badly. Measure quality per group (language, region, device, plan) and set a limit on the gap, not just on the average. Here the cause was English-only embeddings: questions in other languages landed nowhere near the docs that answered them. Multilingual embeddings fixed it for a small extra cost.

Chapters and boss levels

Chapter 1: Getting it working

Make a chatbot that knows your docs, survives a launch, uses tools and shrugs off a jailbreak.

Chapter 2: Making it good

Long documents, slow answers, chats that never end, quality you can measure, your own GPUs.

Chapter 3: Keeping it running

Outages, agent teams, thinking budgets, output your code can trust, and knowledge that goes stale.

Chapter 4: Running it for real

Big prompts, background jobs, fine-tuning, models that change under you, and personal data.

Chapter 5: Advanced

Voice, abuse, temperature, evals you can trust, and attacks hidden in what your agent reads.

Chapter 6: Find the bug

Complete systems with one wrong setting each. Nothing to add: read the symptoms and find it.

Chapter 7: Production readiness

What a demo never needs: who may call you, seeing why an answer went wrong, and serving every group of users well.

Learn AI system design: 10 modules, 34 lessons

Module 1: Foundations (Beginner)

What a model is, what it sees, and why it makes things up.

What an AI app really is

The model is one box. The product is the pipeline around it.

When people say "we built an AI app", they usually mean a pipeline: a request comes in, gets checked, maybe finds some documents, gets sent to a model, and the answer may be checked again before the user sees it.

The large language model (LLM) is the part that writes. Everything else decides what the model sees, which model runs, and whether the answer is safe to ship.

Think of it like this: The model is a brilliant new hire on day one. Smart, fluent, but knows nothing about your company. The pipeline is the onboarding: the docs you hand them, the manager who checks their work, the rule about which tasks go to the senior person.

  • Most quality problems are fixed by changing what the model sees, not the model itself.
  • Most cost and speed problems are fixed by changing which model runs, and how often.
  • Most safety problems are fixed with checks before and after the model.

Takeaway: Design the pipeline, not just the prompt.

How models are made

Read the internet, learn to follow instructions, learn what people prefer.

A modern language model is built in stages. You don't need to train one to build with them, but knowing the stages explains a lot about how they behave.

  • Pretraining. The model reads an enormous amount of text and learns one skill: predict the next token. Along the way it picks up grammar, facts, reasoning patterns and code. The result knows a lot but isn't yet a helpful assistant.
  • Instruction tuning. It's then trained on many examples of instructions paired with good responses, so it learns to answer questions and follow requests rather than just continue text.
  • Preference training (RLHF and similar). People (or other models) compare pairs of answers and say which is better. The model is nudged towards the preferred style: helpful, honest, safe.
  • Distillation. A big model's outputs are used to train a smaller, cheaper one, which is how many fast "small" models get surprisingly good.

Think of it like this: Pretraining is years of reading everything in the library. Instruction tuning is job training. Preference training is feedback from a manager on which drafts work better.

This explains several everyday behaviours: models know a lot of public facts but nothing after their training date or inside your company; they're eager to give an answer (a habit from training); and their size, measured in parameters, roughly tracks how much they can learn.

Takeaway: Training gives general skill. Your system supplies the specific knowledge.

Prompts: the only thing a model sees

If it isn't in the prompt, the model doesn't know it.

A model can't see your database, your website or yesterday's chat. For each request it sees exactly one thing: the text you send, called the prompt. Its answer comes from that prompt plus what it learned in training.

  • System prompt: the role and rules ("You are a support assistant. Only answer from the sources.").
  • Context: documents you looked up, results from tools.
  • History: earlier messages in the conversation.
  • The user's message itself.

Think of it like this: Phoning an expert who forgets everything the moment you hang up. On every call you have to read out who you are, what you discussed before, and the documents they need.

This one idea explains most of AI engineering. RAG works because you paste the right documents in. Chatbots "forget" when old messages aren't resent. Costs grow because everything you paste in is paid for.

Takeaway: Building an AI app is mostly deciding what goes into the prompt.

Tokens, context windows and cost

Everything you send the model is metered.

Models read and write in tokens, roughly ¾ of a word each. You pay for every token you send in (the prompt, the retrieved chunks, the conversation so far) and every token the model writes back. Output tokens usually cost several times more than input tokens.

Each model also has a context window: the most tokens it can take in at once. Go over it and the request fails or gets cut off.

Think of it like this: The context window is a desk. You can only spread so many pages on it. And even when everything fits, a desk buried in paper makes it harder to find the one page that matters ("lost in the middle").

  • Fewer, better chunks beat more chunks: cheaper, faster and often more accurate.
  • A bigger context window is a fallback, not a strategy. It costs more per request.
  • Agents and long chats grow the prompt every turn. Watch it.

Takeaway: Treat the context window as a budget, not a bucket.

Temperature and sampling

Why the same question can get a different answer, and when you want that.

A model doesn't pick "the" next word. For every token it produces a list of possible next tokens with probabilities, for example "Paris" 92%, "the" 3%, "a" 1%, and then picks one. How it picks is called sampling.

  • Temperature 0: always take the most likely token. The same input gives (almost) the same output.
  • Temperature around 0.7: usually the likely token, sometimes a less likely one. Natural, varied writing.
  • Temperature 1 and above: rare tokens get picked more often. More creative, more surprising, more mistakes.
  • Top-p does a similar job a different way: only pick from the smallest set of tokens that together cover, say, 90% of the probability.

The rule of thumb: match the temperature to the task. Extraction, classification, routing, JSON and anything with one right answer want 0–0.2. Writing, brainstorming and naming want 0.5–0.9. Too low on creative work makes everything sound the same; too high on precise work gives different totals for the same invoice.

Even at 0, outputs aren't perfectly repeatable on most hosted APIs (tiny numerical differences and batching can flip a near-tie). If you need the exact same result, cache it or store it.

Think of it like this: Low temperature is an accountant reading the number off the page. High temperature is a jazz musician improvising. Both are skills. Don't hire the jazz musician to do your books.

Takeaway: Temperature trades consistency for variety. Pick per task, not per app.

Why models make things up

A model always produces an answer, whether it knows or not.

An LLM writes by predicting the next most likely words. It was trained on a huge amount of public text, so it is very good at sounding right. But "sounding right" and "being right" are different things.

If you ask about something it never saw (your product, your policies, last week's changes), it doesn't stop. It produces the most plausible-sounding answer. That confident, wrong answer is a hallucination.

Think of it like this: Ask a confident friend for directions in a city they've never visited. They won't say "I don't know". They'll describe a route that sounds perfectly reasonable.

A bigger model hallucinates a bit less on general knowledge, but it still can't know your private data. The reliable fix is to give it the facts at question time.

Takeaway: Hallucination is usually a missing-information problem, not a model-size problem.

Module 2: Giving models knowledge (Beginner)

Let the model look things up, and make sure it finds the right page.

RAG: letting the model look things up

Find the right documents first, then ask the model to answer from them.

Retrieval-augmented generation (RAG) adds a search step before the model. Your documents are split into small pieces (chunks) and indexed. When a question arrives, you find the most relevant chunks and paste them into the prompt with an instruction like "answer using only these sources".

  • Embedding model: turns text into a list of numbers that captures its meaning.
  • Vector database: finds the chunks whose numbers are closest to the question's numbers.
  • LLM: reads those chunks and writes the answer.

Think of it like this: An open-book exam. The student (the model) is still the one writing, but now they're allowed to look up the relevant pages before answering.

RAG only works if the search finds the right page. If retrieval brings back the wrong chunks, the model will happily answer from the wrong page. That's the next wall.

Takeaway: RAG turns "does the model know?" into "did we find it?", which is a problem you can measure and fix.

Getting retrieval right

Chunk size, top-K, hybrid search and reranking.

Retrieval has one job: put the chunk that contains the answer in front of the model. The share of questions where that happens is called recall. Four levers control it.

  • Chunk size. Small chunks are precise but can split an answer in half. Huge chunks keep context but blur the meaning and eat your token budget.
  • Top-K. How many chunks you fetch. More chunks means a better chance of catching the right one, but more noise and more cost.
  • Hybrid search. Embeddings understand meaning but blur exact strings like "E1043" vs "E1034". Keyword search (BM25) nails exact terms. Using both covers both kinds of question.
  • Reranking. Fetch wide (say 12 chunks), then a reranker scores each one against the question and keeps only the best 3–4.

Think of it like this: A librarian (vector search) is great at "books about grief", terrible at "the one with ISBN 978-0-14". The catalogue (keyword search) is the opposite. A good library uses both, and an expert (the reranker) picks the best few off the cart.

Takeaway: When RAG gives wrong answers, look at retrieval before you touch the model.

Ingestion: what goes into the index

Stale or scrambled documents make even perfect retrieval wrong.

Before retrieval can find anything, documents have to be ingested: loaded, converted to text, split into chunks, embedded and stored. Most RAG problems that look like "bad retrieval" are really ingestion problems.

  • Freshness. If prices change on Monday and the index is rebuilt monthly, the bot quotes old prices with total confidence. Even an output judge won't catch it, because the retrieved source says the same thing.
  • Parsing. Plain text extraction flattens tables and multi-column PDFs into word soup, so the answer is in the index but no search will ever match it. Layout-aware parsers keep tables and structure.
  • Deletions matter too: removed documents must leave the index, or retired policies keep being quoted.

Think of it like this: A library is only as good as its catalogue. If new books never get catalogued, and some get catalogued with their pages shuffled, the best librarian in the world can't help you.

Treat ingestion as a real pipeline: re-index on a schedule or on every change, use the right parser per document type, and track how old each document's index entry is.

Takeaway: Fresh, well-parsed data beats a cleverer retriever.

Module 3: Memory and conversations (Intermediate)

Why chatbots forget, and how to remember without going broke.

Why chatbots forget, and why remembering gets expensive

Models remember nothing between messages. Apps fake it by resending the chat.

Chatting with an AI app feels like talking to something that remembers you. It doesn't. Models are stateless: every message is a brand-new request. The app creates the feeling of memory by resending the conversation so far along with each new message.

The simplest version, resending everything, works perfectly on day one. Then conversations get long.

  • Cost grows every turn. Message 40 pays again for the 39 before it, so a conversation's total cost grows much faster than its length.
  • Your rate limit fills up with old messages instead of new users.
  • Answers get worse. The one detail that matters is buried among hundreds of lines (lost in the middle).
  • Eventually the conversation no longer fits in the context window, and requests fail.

Think of it like this: Reading someone the full transcript of every conversation you've ever had before saying anything new. Very thorough. By month two it takes all day.

Takeaway: Memory isn't free: every remembered word is paid for again on every turn.

Memory that scales

Remember facts, not transcripts.

The goal isn't to remember everything. It's to have the right facts in the prompt for this particular message. There are four common strategies, from simplest to smartest.

  • Full history. Resend every turn. Most accurate for short chats, but cost, latency and failures grow with every message.
  • Sliding window. Keep only the last N turns. Cheap and predictable, but anything older simply vanishes, so "what was my budget again?" fails.
  • Rolling summary. Replace older turns with a short running summary and keep the last few word for word. Keeps the gist, but summaries tend to drop specifics like numbers and names.
  • Long-term memory. Store every turn (or the facts pulled out of it) as embeddings, and for each new message retrieve only the few that are relevant. It's RAG, applied to the conversation itself.

Think of it like this: A good doctor doesn't reread your whole file at every appointment. They glance at the summary, and pull up the one old test result that matters today.

Production systems usually combine them: a short window so the conversation flows, a summary for the big picture, and retrieval for specific facts. Prompt caching helps too: providers can reuse the unchanging start of a prompt (system prompt, long documents) at a discount.

Takeaway: Keep prompts small and the important facts in view.

Module 4: Getting reliable answers (Intermediate)

Make models think harder when it matters, return output your code can trust, and know when to fine-tune.

Reasoning models: paying to think

More thinking buys accuracy on hard problems, at a price.

Reasoning models (or "thinking" modes) work through a problem step by step before giving their answer. Those steps are written as hidden tokens: you don't see them, but you pay for them, and they're written before the first visible word appears.

  • On hard, multi-step problems (maths, logic, planning, tricky code) thinking gives a big jump in accuracy.
  • On easy questions it adds little: you pay and wait for thinking you didn't need.
  • Most providers let you set a thinking budget. Gains flatten out: a modest budget often gets most of the benefit.

Think of it like this: Asking someone to show their working. On a hard maths problem it catches mistakes. On "what's 2 + 2?" it's just slower.

This is a new axis next to model size. Sometimes a mid-sized model that thinks beats a big model that doesn't, for less money. Combine it with routing so only the hard questions get the thinking.

Takeaway: Spend thinking where questions are hard, not everywhere.

Structured outputs: answers your code can trust

If code reads the answer, the format must be guaranteed.

Lots of AI features don't show text to a person. They hand data to code: extract fields from an invoice, classify a ticket, fill a form. That code expects an exact format, usually JSON matching a schema.

Asking nicely ("respond only in JSON") works most of the time. At scale, "most of the time" means a steady stream of crashes: a missing bracket, a chatty first sentence, an invented field.

  • Structured output (JSON mode, schema-constrained decoding): the model can only produce tokens that keep the output valid against your schema.
  • Validation: check every response against the schema before use, and retry once with the error message if it fails.
  • Use both: the first prevents almost all problems, the second catches the rest.

Think of it like this: A paper form with boxes versus a blank page that says "please write your details neatly".

Takeaway: Don't parse hope. Constrain the output, then validate it.

Prompting, RAG or fine-tuning?

Three ways to customise a model, for three different problems.

When a model doesn't do what you need, there are three levers. They're often confused, and they fix different things.

  • Prompting (instructions, plus a few examples, known as few-shot). Fastest to try, no training. Great for getting started; limited by how much you can fit, and by paying for those tokens on every call.
  • RAG (retrieval). For knowledge: facts, documents, anything that changes. The model reads the right pages at question time, so updating knowledge just means updating the index.
  • Fine-tuning. For behaviour: your labels, format, tone, or a narrow task done thousands of times. Training is a one-off cost, and a fine-tuned small model can beat a much larger general one at that task.

The classic mistake is fine-tuning to "teach the model our docs". It learns the style of your docs and a fuzzy version of their facts, then confidently mixes them up, and it's out of date the moment the docs change. Facts go in retrieval; behaviour goes in fine-tuning.

Think of it like this: Prompting is giving instructions to a temp. RAG is handing them the right folder. Fine-tuning is training a new hire until your way of working becomes habit.

Takeaway: Start with prompting, add RAG for knowledge, fine-tune for behaviour.

Module 5: Running in production (Intermediate)

Rate limits, cost and speed once real users arrive.

Scaling: rate limits, caching and routing

At scale, tokens through your biggest model are the bottleneck.

Model providers cap how many tokens per minute (TPM) you can send to each model. Go over it and you get HTTP 429 errors, no matter how much you're willing to pay. The biggest models have the tightest limits and the highest prices.

  • Semantic cache. Many questions are near-repeats. If a new question means the same as one already answered, return the stored answer and skip the model entirely.
  • Model routing. Most requests are easy. Send them to a small model that is ~100× cheaper and much faster, and keep the large model for the hard ones.
  • Trim the prompt. Every token you don't send is a token you don't pay for and doesn't count against your limit.

Think of it like this: A hospital doesn't send every patient to the top surgeon. Triage sends the sprained ankles to a nurse, and the receptionist answers "where's the car park?" without paging anyone.

Takeaway: Don't make your strongest model do your easiest work.

Latency and streaming

Users judge speed by when the first words appear.

A model writes one token at a time. A full answer from a large model can take several seconds. If you wait for the whole thing before showing anything, users stare at a spinner.

Streaming sends tokens to the user as they're written. Total time barely changes, but time to first token (TTFT) drops from seconds to well under one, and it feels fast.

Think of it like this: A waiter who brings bread while the kitchen cooks. The meal takes as long as before. The wait feels much shorter.

The catch: anything that must read the complete answer first, like an output judge, silently cancels streaming. You then need to protect quality earlier in the pipeline.

Takeaway: Measure time to first token, not just total time.

Protecting your capacity from abuse

Your provider limits you. You need to limit your users.

Every AI request costs you money, unlike most web requests. That makes free tiers and flat-price plans a target: one script can send thousands of long prompts and burn a month's budget in a day, and use up the rate limit your real users need.

  • Per-user rate limits: requests per minute that no human would hit.
  • Quotas: tokens or spend per user per day or month.
  • Size limits: cap input length, since huge prompts are the expensive part.
  • Watch for outliers: a tiny share of accounts often drives a large share of cost.

Think of it like this: An all-you-can-eat buffet still has a rule against filling suitcases.

Takeaway: Generous for people, strict for scripts.

Module 6: Beyond text: voice and images (Intermediate)

Multimodal input, and building voice assistants that feel like a conversation.

Voice, images and audio

Other kinds of input become tokens too, and voice adds a latency budget.

Multimodal models can read images, audio and documents as well as text. Under the hood, an image or an audio clip is turned into tokens the model processes like words. A single image can cost as much as a page of text, so images aren't free just because they're one file.

Voice assistants usually chain three parts: speech-to-text (STT) turns audio into text, the language model answers, and text-to-speech (TTS) speaks the reply. Some newer models handle audio directly, end to end.

  • Conversation has a latency budget: people expect a reply to start within about a second, or it feels broken.
  • If each stage waits for the previous one to finish, delays stack: transcribe everything, then generate everything, then synthesise everything.
  • Stream every stage: transcribe while the user speaks, stream tokens, and start speaking the first sentence immediately.
  • Smaller, faster models often beat bigger ones in voice, because a quick good answer beats a slow perfect one.

Think of it like this: A good phone call versus a walkie-talkie. Both carry the same words; only one feels like a conversation.

Takeaway: In voice, the time to first sound matters more than anything.

Module 7: Inference: how models actually run (Intermediate)

Prefill and decode, prompt caching, GPUs and batching, self-hosting, batch APIs, and staying up when providers fail.

What happens when you call a model

Reading your prompt is fast. Writing the answer is slow.

Every model call runs in two phases. First the model reads your whole prompt at once (prefill). GPUs are built for this kind of parallel work, so even a long prompt is read quickly. Then it writes the answer one token at a time (decode). Each new token depends on the one before it, so this part can't be parallelised.

  • This is why output length drives latency. A 2,000-token prompt with a 50-token answer is quick; a 50-token prompt with a 2,000-token answer is slow.
  • It's also why output tokens cost several times more than input tokens.
  • Capping the maximum output length is one of the cheapest speed and cost wins there is.
  • While writing, the model keeps a working memory of everything it has read so far (the KV cache), so it doesn't re-read the prompt for every new word. Prompt caching reuses that work across requests.

Think of it like this: Reading a page takes a glance; writing a page takes a while. A model is the same: it skims your prompt in one go, then writes its reply word by word.

Temperature controls how each next token is picked: low means the most likely word almost every time (consistent), high means more variety (creative, but less reliable).

Takeaway: Speed is mostly about how much the model writes, not how much it reads.

Prompt caching: stop paying to re-read

Reuse the part of the prompt that never changes.

Many apps send the same long prefix with every request: a big system prompt, a policy manual, few-shot examples, or the earlier part of a conversation. The model processes it from scratch each time, and you pay for it each time.

Prompt caching keeps the model's processed version of that prefix (its KV cache) around for a few minutes. When the next request starts with exactly the same tokens, it's a cache hit: those tokens cost a fraction of the normal price and are read almost instantly.

  • Put stable content first (system prompt, documents, examples) and changing content last (the user's question).
  • Any change early in the prompt (even a timestamp) breaks the cache for everything after it.
  • Different from a semantic cache: prompt caching still runs the model; a semantic cache skips it entirely for repeated questions.

Think of it like this: Keeping the reference book open on your desk, instead of fetching it from the shelf and finding your page every time.

Takeaway: Same prefix, every time? Cache it.

Serving models on GPUs

Batching and quantization decide how much one GPU can do.

A GPU writing tokens for a single request is mostly waiting: the bottleneck is moving the model's weights through memory, not the maths. Batching fixes that. The GPU works on many requests at once, reusing each pass through the weights for all of them.

  • Bigger batches mean much more total throughput (tokens per second across all requests).
  • But each individual request gets a smaller slice, so it's written more slowly. Throughput and per-request latency pull against each other.
  • Modern servers use continuous batching: new requests join the batch the moment a slot frees up, instead of waiting for the whole batch to finish.

Quantization stores the model's numbers with fewer bits (16 → 8 → 4). The model gets smaller and faster, more fits per GPU, and quality drops slightly: barely at 8-bit, noticeably at 4-bit.

Think of it like this: A bus versus a taxi. One taxi per passenger is fast for each rider but wasteful. A full bus moves far more people per hour, but each stop takes longer. Quantization is fitting more seats into the same bus by making them narrower.

There are more tricks, like speculative decoding, where a small model drafts several tokens and the big model checks them in one pass. They all chase the same goal: more useful tokens per GPU-second.

Takeaway: An idle GPU slot is wasted money; an overfull one is wasted time.

API or your own GPUs?

Pay per token, or pay per hour whether you use it or not.

An API charges per token. You pay nothing when nobody is using it, and someone else handles the hardware, scaling and upgrades. Self-hosting an open-weights model charges per GPU-hour: you pay the same at 3am as at peak.

  • At high, steady traffic, self-hosting can be many times cheaper per request, because busy GPUs spread their hourly cost over lots of requests.
  • At low or spiky traffic it's often more expensive: you pay for idle GPUs, or under-provision and fall over at peak.
  • Self-hosting also means you own capacity planning, on-call, model upgrades and GPU shortages. That's real engineering cost.
  • Reasons to self-host beyond price: data never leaves your infrastructure, no provider rate limits, and full control over the model.

Think of it like this: Taxis versus owning a car. If you drive all day every day, owning is cheaper. If you drive twice a month, the car mostly sits in the garage costing you money.

Many teams mix both: self-host a strong open model for the steady bulk of traffic, and use an API for spikes, the hardest requests, or as a fallback.

Takeaway: Self-hosting pays off when your GPUs stay busy.

Batch and async: not everything is urgent

Work nobody is waiting on shouldn't compete with work somebody is.

Plenty of AI work has no one waiting on it: summarising last year's tickets, tagging a product catalogue, generating embeddings, nightly reports. Running it through the real-time API means paying full price and using up the rate limit your live users need.

  • Batch APIs take a big file of requests and return results within hours, typically at about half the price.
  • Batch traffic usually has its own limits, so it doesn't crowd out live users.
  • Design for it: queue background work, process results asynchronously, and tell users "we'll email you when it's ready" where that's fine.

Think of it like this: Sending a parcel by standard post instead of same-day courier. If it doesn't need to arrive today, why pay for today?

Takeaway: Split real-time work from work that can wait.

When the provider goes down

Retries handle blips. Outages need somewhere else to go.

Model providers have outages and slowdowns like any other service. If your product calls one provider for every request, their bad day is your bad day.

  • Timeouts: never wait forever. Give up on a call after a sensible limit so one slow request doesn't hold everything up.
  • Retries with exponential backoff: try again after a short wait, doubling the wait each time. Great for brief blips.
  • Retry storms: during a real outage, everyone retrying multiplies the load on a provider that is already struggling, and makes it worse.
  • Failover: send the request to a different provider or your own model when the first keeps failing.
  • Circuit breaker: after enough failures, stop calling the broken provider for a while and go straight to the fallback.

Think of it like this: If the shop is closed, knocking louder doesn't help, and neither does the whole street knocking. You go to the other shop.

The backup doesn't need to be as good as the primary. A slightly weaker model that answers is better than a perfect one that returns errors. That's graceful degradation.

Takeaway: Have a plan B before you need it, and cap your retries.

Module 8: Agents and multi-agent systems (Advanced)

Letting models take actions, splitting work across agent teams, and keeping them on a leash.

Agents and tools

Letting the model act, not just talk, and keeping it on a leash.

A plain model can only produce text. If a user asks "where is my order?", the honest answer needs a lookup. Without a tool, the model will invent a plausible status.

An agent runs the model in a loop: think, call a tool (look up the order, issue a refund), read the result, decide what to do next, and repeat until done. Each turn of the loop is another model call, with a longer prompt each time.

Think of it like this: An intern with a phone and a company card. Far more useful than one who can only write memos, but you set a spending limit, because sometimes they'll keep calling the same wrong number all afternoon.

  • Agents multiply cost and latency: a 5-step task is roughly 5 model calls.
  • Some runs get stuck repeating themselves. A step cap stops them failing slowly and expensively.
  • Set the cap just above what real tasks need.

Takeaway: A step budget is a cost control, not just a safety net.

When one agent isn't enough

Split big jobs across a team of focused agents.

A single agent handling a big task ("compare these five vendors") does everything in one long loop. Every search result piles into the same prompt, so it gets slower with every step, and the early details get buried.

A multi-agent system splits the work. The common patterns:

  • Orchestrator and workers. One agent plans and hands sub-tasks to workers that run in parallel, then combines their results. Best for research and anything that splits cleanly.
  • Hand-offs between specialists. A triage agent passes the conversation to a billing agent or a technical agent, each with its own instructions and tools.
  • Reviewer (critic). A second agent checks the first one's work and sends it back if something's wrong.

Think of it like this: One person researching five companies alone versus a lead who gives each company to a different analyst, then writes the summary from their notes. The team finishes sooner and nobody has to hold everything in their head.

The key benefit is context isolation: each worker sees only its own slice of the problem, so its prompt stays small and focused. That's where both the speed and the quality gains come from.

Takeaway: Use multiple agents when a task splits into independent parts, not by default.

Making agent teams work

More agents, more calls, more ways to fail.

Agent teams are powerful and easy to overdo. The costs grow faster than the agent count suggests.

  • Cost multiplies. A planner, four workers making five calls each, and a combiner is over 20 model calls for one question.
  • Hand-offs lose detail. Each agent passes a summary on, and summaries drop things. More agents means more cracks.
  • Agents loop. Two agents can bounce a task back and forth ("can you clarify?") until something stops them. Without a cap on rounds, a loop silently burns your budget.
  • Debugging gets harder: the mistake might be in any agent, or in the gaps between them.

What works in practice: keep teams small (about one worker per real sub-task), give each agent a narrow job and only the tools it needs, add a reviewer to catch what the hand-offs dropped, cap the rounds, and log every hand-off so you can trace failures.

For risky actions (sending money, deleting data, emailing customers), add a human-in-the-loop step: the agent proposes, a person approves.

Think of it like this: Adding people to a late project can make it later. Each new person adds meetings and hand-offs. Agents are the same.

Takeaway: Small teams, narrow jobs, a reviewer, and a hard stop.

Module 9: Safety (Advanced)

Attacks on your prompt, including ones hidden in what your system reads, the layers that stop them, and keeping personal data safe.

Prompt injection and guardrails

Users can try to rewrite your instructions. Layer your defenses.

To a model, your instructions and the user's message are both just text in the same prompt. A prompt injection is a message written to override your instructions: "ignore previous instructions and…". Models resist this better than they used to, but not reliably.

  • Input guardrail: a fast classifier that screens messages before they reach the model.
  • Output judge: a second model that checks the answer before it ships. It catches attacks that slipped through, and many hallucinations too.
  • Every check has false positives: real users who get blocked. Stricter isn't automatically better.

Think of it like this: Airport security has a scanner at the door and a check at the gate. Neither is perfect, so you use both, and you tune them so the queue still moves.

Takeaway: Safety is layered, and every layer costs something.

Indirect prompt injection

The attack hides in what your system reads, not in what the user types.

A language model reads its whole context as one stream of text. Your instructions, the user's message, a retrieved document, an email, a web page, the output of a tool: to the model it's all just text, and it can't reliably tell which parts are instructions and which are data.

So an attacker doesn't need to talk to your chatbot. They put instructions where your system will read them: hidden white text in an email, a comment in a web page, a line in a shared document. When your agent reads it, the instructions arrive with the same authority as everything else. An input guard never sees them, because it only checks what the user typed.

How bad it gets depends on three things. Security researchers call the combination the lethal trifecta:

  • Access to private data (inboxes, files, customer records).
  • Exposure to untrusted content (email, the web, uploaded documents).
  • A way to send data out (email, web requests, posting messages).

With all three, a hidden instruction can turn into "forward the invoices to this address". Remove any one and the damage shrinks. There's no single fix, so you defend in layers:

  • Mark external content as untrusted data: wrap it clearly, strip hidden text, and tell the model never to follow instructions inside it. Helps a lot, never 100%.
  • Least privilege: give each agent only the tools and permissions its job needs. A read-only agent can be fooled, but can't send anything.
  • Approval for risky actions: sending, paying, deleting and changing records go through a policy check and, when unusual, a person.
  • Keep secrets out of the prompt: anything in the system prompt can be coaxed out (a system prompt leak).

Think of it like this: A new assistant opening the post. A letter says "Please wire £10,000 to this account, signed: your boss." A good assistant knows that instructions don't come by post, and that wires need a second signature anyway.

Takeaway: Assume some injected instructions will get through. Design so they can't do much when they do.

Privacy and personal data

Anything in a prompt leaves with the prompt.

Every prompt you send to an API is data you're handing to another company: the user's message, the retrieved documents, the chat history. If those contain names, emails, health or financial details, you're moving personal data, with all the rules that come with it.

  • Redact before sending: detect personal details, swap them for placeholders ("[NAME_1]"), and put the real values back into the answer afterwards. The model rarely needs the actual name to help.
  • Minimise: don't retrieve or include personal data the task doesn't need.
  • Check retention and training settings with your provider, and where the data is processed (residency).
  • For the most sensitive workloads, self-host so the data never leaves your infrastructure.

Think of it like this: Blacking out names on a document before you send it to an outside consultant.

Takeaway: Send the model what it needs, not everything you have.

Module 10: Thinking like an AI engineer (Advanced)

Measuring quality, and the debugging loop that ties it all together.

Evals: you can't fix what you can't see

Measure answer quality before and after every change.

Your dashboard shows speed, cost and errors for free. It does not show whether answers are right. A change that halves your bill can quietly double your wrong answers, and nothing turns red.

Evals fix that. There are two kinds, and you want both.

  • Offline evals: a fixed test set of real questions with known good answers (a golden dataset). Run it before shipping any change, like unit tests for quality.
  • Online evals: a judge model scores a small sample of live answers against their sources, so you notice when real traffic drifts away from your test set.
  • Track the same few numbers every time: accuracy, hallucination rate, retrieval recall. Compare against the last version.

Think of it like this: A restaurant that only tracks how fast plates leave the kitchen. Service has never been quicker. Nobody has tasted the food.

Evals also make debugging honest. Instead of tweaking prompts until something "feels better", you change one thing, rerun, and see the number move, or not.

Takeaway: Make quality measurable first. Then optimise.

Building evals you can trust

A green dashboard is only as honest as its test set and its judge.

Having evals isn't the same as having good evals. The two places they go wrong are what you test and who decides an answer is right.

  • The test set. The 50 examples written at launch are usually easy, clean and stale. Real users ask harder, messier and newer things. Sample real traffic into your test set and refresh it regularly. Include the failures that support tickets reveal.
  • Exact match. Cheap and objective for things like IDs and labels, but it marks a correct answer wrong just because it's worded differently.
  • LLM-as-judge. Scales to thousands of answers, but has biases: it tends to prefer longer and more confident answers, and can miss fluent, plausible mistakes. Check it against human ratings on a sample, so you know how often it's wrong.
  • Human review. The most accurate and the most expensive. Use it to calibrate the automatic judges, not to grade everything.

Run evals in two places. Offline, before shipping: every prompt, model or retrieval change runs the regression suite, like unit tests. Online, after shipping: a judge scores a sample of live traffic so you notice drift. When the two disagree, or when evals disagree with user complaints, trust the complaints and fix the evals.

Think of it like this: A student who only ever sits the same practice exam will ace it. That tells you about the practice exam, not about the student.

Takeaway: Test on real traffic, check your judge against humans, then believe the numbers.

When the model changes under you

Your model is a dependency. Pin it.

Providers improve their models constantly, and many offer a "latest" alias that always points at the newest version. Convenient, until a new version handles your carefully tuned prompt differently: more verbose, a different refusal style, slightly different JSON.

  • Pin a specific, dated model version in production.
  • When a new version comes out, run your evals on it first, compare the numbers, then switch on purpose.
  • Watch provider deprecation dates: pinned versions eventually retire, so upgrading is a scheduled job, not a surprise.

Think of it like this: You wouldn't let a library auto-update in production without running your tests. A model is a dependency too, just a fuzzier one.

Takeaway: Pin versions, upgrade deliberately, let evals decide.

Binding pressure: how to debug any AI system

Find the one limit that hurts most. Fix only that. Repeat.

Real systems have many weaknesses at once, but at any moment one of them hurts more than all the others. Fixing anything else barely moves the numbers.

  • Look at the metrics against your goals.
  • Look at the individual requests that failed and ask why.
  • Name the single limit behind most of those failures.
  • Fix that one thing, then measure again. The binding pressure will move.

Think of it like this: A chain is only as strong as its weakest link. Polishing the strong links does nothing.

Takeaway: This loop (measure, name the pressure, fix, re-measure) is the actual skill. The simulator exists to train it.

AI glossary in plain English (129 terms)

LLM (Large language model)
A program trained on huge amounts of text that writes by predicting the next most likely word, over and over. Analogy: Autocomplete on your phone, scaled up until it can write essays and code. Why it matters: It's the part of the system that writes the answer. Everything else decides what it sees.
Token
The unit models read and write in. Roughly ¾ of an English word; "unbelievable" might be 3 tokens. Analogy: Like syllables for a machine. Why it matters: Pricing, speed and limits are all measured in tokens.
Prompt
Everything you send the model in one request: instructions, retrieved documents, conversation history and the user's message. Analogy: The briefing pack you hand someone before they start a task.
System prompt
The hidden instructions at the top of the prompt that set the model's role and rules ("You are a support assistant. Only answer from the sources."). Analogy: The job description pinned above the desk. Why it matters: Attackers try to override or reveal it.
Inference
Running a trained model to get an answer. Every request you make is an inference call. Analogy: Training is going to school; inference is doing the job.
Context window
The maximum number of tokens a model can read in one request, including the prompt and its answer. Analogy: The size of the desk: only so many pages fit on it at once. Why it matters: Go over it and the request fails or gets cut off.
Input vs output tokens
Input tokens are what you send; output tokens are what the model writes. Output is usually several times more expensive. Why it matters: Long answers cost more than long prompts, token for token.
Training data
The text a model learned from before it was released. It doesn't include your private documents.
Knowledge cutoff
The date the model's training data stops. It knows nothing that happened after, unless you give it the information. Analogy: Someone who's been on a remote island since that date.
Temperature
A setting that controls how random the model's word choices are. Low (0–0.2) is focused and repeatable; high (0.7–1) is varied and creative. Analogy: Low temperature is a careful accountant; high is a jazz improviser. Why it matters: Too high on extraction gives different answers to the same question; too low on writing makes everything sound the same.
Fine-tuning
Training an existing model further on your own examples so it picks up a style or task. It's good for teaching behaviour, not for adding facts that change often. Analogy: Sending an employee on a course, versus handing them the manual (RAG). Why it matters: A fine-tuned small model can beat a large general one on a narrow task, cheaply.
RAG (Retrieval-augmented generation)
Search your documents for relevant pieces first, paste them into the prompt, then ask the model to answer from them. Analogy: An open-book exam instead of a closed-book one. Why it matters: The standard way to make a model answer correctly about your own data.
Embedding
A list of numbers that represents the meaning of a piece of text. Texts that mean similar things get similar numbers. Analogy: Coordinates on a map of meaning: "car" and "vehicle" are neighbours; "car" and "banana" are far apart.
Vector database
A database built to find the stored embeddings closest to a new one, quickly, across millions of items. Analogy: A librarian who finds books by what they're about, not their exact title.
Searching by meaning instead of exact words, so "reset my password" finds a page titled "Recovering account access".
Chunk
A small piece of a larger document, created so search can return just the relevant part instead of a whole 90-page PDF. Analogy: Cutting a book into index cards. Why it matters: Too small splits answers apart; too big blurs meaning and wastes tokens.
Top-K
How many of the best-matching chunks you retrieve for each question (K = 3, 5, 10…). Why it matters: Higher K catches more answers but adds cost and noise.
BM25 (Keyword search)
A classic ranking method that scores documents by how well their exact words match the query. Analogy: Ctrl+F with good judgement. Why it matters: Great for codes, names and IDs that embeddings blur.
Running keyword search and semantic search together and combining the results. Why it matters: Covers both "what does E1043 mean" and "my device keeps restarting".
Reranker
A model that reads each retrieved chunk alongside the question and re-scores how relevant it really is, so you can keep only the best few. Analogy: A first search pulls 12 books off the shelf; an expert skims them and hands you the best 4.
Recall (retrieval)
The share of questions where retrieval actually found the chunk containing the answer. Why it matters: If recall is 70%, up to 30% of answers are built on the wrong pages.
Grounding
Making the model base its answer on specific sources you provided, rather than on memory.
Stateless
A model keeps nothing between requests. Every call starts from a blank slate; anything it should "remember" has to be in the prompt again. Analogy: An expert who forgets every phone call the moment it ends. Why it matters: It's why chat apps resend history, and why long chats get expensive.
Chat history
The earlier messages of a conversation, resent with each new message so the model knows what was said. Why it matters: It grows every turn, and you pay for all of it every turn.
Conversation memory
The strategy that decides which parts of a conversation go back into the prompt: everything, the latest turns, a summary, or retrieved facts. Analogy: Deciding which notes to bring to a meeting.
Sliding window
Keeping only the last N turns of a conversation in the prompt and dropping everything older. Analogy: A whiteboard you keep erasing from the top to make room. Why it matters: Cheap and predictable, but forgets anything older than the window.
Rolling summary
Regularly compressing older turns into a short summary that travels with the conversation, while the latest turns stay word for word. Analogy: Meeting minutes instead of the full recording. Why it matters: Keeps the gist in few tokens, but specific details like numbers and names can get lost.
Long-term memory (Memory retrieval)
Storing past turns, or facts pulled out of them, in a searchable store, and fetching only the ones relevant to the current message. Analogy: An assistant's notebook: they don't read it all out, they flip to the page they need. Why it matters: Keeps prompts small while still remembering details from long ago.
Prompt caching
Providers can store the unchanging beginning of a prompt (system prompt, long documents) and reuse it across requests for less money and time. Analogy: Keeping the reference book open on your desk instead of fetching it from the shelf every time. Why it matters: Cuts cost for apps that resend the same big prefix. Different from a semantic cache, which skips the model entirely.
Reasoning model (Thinking mode)
A model (or mode) that writes out hidden step-by-step reasoning before giving its final answer. Analogy: Showing your working on a maths exam. Why it matters: Much better on hard problems; slower and pricier because the thinking tokens are paid for.
Thinking budget
A cap on how many tokens a reasoning model may spend thinking before it answers. Why it matters: The main dial between accuracy and cost/latency for reasoning models; gains flatten out at higher budgets.
Test-time compute
Spending more computation while answering (thinking longer, trying several answers) instead of training a bigger model. Why it matters: A newer way to buy accuracy: pay per question for extra effort, only when you need it.
Chain of thought
Having a model reason step by step before answering, either by prompting it to or because it's trained to. Analogy: Talking yourself through a problem out loud.
Structured output (JSON mode)
Making the model return data in an exact format, usually JSON matching a schema, so code can use it directly. Why it matters: Without it, a small share of answers break format, which at scale means constant parser crashes.
JSON schema
A precise description of the shape your data must have: which fields, which types, which are required. Analogy: The blank form with labelled boxes.
Constrained decoding
While the model writes, only allowing tokens that keep the output valid against a schema or grammar. Why it matters: Guarantees the format by construction, instead of hoping and checking afterwards.
Output validation
Checking a model's answer against the expected format (and sometimes business rules) before your code uses it, and retrying or failing gracefully if it's wrong.
Ingestion pipeline
The process that gets documents into your index: load, convert to text, split into chunks, embed, store, and keep it updated. Why it matters: Many "retrieval" problems are really ingestion problems.
Re-indexing
Updating the index when documents change, are added, or are deleted, on a schedule or as soon as they change. Why it matters: Determines how out of date your answers can be.
Document parsing
Turning files (PDFs, slides, spreadsheets, web pages) into clean text, ideally keeping tables, headings and layout intact. Analogy: Transcribing a document by hand: sloppy transcription loses the table rows.
Data freshness (Stale index)
How up to date your index is compared with the real documents. A stale index returns old versions. Why it matters: Stale answers are confident and well-sourced, so judges and users rarely catch them.
Cache hit
When the data you need is already in a cache, so it can be reused instead of recomputed. Why it matters: Hit rate is what decides how much any cache actually saves.
Batch API
A way to send many requests at once and collect the results later (usually within 24 hours), typically at about half the price. Why it matters: Cheap, and it keeps background work from eating your real-time rate limit.
Async job (Background job)
Work that runs in the background without anyone waiting on a screen for it, like nightly reports or bulk tagging. Analogy: Leaving the dishwasher running overnight.
Pretraining
The first and biggest training stage: the model reads a huge amount of text and learns to predict the next token. Why it matters: Where general knowledge and skills come from, and why the model knows nothing after its cutoff or inside your company.
Parameters (Weights)
The billions of numbers inside a model that training adjusts. "70B" means about 70 billion of them. Analogy: The strength of every connection in a giant web. Why it matters: More parameters can hold more knowledge and skill, but need more memory and compute to run.
Instruction tuning
Training a pretrained model on many examples of instructions with good responses, so it learns to follow requests instead of just continuing text.
RLHF (Preference training)
Reinforcement learning from human feedback: people compare pairs of answers, and the model is nudged towards the ones they preferred. Analogy: A manager reading two drafts and saying "more like this one".
Distillation
Training a smaller model to imitate a bigger one's outputs, so it's cheaper and faster while keeping much of the skill. Analogy: An apprentice learning by copying a master's work.
Few-shot prompting
Including a handful of worked examples in the prompt to show the model what you want. Why it matters: Quick and training-free, but the examples are paid for on every request.
Model version (Pinning)
The specific, dated release of a model you call. Aliases like "latest" move to new versions automatically; a pinned version doesn't. Why it matters: New versions can change behaviour; pinning makes upgrades deliberate.
PII (Personal data)
Personally identifiable information: anything that identifies a person, like names, emails, phone numbers, IDs, or health and financial details. Why it matters: Sending it to third parties brings legal duties (GDPR, HIPAA and others).
Redaction
Finding personal or sensitive details and replacing them with placeholders before the text is sent anywhere. Analogy: Blacking out names before sharing a document.
Data retention
How long a provider keeps your prompts and responses, and whether they may use them for training. Why it matters: Often configurable; check it before sending anything sensitive.
Data residency
Which country or region your data is stored and processed in. Why it matters: Some regulations and customers require data to stay in a specific region, such as the EU.
Per-user limits
Caps on how much a single account can use: requests per minute, tokens or spend per day. Why it matters: Stops one script from burning your budget and your provider rate limit.
Quota
A usage allowance over a period, like 100,000 tokens per user per day.
Multimodal
Able to take in (or produce) more than text: images, audio, video, documents. Why it matters: Images and audio become tokens too, and can be surprisingly expensive.
Speech-to-text (STT / transcription)
Turning spoken audio into text. Streaming versions transcribe while the person is still talking.
Text-to-speech (TTS)
Turning text into spoken audio. Streaming versions start speaking before the full text exists.
Voice latency (Time to first audio)
How long after the user stops talking until they hear the reply begin. About a second feels natural; several seconds feels broken.
Sampling
How the model picks each next token from its list of probable options. Temperature and top-p are the sampling settings.
Top-p (Nucleus sampling)
Only pick the next token from the smallest group of likely options that together add up to p (say 90%) of the probability. Cuts off the weird long tail. Why it matters: An alternative or companion to temperature; usually tune one, not both.
Determinism
Getting exactly the same output for the same input. Temperature 0 gets close, but hosted models aren't perfectly deterministic. Why it matters: If you need the identical answer again, store or cache it rather than regenerating.
Judge bias
The systematic mistakes an LLM judge makes: favouring longer, more confident or more familiar-sounding answers, and missing fluent errors. Why it matters: An uncalibrated judge can make a bad system look great.
Offline vs online evals
Offline evals run a fixed test set before you ship. Online evals score a sample of live traffic after you ship. Why it matters: Offline catches regressions; online catches drift away from what you tested.
Regression suite
The set of evals that runs automatically on every prompt, model or retrieval change, and blocks the change if quality drops. Analogy: Continuous integration tests, for answer quality.
Indirect prompt injection
Instructions hidden in content the system reads by itself (an email, a web page, a document, a tool result) rather than typed by the user. Why it matters: Input guards don't see it, and agents with tools can be made to act on it.
Lethal trifecta
The dangerous combination for an AI agent: access to private data, exposure to untrusted content, and a way to send data out. Why it matters: With all three, one hidden instruction can leak data. Remove any one leg to cut the risk.
Least privilege
Giving each agent or tool only the permissions its job needs, and nothing more. Analogy: The intern gets a key to the post room, not to the safe.
Untrusted content
Anything that didn't come from you: user messages, emails, web pages, uploaded files, tool results. It should be treated as data to read, never as instructions to follow.
Data exfiltration
Getting private data out of a system, for example tricking an agent into emailing it, or into putting it in a link or image URL it loads.
System prompt leak
Getting a model to reveal its hidden instructions. Assume it can happen, so never put secrets or keys in a prompt.
Prefill
The first phase of a model call: reading the whole prompt at once. GPUs do this in parallel, so it's fast. Analogy: Skimming a page in one glance. Why it matters: Long prompts add surprisingly little latency compared with long answers.
Decode
The second phase: writing the answer one token at a time, each depending on the last. It can't be parallelised, so it's the slow part. Analogy: Writing a page by hand, word by word. Why it matters: Output length, not prompt length, mostly decides how long a call takes.
KV cache
The model's working memory of everything it has read so far in a request, so it doesn't re-read the whole prompt for every new word. Analogy: Notes in the margin so you don't reread the chapter before each sentence. Why it matters: It's what makes prompt caching possible, and it takes up GPU memory.
Max output tokens
A cap on how long the model's answer can be. Why it matters: One of the cheapest ways to cut latency and cost, since writing is the slow, expensive part.
GPU
The chip that runs AI models: thousands of small cores doing maths in parallel, plus fast memory that holds the model. Why it matters: GPU memory decides which models fit; GPU speed decides how fast they write.
Batching
Running many requests through the model at the same time on one GPU. Analogy: A bus instead of a taxi per passenger. Why it matters: Multiplies total throughput, but each request is written a bit more slowly.
Continuous batching
Letting new requests join a running batch as soon as a slot frees up, instead of waiting for the whole batch to finish. Analogy: A bus that picks up passengers at every stop rather than waiting at the depot until it's full.
Quantization
Storing a model's numbers with fewer bits (16 → 8 → 4) so it's smaller and faster. Analogy: Saving a photo as a smaller JPEG: much lighter, mostly looks the same, artefacts if you push it too far. Why it matters: More speed and capacity per GPU for a small quality cost; 4-bit can noticeably hurt accuracy.
Throughput
How much work a system completes per second, for example total tokens written across all requests. Why it matters: Different from latency: you can raise throughput while making each request slower.
Speculative decoding
A small, fast model drafts several tokens ahead, and the big model checks them all in one pass, keeping the ones it agrees with. Analogy: An assistant drafts the email; the expert just approves or fixes it. Why it matters: Speeds up writing without changing the big model's answers.
Open-weights model
A model whose trained weights are published, so you can download it and run it on your own hardware. Why it matters: Makes self-hosting possible: full control, data stays with you.
Self-hosting
Running a model on GPUs you rent or own, instead of calling a provider's API. Analogy: Owning a car instead of taking taxis. Why it matters: Cheaper at high, steady traffic; more expensive when GPUs sit idle, and you own the operations.
GPU utilization
How busy your GPUs are compared with what they could handle. Why it matters: Low means paying for idle hardware; near 100% means queues and timeouts. Aim for busy but not full.
Timeout
The longest you'll wait for a call before giving up on it. Why it matters: Without one, a single stuck call can hold up a user, or your whole system.
Retry
Trying a failed call again, usually after a short wait. Why it matters: Fixes brief blips; makes real outages worse if overused.
Exponential backoff
Waiting longer before each retry (say 0.25s, 0.5s, 1s, 2s), usually with a little randomness so clients don't retry in sync. Analogy: Giving a busy friend more time between each call instead of ringing non-stop.
Retry storm
When a struggling service gets hammered by everyone's retries at once, pushing it from slow to completely down. Why it matters: The reason retries need caps, backoff and circuit breakers.
Failover
Automatically switching to a backup (another provider or your own model) when the primary keeps failing. Analogy: A hospital's backup generator kicking in during a power cut.
Circuit breaker
After enough failures, stop calling a broken service for a while and go straight to the fallback, then test it again later. Analogy: The breaker in your fuse box that trips so a fault doesn't burn the house down.
Latency
How long a request takes from the user asking to the user getting an answer.
Time to first token (TTFT)
How long until the first word of the answer appears on screen. Why it matters: This is what users actually feel as "speed".
Streaming
Showing the answer word by word as the model writes it, instead of waiting for the whole thing. Analogy: Bread arriving while the main course cooks.
p50 / p99 (Percentiles)
p50 is the typical request (half are faster). p99 is the slow tail: 1 in 100 requests is slower than this. Why it matters: Averages hide the users having a terrible time.
Rate limit
A cap the provider puts on how much you can use a model per minute. Exceed it and requests are rejected with HTTP 429.
TPM (Tokens per minute)
The most common kind of rate limit: the total tokens you can send to a model each minute. Why it matters: Long prompts hit it fast, even at low request counts.
Semantic cache
Storing answers and reusing them when a new question means the same thing as an old one, even if worded differently. Analogy: An FAQ that recognises the question however it's phrased. Why it matters: A hit skips the model entirely: near-zero cost and instant.
Model routing
Sending each request to the cheapest model that can handle it, keeping expensive models for hard requests. Analogy: Hospital triage.
Cost per request
What one user question costs you end to end: all the tokens through every model call, plus search and checks.
Observability
Recording what happened inside each request (prompts, retrieved chunks, model calls, timings, cost) so you can see why something went wrong. Analogy: A flight recorder for every request.
Agent
A model running in a loop that can decide to use tools, look at the results, and keep going until a task is done. Analogy: An assistant who can make calls and click buttons, not just write memos.
Tool calling (Function calling)
The model outputs a structured request like "lookup_order(48213)"; your code runs it and hands back the result.
Agent loop
The think → act → observe cycle an agent repeats. Each cycle is another model call. In teams, "looping" also means agents bouncing work back and forth. Why it matters: Cost and latency grow with every step, so loops need a hard cap.
Step budget (Max steps)
The most loop cycles an agent may run before it must stop. Why it matters: Stops stuck agents from burning money, but too low and real tasks fail.
MCP (Model Context Protocol)
An open standard for connecting models to tools and data sources, so one integration works across many AI apps. Analogy: USB-C for AI tools.
Multi-agent system
Several AI agents, each with its own instructions, tools and context, working together on one task. Analogy: A team of specialists instead of one generalist. Why it matters: Faster and more focused on big tasks, but more calls, more hand-offs and more ways to fail.
Orchestrator (Planner / supervisor agent)
The agent that breaks a task into parts, hands them out to other agents, and combines what comes back. Analogy: A project lead with a team of analysts.
Worker agent (Sub-agent)
An agent given one narrow piece of a bigger task, often running in parallel with others. Why it matters: Its prompt holds only its slice of the problem, so it stays small and focused.
Hand-off
Passing work, and a summary of it, from one agent to another. Analogy: A shift change at a hospital: the next nurse only knows what was written in the handover notes. Why it matters: Every hand-off can drop details; fewer, cleaner hand-offs mean fewer gaps.
Context isolation
Giving each agent only the information its own part of the task needs, instead of everything. Why it matters: Smaller prompts are faster, cheaper and less likely to bury the important detail.
Reviewer agent (Critic)
An agent whose only job is to check another agent's output and send it back if something is wrong. Analogy: An editor reading the draft before it's published.
Human in the loop
Requiring a person to approve an agent's proposed action before it happens, usually for risky or irreversible steps. Analogy: The intern drafts the refund; the manager clicks approve.
Tool permissions
Limiting which tools each agent can use, and what those tools are allowed to do. Why it matters: An agent that can only read can't accidentally delete; a narrow toolset is also easier for the model to use well.
Prompt injection
Text crafted to override your instructions, either typed by a user (direct) or hidden in a document, email or web page the model reads (indirect). Analogy: A note slipped into the pile saying "the boss says ignore all previous rules".
Jailbreak
A prompt designed to get a model to break its safety rules or ignore its role.
Guardrail
Any automatic check placed before or after the model to block unsafe inputs or outputs.
LLM-as-judge
Using a second model to grade the first model's answer: is it supported by the sources, is it safe, is it on topic? Why it matters: Catches problems, but must wait for the full answer, so it adds time and breaks streaming.
False positive
When a check flags something harmless, like a guardrail blocking a real customer's normal question. Why it matters: The hidden cost of strict safety settings.
Hallucination
A confident, fluent answer that is wrong or made up. Analogy: Confident directions to a street that doesn't exist. Why it matters: Usually caused by missing information, not a lack of intelligence.
Lost in the middle
Models pay less attention to information buried in the middle of a long prompt than to what's at the start or end. Why it matters: Stuffing in more chunks can make answers worse, not better.
Eval (Evaluation)
A repeatable way to score answer quality: run a test set with known good answers, and have a judge score a sample of live traffic. Analogy: Unit tests, but for answer quality. Why it matters: Without evals, every change is a guess.
Golden dataset (Test set)
A fixed collection of real questions with answers you've checked are correct, used to score every version of your system. Analogy: The answer key for a practice exam you give every new version. Why it matters: Lets you compare versions on the same questions, so improvements are real.
Regression
When a change makes something that used to work worse, often without anyone noticing at first. Why it matters: Cost and speed optimisations are the classic source of silent quality regressions.
Authentication (Auth, API keys)
Checking who is calling before doing any work: a valid key, token or login. Calls without one are turned away at the door. Analogy: The ticket check at the entrance, before anyone reaches the show. Why it matters: A key shipped inside an app or a web page is public. Without auth on your own endpoint, anyone who finds it uses your models on your bill.
Tracing (Request traces)
Recording each step a request went through (prompt, retrieved chunks, model calls, timings) so you can replay why an answer came out wrong. Analogy: A flight recorder you can play back after something goes wrong. Why it matters: Wrong answers don't throw errors. Without traces, debugging a complaint means guessing. Keep every failure, sample the rest, and redact personal data before storing prompts.
Fairness evaluation (Cohort evals)
Measuring answer quality separately for different groups of users (by language, region, device, account type) instead of only on average. Analogy: Checking every classroom's results, not just the school average. Why it matters: A good average can hide one group getting much worse answers, often because the data, embeddings or prompts were built for the majority.
Binding pressure
The single limit hurting your system the most right now. Fixing anything else barely helps. Analogy: The weakest link in a chain.