18 parts · 266 topics · 1,916 chapters
Learn Gen AI engineering
Each topic is a working engineer's account of one problem: what breaks, why, and what to do about it. Chapters are ordered so each follows from the last.
Mid 89 topics · Senior 88 topics · Lead 89 topics
This week
0 / 10
topics read
Your first chapter starts the week.
Python Engineering0 of 2 topics
Part 1 · 3 topics · 21 chapters
Working Foundations
Deliberately tiny. This is the tooling and the arithmetic, not a maths course.
Python Engineering
Build and organize Python programs for AI work.
Vector Arithmetic
Compute and compare vectors using basic operations.
Part 2 · 18 topics · 136 chapters
LLM Mechanics at Inference
How the thing behaves when you call it. Operational mechanics, not architecture theory.
Token Context
Understand how token representation and context limits shape inference behavior.
What a language model is
5 chaptersNext-token continuation, weights, inference
Tokenization
6 chaptersSubwords, token ≠ word
What tokenization actually breaks
8 chaptersDigit-string arithmetic, character-level edits, "1234" vs " 1234" being different tokens, non-English token inflation
Token economics
10 chaptersInput vs output tokens, cost per language, cost per code
Context window
8 chaptersAdvertised vs actually usable
Context degradation
7 chaptersLost-in-the-middle, position bias, distraction, long-context decay
Generation Mechanics
Control generation and reason about its randomness, stopping behavior, latency, and caching.
Autoregressive generation
8 chaptersOne token at a time, why latency scales with output length
Sampling
8 chaptersTemperature, top-p, top-k, penalties, seeds
Logprobs and token-level confidence
8 chaptersPer-token probabilities, when they mean confidence and when they do not
Stop sequences, max tokens, truncation, silent output cutoff
8 chaptersThe four ways output ends, and which one ends it silently
Prefill vs decode
9 chaptersTTFT vs inter-token latency; throughput vs latency
KV cache
9 chaptersWhy prefixes are cheap
Non-determinism in practice
7 chaptersBatching effects, why temperature=0 is usually not reproducible
Knowledge Boundaries
Distinguish supplied information, learned knowledge, and fabricated model output.
Model Variants
Choose among model types and understand their trade-offs and specialized inference modes.
Base vs instruct vs reasoning vs multimodal variants
7 chaptersChat templates and special tokens
Reasoning models
6 chaptersExtended thinking, reasoning-effort budgets, when the latency and tokens are worth it
Model landscape literacy
7 chaptersClosed vs open-weight, size/latency/cost tiers, reading model cards and benchmark claims skeptically
Part 3 · 22 topics · 159 chapters
Model APIs
The daily job, and the closest thing to your existing skill set.
Request Construction
Build well-formed, multimodal, and controllable model requests.
Chat API shape
8 chaptersRoles, message arrays, multi-turn
System prompts
6 chaptersScope, and what belongs there vs in the user turn
Image inputs
7 chaptersResolution and tiling, image token cost, prompting with images
Reasoning-token mechanics
7 chaptersBilled as output, preserving thinking blocks across tool-call turns, budgets interacting with max_tokens, never surfacing raw reasoning
Conversation State
Manage conversation history, persistence, and provider-hosted state.
Conversation state
8 chaptersStateless APIs, owning history yourself
Provider-hosted state and provider-executed tools
8 chaptersServer-side conversation state, hosted file stores, hosted search and code execution
Conversation persistence schema design
7 chaptersTool calls, tool results, attachments, thinking blocks, prompt-version pointers, branch and regenerate semantics, retention
Request Delivery
Integrate, stream, operate, scale, and test model API calls.
Provider SDKs and the differences that actually matter
9 chaptersWhere the SDKs genuinely differ, and where the difference is cosmetic
Streaming
8 chaptersSSE, token deltas, streaming through your own API, cancellation
Streaming in production
6 chaptersResumable generation when a client drops mid-stream, persisting partial output, proxies and CDNs that buffer, backpressure
Error handling
7 chaptersRate limits, 429s, backoff with jitter, overload errors, retries with idempotency, timeouts, partial-stream failure
Concurrency and throughput
7 chaptersAsync clients, pooling, semaphores, worker queues for bulk jobs
Batch and async job endpoints
6 chaptersMuch cheaper, much slower
Testing code that calls an LLM
7 chaptersMocking the provider, record/replay cassettes, response fixtures, snapshot-testing the *rendered* prompt, contract-testing tool schemas, keeping CI fast and free
Cost Control
Budget tokens, use prompt caching, and attribute model spend.
Token counting and budgeting before the call
7 chaptersTruncation and history compaction
Prompt caching mechanics
8 chaptersCache-friendly message ordering (static prefix first, volatile last), explicit breakpoints vs automatic prefix caching, minimum cacheable length, TTLs, cache-write costing more than uncached input, what silently invalidates a cache
Cost tracking per request, user, feature and tenant
7 chaptersAttributing spend to a request, a user, a feature and a tenant
Provider Strategy
Coordinate providers, platform constraints, fallbacks, and model lifecycle.
Multi-provider abstraction
7 chaptersGateways, routers, or a hand-rolled adapter
Cloud model platforms
8 chaptersQuotas, regions, data residency, provisioned throughput
Provider content filters as an operational problem
8 chaptersLegitimate traffic blocked, policy changing without notice, rejection-rate metrics, appeal paths
Fallback chains and graceful degradation across providers
7 chaptersCircuit breakers, degraded modes, and what to serve when nothing answers
Model deprecation and version pinning
6 chaptersRe-qualification when a model is retired
Part 4 · 17 topics · 121 chapters
Evaluation
Before prompting, on purpose. This is what separates mid from senior, and everything downstream is guesswork without it.
Evaluation Basics
Understand why generative systems need probabilistic evaluation rather than ordinary exact-match testing.
Why traditional testing fails
7 chaptersNo exact-match assertions, output distributions, flaky by design
Tests vs evals
7 chaptersDeterministic tests that run free on every commit, vs sampled evals that cost money and run on a gate
Public benchmarks
7 chaptersHow to read them, contamination, why they rarely predict performance on your task
Dataset Diagnosis
Build representative evaluation data and use failures to understand and prioritize system weaknesses.
Building a golden dataset
7 chaptersSourcing from real traffic, hand-labeling, coverage, refresh cadence
Held-out sets and eval-set overfitting
6 chaptersYou will overfit prompts to a visible eval set within a handful of iterations; a held-out set touched rarely; not shipping a difference smaller than the run-to-run noise
Error analysis
7 chaptersReading actual failures, open coding, building a failure taxonomy, prioritizing by frequency × severity
Debugging a single bad output
7 chaptersBisect the prompt, ablate context blocks one at a time, verify the chat template, check for truncation, re-run at temperature 0 vs N samples, diff against a known-good trace
Human evaluation
7 chaptersAnnotation guidelines, agreement between reviewers, expert review loops, when humans are mandatory
Component vs end-to-end evaluation
8 chaptersMeasuring each pipeline stage separately
Scoring Methods
Apply deterministic checks, similarity metrics, and carefully calibrated model judges.
Deterministic and code-based checks
8 chaptersSchema validity, regex, contains/not-contains, structural assertions, tool-call correctness, latency, cost
Retrieval- and extraction-style scoring
7 chaptersExact match, overlap measures, semantic similarity, and where each misleads
LLM-as-judge
9 chaptersPointwise vs pairwise, rubric design, reference-guided grading
Judge design rules
8 chaptersBinary pass/fail per criterion rather than 1–5 scales (mid-scale scores are noise), one criterion per judge call, reasoning before verdict, a judge model from a different family than the generator, judge cost as a line item
Judge failure modes and calibration
6 chaptersPosition bias (and position-swapping as the fix), verbosity bias, self-preference, leniency drift; validating the judge against human labels
The judge as an attack surface
8 chaptersA judge reading model- or user-generated content is an injection target; optimizing a generator against a judge is gaming your own harness
Eval Operations
Select evaluation tooling and integrate cost-aware quality gates into development workflows.
Part 5 · 19 topics · 141 chapters
Prompting & Context Engineering
Prompts are versioned, tested artifacts with an interface contract. Context engineering is the senior half of this stage.
Prompt Design
Construct prompts with clear structure, examples, placement, decomposition, and model-aware adaptations.
Anatomy of a prompt
7 chaptersRole, task, context, constraints, output format, examples
Zero-shot, few-shot, and example selection
8 chaptersHow many examples, chosen how, and when more of them hurt
Delimiters and structure
7 chaptersXML tags, markdown sections, separating instructions from data
Instruction placement and recency
8 chaptersCritical constraints last; prefilling the assistant turn
Prompt decomposition
8 chaptersSeveral focused prompts instead of one mega-prompt
Model-specific prompting differences
10 chaptersPorting a prompt between models
Multilingual prompting and behavior
9 chaptersQuality degradation in lower-resource languages, evaluating per language rather than in aggregate
Reasoning Methods
Use scratchpads, self-critique, and sampling strategies to improve reasoning reliability.
Chain-of-thought, scratchpads
1 chapterWhen reasoning models make this redundant
Self-consistency, majority voting over N samples, best-of-N with a judge
9 chaptersSpending N calls to buy reliability, and when that trade is worth it
Reflection and self-critique in a single prompt, and its limits
7 chaptersModels are poor at spotting their own errors unaided
Prompt Lifecycle
Safely template, version, review, and automatically optimize prompts as production artifacts.
Prompt templating and escaping user input
7 chaptersUser text is untrusted input; templating it is an escaping problem
Prompt versioning, storage and review
8 chaptersPrompts in Git vs a prompt platform; treating a prompt change like a schema migration
Automated prompt optimization
8 chaptersOptimizer-driven and evolutionary prompt search
Context Control
Budget, order, select, compress, and measure context while managing conflicting instructions.
Context engineering — the budget
7 chaptersAllocating a finite window across system prompt, tool definitions, retrieved content, history, and reserved output space
Context engineering — ordering
7 chaptersPosition bias (1.12) wants important content late; prompt caching (2.15) wants stable content early. Resolving that conflict deliberately
Context engineering — selection
7 chaptersJust-in-time retrieval vs pre-loading; making every block earn its tokens
Context engineering — eviction and compaction
7 chaptersRolling summaries, hierarchical summarization, dropping stale turns, what to discard first
Context engineering — measurement
8 chaptersAblating context blocks and re-evaluating, detecting context rot empirically
Instruction conflicts, over-constrained prompts, prompt bloat
8 chaptersDeleting instructions as a debugging technique
Part 6 · 15 topics · 109 chapters
Structured Output & Tool Calling
Turning the model into a typed component. Where your backend instincts get their first real foothold.
Typed Outputs
Produce, validate, repair, stream, and verify structured model responses.
Getting JSON out
6 chaptersJSON mode, response formats, defensive parsing
Schema-constrained generation
7 chaptersJSON Schema, Pydantic/Zod, strict structured outputs
Schema design for LLMs
7 chaptersField naming, descriptions as instructions, enums over free text, flat over deeply nested
Validation, repair loops, retry-on-invalid
5 chaptersWhat to do with output that did not validate, without looping forever
Streaming structured output
7 chaptersIncremental partial-JSON parsing, which fields are safe to render before the object closes
Classification and extraction with LLMs
8 chaptersWhen a cheap classifier or a regex beats an LLM call
Verifier-first design
9 chaptersPairing the stochastic generator with a cheap deterministic checker — schema, compiler, test suite, database constraint, re-retrieval — and looping on failure. The asymmetry between generating and checking. Letting verifiability drive which problems you take on at all
Tool Invocation
Execute model-selected tools through reliable calls, results, and streaming arguments.
Tool Design
Design tool surfaces, descriptions, results, semantics, versioning, and failure handling.
Tool design — granularity and surface
8 chaptersOne broad tool vs many narrow verbs; exposing your existing API vs building a purpose-built surface for a model
Tool design — descriptions
7 chaptersDescriptions function as few-shot examples, and are prompt tokens paid on every turn
Tool design — results
7 chaptersResponse shape, token cost, truncation, pagination and cursors, summarizing large payloads before they reach the window
Tool design — semantics
7 chaptersIdempotency and safe-retry for a non-deterministic caller; error messages written to be *actionable by a model*
Tool versioning without invalidating the prompt cache
7 chaptersChanging a tool's shape without invalidating everything cached behind it
Tool-call failure modes
8 chaptersHallucinated arguments, wrong tool selection, retry loops, selection accuracy collapsing as tool count grows; namespacing and dynamic tool loading as mitigations
Part 7 · 16 topics · 114 chapters
Model Context Protocol (MCP)
The standard interface between agent applications and the tools, data and prompts they use. Its own stage because it is now the default integration surface, and because most of what goes wrong with it is auth and trust, not protocol.
Core Protocol
Understand MCP’s participants, lifecycle, and connection transports.
What MCP is and why it exists
8 chaptersDecoupling tool implementations from the applications that use them, so an integration is written once rather than per-client
Architecture
7 chaptersHosts, clients and servers; connection lifecycle; capability negotiation on initialize
Transports
8 chaptersStdio for local processes, streamable HTTP for remote servers; which applies when, and the operational difference
Protocol Surfaces
Use MCP capabilities to expose tools, context, prompts, and interaction flows.
Tools over MCP
8 chaptersDeclaring them, behavioral annotations (read-only vs destructive vs idempotent hints), and how they reach the model's context
Resources
6 chaptersExposing readable context addressed by URI, resource templates, subscriptions and updates
Prompts
6 chaptersServer-provided prompt templates surfaced as explicit user-invocable entry points
Sampling
8 chaptersA server requesting a model completion *from the client*, and why that inverts the usual trust direction
Elicitation
7 chaptersA server requesting structured input from the user mid-operation
Roots
7 chaptersScoping a server to specific parts of the client's workspace or filesystem
MCP Integration
Build, consume, debug, and assess MCP integrations in real systems.
Building a server
6 chaptersChoosing the surface, keeping tools orthogonal, returning model-legible errors, testing it in isolation from any agent
Consuming servers
7 chaptersDiscovery, registries, configuration, version skew and breakage
Debugging MCP
7 chaptersInspector tooling, protocol tracing, and the common failure modes (capability mismatch, transport hangs, schema rejection)
When MCP is the wrong answer
7 chaptersA direct function call, a skill, or a subagent is often simpler. MCP earns its cost when the integration is reused across clients or owned by another team
Trust Controls
Secure MCP access and govern the risks of multi-tenant and third-party servers.
MCP auth
8 chaptersOAuth flows, authorization servers, token audience binding, and why a token minted for your server must not be replayable against upstream APIs
Multi-tenant servers
7 chaptersPer-user credential isolation, no shared ambient authority, per-request identity
Trusting third-party servers
7 chaptersA server is arbitrary code holding your tokens. Review, pinning, sandboxing, and deciding what you will not install
Part 8 · 11 topics · 73 chapters
Prompt Injection & Tool Safety
Kept deliberately (see Scope). Not a security specialism — the architectural constraints that determine how an agent can be built at all.
Injection Threats
Recognize how untrusted content, model outputs, and tool interfaces create injection and exfiltration risks.
Prompt injection
8 chaptersDirect, and indirect via retrieved documents, web pages, emails, tool outputs, file contents
Why it cannot be prompt-fixed
6 chaptersInstructions and data share one channel
The lethal trifecta
7 chaptersPrivate data + untrusted content + external communication. Break one leg
Data exfiltration channels
7 chaptersMarkdown image URLs, links, tool parameters; URL allowlisting and content-rendering policy
Insecure output handling downstream
6 chaptersModel output rendered as HTML (XSS), interpolated into SQL or a shell, used as a file path or a redirect
MCP as an injection surface
6 chaptersA compromised or malicious server injecting through tool results and resource content
Safe Execution
Design constrained, observable, and resource-bounded agent execution with appropriate human oversight.
Architectural mitigations
7 chaptersLeast-privilege tools, no ambient authority, human confirmation for consequential actions, quarantine patterns, capability-based design
Tool execution safety
6 chaptersAllowlists, timeouts, dry-run and confirm-before-write, audit logs
Sandbox design
7 chaptersIsolation boundaries, egress network policy (the concrete form of 7.3's third leg), filesystem scoping, per-execution credentials, resource caps, snapshot and rollback
Denial-of-wallet
6 chaptersUnbounded loops, adversarial long inputs, hard budget caps
Computer use, browser use and code execution tools
7 chaptersTheir risk profile and when the capability is worth it
Part 9 · 19 topics · 135 chapters
Retrieval
Measured before it is optimized. Most bad RAG is bad search, not bad prompting. Lexical first, deliberately.
Search Foundations
Define relevance, build a lexical baseline, and measure retrieval quality.
The retrieval problem
7 chaptersWhat "relevant" means for a given task
Lexical search
9 chaptersBM25, inverted indexes; why it still beats vectors on exact terms, identifiers, error codes and rare jargon
Retrieval evaluation
7 chaptersRecall@k, precision@k, MRR, nDCG, hit rate; a golden query set; measuring the baseline before adding anything
Embedding Models
Understand, select, and configure embeddings for semantic and multilingual search.
What an embedding is
6 chaptersDense vector, semantic space, dimensionality
Similarity metrics and matching the metric to the model
6 chaptersCosine, dot product, euclidean — and matching the metric to the model
Embedding models
7 chaptersAPI and open-weight options; leaderboard literacy and why rank rarely survives contact with a specific corpus
Embedding input limits and silent truncation
6 chaptersModels have a max sequence length and most libraries truncate past it without warning
Asymmetric search
6 chaptersQuery vs document prefixes and instructions, task-specific embeddings
Multilingual and cross-lingual retrieval
6 chaptersQuery in one language against a corpus in another, per-language evaluation
Vector Infrastructure
Build, filter, combine, compress, and maintain production vector indexes.
Vector indexes
8 chaptersFlat, IVF, HNSW and friends; recall vs latency vs memory; the tuning parameters and what they trade
Vector databases and selection criteria
6 chaptersDefault to pgvector when Postgres is already there, and know the thresholds where that stops — build time and memory at scale, index rebuild pain, hybrid search you assemble yourself
Metadata filtering
6 chaptersPre- vs post-filtering, filtered-ANN recall cliffs, multi-tenancy isolation
Hybrid search
8 chaptersDense + sparse, Reciprocal Rank Fusion, weighted fusion, learned sparse retrieval
Matryoshka embeddings, dimension truncation, quantized and binary embeddings
7 chaptersShrinking vectors on purpose: truncation, quantization, binary
Index maintenance
8 chaptersIncremental upserts, deletes and tombstones, re-embedding after a model change, backfills, versioned indexes, zero-downtime swaps
Result Quality
Improve retrieved results through reranking, richer matching, deduplication, and domain adaptation.
Reranking
8 chaptersCross-encoders vs bi-encoders, retrieve-many-then-rerank-few, and the latency and per-query cost it adds
Late-interaction and multi-vector retrieval
7 chaptersColBERT-style token-level matching, and what it costs to store
Embedding-based deduplication and near-duplicate detection
8 chaptersFinding the near-duplicates before they crowd out your top-k
Adapting the retriever to your domain
9 chaptersFine-tuning an embedding model or training a reranker on your own labelled pairs
Part 10 · 21 topics · 163 chapters
RAG
Retrieval with a generator bolted on, and every failure is still a retrieval failure. Build the naive version first so you have something to measure, then fix what the measurements actually say — not what the blog posts say.
Pipeline Foundations
Build and operate the core document-to-answer pipeline.
RAG architecture
9 chaptersIngest → parse → chunk → embed → index → retrieve → augment → generate
Naive RAG end to end, built once by hand without a framework
8 chaptersThe whole pipeline by hand once, so the framework hides nothing from you
Document parsing
8 chaptersPDF (born-digital vs scanned), HTML, DOCX, tables, slides; OCR; layout-aware parsers
Chunking strategies
9 chaptersFixed-size, overlap, recursive, sentence and paragraph, semantic, layout- and heading-aware, late chunking
Metadata design and contextual chunk headers
8 chaptersPrepending document and section context to each chunk before embedding
Ingestion pipelines
7 chaptersIncremental sync, change data capture, connectors, idempotency, dead-letter queues, backfills
Retrieval Design
Shape queries and choose retrieval architectures for different information needs.
Query transformation
8 chaptersRewriting, expansion, HyDE, multi-query, decomposition, routing
Multi-turn query contextualization
7 chaptersCoreference resolution and history-aware query construction, so "what about the second one?" retrieves something sensible
Retrieval strategies for RAG
8 chaptersTop-k tuning, diversity, parent-document and small-to-big, sentence-window, auto-merging, hierarchical and summary indexes
Structured-data RAG
8 chaptersText-to-SQL, semantic layers, schema-in-prompt, read-only roles, generated-query safety, verifying results before presenting them
GraphRAG and knowledge graphs
7 chaptersEntity and relation extraction, community summarization, multi-hop questions, when the added cost is justified
Long-context vs RAG
8 chaptersWhen to just fill the window, the cost/latency/quality trade, prompt caching over large documents
Evaluation Tuning
Measure RAG quality and systematically improve its parameters.
RAG-specific metrics
7 chaptersFaithfulness and groundedness, answer relevance, context precision and recall, citation accuracy
Systematic pipeline parameter search
7 chaptersSweeping chunk size × overlap × k × rerank depth × query transform, tracking configurations as versioned artifacts, not overfitting the golden set
RAG anti-patterns
9 chaptersOver-chunking, stuffing k=20, no reranker, no evaluation, embedding everything, ignoring lexical search
Grounded Answers
Ground answers, manage uncertainty, and prevent unreliable or unauthorized results.
Citations and attribution
7 chaptersSpan-level grounding, quote extraction, verifiable links, UI affordances
Uncertainty, confidence and abstention
7 chaptersVerbalized confidence and why it is poorly calibrated, logprob scoring and where it fails, self-consistency spread as a proxy, entailment checks against source, thresholding into an "I don't know"
Contradictions, duplicates and stale documents in the corpus
7 chaptersA corpus that disagrees with itself, and which copy wins
Permission-aware RAG
7 chaptersPer-user filtering, row-level security, never leaking documents across tenants
Multimodal Retrieval
Parse and retrieve information from images, charts, tables, and visual documents.
Part 11 · 20 topics · 148 chapters
Agents: The Core Loop
One agent, one loop, done properly. Architectures come next, and only make sense once this is solid.
Core Loop
Define, implement, and reason about the basic agent control loop.
What an agent is
7 chaptersA model, tools, a loop, and a termination condition. Nothing more
Workflows vs agents
8 chaptersWhen a fixed, deterministic control flow is the correct answer and the model is just a step inside it
The agent loop implemented from scratch
8 chaptersMessage accumulation, tool dispatch, stop conditions, iteration caps
ReAct as history
6 chaptersWhy native tool calling superseded hand-parsed Thought:/Action: strings
Planning
7 chaptersUpfront plans vs interleaved reasoning, task decomposition, replanning on failure
Reliable Execution
Make agent execution durable, bounded, concurrent, and practical to operate.
Error recovery
7 chaptersRetries with a modified strategy, loop detection, budget caps on steps/tokens/time/money, circuit breakers
Durable execution
8 chaptersCheckpointing, resumability, durable workflow engines, pauses that outlive a process
Agent state and concurrency
6 chaptersParallel tool calls, race conditions, shared-resource conflicts, per-agent workspace isolation
Agent frameworks
8 chaptersWhat they actually give you (durable state, tracing, retries), and the case for none
Agent cost and latency control
8 chaptersCaching, model tiering per step, parallelism, early termination, step budgets
Oversight & Evaluation
Control agent authority and measure behavior, quality, cost, and failure recovery.
Human in the loop
8 chaptersApproval gates, interrupts, editable plans, escalation paths, confidence thresholds
Agent observability
6 chaptersTrajectory tracing, span hierarchies, replay and time-travel debugging, step-level cost attribution
Agent evaluation
8 chaptersTask success rate, trajectory quality, tool-selection accuracy, step count, cost per task, recovery from error
Multi-turn and conversational evaluation
8 chaptersSimulated users, task completion across turns, where in a session quality collapses, measuring the damage done by compaction (4.16)
Agent identity and delegated authority
7 chaptersActing on behalf of a user, scoped credentials, never handing an agent the human's full session token
Memory Policies
Design, protect, and evaluate what agents remember across sessions.
Memory — the write decision
9 chaptersWhat is worth remembering and who decides (a model call, a heuristic, or the user explicitly)
Memory — conflict and decay
7 chaptersUpdating vs appending when a new fact contradicts an old one, expiry, recency vs relevance at read time
Memory — scope and privacy
8 chaptersPer-thread vs per-user vs per-organization, tenancy leaks, user-inspectable and user-deletable memory
Memory — as an attack surface
7 chaptersA poisoned memory persists across every future session
Memory — evaluation
7 chaptersMeasuring whether the read and write policies actually work
Part 12 · 18 topics · 132 chapters
Agentic Architectures & Multi-Agent Patterns
The named topologies, what each is actually for, and the failure mode each introduces. The recurring senior judgment is that **most of these are more expensive than the single loop and only some of them are better.**
Workflow Design
Choose and compose simple fixed workflows for the task shape.
Choosing an architecture
7 chaptersMatching topology to task shape, and defaulting to the simplest thing that passes evaluation
Sequential chaining
6 chaptersA fixed pipeline of prompts, each consuming the last
Routing / dispatcher
7 chaptersClassify the input, then delegate to a specialist path
Parallelization — sectioning and voting
9 chaptersSplitting independent subtasks, or running the same task N times and aggregating
Reasoning Patterns
Improve outputs through critique, verification, and adversarial comparison.
Reflection / self-critique loop
6 chaptersGenerate → critique → revise, and why a model critiquing its own output unaided plateaus fast
Writer–critic (generator–evaluator) with a *separate* critic
8 chaptersDistinct prompt, distinct role, sometimes a distinct model — why splitting the roles outperforms self-critique
Evaluator-optimizer with an objective signal
7 chaptersLooping until a *verifier* passes rather than until the critic is satisfied
Debate and adversarial ensembles
8 chaptersMultiple agents arguing a position to surface errors neither would catch alone
Agent Topologies
Structure planning, delegation, handoffs, shared artifacts, and isolated sub-agents.
Planner–executor
6 chaptersSeparating "decide what to do" from "do it", and re-planning on executor failure
Orchestrator–worker
8 chaptersA parent decomposing work dynamically, dispatching workers, and synthesizing their results
Hierarchical / supervisor trees
8 chaptersDelegation depth, and why every additional layer compounds error and cost
Swarm / handoff
7 chaptersPeer agents transferring control to each other with no central supervisor
Blackboard / shared-artifact architectures
9 chaptersAgents coordinating through shared state (a file, a document, a task list) rather than by messaging each other
Sub-agent context isolation
7 chaptersThe real reason to split agents — a fresh window per subtask, not role-play
Coordination Control
Manage communication, termination, cost, failure, and architecture-level evaluation.
Inter-agent communication
7 chaptersMessage passing vs shared memory vs structured handoff payloads, and what is lost at every boundary
Termination and convergence
8 chaptersDetecting loops, deadlock between agents, agents waiting on each other, and deciding when to stop
When multi-agent hurts
7 chaptersCoordination overhead, compounding error across steps, cost multiplication, unclear ownership of failure
Evaluating an architecture
7 chaptersRunning the same task through competing topologies and comparing success, cost and latency rather than assuming
Part 13 · 13 topics · 94 chapters
Agent Extensibility: Skills, Config & Subagents
How an agent acquires new capability and standing context without being rebuilt. This is where a lot of current practical leverage lives, and it is almost entirely undocumented as a discipline.
Skill Design
Choose, author, and validate reusable capabilities that agents can load when needed.
The extensibility landscape
8 chaptersPrompt vs tool vs MCP server vs skill vs subagent — what each one is actually for, and the cost of each
Agent skills
7 chaptersA folder of instructions, and optionally scripts and reference files, that an agent loads on demand when the task calls for it
Progressive disclosure
7 chaptersName and description always in context, body loaded when relevant, bundled files read only when needed
Writing a skill
7 chaptersThe description as the routing signal, scoping it narrowly, imperative instructions, bundling scripts and references, what to leave out
Skill vs tool vs MCP server
7 chaptersProcedural knowledge vs a callable capability vs a hosted integration owned by someone else
Testing and iterating on skills
7 chaptersVerifying that it triggers when it should, that it doesn't when it shouldn't, and that its instructions are actually followed
Standing Context
Configure durable, scoped instructions that give agents reliable project context.
Agent configuration files (AGENTS.md, CLAUDE.md and equivalents)
7 chaptersRepo-level standing instructions loaded on every session
What belongs in a config file
7 chaptersBuild and test commands, conventions, architecture notes, invariants, gotchas — versus what belongs in a skill, a tool, or nowhere
Scoping and precedence
7 chaptersNested files in a monorepo, directory-scoped instructions, user vs project vs organization layers, and how conflicts resolve
Config hygiene
7 chaptersKeeping it short, keeping it true, and why a stale instruction is worse than no instruction
Agent Operations
Delegate bounded work, enforce invariants, and distribute extensibility assets as maintained code.
Subagents
7 chaptersA bounded task delegated to a fresh context with a restricted tool set and its own instructions
Hooks and deterministic interception
9 chaptersEnforcing an invariant in code at a lifecycle point rather than asking the model to remember it
Distribution and reuse
7 chaptersPackaging skills, servers and configuration for a team; versioning, review, and treating them as code
Part 14 · 11 topics · 80 chapters
Coding Agents
Its own stage because it is the largest commercial application category, it has the cleanest verifiers of any domain, and it is where a backend engineer's existing skills convert at the highest rate.
Codebase Grounding
Ground the agent in repository structure, conventions, context, and deterministic verification.
Why code is the highest-leverage agent domain
8 chaptersCompilers, linters, type checkers and test suites are free deterministic verifiers
Repo-scale code retrieval
8 chaptersAST and symbol-aware chunking vs text chunking, call-graph and import-graph traversal, ranking files by relevance to a task
Context selection over a codebase
6 chaptersWhich files, how much of each, under the budget from 4.13
Repo conventions as agent input
7 chaptersConfig files, skills and hooks applied to a real codebase
Verified Changes
Create, isolate, test, evaluate, and manage code changes through feedback-driven loops.
Edit formats
7 chaptersWhole-file rewrite vs unified diff vs search-and-replace blocks, and their very different failure rates
Patch application and conflict handling
7 chaptersValidating an edit before it lands
Test execution as the verifier
7 chaptersRunning the suite in-loop, interpreting failures, and detecting tests quietly rewritten to pass
Build, lint and type errors as a feedback signal
7 chaptersThe compiler as a grader: errors are a signal the loop can act on
Sandboxed developer workspaces
9 chaptersPer-task isolation, worktrees or ephemeral environments, credential scoping
Evaluating coding agents
7 chaptersBenchmark-style task sets, pass@k, regression suites on your own repository, human review load as a metric
Long-horizon code tasks
7 chaptersDecomposition, progress tracking, and knowing when to stop rather than thrash
Part 15 · 6 topics · 41 chapters
Data & Annotation for AI
Only the parts that are AI-specific. Your existing data engineering — cleaning, lineage, orchestration, CDC, data contracts — transfers unchanged and is not re-taught.
Evaluation Datasets
Build reliable evaluation data through annotation, synthetic generation, and reproducible versioning.
Labeling and annotation operations
7 chaptersGuidelines, tooling, QA, agreement between reviewers, and budgeting for it
Synthetic data generation for evaluation sets and cold start
7 chaptersDistribution mismatch and its limits
Versioning and lineage for evaluation sets
6 chaptersReproducibility of a result
AI Data Pipelines
Prepare production corpora efficiently while filtering low-quality content and protecting personal data.
Embedding pipeline economics
8 chaptersBatching, incremental re-embedding, backfill cost at corpus scale
Corpus quality filtering for AI use
6 chaptersBoilerplate removal, quality scoring, deciding what to exclude entirely
PII detection and redaction in AI pipelines
7 chaptersFinding and removing personal data before it reaches a provider
Part 16 · 18 topics · 118 chapters
Production LLMOps
Your existing craft applied to a new failure profile. Restricted to the *delta* from ordinary SRE — capacity planning, canaries and runbooks are assumed.
Platform Foundation
Design and operate the gateways, providers, stores, quotas, and capacity behind LLM traffic.
Reference architecture
7 chaptersGateway → orchestration → providers → vector and state stores → evaluation and observability plane
AI gateways and proxies
7 chaptersCentral key management, budgets, routing, logging
Rate limiting and quotas for LLM traffic
7 chaptersToken-bucket on tokens, not requests; per-tenant budgets
Capacity planning for model traffic
7 chaptersTPM/RPM quotas, provisioned throughput, burst handling, multi-region
Build vs buy across the stack
6 chaptersGateway, vector store, evaluation platform, observability, agent framework
Runtime Assurance
Instrument production behavior, protect operational data, and respond to AI-specific incidents.
LLM tracing
6 chaptersA span per model call, prompt and completion capture, trajectory hierarchies
Metrics and SLOs
6 chaptersTTFT, p50/p95/p99, tokens per second, error rate, cost per request — and an SLO on quality, the part with no equivalent in your existing practice
Incident response for AI systems
6 chaptersQuality incidents with no stack trace, provider outages, model-update regressions
Data retention and privacy in logs
6 chaptersRedaction, zero-retention modes, region pinning, customer opt-outs
Efficiency Control
Reduce LLM cost and latency through caching, routing, batching, and response optimization.
Prompt cache operations
6 chaptersHit-rate monitoring, the write-premium vs read-discount cost model, routing stickiness, calculating what a given hit rate is worth
Semantic caching
6 chaptersEmbedding-keyed response cache, similarity thresholds, staleness and correctness risk
Model routing and cascades
7 chaptersCheap model by default, escalate on difficulty or failure; routing to small models where they suffice
Cost optimization portfolio
8 chaptersModel tiering, prompt compression, output-length control, batch endpoints, caching
Latency optimization
7 chaptersStreaming, predicted outputs, parallel calls, prefetching, a smaller model for the first token, skeleton-then-fill
Quality Lifecycle
Safely release changes, evaluate outcomes, learn from users, and detect quality drift.
Release and rollout
6 chaptersPrompt and model versioning, feature flags, canaries, shadow traffic, instant rollback
Online evaluation
8 chaptersA/B tests, interleaving, shadow deployment, guardrail metrics
Production feedback loops
6 chaptersExplicit signals (thumbs), implicit signals (edits, copies, retries, abandonment), converting both into evaluation cases
Drift detection
6 chaptersProvider model updates, data drift, prompt rot; scheduled re-evaluation
Part 17 · 7 topics · 49 chapters
Multimodal & Voice
Image *input* is in Stage 2 and document parsing in Stage 9, because RAG needs both. This is the rest of the modality surface.
Image Systems
Build systems that understand, retrieve, secure, generate, and edit visual content.
Vision-language capability beyond document parsing
7 chaptersScreenshots, UI grounding, bounding boxes, chart reading
Multimodal embeddings and cross-modal retrieval
7 chaptersOne vector space for text and images, and searching across the two
Image-borne prompt injection
7 chaptersInstructions embedded in an image reaching the model
Image generation and editing APIs
7 chaptersCost and latency shape, prompt control, editing operations
Voice Systems
Build speech pipelines and realtime agents for natural voice interaction.
Speech to text
7 chaptersStreaming ASR, diarization, timestamps, word error rate, domain vocabulary
Text to speech
5 chaptersVoice cloning, prosody control, streaming synthesis, latency budgets
Realtime voice agents
9 chaptersSpeech-to-speech models, voice activity detection, turn detection, barge-in and interruption, sub-second latency budgets, realtime transport
Part 18 · 12 topics · 82 chapters
Senior Scope
None of these are about writing more code.
Opportunity Strategy
Choose worthwhile AI problems, product surfaces, prototypes, and economic models.
Problem selection
7 chaptersWhich business problems are genuinely LLM-shaped, using verifiability (5.7) as the primary filter, and killing the ones that aren't
Not everything should be a chatbot
7 chaptersChoosing the surface — inline suggestion, background job, structured form, batch enrichment, or conversation
Feasibility assessment and PoC design
7 chaptersWhat to prototype, what to measure, and kill criteria defined *before* starting
Unit economics
8 chaptersCost per task, user and tenant; gross margin; pricing models; the margin trap of flat-rate pricing over variable-cost inference
Trustworthy Products
Design AI experiences that make uncertainty, errors, and user control explicit.
Designing around an imperfect component
8 chaptersAcceptable error rates, blast radius, reversibility, human oversight, how uncertainty surfaces to the user
AI product UX
9 chaptersStreaming, progressive disclosure, citations, confidence signals, edit-not-accept flows, undo, feedback capture, latency perception
Setting expectations on non-determinism
5 chaptersExplaining "90% accurate" to people who hear "broken", refusing demos-as-requirements
Post-mortems for AI systems and building institutional memory of failure modes
6 chaptersWriting down failure modes so the team stops rediscovering them
AI Stewardship
Sustain technical judgment, portability, research awareness, and organizational standards.
Migration and portability
7 chaptersAvoiding lock-in, where the abstraction boundaries belong, re-qualifying on model updates, deprecation cycles
Reading research
6 chaptersSeparating signal from hype, reproducing a core idea, deciding what to adopt and what to ignore
Staying current sustainably
7 chaptersA small curated source set rather than the firehose, and a personal evaluation suite as a stable benchmark across model releases
AI-specific technical leadership
5 chaptersStandards for reviewing prompts, evals, skills and config; who owns which; annotation as a funded workstream