The whole course on one page
Every lesson's key points, grouped by chapter, to skim before a build or print for revision.
Track 1
Gen AI foundations
00Start here
0Your first agent in 15 minutes5 lessons
0.1 Make your first call in the Playground
- A request names a model, a max_tokens limit and a list of messages. The reply has content, a stop_reason and usage.
- The model keeps no memory between requests. Your code sends the conversation every time.
- The Playground simulates the API in your browser, so keys start with sk-ant-sim- and nothing costs money.
0.2 Give the model one tool
- A tool is a function you describe to the model: a name, a description of when to use it, and a JSON schema for its input.
- The model never runs your tool. It replies with a tool_use block, and your code runs the function.
- The description matters more than the code: it is all the model sees when choosing.
0.3 Watch the loop in the trace
- An agent is a loop: send the conversation, run any tools the model asks for, send the results back, and stop at end_turn.
- Each tool result goes back in a user message as a tool_result block, matched to the call by tool_use_id.
- Always cap the loop. A model that keeps calling tools will not stop on its own.
0.4 How would you test this?
- Before changing a prompt or a tool, write down what good looks like as test cases with pass rules.
- Cover the normal case, an edge case and a failure case.
- Run the same cases after every change. A fix that helps one case can break another.
0.5 Pick your path: exam, builder or no-code
- The exam path follows the Claude Certified Architect domains, then the scenarios and mock exams.
- The builder path covers designing and shipping agents with any model, Claude as the example.
- The no-code path explains how these systems work, cost and fail, without writing code.
1Engineering prerequisites for AI apps7 lessons
1.1 Python async and await for concurrent calls
- Model calls spend almost all their time waiting on the network. async code lets your program start other calls during that wait.
- await pauses one coroutine and hands control back to the event loop. Nothing runs in parallel on the CPU; the waiting overlaps.
- asyncio.gather runs many coroutines together and returns results in the order you passed them, not the order they finished.
- Always cap concurrency with a semaphore, or a burst of calls will hit the provider's rate limits.
1.2 Pydantic models and runtime validation
- Type hints are not checked when the program runs. A Pydantic model checks real data against them and raises a clear error when it does not fit.
- Validate everything that crosses a boundary: model output, tool inputs, HTTP bodies and config.
- A validation error is useful feedback. Send the error text back to the model and ask for a corrected reply, with a retry cap.
- Pydantic can export a JSON Schema from the same model, so the shape you ask for and the shape you check never drift apart.
1.3 Environments and packages: venv, uv and poetry
- A virtual environment is a folder with its own Python packages, so one project's upgrade cannot break another.
- pyproject.toml lists what you depend on. A lock file records the exact versions that were installed, so every machine gets the same set.
- venv plus pip is built in. uv and Poetry add dependency resolution, lock files and faster installs on top of the same idea.
- Never commit the environment folder or a .env file. Commit pyproject.toml and the lock file.
1.4 HTTP APIs: methods, status codes and JSON Schema
- A request has a method (GET reads, POST creates or runs something), a URL, headers and an optional JSON body.
- Status codes come in families: 2xx worked, 4xx your request was wrong, 5xx the server had a problem.
- Retry 429 and most 5xx errors. Do not retry other 4xx errors: fix the request, the key or the permissions instead.
- JSON Schema describes the shape of a JSON value. Model APIs use it for tool inputs and structured output.
1.5 Authentication: API keys and bearer tokens
- An API key or bearer token is a password for software. Whoever holds it can spend your quota and read what it can read.
- Send it in a header over HTTPS. Load it from an environment variable or a secret manager, never from source code.
- Never ship a provider key to a browser or mobile app. Put a small backend in between that holds the key and checks the user.
- If a key leaks, revoke it first, then rotate it and look at usage. Deleting the commit is not enough.
1.6 Streaming with server-sent events
- Server-sent events (SSE) is a simple one-way stream over a normal HTTP response. The server keeps the connection open and writes text events as they happen.
- Each event is a few lines such as event: and data:, ended by a blank line. Model APIs put a small JSON object in each data line.
- Streaming does not make generation faster. It shows the first words sooner, which is what users notice.
- Your code must join the deltas, watch for the final stop event and handle errors that arrive mid-stream.
1.7 Retries with exponential backoff and jitter
- Retry only transient failures: 429, 5xx, overload errors, timeouts and dropped connections. Never retry a 400 or 401 unchanged.
- Exponential backoff doubles the wait each attempt: 1, 2, 4, 8 seconds, up to a cap and a maximum number of attempts.
- Jitter makes each client wait a random part of that delay, so a crowd of clients does not retry in the same instant.
- If the server sends retry-after, wait at least that long. It knows more than your formula does.
01Gen AI concepts
2What an LLM is6 lessons
2.1 From text to tokens
- Models read tokens, not characters or words.
- A token is often a word piece; English averages roughly 3 to 4 characters per token.
- Token counts drive context limits, speed and cost.
2.2 Next-token prediction
- A model outputs a probability for every possible next token.
- Generation is a loop of predict, sample, append.
- Generation stops at an end-of-turn token, a stop sequence or max_tokens.
2.3 The transformer and attention, in pictures
- Transformers process every token in the context in parallel.
- Attention lets each token weigh the relevance of every other token.
- Stacked layers build up meaning from surface patterns to abstract ideas.
2.4 Why the same prompt can give different answers
- Sampling from a distribution makes output vary between runs.
- Lower temperature makes output more focused and repeatable, not more correct.
- Design for variation with clear instructions, examples, validation and evals.
2.5 Tokenizer algorithms: BPE, WordPiece and SentencePiece
- Subword tokenizers learn their vocabulary from data. They start from small units and repeatedly merge pieces that often appear together.
- BPE merges the most frequent adjacent pair. WordPiece picks the merge that most improves the likelihood of the training text. Both mark word boundaries in their own way.
- SentencePiece treats the input as a raw character stream, spaces included, so it works for languages that do not separate words with spaces.
- Byte-level BPE starts from bytes, so it can encode any text with no unknown tokens.
2.6 Lab: compare token counts across tokenizers
- Different tokenizers give different counts for the same text. The gap is small for plain English and large for code, numbers and many other languages.
- Measure on a sample of your real inputs, not on a rule of thumb. Report tokens per word or per character for each tokenizer.
- Budgets, chunk sizes and cost estimates belong to one model's tokenizer. Re-measure when you switch models.
3Context windows, tokens and cost4 lessons
3.1 What counts against the context window
- The context window holds everything in one request plus the reply: system prompt, tool definitions, messages, tool results, images, documents and the output.
- Each turn resends the whole conversation, so a long chat re-reads its history every time.
- Tool definitions and big tool results are easy to forget and often the largest items.
3.2 Input vs output tokens and how pricing works
- Model APIs charge per token, with separate prices for input and output; output usually costs more per token.
- Cost per request = input tokens x input price + output tokens x output price, plus any cache reads and writes.
- Prices differ by model and change over time; always check the current pricing page.
3.3 Estimating tokens for text, code and images
- Tokens are pieces of words; in English, one token is often around three to four characters, but it varies.
- Code, numbers, non-English text and unusual formatting often use more tokens per character.
- For exact counts, use the token counting endpoint; for images, cost grows with image size.
3.4 What happens when you hit the limit
- If input plus requested output exceeds the context window, the request fails or must be trimmed.
- If the reply reaches max_tokens, it stops early and the stop reason says so; the answer may be cut mid-sentence.
- Handle both: trim or summarise input, raise max_tokens where sensible, and check stop_reason in code.
4Embeddings and semantic search10 lessons
4.1 What an embedding is
- An embedding is a list of numbers that represents the meaning of a piece of text.
- Texts with similar meaning get embeddings that are close together, even with different words.
- Embeddings come from embedding models, which are separate from chat models like Claude.
4.2 Similarity: cosine and dot product
- Cosine similarity measures the angle between two vectors: 1 means same direction. In theory 0 means unrelated, but real embedding models put unrelated texts well above 0.
- Dot product also grows with vector length; for normalised vectors, it equals cosine similarity.
- Scores are relative: compare them within one model and task, rather than trusting a fixed cut-off.
4.3 Keyword search vs semantic search
- Keyword search matches words: great for exact terms, ids and names.
- Semantic search matches meaning: great for paraphrases and natural questions.
- Most production systems combine both (hybrid search).
4.4 Where embeddings show up in real systems
- Embeddings power semantic search, RAG retrieval, deduplication, clustering, classification and recommendations.
- In agents, they help recall relevant memories and pick relevant tools or examples.
- They are a building block: useful alone, and essential inside RAG and memory systems.
4.5 Embedding models and dimensions
- An embedding model is a separate model from the chat model; Claude itself doesn't return embeddings, so you pair it with an embedding provider.
- Dimensions are the length of each vector. More dimensions can hold finer meaning but cost more storage and slower search.
- Some models are trained so you can cut vectors shorter (Matryoshka-style) and keep most of the quality.
- Vectors from different models, or different versions, can't be compared. Changing model means re-embedding everything.
4.6 Chunk, document and query embeddings
- You can embed whole documents, chunks, or both. Chunks give precise matches; document vectors give a coarse first filter.
- A chunk embedded without its context loses meaning; adding a short context line or title helps retrieval.
- Queries are short and documents long, so some models use separate query and document modes.
- Averaging many chunk vectors into one document vector blurs it; it works as a rough filter, not a precise match.
4.7 Multimodal embeddings
- A multimodal embedding model maps images and text into the same space, so a text query can find a picture.
- Models like CLIP learn this by pulling matching image and caption pairs together during training.
- Two routes: embed images directly, or have a vision model describe each image and embed the description.
- Diagrams, scanned forms and screenshots often need text extraction too, because fine print is hard to embed.
4.8 Lab: watch nearest neighbours change
- Nearest neighbours depend on three things: the query vector, what's in the store, and which filters run first.
- Using a raw dot product instead of cosine lets long documents win just for being long.
- Filtering by tenant before ranking is a security control, not a tuning choice.
- Ties need a stable tie-break (such as id) so results don't flicker between runs.
4.9 Sparse vectors: TF-IDF, BM25 and SPLADE
- A sparse vector has one slot per word in the vocabulary, and almost every slot is zero. Only the words that matter get a weight.
- TF-IDF weights a word by how often it appears in the document and how rare it is across the collection.
- BM25 improves TF-IDF with term saturation (k1) and document length normalisation (b). It is still the standard keyword baseline.
- SPLADE learns the weights with a neural model and adds related words, so sparse search can match some paraphrases.
4.10 L2 distance, normalisation and Matryoshka embeddings
- L2 (Euclidean) distance is the straight-line gap between two points. Smaller means more similar.
- For unit-length vectors, squared L2 distance equals 2 minus 2 times the cosine, so both give the same ranking.
- Normalise once at write time and once at query time, and set the index metric to what the model was trained for.
- Matryoshka embeddings can be cut to their first numbers, but you must re-normalise after cutting.
5How models are trained7 lessons
5.1 Pretraining
- Pretraining teaches a model to predict the next token on a very large amount of text.
- From that one objective, models pick up grammar, facts, reasoning patterns and coding ability.
- A pretrained model continues text; it isn't yet a helpful assistant that follows instructions.
5.2 Supervised fine-tuning
- Supervised fine-tuning (SFT) trains a pretrained model on example conversations: a prompt and a good response.
- This teaches the assistant format: answer the question, follow instructions, use a helpful tone.
- SFT data is much smaller than pretraining data, but carefully written or selected.
5.3 RLHF
- RLHF collects human judgements of which responses are better, trains a reward model on them, then optimises the assistant to score well.
- It teaches preferences that are hard to write as examples: helpfulness, honesty, avoiding harm, good tone.
- It can over-optimise for what raters like, such as long or agreeable answers, which needs care.
- Modern post-training adds direct preference methods such as DPO and reinforcement learning on tasks a program can check, which is what produces reasoning models.
5.4 Constitutional AI and principle-based safety
- Constitutional AI trains a model using a set of written principles, with the model itself critiquing and revising responses against them.
- AI feedback guided by the principles supplements human feedback, making values more explicit and scalable.
- Anthropic publishes the principles it uses, so the intended behaviour is open to inspection.
5.5 Knowledge cutoffs and what the model can't know
- A model's training data stops at a cutoff date; it doesn't know about later events unless you tell it.
- It also doesn't know your private data, your users, or the current time unless you provide them.
- Supply fresh or private facts through the prompt, retrieval or tools, and give the current date when it matters.
5.6 Foundation models and pre-training at scale
- A foundation model is trained once on broad data at scale, then adapted to many tasks it was never built for.
- Scaling laws say loss falls smoothly and predictably as you add parameters, data and compute together.
- Compute is roughly 6 x parameters x training tokens. For a fixed budget, grow model size and data together; a common rule of thumb is about 20 tokens per parameter.
- Most teams never pretrain. They adapt: prompt first, then retrieval, then fine-tuning or distillation when the eval says so.
5.7 Responsible AI and safety: an overview
- Responsible AI covers fairness, privacy, transparency, misuse and safety. Each needs its own checks.
- Training shapes behaviour, but your product's risks depend on your data, users and tools, so you test them yourself.
- Red teaming means people deliberately trying to make the system fail, then fixing what they find and adding it to the test set.
- Governance makes it repeatable: named owners, documented risks, reviews before launch and monitoring after.
6Sampling5 lessons
6.1 Temperature
- The model produces a probability for every possible next token; temperature reshapes those probabilities before one is picked.
- Low temperature sharpens the distribution toward the most likely tokens; high temperature flattens it, adding variety.
- Temperature changes how predictable output is, not how correct or knowledgeable the model is. Current Claude models no longer accept it; you steer them with prompts, schemas and effort.
6.2 Top-p and top-k
- Top-k keeps only the k most likely tokens before sampling; top-p keeps the smallest set whose probabilities add up to p.
- Both cut off the long tail of unlikely tokens.
- Where these settings exist, change one at a time. Current Claude models don't accept sampling settings at all.
6.3 Stop sequences and max_tokens
- max_tokens caps how many tokens the model may generate in one response.
- Stop sequences end generation as soon as a given string appears; the response says which one matched.
- Use them for structure (stop after a closing tag) and for cost and length control.
6.4 Picking settings for extraction vs creative work
- Extraction and classification: clear criteria, structured output, validation (and low temperature on models that offer it).
- Creative work: higher temperature, maybe several candidates to choose from.
- Settings are a small lever; clear prompts, examples and checks matter more.
6.5 Frequency and presence penalties
- Penalties lower the score of tokens that have already appeared in the output, before sampling.
- A frequency penalty grows with every repeat; a presence penalty is a flat cut once a token has appeared at all.
- Some runtimes use a multiplicative repetition penalty instead. Values near 1 are mild; large values damage grammar.
- Leave penalties off for extraction, code and anything that must repeat exact names. Not every API offers them; the Claude Messages API doesn't.
7Hallucination and grounding4 lessons
7.1 Why models hallucinate
- A model generates plausible text; when it lacks the facts, plausible can be wrong.
- Hallucinations are likely for rare facts, specific numbers, citations, recent events and anything not in the prompt.
- The fix is to supply facts, allow 'I don't know', and verify claims, not just to ask the model to be accurate.
7.2 Grounding with documents and citations
- Grounding means answering from provided sources rather than from memory.
- Ask the model to quote the relevant passage first, then answer from the quote.
- Citations let users and code check each claim against its source.
7.3 Letting the model say "I don't know"
- Models tend to answer something; explicitly allowing 'I don't know' reduces guessing.
- Define what to do instead: ask a clarifying question, say what's missing, or hand off.
- Test it with questions that have no answer in the sources.
7.4 What an eval is and why you need one
- An eval is a repeatable test: inputs, expected behaviour, and a way to score outputs.
- For grounding, evals check that claims are supported, citations are valid and unanswerable questions get honest replies.
- Run evals whenever you change prompts, models or retrieval, so you know if things got better or worse.
8Multimodal and voice9 lessons
8.1 How models read images and documents
- Vision models split an image into patches, turn them into tokens, and process them alongside text.
- They're good at reading text in images, describing scenes, charts and layouts.
- They can struggle with exact counting, precise positions, tiny text and very low-quality scans.
8.2 Speech to text and text to speech
- Speech-to-text (STT) turns audio into text; text-to-speech (TTS) turns text into audio.
- A cascaded voice assistant chains STT, a language model and TTS.
- Each stage adds latency and its own errors, so design for mishearing and keep spoken replies short.
8.3 Realtime voice agents: turn-taking and latency
- Realtime voice needs low latency: long pauses feel broken, so every stage streams.
- Turn-taking means detecting when the user has finished speaking, and handling interruptions (barge-in).
- Speech-to-speech models handle audio directly; cascaded pipelines are easier to control and inspect.
8.4 Image generation basics
- Many image generators are diffusion or flow-matching models: they learn to remove noise step by step to form an image.
- A text encoder turns the prompt into guidance that steers each denoising step.
- Some multimodal LLMs now generate images themselves, writing image tokens the way they write text. Claude reads images but doesn't generate them.
8.5 Worked example: vision, PDFs and voice front ends
- Claude accepts images and PDFs in messages alongside text, so one request can mix them.
- Images are sent as base64 data, URLs or uploaded file ids; PDFs are sent as document blocks.
- For voice, pair Claude with speech-to-text and text-to-speech services, streaming at each step.
8.6 Vision-language models and patch embeddings
- A vision transformer cuts an image into a grid of patches (for example 16 by 16 pixels) and embeds each patch as a vector.
- A vision-language model passes those patch vectors through a small projector so the language model can read them as tokens beside the text.
- More pixels means more patches, so image size drives tokens, latency and cost. Resize before you send.
- Speech models such as Whisper use the same idea on audio: slice a spectrogram into frames, encode them, then decode text.
8.7 Diffusion and flow matching
- A diffusion model is trained to predict the noise that was added to an image at a random noise level.
- Flow matching trains a model to predict a velocity: which way to move from noise towards an image. Straighter paths need fewer steps.
- Both generate by starting from random noise and taking many small steps; most work in a compressed latent space.
- Classifier-free guidance strengthens the prompt at each step; too much makes images harsh and less varied.
8.8 Lab: extract fields from a receipt image
- Ask for a fixed schema with nullable fields, so 'I can't read this' is a valid answer instead of a guess.
- Never trust extracted numbers on their own: check that line items, tax and total add up, and that dates and currencies parse.
- Ask for the raw text the model read beside each value, so a reviewer can see where a mistake came from.
- Anything that fails a check goes to review, not straight into the ledger.
8.9 GANs and VAEs: the generative families before diffusion
- A GAN trains a generator to fool a discriminator. Samples are sharp and fast, but training is unstable and can collapse onto a few outputs.
- A VAE encodes an image to a small latent code and decodes it back. Its latent space is smooth, but averaging over likely outputs makes images blurry.
- Diffusion trades speed for stability and variety: many steps per image, but steady training and good coverage (8.7).
- VAEs live on inside diffusion: latent diffusion uses an autoencoder to compress images before denoising.
9Machine learning basics for LLM builders5 lessons
9.1 Discriminative vs generative models
- A discriminative model learns the chance of a label given an input: it draws a boundary between classes.
- A generative model learns the chance of the data itself, so it can produce new examples; an LLM does this one token at a time.
- You can use a generative model as a classifier by asking it to write the label, but it may write a label you never offered.
- For a fixed label set at high volume, a small discriminative classifier is often cheaper, faster and easier to test.
9.2 Neurons, weights, biases and activations
- A neuron multiplies each input by a weight, adds them up, adds a bias, then passes the sum through an activation function.
- Weights and biases are the parameters: the numbers training adjusts. An LLM's parameter count is mostly these.
- Without a non-linear activation, any stack of layers collapses into one straight-line layer.
- A dense layer with n inputs and m neurons has n x m weights plus m biases.
9.3 Gradient descent and backpropagation
- A loss function scores how wrong the model is; training tries to make it smaller.
- The gradient says which way each parameter should move to raise the loss, so gradient descent steps the opposite way, scaled by the learning rate.
- Backpropagation applies the chain rule from the loss back through each layer, reusing values from the forward pass to get every gradient in one sweep.
- Too high a learning rate makes the loss bounce or explode; too low makes training crawl.
9.4 Training compute vs inference compute
- Training a dense model costs roughly 6 x parameters x training tokens in floating-point operations (FLOPs): a forward and a backward pass for every token.
- Inference costs roughly 2 x parameters FLOPs per token, because it runs only the forward pass.
- Training is a large one-off bill; inference is a bill that grows with every user, so over a model's life it can be the bigger one.
- Training also needs far more memory per parameter: gradients and optimiser state sit next to the weights.
9.5 Lab: a tiny two-layer network by hand
- One training step is always the same four moves: forward pass, loss, backward pass, update.
- With a sigmoid output and cross-entropy loss, the error signal at the output is simply prediction minus target.
- A hidden weight's gradient is that error, times the output weight it passes through, times the ReLU's slope, times its input.
- A ReLU that outputs 0 passes no gradient back, so its incoming weights don't change on that example.
10Inside the transformer7 lessons
10.1 Queries, keys and values
- Each token's vector is multiplied by three learned matrices to make a query (what it is looking for), a key (what it offers) and a value (what it passes on).
- A token's attention scores are its query dotted with every key, divided by the square root of the key size, then turned into weights with softmax.
- The output is the weighted average of the value vectors, so it is a blend of the tokens it attended to.
- In a decoder, a causal mask stops each token attending to tokens after it.
10.2 Multi-head attention
- Multi-head attention runs several smaller attention operations side by side, each with its own query, key and value matrices.
- Each head works on a slice of the model width, so eight heads of 64 cost about the same as one head of 512.
- Head outputs are joined end to end and mixed by an output matrix, so the layer can combine what different heads found.
- Multi-query and grouped-query attention let heads share keys and values, which shrinks the KV cache.
10.3 Positional encodings: sinusoidal and RoPE
- Attention on its own ignores order: shuffle the tokens and each one gets the same weights, just in a different order.
- The original transformer added fixed sine and cosine waves of different speeds to each token's embedding.
- RoPE rotates each query and key by an angle set by its position, so their dot product depends only on how far apart they are.
- Models handle positions they were trained on best; longer contexts need models trained or adapted for them.
10.4 Encoder-only, decoder-only and encoder-decoder
- Encoder-only models (such as BERT) let every token see every other token, and are trained to fill in hidden words; they are good at understanding, not writing.
- Decoder-only models (such as GPT-style and Llama-family models) use a causal mask and next-token prediction; most chat LLMs are built this way.
- Encoder-decoder models (such as T5) read the input with an encoder and write the output with a decoder that attends to it through cross-attention.
- Embedding models and rerankers are often encoder-based, so a RAG system can use all the families at once.
10.5 The KV cache and why long prompts cost memory
- When generating, each new token needs the keys and values of every earlier token, so they are stored instead of recomputed: that store is the KV cache.
- Cache size = 2 (keys and values) x layers x KV heads x head size x bytes per number x tokens; it grows linearly with context length and with concurrent requests.
- A long prompt can need more memory for its cache than a small model needs for its weights, which limits how many users a server can hold.
- Grouped-query attention, cache quantisation, paged memory and prefix caching all cut or share the cost.
10.6 Lab: read an attention map
- Each row of an attention map is one token's query; each column is a key it could look at; each row adds up to 1.
- In a decoder the top-right triangle is empty, because tokens can't attend to later tokens.
- Common patterns include a bright diagonal just below the middle (previous token), a bright first column (a resting place), and long jumps such as a pronoun to its noun.
- Attention weights show where information was read from, in one head of one layer; they are not a full explanation of the output.
10.7 Mixture-of-experts: total and active parameters
- A mixture-of-experts (MoE) model replaces each feed-forward block with many expert blocks and a small router that picks a few experts per token.
- Total parameters set the memory you need; active parameters set the compute per token.
- MoE gives the knowledge of a big model at the per-token cost of a much smaller one, but every expert must still sit in memory.
- Most frontier and many open-weight models are MoE, so read both numbers on a model card.
02Prompt engineering and structured output
11Explicit criteria, roles and XML tags7 lessons
11.1 System prompts that read like a spec
- A strong system prompt reads like a brief for a new colleague: the goal, the audience, the rules and the output.
- State the context Claude can't guess: who the users are, what the product does, what good looks like.
- Put the most important constraints plainly, not buried in a paragraph.
11.2 Explicit criteria beat "be careful"
- Vague words like 'careful', 'concise' or 'accurate' mean different things to different readers.
- Explicit criteria name what to include, what to leave out and when to stop.
- If you can't check whether a rule was followed, rewrite it until you can.
11.3 Roles and audience
- A role in the system prompt sets the perspective and expertise Claude writes from.
- Naming the audience shapes vocabulary, depth and length more than almost any other line.
- Roles work best combined with explicit criteria, not instead of them.
11.4 Structuring prompts with XML tags
- XML tags such as <document>, <instructions> and <example> make the parts of a prompt clear.
- Tags keep pasted content apart from your instructions, which also helps against injected text.
- Ask for output in tags too, so code can pull out the part it needs.
11.5 Message roles: system, developer and user
- Chat APIs separate messages by role: system (or developer) for the app's standing rules, user for the person's request, assistant for the model's replies.
- Models are trained to give system and developer instructions more weight than user text, and user text more weight than tool results and documents.
- APIs name and place these roles differently: some take a top-level system field, some a developer role, some a system instruction setting.
- Roles set priority, not security: enforce anything that must hold, such as permissions, in code.
11.6 Delimiters and Markdown structure
- Delimiters such as triple backticks, triple quotes, lines of dashes or XML tags mark where pasted material starts and ends.
- Markdown headings give a long system prompt a skeleton that both people and models can navigate.
- A delimiter fails when the content contains it, so pick one the content can't contain, or use named tags.
- The style of the prompt nudges the style of the reply: a prompt full of Markdown invites Markdown back.
11.7 Role prompting: when personas help and when they don't
- A persona changes tone, vocabulary and what the model pays attention to. It does not add knowledge the model lacks.
- Expertise framing names a lens and a task. Fake credentials, such as years of experience or awards, add nothing to act on.
- Audience roles usually move the output more than the speaker's role does.
- Keep a persona only if it wins on a fixed test set by more than run-to-run noise.
12Few-shot examples4 lessons
12.1 When examples beat instructions
- Examples show format, tone and judgement that are hard to describe in words.
- Three to five varied examples are often enough.
- Wrap examples in tags such as <example> so they're clearly separate from the real input.
12.2 Choosing examples that cover edge cases
- Choose examples that are varied and include hard and borderline cases, not just easy ones.
- Balance the labels, or the model may lean towards the most common one.
- Draw examples from real data, especially from cases the prompt got wrong.
12.3 Avoiding examples the model copies too literally
- Models can copy surface details from examples: the same phrases, lengths or even values.
- Vary wording, length and content so only the intended pattern is shared.
- Say explicitly that examples show the format and aren't templates to copy.
12.4 Few-shot vs step-by-step reasoning
- Few-shot examples are best for format, style and pattern matching.
- Step-by-step reasoning is best for multi-step logic, maths and weighing evidence.
- For hard judgement calls, examples that include short reasoning combine both.
13Chain of thought and output steering6 lessons
13.1 Asking for reasoning before the answer
- Asking the model to think step by step before answering improves multi-step reasoning.
- The reasoning must come before the answer; reasoning written after a decision just justifies it.
- Guided steps ('first list the rules, then check each one') work better than a bare 'think step by step'.
13.2 Separating reasoning from the final output
- Ask for reasoning in <thinking> tags and the result in <answer> tags.
- Your code shows users or downstream systems only the <answer> part.
- Keeping reasoning lets you debug wrong answers later.
13.3 Prefilling the assistant turn
- Prefilling means putting the first words of the assistant's reply in the request, and the model continues from there.
- On models that accept it, prefilling `{` pushes output straight into JSON and prefilling a tag can skip a preamble.
- Current Claude models reject prefill. Use structured outputs for JSON and a system instruction for format. Prefill still appears in older code, open-weight runtimes and other model APIs.
13.4 When chain of thought hurts
- Reasoning costs output tokens and time.
- Simple lookups, extraction and classification by clear rules rarely need it.
- Measure it: keep chain of thought only where an eval shows it helps.
13.5 Self-consistency and tree of thoughts
- Self-consistency samples several independent reasoning paths and takes the majority final answer.
- It only helps when each path is right more often than wrong and the answers can be compared, such as a number or a label.
- Tree of thoughts branches at each step, scores the partial paths and keeps the best, like a search.
- Both multiply calls and tokens, so use them where an eval shows a real gain on hard, checkable tasks.
13.6 Reasoning models and effort settings
- Reasoning models think in a separate step before the visible answer; you control how much with a token budget or an effort level.
- More effort usually helps hard multi-step tasks and wastes time and tokens on simple ones.
- With a reasoning model, give a clear goal and constraints rather than scripting every reasoning step.
- Set effort per task, not per app, and confirm each setting on your test set.
14Structured output8 lessons
14.1 JSON schemas for output
- A JSON schema states the fields, their types, which are required and which values are allowed.
- Enums for fixed choices stop the model inventing labels.
- Flat, clearly named fields are filled more reliably than deep nesting.
14.2 Constrained decoding and strict schema modes
- Constrained decoding masks out every next token that would break the schema, so the output always parses and fits the shape.
- Strict modes usually accept only a subset of JSON Schema, such as every property required and no extra properties.
- A guaranteed shape is not a guaranteed truth: values can still be wrong, so keep business checks.
14.3 Nullable fields so the model doesn't invent values
- If a field is required and not nullable, the model must put something there, even when the source has nothing.
- Make such fields nullable and say 'null if not stated in the text'.
- This is one of the simplest and most effective ways to reduce invented values in extraction.
14.4 Validation-retry loops
- Always validate structured output in code, even with tool_use.
- On failure, retry with the specific error message so the model can fix that exact problem.
- Cap retries; after the limit, route the item to a person or a fallback queue.
14.5 Batch extraction at scale
- For large jobs that don't need instant answers, the Message Batches API costs less and handles volume.
- Run a pilot on a sample first and check accuracy before the full run.
- Track failure rates by field and send failures to review instead of silently dropping them.
14.6 Forcing structure with tool_use
- Defining a tool whose input_schema is your output shape makes Claude return arguments in that shape.
- Where forced tool choice is supported, tool_choice set to that tool makes the reply always structured. The newest Claude models reject forced tool choice; use structured outputs (14.2) there.
- You never run the 'tool'; you just read its input as the result.
14.7 Mapping typed models to response schemas
- Define the output shape once as a typed model, generate the JSON Schema from it, and parse the reply back into the same type.
- Each type maps to a schema keyword: str to string, int to integer, Optional to a nullable type, Literal or Enum to enum, list to array.
- Defaults and optional fields often become 'not required', which strict modes reject; make the field required and nullable instead.
14.8 Refusals, truncation and validation retries
- Check why the reply stopped before you parse it: a stop reason such as max_tokens or refusal tells you the output is not a normal answer.
- Truncation needs more room or a smaller output; retrying the same request just truncates again.
- A refusal is a decision, not a format error: log it and route it, don't loop on it.
- Only a genuine validation failure gets a retry with the specific errors (14.4).
15Prompt chaining and multi-pass review5 lessons
15.1 Breaking a task into a chain
- A chain breaks one big prompt into steps, each with one clear job.
- Each step is easier to get right, test and debug.
- Pass each step's output to the next in tags, and check between steps where it matters.
15.2 Multi-pass review to cut errors and false positives
- A second pass with a reviewer prompt catches errors the first pass missed.
- A fresh instance reviews better than the same conversation reviewing itself.
- Adding a verification pass that must confirm each finding with evidence cuts false positives.
15.3 Eval-driven prompt iteration
- Prompt changes that look better on one example often make others worse.
- Keep a test set of real inputs with expected outputs, and score every prompt version on it.
- Change one thing at a time, compare scores, and add new failures to the set.
15.4 Versioning and testing prompts
- Store prompts in version control, not in a dashboard or someone's notes.
- Run the prompt test set in CI on every change, and block merges that lower the score.
- Record which prompt version produced each output, so you can trace problems later.
15.5 Prompt templates with variables
- A prompt template is the fixed text of a prompt with named slots, such as {{policy}} and {{question}}, filled in at run time.
- Fixed parts are written, reviewed and versioned once; only the variables change per call.
- Wrap each variable in its own tag so the model can tell your instructions from the data.
- Fail loudly when a variable is missing or unused, instead of sending a prompt with a hole in it.
03Evals
16Write the eval first4 lessons
16.1 Why evals come before prompts
- An eval is a repeatable test: inputs, a way to score outputs, and a pass bar.
- Without one, every prompt change is a guess judged on two or three examples you happen to try.
- Write a small eval first, then change prompts in a loop: change, measure, keep or revert.
16.2 Defining success: criteria you can score
- 'Good answers' isn't testable; 'cites the policy section and stays under 120 words' is.
- Split quality into separate criteria: correct, complete, grounded, safe, right format, right tone.
- Give each criterion a scoring method (exact check, rubric score, human rating) and a target.
16.3 Your first ten test cases
- Start with about ten cases: mostly typical requests, plus a few edge cases and one or two attacks.
- Each case has an input and either an expected answer or the criteria that a good answer must meet.
- Store cases in a file in source control so they're versioned with the prompt.
16.4 How would you test this? A habit for every project
- For every AI feature, ask early: what inputs, what counts as success, and how will we score it?
- A one-paragraph eval plan before building saves days of arguing about quality later.
- Every project in this course ends with this question; answer it before you move on.
17Golden sets and error analysis5 lessons
17.1 Reading traces to find failure modes
- Error analysis means reading real outputs, noting what went wrong in plain words, then grouping the notes.
- The biggest bucket of failures is usually where to work next.
- Look at outputs yourself before building any automated grader; you'll find failures you wouldn't have guessed.
17.2 Building a golden set from real traffic
- A golden set is a curated set of real inputs with trusted expected answers or criteria.
- Pick cases from real traffic to match what users actually send, and redact personal data first.
- Label carefully: a wrong label teaches you the wrong lesson every time you run the eval.
17.3 Coverage: edge cases, adversarial and boring cases
- Coverage means your test set includes each kind of input the system will face, not only the common ones.
- Include boring cases (should be easy), edge cases (limits, missing data), and adversarial ones (injections, rule-breaking).
- Tag cases by type so you can see scores per slice, not just an overall number.
17.4 Keeping a golden set fresh
- Test sets go stale: policies change, products change, users ask new things.
- Add new failures as cases, update labels when the source of truth changes, and retire cases that no longer apply.
- Keep a small frozen set too, so you can compare scores over long periods.
17.5 Failure-mode taxonomies
- A failure-mode taxonomy is a short, agreed list of failure categories, each with a definition, an example and a fix owner.
- Grow it from real notes (17.1): open notes first, then group, then name and define.
- Label the first failure in each trace, so counts do not double up and you fix the root cause.
- Check agreement between two labellers and version the taxonomy like a prompt.
18Graders: code, model and human5 lessons
18.1 Code-based graders
- Code graders are fast, cheap, and give the same result every time: use them wherever a rule can decide.
- Good fits: schema validity, required fields, exact or numeric match, length, banned phrases, tool called.
- They can't judge meaning, tone or faithfulness well; use model graders for those.
18.2 LLM-as-judge and rubrics
- An LLM-as-judge reads the input, the output and a rubric, then gives a score and a reason.
- Clear rubrics with concrete levels and examples give far more consistent scores than 'rate 1 to 10'.
- Ask for the reason before the score, use structured output, and grade one criterion per call when you can.
18.3 Calibrating a judge against humans
- A grader is only useful if it agrees with careful people; measure that before relying on it.
- Have people label a sample, run the grader on the same sample, and compare verdicts.
- Read the disagreements and tighten the rubric or examples; repeat until agreement is good enough.
18.4 Pairwise comparison and position bias
- Pairwise grading asks 'which of these two answers is better?', which is often easier and more consistent than absolute scores.
- Model judges often favour the answer shown first (position bias), or the longer one.
- Run each pair twice with the order swapped, and count a win only when both orders agree.
18.5 Worked example: building a grader in the Playground
- Use Claude as a grader with a rubric prompt and structured output so every verdict parses.
- Keep grader settings fixed (model id, prompt version, effort level) so scores are comparable over time.
- Practise in the Playground's simulated calls first; no real key or spend is needed to design the flow.
19Evaluating agents4 lessons
19.1 Outcome vs trajectory evals
- Outcome evals check the end state: was the ticket resolved, is the file correct, did the test suite pass?
- Trajectory evals check the path: which tools, in what order, with which arguments, and how many steps.
- Use outcome as the main score; add trajectory checks for safety, cost and required steps.
19.2 Tool-call accuracy and argument checks
- Check that the agent picked a suitable tool at each step and filled its arguments correctly.
- Compare against expected calls where there's one right answer; use rules (must, must not) where several paths are fine.
- Argument errors (wrong id, wrong units, missing field) are a common and easy-to-test failure.
19.3 Simulated users and environments
- Multi-turn agents need a counterpart: a simulated user, often a model given a persona and a goal.
- Test in a sandbox environment with fake data and fake tools, never production systems.
- Check simulations against real conversations so the simulated users behave like real ones.
19.4 Cost, latency and step budgets as metrics
- An agent that succeeds but takes 40 steps and costs ten times more may be a regression.
- Record tokens, cost, wall time and steps for every eval run, alongside quality scores.
- Set budgets per task type and fail the eval when a run exceeds them.
20Regression gates in CI4 lessons
20.1 Running evals on every change
- Treat prompts and agent config like code: every change runs the eval suite before merge.
- Run a fast, cheap subset on every pull request and the full suite nightly or before release.
- Fail the check when must-pass criteria drop or a key score falls below its bar.
20.2 Thresholds, flakiness and variance
- Model outputs vary, so the same eval can score differently on two runs with no code change.
- Measure the noise: run the baseline several times to see normal variation.
- Set gates wider than the noise, repeat runs on borderline results, and use enough cases to make differences meaningful.
20.3 Tracking scores over time
- Store every eval run with its versions, scores per criterion and per slice, cost and date.
- Chart scores over time; slow declines are invisible if you only compare each change with the last.
- Link scores to releases so you can see which change moved which metric.
20.4 Worked example: evals with a headless coding agent
- Claude Code's headless mode (claude -p) runs a prompt non-interactively and can return JSON, so it fits CI jobs.
- Use it to grade outputs, summarise eval failures, or review prompt changes, with tools limited to what the job needs.
- Keep the gate decision in code: Claude can grade or explain, but a script compares scores with thresholds.
04RAG architectures
21Naive RAG5 lessons
21.1 The four steps: chunk, embed, retrieve, generate
- RAG answers questions from your documents: chunk them, embed the chunks, retrieve the closest ones to a question, and generate an answer from them.
- It lets a model use private or recent information it was never trained on.
- Indexing (chunk and embed) happens ahead of time; retrieval and generation happen per question.
21.2 Putting retrieved text in the prompt
- Wrap each retrieved chunk in clear tags with its source id, and put the question after the documents.
- Tell the model to answer only from the sources and to say when they don't contain the answer.
- Ask for citations to chunk ids, or use Claude's citations feature, so answers can be checked.
21.3 Where naive RAG breaks
- Naive RAG fails when retrieval misses: bad chunking, vocabulary mismatch, questions needing several documents, or stale indexes.
- It also fails when retrieval succeeds but the model ignores or misreads the chunks.
- Diagnose first: was the right chunk retrieved? Then fix retrieval or generation accordingly.
21.4 Document loaders and parsers
- Retrieval can only find what the parser produced: scrambled or missing text becomes scrambled or missing answers.
- Each format needs its own care: PDFs need reading order rebuilt, HTML needs boilerplate removed, Office files need their structure kept, scans need OCR.
- Keep source, section path, page, version, access control and parser details with every chunk, so answers can be cited, filtered and re-parsed.
- Check every document after parsing: empty pages, repeated headers, garbled characters and flattened tables are the usual failures.
21.5 Prompt augmentation: building the grounded prompt
- Build the prompt in code, in a fixed order: instructions, then delimited sources with ids, then the question.
- Work out the context budget first: window minus instructions, question and room for the answer. Fill it best chunk first and drop the rest.
- Delimit sources clearly and treat their text as data, so a chunk cannot pass for an instruction.
- If nothing relevant was retrieved, say so or ask a clarifying question. Do not send an empty context and hope.
22Vector database internals8 lessons
22.1 Exact vs approximate nearest neighbour search
- Exact search compares the query with every vector: perfect results, but slow at large scale.
- Approximate nearest neighbour (ANN) indexes find most of the true nearest vectors far faster.
- Recall is the share of true nearest neighbours an index returns; you tune indexes to trade recall for speed.
22.2 HNSW graphs
- HNSW builds layered graphs: sparse upper layers for long jumps, a dense bottom layer for fine search.
- A query starts at the top, greedily moves toward closer nodes, and descends layer by layer.
- Settings like M (links per node) and ef (search breadth) trade memory and speed for recall.
22.3 IVF and product quantization
- IVF (inverted file) clusters vectors and searches only the clusters closest to the query.
- Product quantization compresses vectors into short codes, cutting memory many times over at some accuracy cost.
- IVF-PQ combines both for very large collections; rerank top candidates with full vectors to recover accuracy.
22.4 Filtering, hybrid search and metadata
- Real queries need filters: only this tenant's documents, only current policies, only English.
- Filtering before or during search keeps results correct; filtering after can leave too few results.
- Many stores also support hybrid search: keyword (BM25) scores combined with vector similarity.
22.5 Choosing a vector store and sizing it
- Options range from a library in your app, to a vector extension in your existing database, to a managed vector service.
- Estimate size: number of chunks x dimensions x bytes per number, plus index overhead.
- Choose by scale, filtering needs, operations effort and what your team already runs.
22.6 Comparing vector stores and quantization options
- Stores fall into libraries (FAISS), database extensions (pgvector), open-source servers (Weaviate, Qdrant, Milvus, Chroma) and managed services (Pinecone and hosted versions of the others).
- Most support HNSW, metadata filters and some form of hybrid search; they differ in operations, scale and filtering under load.
- Scalar quantization (int8) cuts memory about 4x with small loss; binary quantization cuts it about 32x and needs re-ranking.
- Pick on your measurements: recall at your filter mix, latency at your query rate, and the effort to run it.
22.7 Namespaces and tenant isolation
- A multi-tenant RAG system must never return one customer's chunks to another, whatever the query says.
- Three patterns: a shared index with a tenant filter, a namespace (or partition) per tenant, or a separate index or collection per tenant.
- The tenant id comes from the signed-in session on the server, never from the model or the user's message.
- Test isolation directly: a query from tenant A must return zero chunks from tenant B.
22.8 Sharding, replication and scaling to billions of vectors
- A shard is an independent index over part of the data. A query fans out to the shards, each returns its local top k, and a coordinator merges them.
- Shard by hashed id for an even spread across one big corpus; shard by tenant so a query touches only that tenant's shards.
- Replicas add read throughput and survive node loss, but every write must reach them, and a lagging replica can serve stale or deleted data.
- Size it: vectors × dimensions × bytes per value, plus graph links, times replicas. Compression in RAM with full vectors on SSD usually cuts the node count several times.
23Advanced RAG7 lessons
23.1 Chunking strategies
- Chunks should hold one complete idea: too small loses context, too big dilutes relevance.
- Split on structure (headings, paragraphs, sections) rather than fixed character counts where you can.
- Small overlaps between chunks help when an idea crosses a boundary; test sizes on your own questions.
23.2 Hybrid search: BM25 plus embeddings
- Keyword search (BM25) finds exact terms: codes, names, rare words; vectors find meaning.
- Hybrid search runs both and merges the results, catching what either alone would miss.
- Reciprocal rank fusion is a simple, robust way to merge ranked lists without tuning score scales.
23.3 Reranking
- First-stage search is fast but rough; a reranker scores each query-chunk pair more carefully.
- Retrieve a wider shortlist (say 50), rerank, then pass the best few (say 5) to the model.
- Rerankers can be dedicated cross-encoder models or an LLM asked to score relevance.
23.4 Query rewriting and expansion
- User questions are often short, vague, or depend on earlier turns ('what about the blue one?').
- Rewrite the question into a standalone search query using the conversation, before retrieving.
- Expansion generates several queries or a hypothetical answer to search with, improving recall.
23.5 Contextual retrieval
- A chunk on its own often lacks context: 'Revenue grew 3%' — which company, which quarter?
- Contextual retrieval adds a short, generated description of where the chunk sits in its document before embedding and keyword indexing.
- Prompt caching keeps the cost of generating that context low, since the whole document is reused for every chunk.
23.6 HyDE and multi-query retrieval
- HyDE asks a model to draft a plausible answer, embeds the draft, and searches with it, because answers look more like documents than questions do.
- Multi-query retrieval writes several phrasings of the question, searches each, and merges the lists.
- The draft is only a search key: never show it to the user or treat it as fact.
- Both add a model call and extra searches; keep them only if your test set shows better recall.
23.7 Reciprocal rank fusion step by step
- RRF gives each document 1 / (k + rank) from every list it appears in, and adds them up.
- It uses only ranks, so lists with different score scales (BM25, cosine, a reranker) can be merged without tuning.
- A larger k flattens the curve so agreement across lists matters more; k = 60 is a common default.
- A document missing from a list simply gets nothing from that list.
24Agentic RAG3 lessons
24.1 Retrieval as a tool
- In agentic RAG, search is a tool: the model decides whether to search, what query to use, and whether to search again.
- This handles questions that need no search, one search, or several refined searches.
- Good search tool design: clear description, filters as parameters, compact results with source ids.
24.2 Multi-hop questions
- Multi-hop questions need facts from several documents, where one fact tells you what to look up next.
- An agent can search, read, then search again using what it learned.
- Notes between hops keep the chain of facts clear and citable.
24.3 RAG vs long context vs fine-tuning
- RAG fetches relevant passages at question time: best for large, changing knowledge and citations.
- Long context puts whole documents in the prompt: simplest when the material fits and is used together.
- Fine-tuning changes model behaviour and style; it's a poor way to add facts that change.
25GraphRAG3 lessons
25.1 Knowledge graphs
- A knowledge graph stores entities (people, products, teams) as nodes and relationships as edges.
- Graphs answer relationship questions directly: who reports to whom, what depends on what.
- Text chunks hold facts in prose; graphs hold the connections explicitly.
25.2 Building a graph from documents
- A model can extract entities and relationships from text into a schema you define.
- Entity resolution merges duplicates ('R. Mensah', 'Rita Mensah') into one node.
- Some GraphRAG approaches also cluster the graph into communities and summarise each for broad questions.
25.3 When graphs beat vectors
- Graphs win on relationship and multi-hop questions, and on 'big picture' questions across many documents.
- Vector RAG wins on specific factual questions answered by a passage, with far less setup.
- Start with vector or hybrid RAG; add a graph when evaluations show relationship questions failing.
26Evaluating RAG7 lessons
26.1 Retrieval metrics: recall and precision
- Evaluate retrieval separately from answers: did the right passages come back?
- Hit rate@k (often reported as recall@k): share of questions with a relevant passage in the top k. Strict recall@k: share of all relevant passages that reach the top k. Precision: share of retrieved passages that are relevant.
- MRR and similar metrics reward putting the right passage near the top.
26.2 Answer metrics: faithfulness and relevance
- Faithfulness: every claim in the answer is supported by the retrieved passages.
- Relevance: the answer addresses the question asked; completeness: it covers what the sources say.
- Model graders with rubrics can score these; calibrate them against human labels.
26.3 Building a RAG test set
- A RAG test set needs questions, the passages that answer them, and reference answers or criteria.
- Include questions the documents can't answer, to test honest refusals.
- Tag by type (single fact, multi-hop, comparison, recent change) and report per tag.
26.4 Ranking metrics: MRR and nDCG
- Recall@k ignores order inside the top k; ranking metrics reward putting the best chunk first.
- MRR averages 1 / rank of the first relevant chunk, so it cares only about the first hit.
- nDCG uses graded relevance and a log discount, then divides by the best possible score, giving 0 to 1.
- Use ranking metrics when order matters: reranking, small k, or a model that leans on the first passages.
26.5 Context precision and context recall
- Context precision asks whether the retrieved chunks that matter sit near the top, judged against the question and reference.
- Context recall asks what share of the reference answer's claims can be found in the retrieved context.
- Both need a reference answer, not labelled chunk ids, so a model judge does the matching; check it against people.
- Low context recall points at retrieval missing facts; low context precision points at noise and ordering.
26.6 Synthetic test sets
- A model can write questions, reference answers and source ids from your chunks, giving a large test set quickly.
- Synthetic questions tend to copy the chunk's wording, which makes retrieval look easier than real traffic.
- Ask for varied types (multi-hop, comparison, unanswerable), paraphrase, then filter and have people review a sample.
- Use synthetic cases to widen coverage, and keep real user questions as the anchor.
26.7 RAG eval frameworks: RAGAS, TruLens and rolling your own
- Frameworks package common metrics (faithfulness, relevance, context precision and recall), judge prompts, test set generation and dashboards.
- RAGAS centres on metric functions over test cases; TruLens centres on tracing a running app and scoring each step, framed as the RAG triad.
- Every framework metric is a model judge with its own prompt: pin versions and check it against your own labels.
- A small harness of your own is often enough: labelled cases, a few code metrics, one judge prompt, results per tag.
27Parsing complex documents5 lessons
27.1 Why PDFs are hard: layout, columns and reading order
- A PDF stores characters and their positions on the page, not paragraphs, headings or reading order.
- Naive extraction reads across the page line by line, so two columns get interleaved into nonsense.
- Headers, footers, footnotes, hyphenation and tables add noise; scanned pages may have no text layer at all.
- Check a sample of extracted text by eye before you chunk and embed it.
27.2 Layout-aware parsing tools
- Parsers range from plain text-layer extractors to layout models, OCR engines, cloud document services and vision-language models.
- Layout-aware parsers return typed elements (heading, paragraph, table, figure) with page numbers and positions, not one long string.
- Pick by your documents: clean digital text needs little; columns, tables and scans need layout analysis or OCR.
- Compare parsers on a sample of your own documents and keep the element type and page with every chunk.
27.3 Tables, charts and figures
- Flattened tables lose the link between a number and its row and column headers.
- Keep tables as Markdown or HTML, never split a row, and repeat the header row in every chunk of a long table.
- Charts and figures need text: the caption, a written description, and the underlying numbers if you can get them.
- Store the page and table or figure number with each chunk so answers can cite them.
27.4 Page images as multimodal input
- A vision-capable model can read a rendered page image directly, including charts, scans and odd layouts.
- Page images usually cost several times more tokens than the page's extracted text, and they are slower.
- A hybrid is common: index extracted text, and send page images only for pages that need them or for the pages retrieved.
- Some retrievers embed page images themselves, skipping text extraction for search.
27.5 Lab: parse a report with tables and cite pages
- Start from parsed elements with type and page, not raw text: drop noise, keep tables whole, attach the heading path.
- Every chunk carries its page number, and the prompt asks for answers that cite pages.
- A code check can confirm that each cited page exists and contains the key figure in the claim.
- Score the pipeline on a handful of questions, including one about a table and one the report can't answer.
05Open models, fine-tuning and local inference
28Open-weight models7 lessons
28.1 Open-weight vs closed models
- Open-weight models publish their trained weights so you can download, run and adapt them yourself.
- Closed models, such as Claude, are used through an API or app; the weights stay with the provider.
- Open weights give control over hosting, data and customisation; closed models usually lead on capability and need no infrastructure.
- 'Open weights' isn't the same as open source: training data and code may still be private, and licences vary.
28.2 Model families, sizes and licences
- Open model families come from several labs and are released in sizes, measured in billions of parameters.
- Bigger models are usually more capable but need more memory and are slower.
- Families ship base models (raw next-token predictors) and instruct or chat models (tuned to follow instructions).
- Licences range from permissive to restricted; check commercial use, user limits and acceptable-use rules.
28.3 Reading a model card and benchmarks
- A model card describes what a model is for, how it was trained, how it scored, and its known limits.
- Benchmarks give a rough comparison, but scores can be inflated by test data leaking into training.
- Benchmark tasks rarely match your task, so treat them as a shortlist tool.
- The deciding test is your own eval set run on your own prompts.
28.4 When to use an open model next to a hosted one
- Open models and Claude often work together: each handles the work it suits best.
- Common splits: a small local model for redaction, classification or embeddings; Claude for reasoning, writing and agents.
- Routing by data sensitivity keeps private data local while sending safe, hard tasks to Claude.
- Evaluate each part separately and watch the handoffs between them.
28.5 The open-weights landscape: Llama, Qwen, Mistral, DeepSeek and others
- Several labs publish open-weight families, each in a range of sizes and variants, and new versions arrive every few months.
- Licence styles fall into a few groups: permissive (Apache 2.0, MIT), custom community licences with conditions, and fully open releases that add data and code.
- Licence terms and sizes can change between versions of the same family, so check each release you use.
- No family is best at everything: shortlist by licence, size and language, then test on your own eval.
28.6 Small language models and when to use them
- A small language model (SLM) has roughly a few billion parameters or fewer, small enough for one modest GPU, a laptop or a phone.
- Distillation teaches a small model from a large one; quantisation stores its weights in fewer bits. Together they make SLMs fast and cheap to run.
- SLMs shine on narrow, repeated tasks with clear right answers, on devices and offline, and as the first stop in a small-then-large route.
- They are the wrong choice for open-ended reasoning, long multi-step agent work and broad knowledge questions.
28.7 Build, buy or self-host: total cost of ownership
- There are three broad options: call a hosted model API and build the rest, use a managed agent platform from a cloud provider, or self-host open-weight models.
- Total cost of ownership counts people, operations, evals and risk, not just price per token.
- Self-hosting usually pays off only at high, steady volume, or when data, latency or offline needs leave no choice.
- Build what differentiates you, buy what is common, and keep a thin layer of your own so you can switch.
29Fine-tuning9 lessons
29.1 Prompting vs RAG vs fine-tuning
- Try prompting first, then retrieval (RAG), and fine-tune only when those fall short.
- RAG adds knowledge; fine-tuning changes behaviour: style, format, or a narrow skill.
- Fine-tuning needs good data, evals and upkeep, and must be redone for new base models.
- Fine-tuning a small model can cut cost and latency for a narrow, high-volume task.
29.2 Supervised fine-tuning data
- Supervised fine-tuning (SFT) trains on example inputs paired with ideal outputs.
- Quality beats quantity: a few hundred excellent, varied examples often beat thousands of noisy ones.
- Cover edge cases, include what to refuse or escalate, and match the format you'll use in production.
- Hold out a separate test set, and never let test examples leak into training.
29.3 LoRA and parameter-efficient tuning
- Full fine-tuning updates every weight: costly in memory, time and storage.
- LoRA freezes the base model and trains small add-on matrices (adapters) that adjust its behaviour.
- Adapters are small files; you can keep many for one base model and swap them per task.
- QLoRA combines LoRA with a quantized base model, so large models can be tuned on modest GPUs.
29.4 Preference tuning (DPO and RLHF-style)
- Preference tuning teaches a model which of two answers people prefer, not just one 'right' answer.
- RLHF trains a reward model on preferences, then optimises the model against it with reinforcement learning.
- DPO skips the separate reward model and learns directly from preferred vs rejected pairs, which is simpler to run.
- Preference data needs clear rating guidelines; vague guidelines teach vague behaviour.
29.5 Evaluating a fine-tuned model
- Compare the tuned model with the best prompt-plus-RAG baseline on the same held-out test set.
- Check what you tuned for, and also what you didn't: general skills, safety and refusals can regress.
- Look at failures, not just averages; a better average can hide new, serious errors.
- Re-run the evals whenever you change data, settings or the base model.
29.6 Worked example: fine-tuning options on cloud platforms
- Claude's main customisation tools are prompts, examples, tools, retrieval, Skills and structured outputs.
- Anthropic's own API doesn't offer general self-serve fine-tuning of Claude.
- Fine-tuning of some Claude models has been offered through cloud platforms, such as Amazon Bedrock; check current availability there.
- Most teams reach their goals with prompting and retrieval, and use open models when they truly need to tune.
29.7 Lab: write a decision record for three use cases
- A decision record states the problem, the options tried, the evidence, the choice and when to revisit it.
- Decide per use case: knowledge gaps point to retrieval, behaviour gaps left after prompting point to tuning.
- Every record names a baseline score, a target score and the eval that measured them.
- Write down the upkeep you accept, such as re-tuning for new base models, so the choice can be reviewed later.
29.8 Chat templates and dataset formatting
- A chat template turns a list of messages into one token string, with special tokens marking each turn.
- Each model family has its own template, stored with its tokenizer; using the wrong one quietly degrades quality.
- Store data as messages (JSONL) and let the tokenizer apply the template, rather than hand-writing token strings.
- Mask the loss so the model learns from assistant tokens, and end each reply with the end-of-turn token.
29.9 QLoRA training with TRL and Unsloth
- A QLoRA run loads the base in 4-bit, attaches LoRA adapters, trains them on formatted chat data, then saves the small adapter.
- Hugging Face TRL provides the trainer, PEFT the adapters and bitsandbytes the 4-bit loading; Unsloth wraps the same steps with faster, leaner kernels.
- Effective batch = per-device batch x gradient accumulation; optimiser steps = examples / effective batch x epochs.
- Watch validation loss and your own eval, not training loss alone; stop before the model overfits.
30Local inference8 lessons
30.1 Why run models locally
- Local inference runs a model on your own laptop, server or device instead of calling a hosted API.
- Reasons include privacy, offline use, predictable cost at high volume, low latency on device, and control.
- Costs include hardware, setup, lower capability than frontier models, and operating it yourself.
- Local models suit narrow tasks; hard reasoning usually still goes to a frontier API.
30.2 Quantization
- Quantization stores weights with fewer bits, such as 8 or 4 bits instead of 16.
- Fewer bits means less memory and often faster inference, with some loss in quality.
- 8-bit is usually close to full quality; 4-bit is a common sweet spot for local use; below that, quality drops faster.
- Formats like GGUF package quantized models for local runtimes.
30.3 Inference servers and runtimes
- Runtimes load a model and generate tokens; servers wrap them in an HTTP API for apps.
- Desktop-friendly tools (llama.cpp, Ollama and similar) make it easy to run quantized models on laptops.
- High-throughput servers (vLLM and similar) batch many requests efficiently on GPUs.
- Many expose an API shape that clients already understand, which eases switching.
30.4 Hardware: memory, GPUs and throughput
- Memory is the first limit: the weights plus the KV cache must fit in GPU (or unified) memory.
- Generation speed is often limited by memory bandwidth, not raw compute.
- Throughput (tokens per second across users) and latency (time per user) trade off through batching.
- Measure time to first token and tokens per second on your real prompts.
30.5 Hybrid setups: local models with a cloud fallback
- Hybrid setups run some requests locally and send others to a cloud model such as Claude.
- Route by data sensitivity, difficulty, connectivity and cost.
- Fall back to the cloud when the local model is unsure, overloaded or offline, but only for data allowed to leave.
- Keep one interface in your app so the route is configuration, and log every routing decision.
30.6 Quantization formats: GGUF, AWQ and FP8
- GGUF is a single-file format for llama.cpp and tools built on it, with many quantization levels such as Q4_K_M and Q8_0.
- AWQ is a 4-bit, weight-only method for GPUs that protects the weights that matter most to activations.
- FP8 stores numbers as 8-bit floats and is fast on recent data-centre GPUs with native FP8 support.
- The format follows the runtime and hardware: choose the runtime first, then a format it supports well.
30.7 Desktop runners: Ollama, LM Studio and llama.cpp
- llama.cpp is the inference engine; Ollama and LM Studio are friendlier runners, and both have built on llama.cpp.
- Ollama is command-line first and runs a background server; LM Studio is a desktop app with a model browser and a built-in server.
- All three can expose a local HTTP API, so your app calls localhost instead of a cloud endpoint.
- Pin the exact model file and settings, because the same model name can mean different quantizations.
30.8 Speculative decoding and other serving speed-ups
- Speculative decoding lets a small draft model guess several tokens, and the large model checks them all in one pass.
- Accepted guesses are free extra tokens; the verification rule keeps the output the same as the large model alone would give.
- The speed-up depends on how often the draft is right: high on predictable text, low on surprising text.
- Other speed-ups include continuous batching, paged KV cache, prefix caching and a quantized KV cache.
31Alignment and distillation5 lessons
31.1 Preference data: chosen and rejected
- A preference record is a prompt plus two answers, one marked chosen and one rejected.
- The pair should differ in the quality you want to teach, and as little as possible in anything else.
- Pairs come from human raters, from an AI judge guided by written principles, or from both.
- Check for length bias, ties, near-duplicates and rater disagreement before training.
31.2 DPO step by step
- DPO compares how much the model being trained has raised the chosen answer, relative to a frozen reference copy, against the rejected one.
- The loss is small when the chosen answer gained more than the rejected one, and large when it is the other way round.
- Beta sets how strongly the model is pulled away from the reference: higher beta means a sharper push and less drift allowed.
- No reward model and no sampling during training: just pairs, two models and an ordinary training loop.
31.3 GRPO and verifiable rewards
- GRPO samples several answers to the same prompt, scores each one, and compares every score with the group's average.
- Answers above the average are reinforced and answers below it are discouraged; no separate value model is needed.
- Verifiable rewards come from a checker, such as unit tests, an exact answer match or a format rule, not from a judge's opinion.
- If every answer in a group gets the same score, that group teaches nothing, so prompts must be neither too easy nor too hard.
31.4 Distillation: teacher and student models
- Distillation trains a small student model to copy a large teacher's behaviour on a task.
- Logit distillation copies the teacher's full probability spread; data distillation trains on the teacher's written answers.
- A distilled student can be far cheaper and faster on its narrow task, but it rarely beats the teacher there and loses breadth.
- Test the student on held-out examples with trusted labels, not only on agreement with the teacher, and check the teacher's terms of use.
31.5 Lab: build a small preference dataset
- Start from one narrow task and a written rating guide, then collect varied prompts.
- Generate two or more answers per prompt from the model you plan to tune, and rate them against the guide.
- Check length balance, ties, near-duplicates and agreement on a double-rated sample before you keep any pair.
- Split by prompt, so no prompt appears in both training and test, and save one JSON record per line.
06AI product and UX
32Designing AI products6 lessons
32.1 Designing for latency
- AI responses take seconds or minutes, so the interface must make waiting feel purposeful.
- Stream text as it's generated; show steps for agents; let users keep working meanwhile.
- Set expectations: say roughly how long a task will take and what's happening now.
- Cut real latency too: smaller models for simple steps, caching, parallel calls, lower effort.
32.2 Showing uncertainty and sources
- Users need cues to decide how much to trust an answer: sources, confidence and scope.
- Show citations next to the claims they support, and make them easy to open.
- Say clearly when the system doesn't know, or when an answer is outside what it covers.
- Avoid fake precision: an invented confidence percentage misleads more than it helps.
32.3 Human handoff and undo
- Give users an easy way to reach a person, and pass the context along so they don't repeat themselves.
- Put human approval before high-impact, irreversible actions.
- Offer undo, drafts and previews so users can recover from AI mistakes.
- Design the handoff from both sides: the user's experience and the human agent's screen.
32.4 Trust, onboarding and expectations
- Tell users what the feature does well, what it doesn't do, and that it can make mistakes.
- Show good example requests so users learn what to ask.
- Aim for calibrated trust: not blind faith, not total suspicion.
- Collect feedback in context, and show users that it leads to improvements.
32.5 Measuring business value
- Measure outcomes the business cares about: time saved, resolution rate, conversion, errors avoided.
- Pair them with quality and safety metrics, so gains don't hide harm.
- Compare against a baseline with experiments or holdouts, not before-and-after impressions.
- Count the full cost: model usage, infrastructure, human review and maintenance.
32.6 Worked example: streaming UX and citations
- Stream Claude's replies and render text as it arrives; show tool steps for agents.
- Use citations from document blocks to link claims to sources in the UI.
- Handle stop reasons visibly: show cut-off, refused or failed replies as such, not as finished answers.
- Keep the UI honest during errors: partial streams are marked incomplete, with a retry.
Track 2
Agentic AI
07Tool design and MCP
33The tool use loop6 lessons
33.1 Defining tools
- A tool definition is a name, a description and a JSON Schema for its input.
- The description is a prompt: say what the tool does, when to use it and when not to.
- Claude only sees the definition, never your implementation.
33.2 The request, tool_use, tool_result cycle
- Claude returns tool_use blocks with stop_reason tool_use; your code runs the tool.
- Results go back as tool_result blocks in a user message, matched by tool_use_id.
- Loop until stop_reason is end_turn, with a cap on iterations.
33.3 Parallel tool calls
- Claude can return several tool_use blocks in one turn when calls are independent.
- Run them (in parallel if you like) and return every result in one user message.
- Dependent calls happen across turns, because each needs the previous result.
33.4 tool_choice: auto, any, a named tool, none
- auto lets Claude decide; any forces some tool; tool forces a named tool; none forbids tools.
- Forcing a named tool is a reliable way to get structured output.
- Forcing skips Claude's free-text reasoning before the call, so use it deliberately.
33.5 Forcing tools to run in order
- Prompts express preferred order, but code enforces required order.
- Gate tools in your loop, expose them in stages, or force a named tool per step.
- Hooks can block a call that breaks a precondition.
33.6 Function calling from first principles
- Function calling is a contract: you describe functions in JSON Schema, the model replies with a name and arguments, and your code does the rest.
- The model never runs anything. It only writes a request, which may be wrong.
- Validate the name and the arguments before you execute, and send errors back as results the model can fix.
- The loop ends when the model answers in text or a turn cap is hit.
34Designing good tools6 lessons
34.1 Names and descriptions that don't confuse
- Claude chooses tools from their names and descriptions alone, so these are prompts.
- Say what the tool does, when to use it, when not to, and what it returns.
- Two tools with overlapping descriptions cause wrong picks; merge them or sharpen the line between them.
34.2 Input schemas and required fields
- The input schema is the contract for each call: types, required fields, allowed values.
- Enums and formats stop invalid values before your code runs.
- Describe each parameter, including units, formats and examples.
34.3 Structured errors: isError, errorCategory, isRetryable
- A tool error should tell the agent what went wrong and what to do next.
- Mark failures clearly (is_error in the API, isError in MCP) and include a category such as validation, permission, transient or business.
- Say whether a retry could help; never return an empty success when the call failed.
34.4 How many tools is too many
- Every tool definition costs context, and similar tools compete for selection.
- Accuracy drops as the list grows long, especially with overlapping tools.
- Give each agent or subagent only the tools for its role; load others on demand where the platform allows it.
34.5 Limiting what a tool can touch
- A tool should only reach the data and actions its job needs.
- Scope credentials, paths and queries inside the tool, not in the prompt.
- Prefer narrow actions (issue_refund up to a limit) to general ones (run_sql).
34.6 Feeding errors and stack traces back to the model
- Send the model the error type, a short message, the input that caused it and a suggested next step, not the whole trace.
- Keep the few frames from your own code that point at the cause; drop framework noise and repeated lines.
- Strip secrets, tokens, internal hostnames and personal data before any error text leaves the tool.
- For coding agents, the failing test name, assertion and the line in the user's code are the useful part.
35MCP explained6 lessons
35.1 Why MCP exists
- Without a standard, every AI app needs a custom integration for every tool: M apps times N tools.
- The Model Context Protocol (MCP) is an open standard so one server works with any compatible app.
- Build a tool once as an MCP server and use it from Claude Code, Claude Desktop, the Agent SDK and other clients.
35.2 Hosts, clients and servers
- The host is the AI app (such as Claude Code); it runs one MCP client per connected server.
- Servers expose capabilities; clients discover them and relay calls.
- Messages are JSON-RPC 2.0 requests and responses.
35.3 Tools, resources and prompts
- Tools are actions the model can call, such as create_issue.
- Resources are data the app can read into context, such as a file or a database schema.
- Prompts are reusable templates a user can pick, often shown as slash commands.
35.4 Transports: stdio and HTTP
- stdio runs the server as a local process and talks over standard input and output.
- Streamable HTTP runs the server remotely, shared by many users, with normal web authentication.
- stdio servers must never print logs to stdout, because that corrupts the protocol stream.
- In the 2026-07-28 revision, Streamable HTTP is stateless: no session id, routing headers on every request, and one opt-in stream for notifications. The older HTTP+SSE transport is deprecated.
35.5 The N×M problem: why a shared protocol pays off
- Pairwise glue costs N×M integrations; a shared protocol costs N clients plus M servers, so N+M.
- The bigger saving is maintenance: a change to one tool's API touches one server, not N integrations.
- A protocol has a fixed cost per side, so it only pays off once several apps and several tools share it.
- The protocol fixes messages, discovery, schemas, errors, transports and negotiation. Tool quality, consent and security stay with you.
35.6 Capability negotiation and the connection lifecycle
- In handshake-based revisions (2025-11-25 and earlier), every connection starts with initialize, its response, then notifications/initialized.
- The client offers its latest version; the server echoes it or offers its own latest; the client disconnects if it cannot speak that version.
- Each side may only use capabilities the other declared, such as tools, resources with subscribe, or listChanged notifications.
- Revision 2026-07-28 drops the handshake: each request carries its version and client capabilities in _meta, and server/discover reports what a server supports.
36Configuring MCP5 lessons
36.1 The `.mcp.json` file and scopes
- .mcp.json at the project root lists the team's shared MCP servers.
- Local scope is just you in this project; user scope is you in every project.
- Commit .mcp.json so the whole team gets the same servers, but never put secrets in it.
36.2 Environment variable expansion and secrets
- Reference secrets as ${VAR} in .mcp.json; each person sets the value in their own environment.
- ${VAR:-default} gives a fallback for non-secret values like URLs.
- Never commit tokens; rotate any that leak.
36.3 Splitting tools across agents
- Connecting a server exposes all its tools; you still decide which ones each agent may use.
- MCP tools are named mcp__<server>__<tool>, so allow and deny rules can target them.
- A research subagent might get read-only tools, while a separate agent holds the write tools.
36.4 Debugging an MCP server that won't connect
- Check the server's status first (/mcp in Claude Code) and read the error.
- Run the server command yourself in a terminal to see startup errors.
- Common causes: wrong command or path, missing environment variables, logs on stdout, and expired auth.
36.5 MCP authorization: OAuth 2.1 and client identity
- A remote MCP server is an OAuth resource server. It publishes metadata that names its authorization server, and the client gets a token from there.
- Clients identify themselves with a Client ID Metadata Document: an HTTPS URL that describes the client. Dynamic client registration is deprecated in the 2026-07-28 revision.
- Every token is bound to one server (its audience) and must be checked for that audience, issuer and scope on every request.
- Never pass the user's token through to a downstream API. Exchange it for a new token scoped to that API.
37Built-in tools5 lessons
37.1 File tools: Read, Write, Edit
- Read returns a file's contents, and can return a range of lines for large files.
- Edit replaces an exact string, which must be unique in the file; Write replaces the whole file.
- Prefer Edit for small changes: it's cheaper and less likely to clobber other content.
37.2 Bash, Grep and Glob
- Glob finds files by name pattern, such as **/*.test.ts.
- Grep searches file contents with regular expressions, and can return only matching file names.
- Bash runs shell commands such as tests and builds; scope it with permission rules.
37.3 Server tools: web search and code execution
- Client tools run in your code; server tools run on Anthropic's side and their results come back in the same response.
- Web search lets Claude search the web and cite sources; you can limit domains and the number of searches.
- Code execution runs code in a sandbox for analysis and charts.
37.4 Computer use
- Computer use lets Claude operate a desktop through screenshots, mouse and keyboard actions.
- Your code runs the actions in a sandboxed machine and returns new screenshots.
- Chapter 39 covers the loop, reliability and safety in depth.
37.5 Sandboxed code execution: containers and hosted sandboxes
- Code an agent writes is untrusted input that happens to be executable: run it somewhere it can't hurt you.
- A container (such as Docker) isolates code on your own machine; a hosted sandbox (such as E2B) runs it in a short-lived remote machine.
- Isolation alone is not enough: switch off the network, mount no secrets, cap CPU, memory and time, and throw the sandbox away afterwards.
- Containers share the host kernel, so for code from strangers prefer stronger isolation such as microVMs or gVisor.
38Agent interoperability and A2A7 lessons
38.1 Why agents need to talk to agents
- Organisations end up with many agents built on different frameworks and by different vendors.
- Without a shared protocol, each pair of agents needs custom glue.
- Agent-to-agent protocols let one agent hand a task to another without knowing how it's built.
38.2 MCP vs A2A: tools vs peers
- MCP connects an agent to tools and data: the agent stays in control and calls functions.
- A2A connects an agent to another agent: a peer with its own reasoning takes on a task.
- They're complementary: an agent can use MCP for its tools and A2A to work with other agents.
38.3 Agent cards, discovery and capabilities
- An agent card is a JSON document describing an agent: name, endpoint, skills, supported features and how to authenticate.
- Agents commonly publish their card at a well-known URL, or list it in a registry.
- Clients read the card to decide whether, and how, to send a task.
38.4 Tasks, messages and artifacts in A2A
- A task is the unit of work, with an id and a state such as submitted, working, input-required, completed or failed.
- Messages carry the conversation, made of parts: text, files or structured data.
- Artifacts are the outputs a task produces, such as a booking confirmation or a report.
38.5 Long-running tasks, streaming and push updates
- Short tasks can return in one response; long ones need progress updates.
- Streaming sends updates over an open connection while the client waits.
- Push notifications call the client's webhook when something changes, so nobody has to stay connected.
38.6 Security and trust between agents
- Authenticate both ways using the schemes listed in the agent card, such as OAuth 2.0.
- Treat everything a remote agent returns as untrusted input, just like a web page.
- Limit what remote agents can trigger, and keep a person in the loop for costly actions.
38.7 Worked example: exposing an agent over A2A
- There's no special switch: you wrap your Claude agent in an A2A server.
- The agent card advertises the agent's skills; incoming messages start or continue an Agent SDK run.
- Map run progress to task states, questions to input-required, and final outputs to artifacts.
39Computer use and browser agents5 lessons
39.1 The perception and action loop
- The loop: take a screenshot, decide an action, perform it, take a new screenshot, repeat.
- Each step is a full model call with an image, so tasks take many slow turns.
- Use computer use only where no API or structured tool exists.
39.2 Screenshots vs accessibility trees vs DOM
- Screenshots work on any app but need visual reasoning and precise coordinates.
- Accessibility trees give named, structured elements for native and web apps.
- In browsers, the DOM (or a cleaned-up version of it) allows precise targeting by element.
39.3 Reliability: waits, retries and verification
- Wait for pages and elements to settle before acting.
- After each important action, verify with a fresh screenshot that it worked.
- Set step and time limits, and recover from known blockers like pop-ups and logouts.
39.4 Safety: untrusted pages and confirmation steps
- Anything on screen can contain prompt injection: web pages, emails, documents, even images.
- Run computer use in an isolated VM or container with minimal access and no saved credentials.
- Require human confirmation before purchases, sending messages, deleting data or accepting terms.
39.5 Worked example: a computer use tool
- You add the computer use tool to a request with the screen size; Claude replies with actions such as screenshot, click, type and key.
- Your code performs each action in a sandboxed desktop and returns a screenshot as the tool result.
- Anthropic provides a reference implementation with a container, which is the easiest way to start.
08Agentic AI and orchestration
40Workflows vs agents3 lessons
40.1 What makes a system agentic
- In a workflow, your code decides the steps. In an agent, the model decides the next step at run time.
- Every agent has a model, tools it can call, and a loop that feeds results back until a stop condition.
- Agentic is a spectrum: most useful systems mix fixed steps with a few model-made choices.
40.2 When a workflow is enough
- If you can draw the steps as a flowchart before the task starts, use a workflow.
- Agents pay off when the number and order of steps depends on what the model finds.
- Start with one well-prompted call, then a workflow, then an agent, and let evals justify each step up.
40.3 The cost of autonomy
- Each extra turn re-sends the whole conversation, so agent cost grows faster than the number of steps.
- Errors compound: ten steps that are each 95% right finish correctly only about 60% of the time.
- Agents need turn limits, budgets, tracing, sandboxed tools and a way to hand off to a person.
41Workflow patterns5 lessons
41.1 Prompt chaining
- Chaining splits a task into fixed, sequential LLM calls.
- Code gates between steps catch problems early.
- It trades latency for accuracy on each simpler step.
41.2 Routing
- Routing classifies the input, then sends it down a specialised path.
- Each route gets its own prompt, tools or model, tuned independently.
- Easy requests can go to a smaller, cheaper, faster model.
41.3 Parallelization: sectioning and voting
- Sectioning runs different parts of a task at the same time.
- Voting runs the same task several times and compares answers.
- The split is fixed in code; results are combined in code.
41.4 Orchestrator-workers
- An orchestrator LLM decides the subtasks at run time.
- Workers handle subtasks; a final step synthesizes their results.
- Use it when the split depends on the input and cannot be hard-coded.
41.5 Evaluator-optimizer
- One call generates; another evaluates against explicit criteria and gives feedback.
- The loop repeats until approval or a round limit.
- Works when clear criteria exist and feedback measurably improves the result.
42The agent loop and agent SDKs4 lessons
42.1 The agent loop
- The loop: gather context, take an action, check the result, and decide whether to continue.
- Checking can be a test run, a linter, a schema check or a second model call.
- The loop ends on a stop condition you choose, not only when the model says it's done.
42.2 Building with an agent SDK
- The Agent SDK runs the agent loop for you: tool calls, results, context management and retries.
- query() streams messages; the final one has type "result" with the answer, turn count and cost.
- allowedTools limits which tools the agent may use; start narrow and widen only when needed.
42.3 Stop conditions, turn limits and budgets
- Every agent needs a hard turn limit and a cost or time budget enforced in code.
- Detect loops: the same tool called with the same input several times means stop.
- When a limit trips, end gracefully: say what was done, what wasn't, and what happens next.
42.4 Session state across turns
- Within a run, state is the conversation history the loop sends each turn.
- Agent SDK sessions can be resumed by id, so a later query continues with the same history.
- Store durable facts (decisions, progress, ids) outside the conversation, in files or a database.
43Subagents5 lessons
43.1 Why use subagents
- A subagent runs with its own context window and returns only a summary to its parent.
- Use subagents to keep exploration out of the main context, to run independent work in parallel, or to give a task narrower tools.
- Subagents add tokens and coordination; tightly coupled tasks are better kept in one agent.
43.2 The Task tool and allowedTools
- The parent starts subagents through the Task tool; the subagent's description tells the parent when to use it.
- Each subagent can have its own tools list, so a reviewer can be read-only.
- The parent must be allowed to use the Task tool, or it cannot start subagents at all.
43.3 Passing the right context to a subagent
- A subagent starts with no memory of the parent's conversation; it only knows what the brief says.
- A good brief has the goal, the relevant facts, the boundaries and the exact shape of the result.
- Ask for compact, structured results so the parent's context stays small.
43.4 Propagating errors instead of swallowing them
- A subagent that hides a failure ("no results") makes the parent believe something false.
- Report errors explicitly: what failed, why, and whether a retry could help.
- The parent then retries, reroutes, or tells the user about the gap.
43.5 Handling partial failure
- Decide up front which subagent results are required and which are optional.
- Retry failed subagents a limited number of times, then continue with what you have if the task allows.
- Always say which parts are missing, so nobody mistakes a partial answer for a complete one.
44Hooks and the agent lifecycle4 lessons
44.1 Lifecycle events
- Hooks are your code that runs at fixed points in the agent's lifecycle, outside the model.
- Key events: SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, Stop, SubagentStop, PreCompact, SessionEnd and Notification.
- Because a hook is code, it runs every time. The model can't forget or talk its way past it.
44.2 PreToolUse: block or modify a call
- PreToolUse runs before the tool, so it is the place to stop a bad call before anything happens.
- A hook can return allow, deny or ask, with a reason the model sees.
- In Claude Code a command hook reads JSON on stdin; exit code 2 blocks the call and sends stderr back to Claude.
44.3 PostToolUse: check or log a result
- PostToolUse runs after the tool, so it can't prevent the call, but it can check and react to the result.
- Common uses: run the formatter or tests after an edit, flag bad output, and write an audit log.
- A Stop hook can refuse to let the agent finish until a check passes, which turns 'done' into a tested claim.
44.4 Hooks vs prompt instructions
- Prompts guide behaviour well most of the time; hooks and permissions enforce it every time.
- Use prompts for judgment and style, permissions for which tools exist, and hooks for conditional rules on inputs and outputs.
- If breaking a rule once would be costly or irreversible, enforce it in code.
45Guardrails and escalation4 lessons
45.1 Permissions and least privilege
- Give an agent only the tools and scopes its task needs, and nothing it might need someday.
- Claude Code settings have allow, deny and ask lists; deny wins over allow.
- Scope credentials too: a read-only token can't be talked into writing.
45.2 Human-in-the-loop checkpoints
- Put a person in the loop before actions that are irreversible, costly or visible to others.
- Show the reviewer exactly what will happen: the tool, the inputs and the expected effect.
- Too many approvals train people to click yes without reading, so ask only where it matters.
45.3 When to escalate instead of resolve
- Escalate when the agent lacks authority, lacks information, sees conflicting policy, or the customer asks for a person.
- Don't escalate on sentiment alone; an annoyed customer with a simple problem still wants it solved.
- A good handoff includes a summary, what was tried, the facts found and the decision needed.
45.4 Prompt injection and untrusted content
- Prompt injection is text in a web page, email, file or tool result that tries to give the agent new instructions.
- Tell the model that tool content is data, but don't rely on that alone; models can still be fooled.
- Limit the damage: least privilege, approval before risky actions, and hooks that check outgoing calls.
09Agent architectures
46ReAct3 lessons
46.1 Reason, act, observe
- ReAct interleaves reasoning and acting: think about what to do, take an action, read the result, repeat.
- Each observation feeds the next thought, so the agent adapts to what it finds.
- It suits open-ended tasks where you can't plan every step in advance.
- The loop needs a stop rule: an answer, a step limit, or a budget.
46.2 ReAct with native tool use
- Claude's tool-use loop is ReAct built into the API: thinking or text, then tool_use, then your tool_result.
- You don't need to parse 'Thought:' and 'Action:' strings; tool calls arrive as structured blocks.
- Adaptive thinking gives a hidden reasoning step between tool calls.
- Your code owns the loop: run tools, return results, enforce limits.
46.3 Failure modes: loops and drift
- Loops: the agent repeats the same action because results don't change its view.
- Drift: the agent wanders off the user's goal after many steps.
- Fixes include step limits, detecting repeated calls, clearer tool errors, and restating the goal.
- Log full traces so you can see exactly where a run went wrong.
47Plan-and-execute and ReWOO5 lessons
47.1 Planning up front
- Plan-and-execute splits the work: a planner writes the steps, then executors carry them out.
- Planning up front gives structure, predictable cost and a plan humans can review.
- It's weaker when early results should change the plan, so add replanning.
- Executors can be cheaper models, since each step is narrow.
47.2 ReWOO: planning without observations
- ReWOO (Reasoning WithOut Observation) plans every tool call up front, using placeholders for results it hasn't seen.
- A worker runs all the calls, then a solver writes the answer from the plan plus the results.
- It saves tokens because the model isn't re-prompted with growing history after each call.
- It can't react to surprises mid-run, so it suits predictable, lookup-style tasks.
47.3 Replanning when a step fails
- Replanning updates the remaining plan when a step fails or returns something unexpected.
- Trigger it on errors, on results that break the plan's assumptions, or at checkpoints.
- Pass the planner the goal, what's done, what failed, and why.
- Limit replans, and escalate to a human when the plan keeps failing.
47.4 Plan mode in a coding agent as an example
- Plan mode in Claude Code has Claude explore and propose a plan without editing files or running changes.
- You review and refine the plan, then let it execute.
- It's plan-and-execute with a human approval gate between the two halves.
- Use it for multi-file or risky changes; skip it for small, obvious edits.
47.5 Task decomposition: splitting work an agent can finish
- A good subtask fits in one context, uses a few tool calls and ends with a check you can run.
- Split by step for pipelines, by component for systems, and by question for research.
- Write dependencies as a small graph: subtasks with no unmet dependencies can run in parallel.
- Do not decompose when the task is small, or when the parts depend on each other so tightly that splitting loses the context.
48Reflection and self-critique3 lessons
48.1 Self-critique loops
- A self-critique loop drafts, critiques against criteria, then revises.
- Critique works best against explicit, checkable criteria, not 'make it better'.
- Gains are real for writing, code and analysis, but usually shrink after one or two rounds.
- Tool feedback (tests, linters, validators) beats the model's opinion of its own work.
48.2 Separate critic vs same-model reflection
- Same-model reflection asks the author to review its own work; it's cheap but shares the author's blind spots.
- A separate critic uses a fresh context, a different prompt, or another model, and catches more.
- A fresh context matters most: a reviewer that didn't write the draft judges it more fairly.
- For high-stakes outputs, add independent checks: tools, a second model, or a person.
48.3 Knowing when to stop
- Stop when the criteria pass, when a round limit is hit, or when changes stop improving the score.
- Endless revision can make outputs worse: longer, blander, or drifting from the task.
- Track a score or a checklist per round so you can see when gains flatten.
- If the limit is hit without passing, return the best version and flag what still fails.
49Multi-agent topologies5 lessons
49.1 Supervisor
- A supervisor agent receives the task, delegates parts to worker agents, and combines their results.
- Workers have narrow roles and tools; the supervisor holds the plan and the final answer.
- It's the most common multi-agent shape and the easiest to debug.
- The supervisor can become a bottleneck, and everything depends on how well it delegates.
49.2 Hierarchical teams
- Hierarchical teams stack supervisors: a top supervisor manages team leads, who manage workers.
- It mirrors an organisation chart and suits very large tasks with distinct sub-domains.
- Each layer adds latency, cost and a place where information gets lost.
- Most tasks need at most one supervisor layer; add more only when one supervisor is overwhelmed.
49.3 Pipelines and handoffs
- A pipeline passes work through fixed stages, each handled by a specialised agent or prompt.
- A handoff transfers the conversation or task to another agent, which takes over completely.
- Pipelines are predictable and easy to test stage by stage.
- Handoffs need a clear payload: the goal, what's done, the key facts and what's expected next.
49.4 Swarms and peer-to-peer
- In a swarm, agents talk to each other directly with no central controller, passing work as they see fit.
- It can explore widely and adapt, but is hard to predict, bound and debug.
- Costs and loops can grow quickly without a coordinator to stop them.
- Most production systems prefer a supervisor or pipeline, using peer messaging only within clear limits.
49.5 Shared vs isolated context
- Shared context gives every agent the full history; isolated context gives each agent only what its job needs.
- Isolation keeps each context small and focused, and stops one agent's noise confusing another.
- Sharing avoids re-explaining but costs tokens and spreads irrelevant detail.
- A common middle ground: isolated workers, plus a shared store of results and references.
50Choosing an architecture4 lessons
50.1 Start simple
- Use the simplest design that meets the need: a single call, then a workflow, then one agent, then several.
- Each step up adds cost, latency and new ways to fail.
- Move up only when you can show the simpler design falls short on your eval.
- Many 'agent' problems are solved by better prompts, retrieval or a fixed workflow.
50.2 Cost and latency trade-offs
- Cost grows with the number of calls and with how much context each call re-sends.
- Agents re-send growing history every step; multi-agent systems multiply that by the number of agents.
- Latency comes from sequential steps; parallel calls and smaller models cut it.
- Prompt caching, compaction and lower effort are the main levers once the shape is chosen.
50.3 Reliability and debuggability
- Fixed workflows are the most predictable; open agents trade predictability for flexibility.
- Every extra agent and handoff adds a place where errors can start or get hidden.
- Debuggability needs full traces: every prompt, tool call, result and decision.
- Put hard rules in code (permissions, validation, hooks), not only in prompts.
50.4 Worked decision examples
- Start from the task's shape: fixed steps, open-ended investigation, or broad parallel exploration.
- Then apply constraints: latency, cost, risk of actions, and need for human review.
- Choose the simplest architecture that fits, and say what would make you change it.
- Exam scenarios usually hinge on one constraint; find it first.
51Agent frameworks compared6 lessons
51.1 What a framework gives you, and what it hides
- Frameworks give you a loop, tool plumbing, state, memory helpers, tracing and multi-agent patterns.
- They save time but can hide the prompts, the message history and the exact calls being made.
- Hidden behaviour makes debugging and cost control harder.
- Whatever you use, make sure you can see the final prompt and every model call.
51.2 Vendor agent SDKs
- The Claude Agent SDK is the harness behind Claude Code, packaged as a library for Python and TypeScript.
- It includes the agent loop, built-in tools (files, shell, search), sessions, hooks, subagents and permissions.
- You can add your own tools, often as MCP servers.
- It fits agents that work with files, code and commands, or that want Claude Code's proven controls.
51.3 Graph-based frameworks (LangGraph and similar)
- Graph frameworks (LangGraph and similar) model an agent as nodes (steps) and edges (transitions) over shared state.
- They make control flow explicit: loops, branches, retries and human-approval steps are drawn into the graph.
- Checkpointing state lets runs pause, resume and be inspected.
- The trade-off is more structure and framework concepts to learn.
51.4 Multi-agent frameworks and conversation-style orchestration
- Some frameworks (CrewAI, the group-chat patterns in Microsoft Agent Framework, and similar) organise agents as roles that talk to each other in a conversation or crew.
- You define roles, goals and tools; the framework manages turn-taking and task handoffs.
- They're quick for prototyping multi-role ideas, but conversations can wander and cost a lot.
- Add turn limits, clear termination conditions and tracing before production use.
51.5 No framework: the plain loop
- A plain loop is a few dozen lines: call the model, run any tool calls, send results back, stop on a final answer.
- You see and control every prompt, call and token.
- You write your own state, retries, tracing and limits, which is often less work than it sounds.
- It's a strong default for small to medium agents and for learning how agents really work.
51.6 Choosing for your team
- Choose by the job: file and code agents, explicit graphs with checkpoints, role-based prototypes, or a plain loop.
- Weigh your team's skills, observability needs, model features and how hard it would be to leave.
- Keep business logic and tools in your own code, so they move with you.
- Pilot with your eval set before committing.
52Graph-based orchestration6 lessons
52.1 Agents as state machines: nodes, edges and state
- A graph agent is a state machine: nodes do work, edges decide what runs next, and a shared state object carries everything between them.
- Each node reads the state and returns only the fields it changed; the runtime merges the update.
- Design the state first. If a value is not in the state, no later node can see it, and no checkpoint can save it.
- Small, well-named nodes make the graph easy to review, test and trace.
52.2 Conditional edges and cycles
- A conditional edge is a small function that reads the state and returns the name of the next node.
- Cycles (edges that point back to an earlier node) are what let a graph retry, fix and refine.
- Every cycle needs a guard: a counter in the state, checked by the router, plus the framework's own step limit as a backstop.
- Route on facts in the state (a test result, a score, a flag), not on the model's free text.
52.3 Lab: loop until the tests pass
- A graph runner is a short loop: run the current node, merge its update into the state, ask the edge which node is next.
- The test node is ground truth: it runs real checks and writes passed and failures into the state.
- The router after test picks done, fix or give up, and the attempt counter keeps the cycle bounded.
- A run ends with a clear status, either passed or gave_up, never a silent success.
52.4 Interrupt, inspect and resume
- A checkpointer saves the state after every node, keyed by a run or thread id, so a run can stop and continue later.
- An interrupt pauses the run before (or inside) a node and waits for outside input, typically a human approval.
- While paused, a person can inspect the state, edit it, and then resume from the same point.
- Nodes with side effects must be safe to run again, because a resumed or replayed run may repeat them.
52.5 Streaming intermediate events to the UI
- Long graph runs feel broken if the screen stays blank; streaming events shows progress as each node starts and finishes.
- Stream three levels as needed: node progress, state updates, and model tokens inside a node.
- Give every event a run id, a sequence number and a type, so the UI can order, de-duplicate and reconnect.
- Send the UI what it needs to show, not the whole state; leave out secrets and raw internals.
52.6 Graph frameworks compared
- Graph-style tools differ mainly in how you declare the graph, how state is stored, and how pauses and streaming work.
- Explicit graph libraries (LangGraph, pydantic-graph and similar) draw nodes and edges; event-driven tools (LlamaIndex Workflows, CrewAI Flows and similar) wire steps by the events they emit.
- Durable workflow engines (Temporal and similar) are not agent-specific but give strong retries and long-running state.
- A plain-Python graph like the one in 102.3 is often enough; adopt a tool when you need its checkpoints, interrupts or tracing.
53Specialised agents: coding, research and browser5 lessons
53.1 Coding agents: repo maps, diffs and test loops
- A coding agent cannot read a whole repo, so it starts from a repo map: files, symbols and how they connect.
- It changes code as small diffs, which are cheap to review, easy to apply and easy to undo.
- The test run is the agent's feedback signal: edit, run, read the failure, edit again, with a step limit.
- A failing test written before the fix is the clearest definition of done.
53.2 Deep research agents: search, read, synthesise
- A deep research agent plans sub-questions, fans out searches, reads the best sources and writes a cited report.
- Parallel workers each search one sub-question in their own context and return short, sourced notes.
- Every claim in the final report should point to a source the agent actually read.
- Set a budget for searches and pages, and stop when new sources stop adding new facts.
53.3 Browser agents with Playwright
- Playwright is a browser automation library: code opens pages, finds elements and clicks, types and reads.
- A browser agent wraps Playwright actions as tools and lets the model choose the next action from a snapshot of the page.
- Locators by role, label or text are far more reliable than coordinates, and Playwright waits for elements to be ready.
- Check the page after every action, and keep risky actions behind a confirmation step.
53.4 Sandboxing specialised agents
- Specialised agents run code, open pages and touch files, so each run belongs in a sandbox, not on a person's machine.
- Sandboxes range from restricted processes to containers to micro-VMs; stronger isolation costs more start-up time.
- Limit four things: the files it can see, the network it can reach, the secrets it holds and the time and resources it can use.
- Throw the sandbox away after the run and keep only the outputs you asked for, such as a diff or a report.
53.5 Lab: a bug-fixing agent in a sandbox
- The lab loop is: run tests, read the failure, propose one small edit, apply it in the sandbox, run tests again.
- The sandbox holds a copy of the code; only the final diff and the test log come out.
- A step limit and a 'no edits to tests' rule stop the agent from looping forever or cheating.
10Memory for agents
54The memory types map5 lessons
54.1 Short-term vs long-term
- A model has no memory between calls: everything it 'remembers' is in the context you send.
- Short-term (working) memory is the current context window: this conversation, these tool results.
- Long-term memory lives outside the model in stores you build, and is loaded back into context when needed.
54.2 Episodic memory: what happened
- Episodic memory records what happened: past conversations, tasks, outcomes and mistakes.
- Raw transcripts are too long to reload; store short summaries with time, participants and outcome.
- Episodes help agents stay consistent with past decisions and avoid repeating failures.
54.3 Semantic memory: facts
- Semantic memory holds facts: user preferences, account details, project conventions, domain knowledge.
- Store facts as small, separate entries with a source and date, so they can be updated or removed.
- Facts from a system of record (like a database) should be looked up fresh, not copied into memory.
54.4 Procedural memory: how to do things
- Procedural memory holds how to do things: steps, checklists, house style, tool recipes.
- In practice it often lives in system prompts, CLAUDE.md files, skills and few-shot examples.
- Procedures can be learned: when an agent finds a working method, save it for next time.
54.5 Short-term memory in practice
- Short-term memory is the message buffer you send with each request, and it has a token budget.
- Trimming drops the oldest turns: cheap and exact, but it forgets.
- Summarising folds old turns into a short note; pinning keeps key facts at the top so neither trimming nor summarising loses them.
- Promote a fact to long-term memory when it should outlive this session, such as a stable preference or a decision.
55Working memory4 lessons
55.1 The context window as working memory
- The context window is everything the model can see right now; it's the agent's working memory.
- It has a hard size limit, and quality can drop well before the limit when it's full of clutter.
- Long agent runs fill it with tool results and history; plan for trimming and summarising.
55.2 Session state and scratchpads
- Session state is structured data your app keeps for the session: ids, progress, decisions.
- A scratchpad (or notes file) is where an agent writes plans and findings during a task.
- Keeping state outside the chat lets you rebuild a clean context at any time.
55.3 What to keep in context and what to store
- Keep in context what the next steps need; store what may matter later; drop what won't.
- Large tool results can be summarised or replaced with a pointer once used.
- Durable facts and decisions move to long-term memory at the end of a session.
55.4 Sliding windows and recursive summaries
- A sliding window keeps only the last N turns (or the last N tokens) in full; everything older leaves the context.
- A recursive summary keeps what left: each time turns slide out, the old summary plus those turns become a new summary.
- Measure the window in tokens, and never split a tool call from its result.
- Summaries of summaries drift, so pin exact facts outside the summary.
56Long-term stores4 lessons
56.1 Vector databases
- A vector database stores embeddings and finds items by meaning, not exact words.
- Good for large, fuzzy memory: past conversation summaries, notes, documents.
- Always store metadata (user, date, type) alongside vectors so you can filter and expire memories.
56.2 Key-value and relational stores
- Key-value stores give fast exact lookups: user id to preferences, session id to state.
- Relational databases hold structured facts with relationships and are queried precisely.
- Expose them to the agent through narrow tools, not raw query access.
56.3 File-based memory: project memory files and memory tools
- Plain files are a simple, readable, versionable memory: easy for people and agents to inspect and edit.
- Claude Code loads CLAUDE.md files as project and user memory at the start of each session.
- Claude's memory tool lets an agent create, read and update files in a memory directory that your app stores.
56.4 Choosing a store
- Match the store to the question: exact lookups to key-value or SQL, fuzzy recall to vectors, curated notes to files.
- Systems of record stay the source of truth; memory holds what they don't.
- Start simple; add a vector store only when you have enough memory that search is needed.
57Managing memory over time5 lessons
57.1 Deciding what to remember
- Not everything is worth remembering: store what is durable, specific and likely to matter again.
- Good memories: stated preferences, decisions, recurring problems, and lessons from failures.
- Ask the user before storing sensitive facts, and let them see and delete what's stored.
57.2 Retrieving the right memory
- Retrieve a few relevant memories, not all of them; more memory isn't better context.
- Rank by a mix of relevance (similarity to the task), recency, and importance.
- Filter by owner and type first, then rank; show memories with their date and source.
57.3 Consolidation and summarization
- Memory stores grow messy: duplicates, near-duplicates and contradictions pile up.
- Run consolidation: merge duplicates, update changed facts, and summarise many small episodes into fewer larger ones.
- Keep provenance so a merged memory can be traced back to its sources.
57.4 Forgetting, privacy and stale memories
- Memories go stale; give them lifetimes and lower the weight of old, unused ones.
- Users must be able to see and delete what's stored, and deletion must reach every store and copy.
- Treat stored memories as untrusted input: a poisoned memory can steer future sessions.
57.5 Memory layers in practice: extract, update and decay
- A memory layer sits between your agent and its stores: after each exchange it extracts candidate facts, then reconciles them with what is already stored.
- Reconciling means one of four operations per candidate: add, update, delete or do nothing.
- Decay lowers the weight of memories that are old and unused, so retrieval favours what is fresh and useful.
- Mem0 is one open-source example of this pattern; you can also build it yourself with a model call and a store.
11Context engineering and reliability
58Context engineering7 lessons
58.1 Context engineering as a discipline
- Context engineering is choosing what goes into the model's context on each turn: instructions, tools, data, history.
- The context window is a limited budget, and attention spreads thinner as it fills.
- The goal is the smallest set of high-signal tokens that lets the model do the next step well.
58.2 Just-in-time retrieval
- Instead of pasting everything at the start, give the agent tools to fetch what it needs when it needs it.
- Keep lightweight references, such as file paths, URLs and ids, and load the content only when used.
- This is how coding agents handle big repos: search, then read only the relevant files.
58.3 Trimming and clearing tool results
- Tool results are often the largest part of an agent's context.
- Once a result has been used, its raw content is rarely needed again.
- Replace old results with a short placeholder or summary, keeping ids so they can be fetched again if needed.
58.4 Subagent context isolation
- A subagent explores in its own context window and returns only a short result.
- The main agent's context stays focused on the overall task.
- Ask for a compact, structured result: findings, sources, and what's still unknown.
58.5 Notes files and external memory
- Agents can write notes, such as a progress file or a to-do list, and read them back later.
- Notes survive compaction and new sessions, so the agent doesn't lose track.
- Keep notes short and structured: goal, decisions, done, next.
58.6 Worked example: context editing and a memory tool
- Context editing can automatically clear older tool results once the context passes a threshold you set.
- The memory tool lets Claude create, read and update files in a memory directory that persists across conversations.
- With the memory tool, your application stores the files, so you control where data lives and how long.
58.7 Skills and progressive disclosure
- A skill is a folder holding a SKILL.md file (a short name and description, then instructions) plus optional scripts, templates and reference files.
- Progressive disclosure: the agent sees only each skill's name and description until a task needs it, then loads the instructions, then any extra files.
- Skills package procedures (how to do things). Tools perform actions, and retrieval supplies facts.
- The format is open and used by several agent products, so a skill written once can travel between them.
59Budgeting the context window3 lessons
59.1 Where tokens go
- A request's tokens come from the system prompt, tool definitions, history, documents and tool results.
- Count before cutting: the token counting endpoint and the usage field show what each part costs.
- Output tokens cost more than input, and max_tokens must leave room for the answer.
59.2 Trimming tools and history
- Load only the tools the current task needs, and keep their descriptions tight.
- Trim history: drop small talk, clear old tool results and summarise older turns.
- Cache the stable prefix (system prompt and tools) so repeating it costs much less.
59.3 Lost in the middle: where to put key facts
- Models tend to use information at the start and end of a long context better than information buried in the middle.
- For long inputs, put documents near the top and your question and instructions at the end.
- Repeat or pin critical facts near the end, and ask the model to quote relevant passages first.
60Summarization and compaction4 lessons
60.1 Progressive summarization
- Progressive summarisation keeps recent turns in full and replaces older turns with a running summary.
- The summary should keep goals, decisions, facts, open questions and commitments.
- Summaries lose detail, so keep exact values such as ids, amounts and dates verbatim.
60.2 Compaction
- Compaction replaces the conversation so far with a summary so the agent can keep working.
- Claude Code compacts automatically near the limit, and on demand with /compact.
- Give compaction instructions: what must survive, such as the plan, failing tests or file paths.
60.3 Context editing and clearing tool results
- Clearing old tool results is cheap and loses little if the results were already used.
- Summarising history costs a model call and can lose detail.
- Try clearing tool results first; summarise only when the conversation itself is too long.
60.4 Preserving critical information
- Some facts must never be paraphrased or dropped: ids, amounts, deadlines, constraints, promises.
- Keep them in a structured 'case facts' block that is copied forward unchanged.
- Check that summaries didn't contradict the pinned facts.
61Sessions4 lessons
61.1 Resuming a session
- Resuming loads a saved session's history so the agent continues where it stopped.
- In the Agent SDK pass resume with a session id; in Claude Code use --continue or --resume.
- Resume when the earlier context helps; start fresh when it's stale or unrelated.
61.2 Forking with fork_session
- Forking creates a new session that starts with a copy of an existing session's history.
- The original session is left unchanged, so you can compare approaches side by side.
- In the Agent SDK set forkSession (fork_session in Python) when resuming; Claude Code has --fork-session.
61.3 Isolating sessions
- Each user, ticket or CI job should get its own session.
- Shared sessions can leak one user's data into another's answers.
- Store session ids with an owner and an expiry, and check ownership before resuming.
61.4 Checkpointing agent state to SQLite or Postgres
- A checkpoint is a saved snapshot of an agent's state after a step, keyed by a thread id and a step number.
- Write the checkpoint after each step commits, so a restart resumes from the last good step instead of from zero.
- SQLite suits one process on one machine; Postgres suits many workers, many users and production backups.
- Checkpoints let you resume, replay and inspect a run, but tools with side effects still need idempotency keys.
62Long documents and large codebases3 lessons
62.1 Long documents: chunk, summarize, cite
- Split long documents into chunks along natural boundaries such as sections.
- Process chunks separately (map), then combine the results (reduce).
- Keep source references on every extracted fact so answers can cite pages or sections.
62.2 Exploring large codebases without overflowing context
- Start with structure: directory layout, README, CLAUDE.md, entry points.
- Use Grep and Glob to find relevant code, then read only those parts.
- Delegate broad exploration to subagents that return short findings.
62.3 Multi-turn state that lasts
- In long interactions, keep important state in structured form, not only in the chat history.
- Update state through tools so changes are explicit and logged.
- Give the model the current state each turn, rather than making it reconstruct state from history.
63Reliability4 lessons
63.1 Confidence scoring
- Ask for a confidence level or evidence with each output, and route low-confidence items to review.
- Self-reported confidence is a rough signal; calibrate it against labelled data.
- Better signals: agreement between runs, validation checks and whether evidence was found.
63.2 Retries and idempotency
- Retry transient failures (429, 500, 529, timeouts) with exponential backoff and jitter; don't retry invalid requests.
- Retrying an action with side effects can repeat it: two refunds instead of one.
- Use idempotency keys so a repeated request has the same effect as one.
63.3 Graceful fallback
- Plan what happens when the model, a tool or a dependency is slow or down.
- Fallbacks include a different model, a cached answer, a simpler path, or a hand-off to a person.
- Tell users honestly what happened; don't make up an answer.
63.4 Observability and logging
- Log every model call and tool call with inputs, outputs, tokens, latency and errors, linked by a run id.
- Watch error rates, latency, cost per task, turns per task and escalation rate.
- Redact secrets and personal data before logging.
12Guardrails and agent security
64Guardrails in depth11 lessons
64.1 Where guardrails sit in a system
- Guardrails are checks around the model: before input reaches it, on what it decides to do, and on what it outputs.
- No single layer is perfect, so stack several cheap ones (defence in depth).
- Put each check where it's cheapest and most reliable: often in code, not in the prompt.
64.2 Input filtering and classification
- Input checks catch problems early: oversized inputs, personal data, off-topic or abusive requests, likely jailbreaks.
- Rules (length, regex, allow-lists) are cheap and predictable; small model classifiers handle fuzzier cases.
- Decide what to do on a hit: block, redact, ask for clarification, or route to a person.
64.3 Output filtering and validation
- Validate structure: does the output match the schema and business rules?
- Check content: personal data, unsafe content, promises the business can't keep.
- Check grounding: are claims supported by the sources the model was given?
64.4 Policy layers: rules outside the prompt
- A policy layer is code that decides who may do what, using facts the model can't change.
- Rules like refund limits, data access and role permissions belong there, not only in the prompt.
- The prompt can explain the rules so the model rarely hits them; the policy layer enforces them.
64.5 Approval gates for risky actions
- Approval gates pause an action until a person (or a stricter system) says yes.
- Gate actions that are irreversible, costly, external or unusual for this user.
- Show the reviewer the exact action and its effect, and log who approved it.
64.6 Content moderation pipelines
- Define clear categories and policies first; the model applies them.
- Use a fast model for first-pass labels with reasons, and send borderline cases to people.
- Measure precision and recall per category on a labelled set, and revisit as policies change.
64.7 Testing guardrails: false positives and bypasses
- A guardrail that blocks good requests hurts users; one that misses bad ones hurts safety. Measure both.
- Build test sets of normal requests, edge cases and known attacks, and run them in CI.
- Re-test when prompts, models or policies change.
64.8 Worked example: hooks, permissions and moderation prompts
- Claude Code and the Agent SDK give you permission rules, permission modes, hooks and canUseTool for action checks.
- A small, fast Claude model makes a good input or output classifier with a strict schema.
- Combine them: classify input, enforce policy on tools, validate output, and log every decision.
64.9 Topical and off-rail classifiers
- A topical classifier labels each request as in scope, out of scope or unsure, before the main model answers.
- Define scope with a written list of allowed topics plus examples near the edge, not with a list of banned words.
- Off-rail does not mean harmful: answer with a polite redirect, and send unsure cases down a careful path.
- Measure it on real traffic: blocking good questions is a failure too.
64.10 PII and secret detection and redaction
- Scan at every boundary: user input, tool results, model output and anything written to logs.
- Combine detectors: patterns with checksums for structured data, named-entity models for names and addresses, entropy and known prefixes for secrets.
- Redact with typed placeholders such as <EMAIL_1> so the model can still reason about the text.
- Reversible tokens restore the real values only at the last step, in code the model cannot see.
64.11 Guardrail frameworks compared
- Guardrail tools fall into a few kinds: rail and dialogue frameworks, validator libraries, safety classifier models, PII tools and managed cloud services.
- Each kind covers some layers well and others not at all; most systems combine two or three.
- Whatever you choose, permissions and policy for actions still live in your own code.
- Judge a framework on your own test sets: latency added, false blocks and bypasses.
65Agent security10 lessons
65.1 Threat modelling an agent
- List what an attacker might want (assets), where they can reach in (entry points), and where trust changes (boundaries).
- For agents, every source of text the model reads is an entry point, not only the user.
- Rank threats by likelihood and impact, then design controls for the top ones.
65.2 Direct and indirect prompt injection
- Direct injection: the user types instructions to override the system prompt.
- Indirect injection: instructions hide in content the agent reads, such as a web page, email, file or tool result.
- Indirect injection is worse for agents, because the attacker needn't be the user and the agent can act on it.
65.3 Tool and MCP server poisoning
- A malicious or compromised tool can hide instructions in its description or results.
- Tool descriptions are read by the model, so they're a prompt-injection channel too.
- Vet third-party MCP servers, pin versions, review changes, and restrict what each can access.
65.4 Data exfiltration through tools
- Exfiltration is getting private data out: through emails, HTTP requests, file writes, even rendered image links.
- The dangerous mix is private data plus untrusted input plus a way to send data out.
- Remove at least one of the three, or put a gate on outbound actions.
65.5 Least-privilege tool design
- Assume the agent will sometimes be fooled; limit what that can cost.
- Scope credentials narrowly, filter data by the real user, and cap action sizes.
- Split read and write tools, and keep high-impact actions behind gates.
65.6 Sandboxing code and browsers
- Agents that run code or control a browser need a sandbox: an isolated place with limited access.
- Limit the filesystem, block or allow-list the network, and drop extra privileges.
- Throw the sandbox away after each task so nothing persists between users.
65.7 Red-teaming your agent
- Red-teaming means deliberately attacking your own system to find weaknesses before others do.
- Cover direct and indirect injection, data exfiltration, tool misuse, cost attacks and harmful outputs.
- Every finding becomes a regression test, so the same hole can't reopen.
65.8 Worked example: agent SDK permission callbacks
- The Agent SDK checks permissions in order: hooks, permission rules, the permission mode, then canUseTool.
- canUseTool is your code deciding allow or deny for each call, with full context, and optionally changed input.
- Use it for rules that depend on runtime facts, such as the user's role or the amount.
65.9 Dual-LLM privilege separation
- A privileged model plans and calls tools but never reads untrusted content; a quarantined model reads untrusted content but has no tools.
- The quarantined model's output goes back as a reference, such as $SUMMARY_1, that plain code fills in at the end.
- An injection in a web page or email can then change a summary, but cannot choose which tools run or where data goes.
- The cost is capability: the privileged model cannot reason about what the content says.
65.10 Agent identity, delegated access and the confused deputy
- An agent needs its own identity, separate from any user, so you can grant, limit, audit and revoke what it does.
- When an agent acts for a user, it should carry that user's delegated, narrowly scoped authority, not a shared service account.
- Token exchange swaps a user's token for a short-lived one scoped to a single downstream service, recording both the user and the agent.
- A confused deputy is a privileged agent tricked into using its power for someone who lacks it. Check the user's rights, not just the agent's.
66Governance and compliance7 lessons
66.1 Audit logs for agent reasoning and actions
- Traces help engineers debug; an audit log lets someone later prove who did what, on whose behalf, with what authority and with what result.
- Record every consequential action, including denials and human approvals, with the inputs and policy decision that led to it.
- Make the log append-only and tamper-evident, with its own access rules and retention period.
- A model's written rationale is useful context but not proof of why it acted; the recorded inputs, decision and action are the evidence.
66.2 Data retention and zero-data-retention agreements
- Retention is how long each copy of data is kept; an AI system makes many copies: provider side, logs, traces, caches, vector stores, eval sets and backups.
- A zero-data-retention (ZDR) arrangement means the provider does not keep your inputs and outputs after the request is served, apart from stated exceptions.
- ZDR covers the provider's copies only; your own logs, caches and stores still need their own limits.
- Some features need stored data and may not be available under ZDR; check eligibility before you design around them.
66.3 Data residency and where prompts are processed
- Storage residency says where data rests; processing location says where the model actually reads the prompt. Commitments may cover one or both.
- Cross-region and global routing options move inference to wherever capacity is free, which can break a processing promise.
- Ask every vendor in the path: where is it processed, where is it stored, who can access it from where, and which sub-processors are involved.
66.4 Bias and fairness audits
- Start from the harm: unfair allocation (who gets a loan or an interview), worse quality of service for some groups, or stereotyped and demeaning content.
- Compare outcomes and error rates per group; one overall accuracy number can hide a large gap.
- For LLM features, counterfactual tests swap only a name, pronoun or dialect and check whether the answer changes.
- Fairness metrics can conflict; choose the ones that match the harm, write down the trade-off, and repeat the audit after every major change.
66.5 The EU AI Act in brief
- The EU AI Act is an EU regulation that sorts AI systems by risk: unacceptable (prohibited), high risk, limited risk with transparency duties, and minimal risk.
- High-risk systems, such as many used in hiring, credit, education or essential services, carry duties for risk management, data governance, documentation, logging, human oversight and accuracy.
- Separate rules apply to providers of general-purpose AI models; duties also differ for providers and deployers of a system.
- It can apply to organisations outside the EU whose systems are used in the EU. This lesson is an overview, not legal advice.
66.6 The NIST AI Risk Management Framework in brief
- The NIST AI RMF is a voluntary framework from the US National Institute of Standards and Technology for managing risks from AI systems.
- It has four functions: Govern (culture, policies, roles), Map (context and risks), Measure (assess and track them) and Manage (prioritise, act and monitor).
- Govern runs across the other three; the rest repeat through the system's life rather than happening once.
- A companion Playbook suggests actions, and a Generative AI Profile applies the framework to generative models.
66.7 Lab: a compliance checklist for an enterprise agent
- A useful compliance checklist is a list of testable items, each with an owner and a piece of evidence, not a list of good intentions.
- Group items by the questions reviewers ask: what the system is, what data it touches, what it can do, what is recorded, how it is tested and who responds.
- Mark items as blockers or follow-ups so a launch decision is clear, and re-run the checklist after every major change.
13Production: observability, deployment and scale
67Observability and tracing9 lessons
67.1 Traces, spans and what to log
- A trace is one request end to end; spans are its steps: each model call, tool call, retry and handoff.
- On every span record timing, status, model, token counts, cost and ids that link it to the user request.
- Without traces, an agent that made twelve calls and gave a wrong answer is nearly impossible to debug.
67.2 Token, cost and latency dashboards
- Watch three families of numbers: volume (requests, tokens), cost, and latency (time to first token and total).
- Use percentiles (p50, p95, p99), not averages: a few very slow agent runs hide inside a good average.
- Slice by feature, model, prompt version and tenant so a change shows up where it happened.
67.3 Logging prompts safely: redaction and retention
- Prompt and output text is the most useful debugging data and often the most sensitive.
- Redact or tokenise personal data before it is stored, limit who can read raw logs, and delete them on a schedule.
- Keep metadata (tokens, timings, ids) longer than full text.
67.4 Online evals and drift detection
- Offline evals test known cases; online evals score a sample of real traffic as it happens.
- Use cheap signals (thumbs down, retries, escalations) plus model or code graders on sampled runs.
- Drift is a change over time in what users send or how the system answers; watch for it and refresh your test sets.
67.5 Debugging an agent from its trace
- Start from the failing trace and walk it step by step: what did the model see, decide and receive?
- Common patterns: a wrong tool choice, a bad tool result taken as truth, a loop, context lost after trimming.
- Fix at the step that went wrong, then add the case to your evals.
67.6 Worked example: usage fields, request ids and OpenTelemetry
- Each Messages API response includes a usage object with input, output and cache token counts.
- Each response has a request id; log it so you and Anthropic support can find a specific call.
- Claude Code can export metrics and events with OpenTelemetry; prompt text is left out unless you opt in.
67.7 OpenTelemetry for LLM and agent traces
- OpenTelemetry is a vendor-neutral standard: your code creates spans, an exporter sends them over OTLP, and any compatible backend can show them.
- The generative AI semantic conventions give shared names for model calls, tool calls and agent steps, such as gen_ai.request.model and gen_ai.usage.input_tokens.
- Propagate trace context to tools and other services so a whole agent run lands in one trace.
- Prompt and response text is opt-in; the conventions are still evolving, so pin the version you follow.
67.8 Tracing tools: LangSmith, Phoenix, Langfuse and others
- Tracing tools fall into a few families: framework-linked platforms, open-source self-hostable tools, OpenTelemetry instrumentation libraries, and general APM products.
- Decide first where trace data is allowed to go; that often rules out options before features matter.
- Instrument with OpenTelemetry where you can, so switching tools later means changing an exporter, not your code.
67.9 Time to first token and other latency metrics
- Time to first token (TTFT) is how long until the first piece of the answer arrives; it is what a person feels in a streaming UI.
- Time per output token sets how fast the rest streams; end-to-end latency is roughly queue time + TTFT + output tokens x time per token.
- Long inputs mostly raise TTFT; long outputs mostly raise total time. Prompt caching and shorter prompts help the first; shorter answers help the second.
- Measure on the client, to the first content event, and chart percentiles by feature.
68Serving patterns5 lessons
68.1 Sync, streaming and async jobs
- Synchronous: the caller waits for the full answer. Fine for short, fast calls.
- Streaming: tokens arrive as they are made, so a person sees progress within a second or two.
- Async jobs: accept the request, return a job id, and deliver the result later by polling or webhook.
68.2 Queues, workers and back-pressure
- A queue between your API and your workers smooths bursts and lets work survive restarts.
- Workers pull jobs at the rate your rate limits and budget allow.
- Back-pressure means saying 'not now' early (reject, defer or degrade) instead of letting everything get slow.
68.3 Idempotency and retries at scale
- At scale, retries happen constantly: network blips, worker restarts, duplicate webhooks.
- A retry must not double an effect: give each operation an idempotency key and record completion.
- Separate the model call (safe to repeat, costs money) from side effects (must happen once).
68.4 Batch processing for offline work
- Work nobody is waiting on (nightly tagging, backfills, eval runs) can go through a batch interface.
- Batch trades latency for lower cost and higher throughput.
- Design for partial failure: each item has its own id and result, and failed items are retried alone.
68.5 Worked example: batch APIs and streaming in production
- The Message Batches API processes many requests asynchronously at a discount compared with standard calls.
- Each request in a batch has a custom_id; results come back per request, with success or error.
- Streaming sends server-sent events; handle errors mid-stream and keep partial text if useful.
69Scaling and rate limits5 lessons
69.1 Horizontal scaling of stateless agents
- Horizontal scaling means adding more identical workers; it only works if any worker can pick up any job.
- Keep conversation and agent state in a shared store, not in a worker's memory.
- Your real ceiling is usually the model rate limit and budget, not CPU.
69.2 Rate-limit budgeting across users and tenants
- Your provider rate limit is one shared budget: requests and tokens per minute.
- Give each tenant or feature its own slice, enforced in your code before calling the API.
- Token buckets are a simple way to allow short bursts while holding a steady average.
69.3 Fair queuing and priority lanes
- Put work in separate lanes: interactive first, then agents, then background.
- Within a lane, take turns between tenants (fair queuing) so one big tenant can't block others.
- Protect low-priority work from waiting forever with ageing or a reserved share.
69.4 Load testing an LLM system
- Load test the parts you own (queues, limiter, workers, database) with a fake model that mimics latency and errors.
- Use realistic traffic shapes: bursts, long and short prompts, streaming and slow clients.
- Run a small, short test against the real API to confirm limits and headers, then stop.
69.5 Worked example: rate-limit tiers, headers and 429 handling
- Claude API limits are measured in requests per minute and input and output tokens per minute, per model, and grow with your usage tier.
- Responses include headers showing remaining budget and reset times; a 429 includes a retry-after header.
- On 429 or overload errors, back off with jitter and honour retry-after; don't hammer the API.
70Caching layers and multi-region5 lessons
70.1 Response, semantic and prompt caches
- A response cache returns a stored answer for an identical request; no model call at all.
- A semantic cache returns a stored answer for a similar request, matched by embeddings; useful but risky.
- A prompt cache reuses the model's work on a repeated prompt prefix; the model still answers fresh.
70.2 Cache keys, TTLs and invalidation
- A cache key must include everything that changes the answer: model, prompt version, settings, user scope, data version.
- Set a time to live (TTL) that matches how fast the underlying facts change.
- Invalidate on change: when the prompt, model or source data updates, old entries must stop being served.
70.3 Multi-region and failover
- Run your own app in more than one region so a regional outage doesn't take you down.
- Plan model fallbacks: another region, another platform hosting the same model, or a smaller model.
- Test failover regularly; an untested fallback often fails when you need it.
70.4 Data residency
- Data residency means keeping data, and sometimes processing, inside a chosen geography.
- Map every place data goes: model calls, logs, traces, caches, vector stores, backups, sub-processors.
- Choose regions and platforms that match your commitments, and check fallbacks follow the same rules.
70.5 Worked example: cloud platforms and regional endpoints
- Claude is available through the Claude API, Amazon Bedrock and Google Cloud Vertex AI.
- The request shape is close to the Messages API, but auth, model ids, regions and some features differ by platform.
- Check feature availability per platform before relying on it in a fallback.
71Cost at scale6 lessons
71.1 Unit economics of an AI feature
- Measure cost per useful outcome (a resolved ticket, a finished report), not only per API call.
- Cost per task = calls per task x tokens per call x price, plus retries, tools and infrastructure.
- Compare that cost with the value of the outcome to see if the feature pays for itself.
71.2 Model routing for cost
- Many requests are easy; send them to a smaller, cheaper model and save the larger model for hard ones.
- Route by rules (task type, input size), by a small classifier, or by escalating when the small model is unsure.
- Evaluate each route on its own slice of traffic; a router is only as good as its worst route.
71.3 Budgets, quotas and alerts
- Set spending limits at several levels: per request (max tokens, max steps), per user or tenant, per feature, and organisation wide.
- Alert on cost rate, not only on monthly totals, so a runaway loop is caught in minutes.
- Decide in advance what happens at each limit: warn, slow down, degrade or stop.
71.4 Cutting cost without losing quality
- The main levers: prompt caching, shorter prompts and outputs, lower reasoning effort, routing, batching, trimming context, and fewer retries.
- Change one lever at a time and run your evals; cheaper but worse is not a saving.
- Start with the biggest line on the bill: find it in your traces.
71.5 Worked example: choosing between model tiers by cost
- Claude models come in tiers: Haiku is the smallest and fastest; Sonnet balances capability and cost; Opus and Fable are the larger, more capable models.
- Pick by evaluation: start with the cheapest model that might work, measure, and move up only where it fails.
- Prices and model lists change; read the current models and pricing pages rather than relying on remembered numbers.
71.6 Model cascades: try small, escalate to large
- A cascade sends each request to a small model first and escalates to a larger one only when a check says the answer is not good enough.
- The escalation signal is the whole design: prefer checks you can verify (schema, tests, citations, a calibrated scorer) over the model saying it is confident.
- Tune the threshold on a labelled set and measure the false-accept rate: wrong answers the small model was allowed to ship.
- Escalated requests pay for both calls and wait for both, so count cost and latency together.
72Rollouts and incident response7 lessons
72.1 Versioning prompts, tools and models
- Treat prompts, tool definitions and model ids as versioned config, stored in source control.
- Log the versions on every trace so you can tell which change caused a behaviour.
- A release is a specific combination: prompt v14 + tools v6 + model id; test and ship them together.
72.2 Shadow, canary and A/B rollouts
- Shadow: run the new version on real traffic but don't show its output; compare offline.
- Canary: show the new version to a small slice (say 5%) and watch metrics before widening.
- A/B test: split traffic to measure which version is better on a chosen outcome.
72.3 Feature flags and kill switches
- Feature flags turn features, prompts or routes on and off without a deploy.
- A kill switch is a flag that disables a risky feature instantly, falling back to a safe path.
- Test kill switches before you need them, and make clear who may flip them.
72.4 Model upgrades and deprecations
- Model providers release new models and retire old ones on published schedules.
- Treat a model upgrade like any release: evals, prompt tuning, shadow or canary, then full rollout.
- Track deprecation dates for every model id you use, and leave time to migrate.
- Pin dated model ids in production and read each migration guide: new generations can remove API parameters, not just change answers.
72.5 Incident response and post-mortems
- AI incidents include outages, quality drops, harmful outputs, data leaks and cost spikes.
- Respond in order: detect, contain (kill switch, rollback), communicate, fix, then learn.
- A blameless post-mortem records the timeline, causes and follow-ups, including new eval cases and guardrails.
72.6 Worked example: migrating between model versions
- Check the deprecations page for retirement dates and recommended replacement models.
- Read the migration notes for the new model: behaviour, parameters and tool use can change between generations.
- Run your evals on the new model id, tune prompts, then roll out gradually with the old model as fallback.
72.7 Reference architecture: an AI system end to end
- A production AI system is mostly ordinary software around the model: an edge, a gateway, an orchestrator, tools, data and a feedback loop.
- An AI gateway is the one place every model call passes through: identity, quotas, routing, redaction, caching, logging and failover.
- The orchestrator owns the loop and its limits; tools sit behind least privilege and approvals; retrieval and memory are separate stores with their own access rules.
- Traces feed evals, evals gate releases, and releases roll out behind flags. That loop is what keeps quality from drifting.
No key points match. Try a shorter word.