A field guide for builders · Anime · comic · manga edition
Building With Intelligence
A rigorous guide to AI, agents, memory, personal intelligence, and autonomous systems—from probability to production and frontier governance.
Edition 1.2 · Interactive learning edition · Research cutoff: Offline-capable local app · No analytics, external network calls, or third-party code
Preface
The system is larger than the model
Most introductions teach AI as a parade of model names. This book teaches it as a sequence of decisions: what must be predicted, what must be known, what may be delegated, what must be verified, and what should remain ordinary software.
A language model can produce a convincing answer without possessing a database of facts, a goal of its own, or permission to act. An agent can look purposeful while merely repeating a loop chosen by its developers. A memory can improve continuity while preserving an old mistake. The central craft of applied AI is therefore not making a model sound intelligent. It is arranging evidence, software, authority, state, and human judgment so the whole system behaves usefully under uncertainty.
Who this is for
Beginners may read from the start. Founders and product managers can jump to Chapters 9, 18, 21, and 24. Engineers should read Chapters 7 and 12 before the production chapters. Researchers can use Chapters 22, 23, and 27 as an evidence checklist. No prior mathematics is assumed; optional formal sections supply notation without making it a gate.
How to read this book
Each chapter moves through three layers: Simple intuition, Technical mechanism, and Production decision. Collapsible sections hold optional depth. Sources sit beside the chapter they support. “Research finding” means a paper reported a result; it does not mean the result automatically generalizes. “Vendor claim” means the source describes its own system and was not independently reproduced here.
Ten possible titles for a later edition
The Intelligence Stack — Models, Memory, Tools, and Trust in Production AI
Engineering Useful Intelligence — From Probability to Reliable Agents
Beyond the Model — A Systems Guide to AI Products and Agents
The Agent Builder’s Field Manual — Architecture, Memory, Safety, and Evaluation
Intelligence, Bounded — Building AI Systems That Know When to Stop
Models Are Not Systems — The Practical Architecture of Applied AI
Reasoning Under Permission — A Guide to AI Agents That May Act
The Reliable Agent — Evidence, State, Tools, and Human Control
From Tokens to Tools — How Modern AI Systems Actually Work
Building With Uncertainty — The Engineering Discipline of AI
The recurring cases
Atlas, a synthetic research assistant, anchors retrieval, memory, and provenance. Northstar Support shows business workflows. Patch is a coding agent. Harbor Clinic is a fictional scheduling and intake service containing no real patient data. These systems become more capable chapter by chapter, but capability never silently expands authority.
Production ruleIf a deterministic component can satisfy the requirement more cheaply, predictably, and safely, use it. “Could software do this without inference?” is the book’s recurring design question.
Curriculum map
What the reader should be able to do
Reader
Outcome
Fast path
Beginner
Explain models, agents, tools, state, retrieval, memory, ontologies, and graphs without anthropomorphism.
1–8, 12–15
Founder / PM
Choose the least complex architecture that meets the outcome, risk, and cost envelope.
Separate mechanism claims from end-task evidence and audit comparisons for parity and leakage.
14, 21–23, 27
Prerequisite graph
Probability → learning and evaluation → language models → prompts and context → retrieval and tools → workflows and agents → state and memory → production controls → evaluation → architecture choice. Chapters may refer backward across this chain, never forward to an undefined dependency.
Terminology policy
Model means a learned function. System includes model plus surrounding software. Agent requires a model-driven action loop; it does not mean “anything using AI.” State records what is true for a process; memory is retained experience selected for later use. Grounding supplies evidence; it does not certify truth. Proof is reserved for formal proof unless explicitly qualified as an operational evidence receipt.
Field map · before Chapter 1
There is no single ladder of intelligence
“AI,” “agent,” “personal intelligence,” “AGI,” and “superintelligence” answer different questions. A useful map separates what a system can do, how broadly it generalizes, how independently it acts, where it exists, and whose interests it serves.
Use this map throughout the book: capability is not autonomy; breadth is not reliability; personalization is not general intelligence; and a superhuman result on one task is not superintelligence.
Five dimensions, not one score
Dimension
Question
Why it matters
Performance
How well does it perform the evaluated task?
A system may be superhuman at chess and unusable at scheduling.
Generality
Across how many genuinely different tasks and environments does competence transfer?
Broad benchmark coverage can still depend on enormous priors and familiar task formats.
Learning efficiency
How much new skill follows from limited experience?
François Chollet argues that displayed skill alone can hide how much prior data and engineering purchased it.
Autonomy
How far may the system select and execute actions without intervention?
A modest model with payment authority can create more risk than a brilliant read-only model.
Alignment and ownership
Whose goals, data, permissions, and accountability govern it?
This distinguishes a personal assistant from an employer, platform, public, or collective agent.
Narrow predictorlow breadth · bounded task
Narrow superhuman systemAlphaGo-like shape
General-purpose modelbroad but jagged
Tool-using generalistbreadth + action loop
Hypothetical ASIbroadly superhuman
A conceptual map, not a measurement of named products. Autonomy is a third axis not shown: any point can be advisory, collaborative, or highly autonomous.
A practical taxonomy of systems
Symbolic and deterministic intelligence
Rules, search, solvers, compilers, and theorem provers can exhibit impressive problem solving inside explicit representations. Their guarantees come from specified mechanisms, not human-like understanding.
Predictive intelligence
Learns mappings from examples: risk scores, forecasts, perception, ranking, and anomaly detection. Its central questions are generalization, calibration, shift, and decision cost.
Generative intelligence
Produces text, code, images, audio, video, or structured candidates. It expands the set of plausible outputs, which makes evidence and selection crucial.
Agentic intelligence
Places models inside observe–choose–act loops. Agency describes system organization and permission; it is not proof of higher intelligence.
Personal intelligence
A design category used in this book. A persistent system learns one person’s goals, boundaries, preferences, context, and history. It may be narrow or general, weak or strong. Its hardest problems are consent, identity, memory governance, conflicts of interest, portability, and revocation.
Embodied intelligence
Acts through a robot, vehicle, device, or simulated body. Physical state, uncertainty, latency, irreversible effects, and world models become central.
Collective intelligence
Coordinates people, models, institutions, tools, or agents. The system’s performance depends on communication, incentives, aggregation, diversity, and governance—not merely its strongest member.
Scientific intelligence
Supports or automates hypothesis generation, experiment design, simulation, analysis, and critique. Novel-looking output is not discovery until methods, evidence, and reproducibility survive expert scrutiny.
Artificial general intelligence (AGI)
An unsettled term for broadly capable artificial intelligence. One useful research framework separates breadth, performance level, and autonomy rather than using a binary label. This book makes no claim that a particular current system has crossed an AGI threshold.
Artificial superintelligence (ASI)
A hypothetical system that substantially exceeds human capability across a broad range of cognitive work—not a system that beats humans at one benchmark. No accepted test, arrival date, or demonstrated ASI exists at this research cutoff.
The jagged frontierThe 2026 International AI Safety Report describes current general-purpose capability as rapidly improving but uneven: systems can excel on difficult standardized tasks and still fail at apparently simpler spatial, counting, or long-workflow recovery tasks. Never interpolate reliability from the most impressive demonstration.
Interactive lab: classify a proposed intelligence
Move three axes. The output is a design description, not a prediction that such a system exists.
A moderately capable, narrow, advisory personal system. Its design priority is consent and scoped memory.
What “personal intelligence” could become
A mature personal intelligence would not merely remember a favorite restaurant. It would maintain a user-controlled model of goals, commitments, relationships, permissions, preferred ways of learning, and boundaries across time. It could assemble context for work, teach unfamiliar material, simulate options, coordinate tools, and preserve continuity across devices and providers.
That promise creates a constitutional problem: who may modify its model of the person, whose interests win when platform and user incentives conflict, what must be forgotten, how can a user inspect inferences, and how does authority expire? More personalization and more autonomy are not automatically more helpful. A 2025 controlled study of 450 participants reported that autonomy and personalization interact with privacy concern and willingness to use; the result is evidence about that experiment, not a universal law.
Design principleA personal intelligence should be legible, corrigible, portable, compartmentalized, and revocable before it becomes deeply autonomous.
How this edition teaches
Explain
Plain language comes first, then a worked example, then the technical mechanism and production boundary.
Predict
Interactive labs ask for a guess before showing how probabilities, architectures, or metrics change.
Retrieve
Every chapter ends with a teach-back, one knowledge check, and the explanation behind the answer.
Build
A studio task produces an artifact; the project ladder turns those artifacts into a capstone system design.
An audio-ready teaching edition
Future prerecorded narration should not be one continuous robot reading. Each chapter is prepared for four separately editable segments:
Chapter story5–10 minute guided narration with the main conceptual arc.
Concept clip60–120 seconds for a formula, diagram, or difficult distinction.
Pause and predictA question followed by silence, then the worked answer.
Production debriefA short staff-engineer explanation of what changes in a real system.
No audio or text-to-speech service is embedded in this edition. Every chapter retains an empty stable data-audio-src; when reviewed recordings exist, the reader can expose native audio controls while the HTML remains the canonical transcript.
Primary sources and further reading
Chollet, “On the Measure of Intelligence” (2019), arXiv.
Morris et al., “Levels of AGI for Operationalizing Progress on the Path to AGI” (2023), arXiv.
Richens, Everitt, and Abel, “General agents need world models” (ICML 2025), PMLR.
“Autonomy Matters: A Study on Personalization–Privacy Dilemma in LLM Agents” (2025 preprint), arXiv.
Part I
Learning to think about AI
Before building an agent, learn what a prediction is, what uncertainty means, and how learned systems fail outside the examples that shaped them.
Chapter 1
What AI is—and is not
AI is a family of engineered methods, not a substance placed inside software. The useful question is not “Is it intelligent?” but “What mapping does it perform, under which conditions, with what evidence of reliability?”
5 minComplete
Audio not available in this edition.
What you will learn: how automation, machine learning, generative models, and agents differ; why prediction can produce intelligent-seeming behavior; and why capability never guarantees dependable operation.
The simple explanation
A thermostat applies a rule. A spam classifier learns a boundary from labeled email. A language model learns statistical structure that lets it generate text. An agent places a model inside a loop that observes, chooses, and sometimes acts. These are progressively different architectures, not ascending ranks on a single “intelligence” meter.
Mental modelA model is a map, not a traveler. The application chooses where to consult the map, what observations to show it, whether to trust a suggested route, and whether anyone may move.
Prediction, generation, and apparent intelligence
A learned model estimates an output from inputs. For a classifier, that output may be a probability over labels. For a language model, it is a probability distribution over the next token, repeatedly sampled to form a sequence. Rich internal representations and enormous training corpora make next-token prediction surprisingly capable, but the training objective does not by itself include truthfulness, authorization, or concern for consequences.
This explains a central asymmetry. A system may be capable of writing an excellent discharge summary and still be unreliable at never inventing a medication. Capability asks, “Can it sometimes do the task?” Reliability asks, “Under the specified conditions, how often does it meet all requirements, including rare but costly ones?”
A short conceptual history
Early symbolic AI emphasized explicit rules and search. Statistical machine learning shifted attention toward learning patterns from data. Deep learning made learned representations central. The transformer made large-scale sequence modeling more parallel and effective. Instruction tuning and feedback made general models easier to direct. Tool interfaces and orchestration then turned text generators into components that could query and act. Each shift changed what was convenient; none repealed the need for software engineering or evidence.
Anthropomorphism is a lossy shorthand
Words such as “knows,” “believes,” and “decides” can compress a discussion, but they import assumptions. A model can output “I remember” when no persistent record exists. An agent’s “goal” may be a string in a prompt. Use operational language when consequences matter: the system retrieved a record, the model assigned a score, the policy allowed a tool call.
Worked classification. Harbor Clinic sends a fixed reminder 24 hours before every appointment: automation. It predicts no-show risk from past examples: machine learning. It drafts a personalized reminder: generative model. It checks availability, proposes alternatives, waits for confirmation, and books through a permitted API: a tool-using workflow or agent, depending on whether model judgment controls the loop.
Common mistakeCalling an application “an agent” because it uses a language model hides the real design. Name the loop, state, tools, stopping rule, and authority boundary.
Decision framework
Use rules when inputs and acceptable outputs can be enumerated.
Use learned prediction when patterns matter and an evaluation set represents deployment.
Use generation when several outputs may be acceptable and review or constraints can catch failures.
Use an agent only when choosing among actions under changing observations creates enough value to justify new failure modes.
Summary, key terms, and exercises
Summary: AI is learned or rule-based computation embedded in a larger system. Intelligence-like output is not evidence of truth, agency, or reliability. Key terms: automation, model, inference, generative model, agent, capability, reliability.
Classify three features in an app you use as rules, predictions, generation, or action loops.
Write one capability claim and the stronger reliability evidence it would require.
Learn it, test it, build it
Teach it back: Explain model, system, and agent without using the word “smart.”
Studio task
Make a one-page map of three AI features you use and classify each mechanism.
Evidence of completion: Each classification names inputs, outputs, authority, and one failure.
Primary sources and further reading
A. Turing, “Computing Machinery and Intelligence” (1950), Mind.
Vaswani et al., “Attention Is All You Need” (2017), arXiv.
Ouyang et al., “Training Language Models to Follow Instructions with Human Feedback” (2022), arXiv.
Chapter 2
The minimum mathematics
Probability is not decorative theory. It is the language for deciding what a score means, how evidence changes belief, and which mistakes a product can afford.
5 minComplete
Audio not available in this edition.
What you will learn: variables, vectors, conditional probability, Bayes’ rule, distributions, expectation, variance, calibration, precision, recall, and why averages can conceal harm.
Variables, functions, and vectors
A variable names a quantity. A function maps inputs to outputs: f(x)=y. A vector is an ordered list of numbers, such as a patient-free synthetic appointment represented by [days since booking, prior cancellations, travel distance]. Dimensions are positions in that representation. In modern models, many dimensions do not have simple human labels; together they encode a useful geometry.
Conditional probability and Bayes
P(A|B) means the probability of A given B. It is not generally equal to P(B|A). Bayes’ rule reverses the condition:
Plain intuition. Start with how common a condition is, then update with how compatible the evidence is.
Formal form. P(A|B) = P(B|A)P(A) / P(B).
Suppose 1 in 100 messages is truly urgent. A detector catches 90% of urgent messages and falsely flags 5% of ordinary ones. In 10,000 messages, about 100 are urgent: 90 are caught. Of 9,900 ordinary messages, 495 are falsely flagged. Among 585 alerts, only 90—about 15%—are truly urgent. High sensitivity did not create high confidence because the base rate was low.
Interactive lab: why base rates change an alert
Adjust a detector and inspect a synthetic cohort of 10,000 cases. The posterior shown is the precision of a positive alert.
Default example: 90 true alerts and 495 false alerts; precision is 15.4%. Most alerts are false even though sensitivity is high.
True alerts0
False alerts0
Distributions, expectation, and variance
A distribution assigns probabilities across possible values. Its expectation is the probability-weighted average. Variance describes spread around that average. Two systems can have the same mean latency or accuracy while one has a dangerous tail. Production decisions need percentiles, subgroups, and failure categories, not only averages.
Calibration is not accuracy
A calibrated system that labels many cases 70% confident should be correct on roughly 70% of those cases. A perfectly accurate classifier can be poorly calibrated in its scores; a calibrated forecaster may still be too inaccurate to use. Calibration must be checked on representative data and can deteriorate after distribution shift.
Predicted positive
Predicted negative
Actually positive
True positive
False negative
Actually negative
False positive
True negative
Precision asks: of predicted positives, how many were right? Recall asks: of actual positives, how many did we find? A fraud investigation queue may prioritize precision when review is expensive. A safety screen may prioritize recall, then use a second stage to manage false alarms. The correct threshold comes from consequences, not convention.
Technical Correlation, causation, and interventions
Correlation is statistical association. Causation asks what would change under an intervention. A model can exploit a hospital identifier correlated with severity without learning anything clinically causal. Randomization, natural experiments, causal assumptions, and domain knowledge—not prediction accuracy alone—support causal claims.
WarningAn overall 95% success rate can coexist with 50% success for a rare language, tool, or user group. Report denominators and slices that correspond to plausible harms.
Production decision
Before choosing a metric, write the cost of each cell in the confusion matrix. Add abstention as an explicit output. Track calibration and error rates over time. If the deployment distribution changes, old confidence estimates are historical evidence, not a warranty.
Summary: probabilities are conditional, scores need calibration, errors have asymmetric costs, and means hide tails. Key terms: prior, likelihood, posterior, distribution, expectation, variance, calibration, precision, recall, base rate.
Recompute the alert example if the base rate rises to 10%.
For a support escalation classifier, assign a cost to each confusion-matrix cell and choose which metric should lead.
Learn it, test it, build it
Teach it back: Teach Bayes’ rule using a smoke alarm or medical-free synthetic alert.
Studio task
Build a 1,000-case confusion matrix for two different base rates.
Evidence of completion: Show precision, recall, denominators, and the product decision that changes.
Primary sources and further reading
G. Brier, “Verification of Forecasts Expressed in Terms of Probability” (1950), Monthly Weather Review.
Guo et al., “On Calibration of Modern Neural Networks” (2017), PMLR.
Saito and Rehmsmeier, “The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets” (2015), PLOS ONE.
Chapter 3
How machines learn
Training does not pour facts into a database. It adjusts parameters so examples that resemble the training experience tend to receive useful outputs.
4 minComplete
Audio not available in this edition.
What you will learn: supervised, unsupervised, self-supervised, and reinforcement learning; training splits; representations and embeddings; optimization; leakage, shift, and feedback loops.
Four learning arrangements
Supervised learning uses input-output examples, such as emails labeled spam or not spam.
Unsupervised learning seeks structure without task labels, such as clusters.
Self-supervised learning creates targets from the data itself. Predicting masked or next tokens turns abundant text into training examples.
Reinforcement learning learns behavior from reward signals across actions and consequences. In language-model post-training, human or model preferences can shape a reward or directly optimize preferences.
Training is optimization
A model contains adjustable parameters. A loss function measures disagreement between predictions and training targets. Optimization repeatedly changes parameters to reduce loss. Features are input measurements; learned representations are internal features discovered during training. An embedding is a vector representation whose geometry is useful for some objective.
Mental modelTraining is sculpting a landscape of tendencies, not filing sentences into drawers. Retrieval systems add drawers later; they are a separate mechanism.
Generalization and overfitting
The training set fits parameters. A validation set guides choices such as architecture or thresholds. A test set estimates performance after choices are frozen. Repeatedly tuning on the test set turns it into another validation set. Overfitting occurs when a system captures quirks that help on observed examples but fail on new ones.
Leakage example. Northstar Support builds a cancellation predictor. The exported training table contains a “refund issued” field written after cancellation. The model scores brilliantly, but the feature is unavailable when a prediction must be made. This is temporal leakage: information from the future crossed into training.
Distribution shift and feedback
Independent and identically distributed examples are a useful mathematical simplification, not a promise about production. Users change, policies change, attackers adapt, and the model’s own outputs alter future data. If a triage model routes only high-scoring cases to experts, labels for low-scoring cases disappear; retraining then learns from its prior selection policy. This is a feedback loop.
Technical Why loss is not the product objective
Cross-entropy rewards assigning probability to the observed class or token. A product may care about successful task completion, absence of unsafe actions, latency, or correction burden. Training loss is a proxy. Validation must reconnect the proxy to the actual outcome and preserve hard constraints separately.
Production ruleBind every evaluation record to the data snapshot, split procedure, prompt, model, tools, configuration, and time. Otherwise a score is an anecdote with decimals.
Summary: learning minimizes a chosen loss over examples; generalization is empirical and conditional. Leakage, shift, and feedback can invalidate apparently strong results. Key terms: parameter, feature, representation, embedding, loss, optimization, generalization, overfitting, leakage, distribution shift.
Identify one feature in a product dataset that might leak future information.
Describe how deployment could change the labels later collected for retraining.
Learn it, test it, build it
Teach it back: Explain training, validation, and testing as three different jobs.
Studio task
Audit ten candidate features for leakage and deployment availability.
Evidence of completion: Document when each field becomes known and who writes it.
Primary sources and further reading
Devlin et al., “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding” (2018), arXiv.
Goodfellow, Bengio, and Courville, Deep Learning (2016), official open text.
Sculley et al., “Hidden Technical Debt in Machine Learning Systems” (2015), NeurIPS proceedings.
Part II
From language models to useful systems
A fluent model becomes a dependable component only when context, evidence, schemas, and permissions are engineered around it.
Chapter 4
How modern language models work
A language model repeatedly predicts a distribution over the next token. Transformer attention lets each position construct a context-dependent representation of other positions.
4 minComplete
Audio not available in this edition.
What you will learn: tokens, embeddings, attention, transformers, pretraining, context windows, sampling, and why fluency and truth separate.
From characters to tokens
Tokenization converts text into units from a learned vocabulary: common words, fragments, punctuation, or bytes. The model maps each token to an embedding and combines it with position information. Token counts—not word counts—usually determine context and API cost.
Attention and the transformer
In self-attention, each position produces a query, key, and value. Similarity between a query and keys determines how much their values influence the new representation. Multiple heads learn different interaction patterns. Feed-forward layers transform each position; residual connections and normalization stabilize deep stacks. “Attention” is a numerical routing mechanism, not human attention or an explanation of intent.
Technical The compact equation
Attention(Q,K,V) = softmax(QKᵀ/√d)V. The dot products score compatibility; scaling prevents large dimensions from making softmax excessively sharp; the weighted sum mixes values. Causal models mask future positions during next-token training.
Pretraining and post-training
Pretraining exposes a model to broad corpora and optimizes token prediction. Instruction tuning teaches response patterns from demonstrations. Preference optimization or reinforcement learning can make outputs better match human judgments. These stages shape behavior but do not create a guaranteed internal fact table, a stable identity, or access to events after the training cutoff.
Context and sampling
The context window is the bounded sequence available during a request. Larger windows reduce some truncation pressure but do not guarantee that every included detail will influence the answer correctly. Temperature rescales token logits before sampling: higher values generally flatten the distribution and increase variation. It is not a “creativity” or “truth” dial.
Worked next-token view. After “The capital of France is”, a model might assign Paris .96, Lyon .01, and other tokens the remainder. Sampling once produces a token; the token re-enters the context; the process repeats. A confident continuation can still be wrong when the premise is false, evidence is missing, or training patterns are misleading.
WarningTraining knowledge is compressed statistical influence. Runtime knowledge is evidence supplied or queried now. Use retrieval or authoritative tools for facts that must be current, private, attributable, or complete.
Why fluency is not truth
The objective rewards plausible continuation. It does not inherently check a claim against reality. Hallucination is therefore not a detachable typo module; it is a system-level mismatch between generation and the requirement for supported claims. Grounding, abstention, verification, and evaluation reduce risk, but no prompt turns generation into a proof engine.
Summary: transformers build contextual token representations and generate one token at a time. Context is temporary input; weights are learned tendencies. Key terms: token, embedding, attention, transformer, pretraining, post-training, context window, logit, temperature.
Explain why a 200-page document fitting in context does not imply every fact is equally accessible.
Name two product requirements that demand runtime evidence rather than training recall.
Learn it, test it, build it
Teach it back: Explain next-token prediction without implying the model stores a fact database.
Studio task
Tokenize five multilingual or code examples with any documented tokenizer.
Evidence of completion: Compare token counts and explain cost or truncation implications.
Primary sources and further reading
Vaswani et al., “Attention Is All You Need” (2017), arXiv.
Brown et al., “Language Models are Few-Shot Learners” (2020), arXiv.
Ouyang et al., “Training Language Models to Follow Instructions with Human Feedback” (2022), arXiv.
Chapter 5
Prompting as interface design
A prompt is an interface to probabilistic behavior. It can clarify a task; it cannot enforce permissions, transactions, secrecy, or correctness.
4 minComplete
Audio not available in this edition.
What you will learn: instruction layers, zero- and few-shot prompting, decomposition, critique, context engineering, injection, and the boundary between prompt and architecture.
Specify the contract
A useful prompt states the outcome, audience, available evidence, constraints, and output shape. Few-shot examples show behavior that prose may describe ambiguously. Structured output constrains syntax. Decomposition separates a difficult task into inspectable stages. None of these mechanisms makes the output deterministic across model versions or inputs.
Many platforms distinguish instruction sources—system, developer, user, and tool—but names and precedence are runtime-specific. The durable idea is provenance: the application must know which text came from its policy, its operator, an end user, a retrieved page, or a tool result.
Better interface. Instead of “Summarize these tickets,” ask for five recurring issue categories, one representative ticket ID per category, an uncertainty note, and valid JSON matching a schema. Then validate IDs against the allowed ticket set. The schema catches malformed structure; the ID check catches unsupported references.
Context engineering
Context engineering chooses what enters the request, in what order, with which labels and limits. It includes retrieval, tool descriptions, state summaries, examples, policies, and prior turns. More context can add distraction, contradictory instructions, private data, latency, and cost. Selection is part of system behavior.
Reasoning traces and critique
Prompted intermediate reasoning can improve some multi-step tasks, but a fluent trace is not a faithful audit log of hidden computation. Ask for concise justifications, cited evidence, calculations, or verifiable artifacts when those help review. Self-critique can catch errors, but the same model can repeat the same misconception; independent checks are stronger when available.
Prompt injection
When a model processes untrusted content, that content can contain text that competes with the application’s instructions. Retrieved documents, web pages, emails, and tool output are data from the application’s perspective, even though the model sees more tokens. Delimiters and warnings may help behavior but do not form a security boundary.
Production ruleEnforce authorization outside the model. Give the model the smallest tool set and data slice needed. Treat every proposed write as untrusted input to deterministic policy and schema validation.
Decision framework
Use prompting for task description, examples, tone, and output contracts.
Use code for permissions, invariants, calculations that must be exact, and state transitions.
Use retrieval for current or private evidence.
Use evaluation to learn whether a prompt works; do not judge from a few attractive examples.
Summary: prompting is powerful interface design, not a production security or correctness architecture. Key terms: zero-shot, few-shot, decomposition, structured output, context engineering, prompt injection.
Rewrite a vague prompt as an outcome-evidence-constraints-schema contract.
Mark every input source as trusted policy, operator request, untrusted content, or tool output.
Learn it, test it, build it
Teach it back: Turn a vague prompt into outcome, evidence, constraints, and output contract.
Studio task
Create five prompt variations and run a small stability test.
Evidence of completion: Report output variance instead of choosing only the best result.
Primary sources and further reading
Wei et al., “Chain-of-Thought Prompting Elicits Reasoning in Large Language Models” (2022), arXiv.
Zhou et al., “Least-to-Most Prompting Enables Complex Reasoning” (2022), arXiv.
Greshake et al., “More than you’ve asked for: A Comprehensive Analysis of Novel Prompt Injection Threats” (2023), arXiv.
Chapter 6
Retrieval and grounding
Retrieval finds candidate evidence. Generation turns selected evidence into an answer. Authority, freshness, and correctness remain separate tests.
4 minComplete
Audio not available in this edition.
What you will learn: lexical and dense search, embeddings, reranking, hybrid retrieval, RAG, chunking, metadata, citations, provenance, freshness, and authority.
Search has different failure modes
Lexical retrieval rewards shared terms and is strong for exact names, codes, and rare phrases. Dense retrieval embeds queries and passages, then compares vectors; it can match paraphrases but may blur distinctions. Hybrid systems combine candidates. A reranker spends more computation scoring query-passage pairs. Each stage trades recall, precision, latency, and inspectability.
RAG as a pipeline
Retrieval-augmented generation usually means: transform a question, retrieve candidate chunks, filter or rerank them, assemble context, generate an answer, and attach citations. Failures can occur at every arrow. The answer model cannot use a decisive source that retrieval omitted. A high retrieval score says “similar under this mechanism,” not “true,” “authorized,” or “complete.”
The security and evidence boundary begins before retrieval: only sources the caller may access should become candidates.
Chunking and metadata
Chunks must be small enough to retrieve precisely but large enough to preserve meaning. Fixed windows are simple; structure-aware chunks preserve headings, tables, or code units. Useful metadata includes source identity, version, valid time, owner, jurisdiction, access policy, and canonical URL. Metadata filters can improve both security and relevance, but ingestion-time permissions must be rechecked at query time.
Atlas answers a policy question. A semantic search retrieves a friendly onboarding guide from 2024 and a terse policy amendment from 2026. Similarity ranks the guide first; authority and date make the amendment controlling. A robust system returns both, identifies the conflict, and explains which source governs. “Top result wins” would produce a polished error.
Citations and provenance
A citation should bind a claim to a passage the reader can inspect. Validate that cited sources were actually in context and that each citation supports the adjacent claim. Provenance records where content came from and how it was transformed. It helps auditing; it does not guarantee that the source itself is correct.
WarningFreshness, authority, relevance, and truth are four different properties. Build and evaluate them separately.
When to query the source live
Use a derived index to nominate documents. Query the source-of-truth system live when values change frequently, consequences are high, completeness matters, or access can change. A scheduling assistant should query current availability; it should not treat a remembered slot or yesterday’s index as bookable inventory.
Summary: RAG is a staged information-retrieval system. Retrieval improves access to evidence but does not certify answers. Key terms: lexical retrieval, dense retrieval, embedding, reranker, RAG, chunk, metadata, provenance, authority.
Design a retrieval test with separate relevance, authority, and freshness labels.
List three fields that must be read live rather than remembered in your domain.
Learn it, test it, build it
Teach it back: Explain why the most relevant document may not be authoritative.
Studio task
Build a ten-document corpus with one stale and one conflicting source.
Evidence of completion: Measure recall and show an authority-aware answer.
Primary sources and further reading
Lewis et al., “Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks” (2020), arXiv.
Karpukhin et al., “Dense Passage Retrieval for Open-Domain Question Answering” (2020), arXiv.
Tool use crosses the boundary from language to effects. The model may propose an operation; the host application decides whether, how, and under whose authority it runs.
4 minComplete
Audio not available in this edition.
What you will learn: function calling, schemas, read/write separation, least privilege, idempotency, retries, timeouts, partial failure, and why model intent is not authorization.
The tool contract
A tool exposes a name, purpose, input schema, and execution handler. The model emits a structured proposal. The application validates it, checks policy, executes through ordinary code, and returns a bounded result. Structured output narrows syntax; it does not make values safe or semantically correct.
The host must verify that the slot exists, the caller may hold it, the duration is allowed, and the operation is not a duplicate. A schema cannot decide those facts.
Read and write are different trust classes
Reading a public knowledge base is usually reversible. Sending an email, charging a card, changing a record, or deleting data creates external effects. Separate read tools from write tools. Require previews or approvals for consequential writes. Keep credentials inside the execution service; do not place them in prompts.
Idempotency, retries, and partial failure
Networks fail ambiguously. A timeout does not reveal whether the remote system committed the request. Retrying a non-idempotent “charge” can double-charge. Supply an idempotency key bound to the business operation and make repeated execution return the same result. Define timeouts, bounded retries with backoff, and a reconciliation path for unknown outcomes.
Failure timeline. Patch asks a deployment tool to create release R17. The service commits, but the response is lost. A blind retry creates R18. With key release:commit-abc, the service recognizes the same logical action and returns R17. The model’s wording is irrelevant; the server owns deduplication.
Design the result, not only the call
Tool results need stable status codes such as succeeded, rejected, retryable, or outcome_unknown. Return only necessary data. Treat tool output as untrusted if it contains external content. Preserve audit fields: actor, authority, tool version, validated arguments, idempotency key, result, timestamps, and approval reference.
Production ruleA tool description is not a permission system. Enforce least privilege and business invariants in the executor every time.
Tool checklist
Can this be a narrower operation?
Is it read-only, reversible, or externally consequential?
Who authorizes it, and can that authority be delegated?
What makes retries safe?
What happens after timeout or partial success?
What evidence proves the observed outcome?
Summary: tool calling is a proposal-execution protocol. Schemas validate shape; deterministic code validates authority and invariants. Key terms: function calling, schema, least privilege, idempotency, timeout, backoff, partial failure, reconciliation.
Rewrite a broad “manage calendar” tool as three least-privilege tools.
Define the idempotency key and unknown-outcome path for one write operation.
Learn it, test it, build it
Teach it back: Explain model proposal versus host execution.
Studio task
Specify one read tool and one write tool for the same domain.
Evidence of completion: Include schema, permission, timeout, result states, and audit fields.
Primary sources and further reading
Schick et al., “Toolformer: Language Models Can Teach Themselves to Use Tools” (2023), arXiv.
Yao et al., “ReAct: Synergizing Reasoning and Acting in Language Models” (2022), arXiv.
IETF, “The Idempotency-Key HTTP Header Field” (work in progress), official datatracker.
Part III
Understanding agents
Agency is a spectrum produced by loops, tools, state, and permission—not a personality hiding inside a model.
Chapter 8
What an AI agent actually is
An AI agent is a system in which a model helps select the next action from observations in a loop. Autonomy depends on which actions, how many iterations, and what approval boundaries the system permits.
4 minComplete
Audio not available in this edition.
What you will learn: the components of an agent; agent versus chatbot, program, and workflow; autonomy as a spectrum; and when the term helps.
The seven-part anatomy
Model: proposes interpretations or actions.
Instructions: define task and behavioral constraints.
State: records the current process.
Tools: expose observations or effects.
Environment: the world changed or inspected by tools.
Loop: observe → choose → act → observe.
Stopping condition: success, failure, budget, deadline, or human decision.
A chatbot may generate one response without acting. An ordinary program selects branches developers enumerated. A workflow follows explicit states and transitions, perhaps using models inside steps. In an agent, model output selects at least some next actions dynamically. Hybrids are common and often preferable.
Mental modelA workflow is a railway with known stations. An agent is a driver choosing among permitted roads. The safe system still supplies a map, guardrails, fuel limit, destination, and places where a human takes the wheel.
Degrees of autonomy
Level
Model role
Example
Advisory
Suggests; human acts
Draft a reply
Constrained execution
Selects among narrow, reversible tools
Search approved documents
Workflow autonomy
Advances allowed states under gates
Resolve routine support cases
Open-ended autonomy
Plans many actions across broad tools
Long-running research or coding
Risk rises with tool power, iteration count, hidden state, environmental uncertainty, and irreversibility. A one-step payment tool can be riskier than a 20-step read-only research loop. Count consequences, not just steps.
When the label becomes harmful
“Agent” can conceal missing specifications. Ask instead: which decisions are model-selected? Which state transitions are deterministic? Which tools can write? How is success verified? Who can stop it? If a team cannot answer, the system is not yet designed.
Common mistakeGiving a model a goal and a shell is not an architecture. It is an unbounded delegation of interpretation to the least verifiable component.
Summary: agents are model-guided action loops embedded in host software. Autonomy is multidimensional. Key terms: observation, action, environment, policy, loop, stopping condition, autonomy.
Draw the seven components for a familiar “agent” product.
Identify which autonomy dimension most affects its risk.
Learn it, test it, build it
Teach it back: Name all seven parts of an agent using one concrete example.
Studio task
Draw the observe–choose–act loop for a bounded assistant.
Evidence of completion: Mark model-selected steps and deterministic gates.
Choose the simplest architecture that meets the outcome and failure budget. Complexity is justified only by measured value that a simpler system cannot deliver.
6 minComplete
Audio not available in this edition.
What you will learn: when to reject an agent, when a workflow is enough, when memory or graphs help, and where human approval belongs.
The decision tree
Start with requirement structure, not fashion. Every “yes” to more autonomy creates new evaluation and control obligations.
Interactive lab: earn architectural complexity
Score a use case. The suggestion is a discussion aid; consequences and domain constraints still require expert judgment.
Default recommendation: put one model inside an explicit workflow, query current data live, and require human approval before consequential action.
Comparison table
Pattern
Use when
Avoid when
Main cost / risk
Deterministic code
Rules and invariants are knowable
Inputs require semantic judgment
Rule maintenance
Rules engine
Policies change and need audit
Policy cannot be enumerated
Conflicts and rule sprawl
Single model call
One bounded fuzzy transformation
External effects or long dependencies
Output variance
Prompt chain
Known stages benefit from separate contexts
One call performs equally well
Latency, error compounding
Workflow / state machine
States and allowed transitions are known
The path genuinely cannot be specified
Design effort
Tool-using agent
Observations change the next useful action
Writes are high-risk or success is vague
Loop variance, tool risk
Planner–executor
A plan improves coordination and can be checked
Plans go stale after every action
Extra calls, plan anchoring
Subagents
Parallel, separable work has clear merge criteria
Context is tightly coupled
Coordination and duplicated tokens
Retrieval
Current/private evidence must be found
The source can be queried exactly
Index freshness and recall
Persistent memory
Selected past experience improves later work
Live source state answers the question
Staleness, poisoning, deletion
Ontology / knowledge graph
Shared semantics or multi-hop relations matter
Tables and joins answer the need
Curation and entity resolution
Event-driven + saga
Long-running cross-service effects need recovery
A local transaction suffices
Eventual consistency
Human in the loop
Judgment, accountability, or consequence warrants it
The review is ceremonial or overloaded
Delay and attention
When should I not use an agent?
Do not use an agent when a query, formula, rules engine, search endpoint, or explicit workflow can meet the requirement. Do not use one when success cannot be observed, rollback is unavailable, tool permissions cannot be narrowed, or no evaluation set represents the task. A persuasive demo is not a substitute for an operating envelope.
Workflow or agent?
Prefer a workflow when states and transitions are known, compliance requires a fixed process, or failure recovery matters more than path flexibility. Put models inside bounded steps for extraction, classification, drafting, or ranking. Use an agent when the useful next step depends on open-ended observations and the allowed action set remains safe.
Memory, live data, ontology, or SQL?
Query live systems for current inventory, permissions, balances, schedules, or configuration. Use memory for preferences, past attempts, strategies, and historical context—never as an automatic replacement for the source. Use SQL when entities, fields, and joins suffice. Add an ontology when several systems use inconsistent concepts and shared meaning is itself a requirement. Add a graph when relationship traversal, provenance, or evolving multi-hop connections are central and measured query value exceeds maintenance cost.
Subagent or one strong agent?
Delegate when tasks are separable, can run concurrently, need different tools or contexts, and have a deterministic merge or review step. Stay single-agent when every worker needs the same large context, outputs depend tightly on one another, or failures cannot be attributed. Measure quality, latency, cost, and correction burden against a one-agent baseline.
Where should a human approve?
Place approval before irreversible or externally consequential state transitions, not after prose generation. Show the reviewer the exact proposed action, destination, changed fields, evidence, uncertainty, reversibility, and authorization scope. Approval should expire if the action changes.
Use this / avoid thisUse models to interpret ambiguity; use deterministic software to enforce invariants. Use agents to navigate bounded uncertainty; avoid giving them authority merely because they can describe an action.
Cost and reliability
Every added call introduces latency, cost, and another conditional failure. If each of five dependent stages succeeds 95% of the time and failures are independent, end-to-end success is about 77%. Independence rarely holds, but the arithmetic teaches the direction: chains multiply opportunities to fail. Parallel branches can improve coverage yet raise aggregation and conflict costs.
Summary: architecture is a ladder of justified complexity. Start deterministic, add bounded inference, then state, tools, memory, or multiple agents only for measured needs. Key terms: workflow, state machine, planner–executor, ontology, knowledge graph, human-in-the-loop.
Apply the tree to a travel planner and identify the first irreversible action.
Replace one imagined agent with a workflow and list what capability is lost.
Learn it, test it, build it
Teach it back: Defend the least complex architecture for a product idea.
Studio task
Apply the chapter decision tree to three product ideas.
Evidence of completion: For each, state what you rejected and why.
Planning is useful only when it improves action under a budget. A plan is a hypothesis about future steps, not a contract with the environment.
4 minComplete
Audio not available in this edition.
What you will learn: ReAct-style loops, plan-and-execute, critique, tree search, replanning, budgets, and long-horizon failure.
Four loop shapes
Reason-and-act alternates model decisions with tool observations. Plan-and-execute drafts a sequence, then performs or revises it. Reflection converts feedback into another attempt or retained lesson. Tree search explores multiple candidate reasoning paths and evaluates intermediate states. These are control patterns; paper results on selected tasks do not make one universally superior.
Planning versus replanning
A plan can reduce drift, expose missing prerequisites, and enable approval. It can also anchor the system to assumptions that the first observation invalidates. Attach preconditions to steps. Replan after material environmental changes, not after every token. Preserve completed effects so replanning does not repeat them.
Patch’s plan. (1) reproduce bug, (2) locate cause, (3) edit, (4) test, (5) summarize. If reproduction fails because the dependency is unavailable, blindly moving to step 2 fabricates confidence. The loop should stop with an evidence-labeled blocker or choose an approved diagnostic branch.
Stop conditions and budgets
Define maximum model calls, tool calls, wall time, tokens, money, repeated states, consecutive failures, and side-effect count. Also define success evidence. “The model says done” is not a stopping proof. For code, success might require specified tests at a bound commit. For research, it might require coverage of named questions and inspected primary sources.
Why long horizons fail
Small errors compound; context fills with stale detail; tools return ambiguous outcomes; goals drift; and evaluation becomes sparse. Checkpoint durable state outside the context window. Verify local milestones. Use typed failure states. Escalate when progress stops rather than rewarding endless activity.
WarningReflection adds another model sample, not independent truth. Couple it to tests, source checks, simulators, or human review wherever possible.
Choosing a loop
Use a fixed workflow for known steps.
Use ReAct for bounded information gathering where each observation changes the next query.
Use an explicit plan when dependencies or approval benefit from preview.
Use branching search only when intermediate states can be scored and the value justifies multiplied cost.
Summary: agent loops manage uncertain paths; budgets and evidence gates keep them finite. Key terms: ReAct, plan-and-execute, reflection, tree search, checkpoint, stop condition.
Write success, failure, and budget stop conditions for a research agent.
Identify one plan step whose outcome should force replanning.
Learn it, test it, build it
Teach it back: Explain why a plan is a hypothesis, not a promise.
Studio task
Write success, failure, no-progress, and budget stops for one agent.
Evidence of completion: Test them against three failure timelines.
Multiple agents create an organization made of probabilistic components. Specialization and parallelism can help, but communication does not turn correlated errors into independent evidence.
4 minComplete
Audio not available in this edition.
What you will learn: delegation, role specialization, supervisor-worker, debate, shared state, coordination costs, error propagation, and evaluation.
Why divide the work?
Subagents can isolate contexts, use different tools, run independent tasks concurrently, or create explicit review roles. A supervisor-worker pattern assigns and merges work. A blackboard pattern lets workers contribute to shared structured state. Debate asks models to challenge positions. Each pattern needs a reason that a single agent with the same total budget cannot provide.
The independence trap
Three agents using the same model, prompt assumptions, retrieved sources, and evaluator are not independent experts. Majority vote can amplify a shared misconception. Role names such as “security specialist” do not confer credentials. Diversity must arise from evidence, tools, methods, data, or models—and still requires measurement.
Good delegation. Atlas assigns one worker to retrieve papers, one to inspect official specifications, and one to audit claim-to-source alignment. Outputs use a shared schema, each citation is re-opened by the integrator, and the one-agent baseline uses the same overall call budget. The roles produce separable artifacts and a testable merge.
Shared state and communication
Use typed shared state rather than free-form transcripts when possible. Record task ID, owner, input evidence, output artifact, status, assumptions, and dependencies. Limit messages to what the recipient needs. Concurrent workers require conflict handling; “last writer wins” can erase valid work.
Failure modes
Delegation ambiguity: workers solve different interpretations.
Error propagation: a supervisor trusts an unsupported worker summary.
Coordination tax: tokens and latency exceed useful work.
Deadlock or churn: agents wait, reassign, or critique indefinitely.
Evaluation bias: the supervisor and judge share the same blind spot.
Production ruleEvery delegation needs a bounded task, an output contract, ownership, deadline or budget, and an acceptance test. Re-open source evidence at integration boundaries.
Proving that multiple agents helped
Compare against one strong agent under both equal-compute and native-default budgets. Hold model, tools, task set, and scoring constant. Report task success, severe failures, latency, cost, and human correction burden. Run ablations: remove the reviewer, remove parallelism, or replace worker messages with direct evidence.
Summary: multi-agent design is distributed-systems design plus model uncertainty. Use it for separable work and measured specialization, not theatrical teams. Key terms: supervisor-worker, delegation, blackboard, debate, coordination cost, ablation.
Take a tightly coupled task and explain why delegation would harm it.
Design an equal-budget single-versus-multi-agent evaluation.
Learn it, test it, build it
Teach it back: Explain why three same-model agents are not three independent experts.
Studio task
Split one task into candidate subagent jobs, then remove unnecessary roles.
Evidence of completion: Keep only separable work with an acceptance test.
Kim et al., “Capable Language Models Can Outgrow the Benefits of Collaboration” (2026), Nature Machine Intelligence. Multi-agent effects varied widely under matched compute; its reported selection threshold is not a universal law.
Part IV
State, memory, and knowledge
Continuity becomes trustworthy only when process state, remembered experience, live evidence, and shared semantics remain distinct.
Chapter 12
State is not memory
State records where a system is now. Memory retains selected information from before. Context is what a model can see during one inference. Confusing them creates stale actions and unrecoverable workflows.
4 minComplete
Audio not available in this edition.
What you will learn: seven kinds of state, their lifetimes and owners, and why a source-of-truth system must remain authoritative.
Kind
Question answered
Typical lifetime
Request state
What belongs to this call?
Milliseconds to minutes
Conversation state
What has been said in this session?
Session
Model context
What tokens can this inference use?
One call
Workflow state
Which durable step and transitions apply?
Until process completion
Operational database state
What records exist now?
Business-defined
Persistent memory
What past experience may help later?
Policy-defined
Source of truth
Which system has authority for this fact?
Domain-defined
Harbor Clinic’s conversation says, “Tuesday afternoon works.” The workflow records awaiting_confirmation. The scheduling database says slot S42 is currently free. Memory says the synthetic user usually prefers afternoons. Only the scheduling system can confirm inventory; preference memory may rank choices but cannot reserve one.
Durable state belongs outside the prompt
A context window can be truncated, summarized incorrectly, or rebuilt differently. Store workflow state in a transactional system with explicit versions and allowed transitions. Construct model context as a view over that durable state. The model proposes; the state machine validates and commits.
State transition.offered → held → confirmed is allowed. offered → completed is not. A model output saying “appointment confirmed” cannot skip payment or identity gates. The host compares the expected state version, performs the transaction, and returns the new state.
Ownership and time
For each field, document owner, update path, valid time, retention, and conflict rule. Duplicated state drifts. Caches need invalidation. Event streams need projections and replay semantics. Summaries should carry the version of the records they summarize.
Common mistakePutting “the current workflow status” into memory creates a second, stale source of truth. Store the status once; let memory retain only useful historical experience.
Decision framework
If the fact changes business behavior now, locate its authoritative store.
If a process must resume after failure, checkpoint workflow state.
If the information only helps select context, it may be memory.
If a model needs it for this call, render a bounded context view—do not transfer ownership to the prompt.
Summary: state, context, memory, and truth have different owners and lifetimes. Key terms: request state, workflow state, checkpoint, projection, source of truth, context.
Inventory five fields in an assistant and assign an owner and lifetime.
Find one piece of “memory” that should instead be queried live.
Learn it, test it, build it
Teach it back: Distinguish context, workflow state, memory, and source of truth.
Studio task
Create a state inventory for one assistant.
Evidence of completion: Assign owner, lifetime, version, update path, and conflict rule.
Primary sources and further reading
Gray and Reuter, Transaction Processing (1992), Morgan Kaufmann.
Memory is a governed pipeline for retaining, selecting, revising, and deleting past information. Retrieval from a memory store is recollection, not certification.
4 minComplete
Audio not available in this edition.
What you will learn: memory types, candidate and reviewed memory, consolidation, two clocks, conflicts, poisoning, forgetting, and deletion.
Memory by function
Working memory holds short-lived task detail.
Episodic memory records an event or attempt in context.
Semantic memory retains generalized facts or associations.
Procedural memory retains a strategy or method.
Prospective memory records an intention to revisit something later.
These labels are useful design functions, not claims that software memory duplicates human cognition. One item may move through layers: a failed retrieval is an episode; repeated reviewed failures may justify a procedural warning.
Candidate before reviewed
Model-generated memory should enter as a candidate with origin, time, scope, and supporting evidence. Promotion needs policy or review. Otherwise a hallucination can become more persuasive merely because the same system recalls it later. Separate “frequently retrieved” from “authoritative.”
Consolidation and progressive memory
Long histories exceed context budgets. Consolidation compresses episodes into scenes, summaries, facts, or procedures. Every compression can omit exceptions and change meaning. Preserve lineage to the inputs, retain conflicts, and make the derived item replaceable. Hierarchical retrieval can first select a coarse scene, then reopen the underlying event.
Two clocks
Valid time says when a fact applied in the represented world. Transaction time says when the system recorded it. “The preference was valid from June, learned in August, superseded in September” needs both clocks. Overwriting one row destroys the ability to answer what the system knew at an earlier time.
Conflict. Atlas remembers “Use APA citations” from January and “Use IEEE citations for this project” from July. A similarity-only store may return either. A governed store preserves both, applies scope and valid time, and exposes the unresolved conflict if neither policy dominates.
Poisoning, forgetting, and deletion
Memory poisoning inserts content meant to steer future behavior. Defenses include trusted ingestion paths, origin labels, content screening, review, access control, and preventing recalled text from granting authority. Forgetting can mean retrieval suppression, logical deletion, model-side unlearning, or physical erasure; these are not equivalent. Backups, write-ahead logs, derived indexes, and downstream copies complicate deletion.
Production ruleMemory may nominate what to inspect. Current evidence, policy, and authorization decide what is true and what may happen.
Should this use memory?
Does past experience materially improve a future task?
Can the live source answer more safely?
Can origin, scope, time, review state, and deletion be represented?
Can harmful memories be found, superseded, and purged through derivatives?
Will an evaluation measure benefit and correction burden?
Summary: memory is a lifecycle, not a vector database. Useful memory remains scoped, temporal, provenance-bearing, revisable, and non-authoritative by default. Key terms: episodic, semantic, procedural, prospective, consolidation, lineage, valid time, transaction time, poisoning.
Classify six retained items by memory type and review requirement.
Specify what “delete” must mean across the primary store, indexes, logs, and backups.
Learn it, test it, build it
Teach it back: Explain why recalled content remains a candidate, not truth.
Studio task
Model a preference change without overwriting history.
Evidence of completion: Show candidate, review, conflict, supersession, and deletion states.
A remembered claim can nominate evidence without becoming evidence. SourceCairn illustrates one operational architecture for keeping discovery, verification, and execution in separate trust domains.
5 minComplete
Audio not available in this edition.
What you will learn: derived discovery versus authoritative evidence, typed claims, receipts, lineage, mutation invalidation, point-in-time capsules, and the limits of operational “proof.”
The trust-plane split
A search index, embedding, summary, or graph is derived discovery. It helps find likely evidence. The authoritative source answers the claim. A verifier re-reads that source and checks a typed proposition. An executor separately decides whether the verified proposition and caller authority permit an action.
Verification does not authorize execution. The final gate still checks policy, identity, and exact consequence.
Typed claims and evidence receipts
“The deployment uses encryption” is underspecified. A typed claim names scope, subject, predicate, operator, and value. An evidence receipt can bind that claim to source identifiers, content hashes, repository or runtime state, policy version, verifier version, time, and conflicts. Revalidation detects whether the evidence state changed.
A receipt proves only what its verifier and trust model check. A hash proves content identity, not truth. A fresh repository proves local source state, not necessarily the deployed system. Runtime claims require runtime observations. Missing relevant evidence can still make a narrow receipt misleading.
SourceCairn: a transparent experimental case
Artifact status, inspected 22 August 2026. SourceCairn is a local developer-knowledge prototype in this workspace. Its documentation and tests implement a default-off progressive memory, candidate review, bitemporal records, exact lineage, scope checks, deletion propagation, typed claim verification, and point-in-time memory-to-evidence capsules. Its stated rule is “memory may suggest; evidence decides.” No client integration is enabled by default.
A reviewed semantic memory may nominate an exactly matching typed claim. The bridge hashes its accessible lineage, re-opens nominated source lines through an independent verifier, and emits a capsule with memory_authority_granted=false, promotion_performed=false, and reusable_as_receipt=false. Source mutation, supersession, scope mismatch, or capsule tampering invalidates focused test cases.
Research finding · local prototype, not peer reviewedIts visible RepoTruthBench v2 development calibration is deliberately weak: raw current FTS found answer-bearing targets in 17/20 target-conditioned tasks; the bounded Librarian found complete evidence in 12/20; Preflight found complete target evidence in 5/20; exact trust verdict success was 0/20 because all receipts failed closed as partial. Receipt invalidation after registered source change was 20/20. No answering model, external memory baseline, held-out pack, or end-task utility study ran.
What SourceCairn does not prove
It does not establish category leadership, improved task success, formal soundness, authenticated reviewers, privacy of arbitrary text, a secure OS sandbox, or deployed/runtime truth from repository evidence. Its filters cannot prove PHI or secrets absent. The point-in-time capsule is unsigned and not a durable cryptographic proof.
Operational proof versus mathematical proof
Proof-carrying code historically joins executable code with machine-checkable evidence that it satisfies a formal safety policy. Recent agent papers use “proof” more broadly for evidence-gated lifecycle states or action certificates. This can be useful, but state the verifier, assumptions, and property. A passing test receipt is operational evidence that named tests ran on bound material; it is not a theorem that the program is correct.
Production ruleBind approval to a canonical action and current evidence, not a mutable natural-language summary. If the target, arguments, authority, or evidence changes, approval should no longer apply.
Summary: provenance supports traceability; current-source verification supports a typed claim; neither alone grants authority. SourceCairn is a useful experimental separation of these planes, with unproven utility and formal guarantees. Key terms: typed claim, evidence receipt, lineage, evidence capsule, invalidation, trust model, proof-carrying code.
Take “tests passed” and specify the minimum receipt fields needed to evaluate it.
Name three changes that should invalidate approval for a tool action.
Learn it, test it, build it
Teach it back: Explain “memory may nominate; evidence decides.”
Studio task
Design a receipt for “tests passed.”
Evidence of completion: Bind source state, command, environment, results, policy, verifier, and expiry.
Akewar and Ranjan, “SafeCommit” (2026 preprint), arXiv.
Local primary artifact inspected for the case study: SourceCairn README, authority model, memory-proof design, claim ledger, and RepoTruthBench v2 development results, all dated or checked 21–22 August 2026. They are summarized inside this self-contained edition rather than linked as external dependencies.
Chapter 15
Ontologies and knowledge graphs
A graph makes relationships explicit. An ontology makes meanings and constraints explicit. Neither rescues poor source data or removes the cost of agreeing on concepts.
4 minComplete
Audio not available in this edition.
What you will learn: taxonomies, schemas, ontologies, graph databases, knowledge graphs, temporal relations, entity resolution, symbolic reasoning, and Graph RAG.
From lists to meaning
A taxonomy arranges categories, often hierarchically. A schema defines fields and allowed structure. An ontology defines concepts, relations, and sometimes logical constraints. A graph represents nodes and edges. A graph database is storage optimized for graph operations; a knowledge graph combines entities and relations intended to represent domain knowledge, usually with provenance.
When SQL is enough
If the application asks stable questions over well-defined tables—appointments by provider, tickets by account, orders by status—relational storage and indexes are excellent. Recursive queries and join tables already represent graphs. A graph database is justified when variable-depth traversal, path finding, relationship-centric access, or frequent schema evolution materially improves the workload.
Entity resolution. “OpenAI,” “Open AI,” and a company identifier may refer to one entity; “Apple” may refer to a company or fruit. If resolution merges the wrong nodes, multi-hop reasoning spreads the error. Preserve source assertions and confidence; do not silently collapse uncertain identities.
Time and provenance
Facts such as “Alex reports to Morgan” have valid intervals. Store the assertion’s source and transaction history. A temporal graph supports “who was the manager when this approval occurred?” rather than overwriting yesterday with today.
Graph RAG and symbolic reasoning
Graph retrieval can expand from seed entities through selected relations, support multi-hop questions, or retrieve community summaries. It helps only if entity and edge quality support the needed paths. Symbolic rules can infer consequences from explicit premises, but those consequences inherit the premises’ errors and the ontology’s assumptions.
Common mistakeBuilding an enterprise ontology before identifying queries, owners, update rates, and evaluation turns disagreement into expensive infrastructure.
Ontology decision checklist
Do several systems use materially different meanings for the same terms?
Must rules or interoperability depend on shared semantics?
Who owns concept changes and version migration?
Can a simpler schema mapping solve the immediate problem?
Which measured queries improve because relations are explicit?
Summary: ontologies govern meaning; graphs govern relationship representation. Use them when semantics or traversal are first-class requirements, not as prestige layers. Key terms: taxonomy, schema, ontology, entity, relation, graph database, knowledge graph, entity resolution, temporal graph.
Model one domain question in SQL and as a graph traversal; compare maintenance.
List two entity-resolution ambiguities and the cost of a false merge.
Learn it, test it, build it
Teach it back: Explain taxonomy, schema, ontology, graph database, and knowledge graph.
Studio task
Answer one question in SQL and as a graph traversal.
Evidence of completion: Compare correctness, latency, provenance, and maintenance.
Rasmussen et al., “Zep: A Temporal Knowledge Graph Architecture for Agent Memory” (2025 preprint), arXiv.
Part V
Building production agent systems
Production turns model behavior into an accountable service: durable state, constrained authority, recovery, observability, privacy, and cost control.
Chapter 16
Architecture patterns
Patterns are reusable answers to recurring forces. They are not product requirements; each adds specific state, recovery, and evaluation obligations.
4 minComplete
Audio not available in this edition.
What you will learn: router, pipeline, supervisor, blackboard, event-driven agent, saga, approval queue, trust lanes, local versus hosted, and stateless versus stateful services.
Pattern
Core use
Hard part
Router
Select model, tool, or workflow
Misrouting and fallback
Pipeline
Known ordered transformations
Compounded errors
Supervisor
Delegate and integrate tasks
Trusting summaries
Blackboard
Share structured partial results
Conflicts and ownership
Event-driven agent
React to asynchronous changes
Duplicates and ordering
Saga
Coordinate long-lived effects
Compensation semantics
Approval queue
Gate consequential actions
Reviewer overload and drift
Trust lanes
Keep advisory output separate from authoritative state. A retrieval-verification-execution split lets broad discovery nominate evidence, a narrow verifier assess typed claims, and a separately authorized executor perform effects. Failure or compromise in one lane does not automatically confer power in another.
Local-first or hosted?
Local-first can reduce data movement and support offline control but shifts patching, capacity, model quality, and device trust to the operator. Hosted services can improve elasticity and access to frontier models but add vendor dependency, egress, residency, and availability concerns. Hybrid systems often retain sensitive state and policy locally while calling hosted inference with minimized context.
Stateless and stateful services
Stateless workers scale and retry easily because durable truth lives elsewhere. Stateful orchestrators coordinate long processes but need leases, checkpoints, versioned transitions, and recovery. Do not make a model context the state store.
Support architecture. A deterministic router sends password resets to a workflow and ambiguous product questions to retrieval. Draft replies remain advisory. Refunds enter an approval queue; the payment service owns idempotent execution. An event records outcomes for reconciliation and evaluation.
Production ruleDraw trust boundaries and state ownership before drawing model boxes. Model choice is usually easier to change than misplaced authority.
Summary: production patterns allocate selection, state, coordination, and authority. Choose them for forces you can name. Key terms: router, pipeline, supervisor, blackboard, event-driven, saga, advisory lane, authoritative lane.
Draw the trust lanes for a refund assistant.
Choose which services can be stateless and identify the durable owner of each state.
Learn it, test it, build it
Teach it back: Explain advisory and authoritative lanes with one action.
Studio task
Draw a retrieval–verification–execution architecture.
Evidence of completion: Mark trust boundaries, durable state, and recovery ownership.
Reliable agents are reliable distributed systems with an unusually variable decision component. Durable state and recovery—not optimistic prompting—carry the guarantee.
4 minComplete
Audio not available in this edition.
What you will learn: state machines, concurrency, transactions, outbox/inbox, deduplication, checkpoints, compensation, retries, observability, reconciliation, and dead-letter queues.
Make transitions explicit
Represent workflow states and allowed transitions in code or data. Use optimistic version checks or locks so two workers cannot both advance stale state. Keep business identifiers stable across retries. A transaction can atomically update local records; it cannot atomically control a remote email or payment service without a protocol.
Outbox and inbox
The transactional outbox writes the business change and an event-to-send in one local transaction. A relay later publishes the event. The receiver’s inbox records message IDs so duplicates do not repeat effects. Delivery is commonly at least once; processing must be idempotent.
Timeouts, retries, and backoff
Set deadlines at every dependency. Retry transient failures only, cap attempts, add exponential backoff and jitter, and preserve a global task budget. A retry storm can turn a partial outage into a full one. Circuit breakers and queues protect dependencies, but queued work must expire when no longer useful.
Checkpointing and compensation
Checkpoint after verified milestones and external effects. A compensation is a business action that semantically reverses or offsets an earlier action; it is not a database rollback. Refunding a payment does not erase fees, emails, or user confusion. Track compensation failure as its own state.
Unknown outcome. An appointment booking times out after the vendor may have committed it. The system records booking_outcome_unknown, queries by idempotency key, reconciles, then either confirms or safely retries. Asking the model to guess is not recovery.
Observability and reconciliation
Trace task IDs across model calls, retrieval, tool proposals, approvals, state transitions, and effects. Log structured metadata without indiscriminately retaining prompts or sensitive content. Metrics need denominators: completion, abstention, retry, compensation, stale-memory, approval rejection, latency, and cost. Reconciliation periodically compares intended and external state; dead-letter queues require ownership and replay rules, not eternal storage.
Production ruleEvery external effect needs a stable identity, observable outcome, retry policy, and reconciliation path.
Summary: reliability comes from explicit state, safe repetition, bounded failure, and evidence of outcomes. Key terms: transaction, outbox, inbox, deduplication, checkpoint, compensation, backoff, reconciliation, dead-letter queue.
Write the unknown-outcome state for one external API call.
Choose five metrics that reveal recovery burden, not just happy-path success.
Learn it, test it, build it
Teach it back: Explain why a timeout does not mean failure.
Studio task
Write a failure timeline for a payment-free synthetic booking.
Evidence of completion: Include duplicate delivery, timeout, retry, compensation, and reconciliation.
Primary sources and further reading
Gray and Reuter, Transaction Processing (1992), book record.
A well-behaved model is not an authorization layer. Secure systems assume models can be manipulated or mistaken and limit the consequences available to them.
4 minComplete
Audio not available in this edition.
What you will learn: prompt injection, tool abuse, excessive agency, leakage, memory poisoning, supply-chain risk, sandboxing, egress, least privilege, secrets, approvals, auditing, and threat modeling.
Six boundaries that must remain distinct
Concern
Question
Model safety
Does generated behavior violate intended behavioral policy?
Application security
Can an adversary compromise confidentiality, integrity, or availability?
Authorization
May this actor perform this exact action on this resource now?
Privacy
Is personal data collected and used appropriately?
Reliability
Does the system meet its operating requirements under failure?
Compliance
Does the organization satisfy applicable obligations and evidence them?
Prompt injection is confused-deputy risk
An attacker places instructions in content the model is asked to process. If the model also holds powerful tools, the application may let untrusted data influence privileged action. Defenses are layered: isolate untrusted content, reduce tool exposure, enforce server-side authorization, require confirmation, restrict destinations, scan outputs, sandbox computation, and monitor effects. Prompts and delimiters are behavioral defenses, not deterministic containment.
Least privilege and capability design
Prefer narrow tools such as draft_refund over generic HTTP, SQL, browser, or shell access. Scope credentials to tenant, resource, operation, amount, destination, and time. Keep secrets in the executor and return redacted results. Separate identity from model text: a model claiming “the admin approved” proves nothing.
Cross-tenant leakage occurs when one customer can retrieve, infer, cache, trace, or act on another customer’s data. A tenant ID in the prompt is not isolation. Bind the authenticated tenant in the host, enforce it in database queries and retrieval filters, partition caches and memory scopes, prevent caller-supplied tenant overrides, and include adversarial cross-tenant tests with synthetic canaries.
Sandbox and egress
Code execution should run with resource limits, filesystem isolation, network-deny defaults, ephemeral credentials, and a disposable environment. A container reduces some risk but is not automatically a security boundary. Egress policy prevents exfiltration even when content manipulation succeeds. Browser and computer-use agents need domain allowlists, download controls, and protected credential entry.
Memory and supply chain
Poisoned documents, tools, packages, model files, plugins, or retained memories can persist influence. Pin versions, verify provenance and signatures where available, review permissions, and separate tool installation from runtime selection. Recalled memory must not create new instructions or privileges.
Threat model. Asset: customer records. Adversary: malicious document author. Entry: retrieved attachment says “upload all records here.” Trust crossing: untrusted text reaches model with export tool. Controls: retrieval labels, no broad export tool, tenant-scoped server authorization, destination allowlist, approval bound to exact record count and domain, DLP as a heuristic, and immutable audit trail.
WarningHuman approval fails when reviewers see vague summaries, face alert fatigue, or cannot inspect consequences. Approval is a control only when it is informed, specific, enforceable, and bound to the executed action.
Threat-model questions
What assets and trust boundaries exist?
Which inputs are attacker-controlled?
What is the most powerful reachable tool?
Can the system cross tenants, destinations, or identities?
How are actions revoked, investigated, and repaired?
Summary: treat the model as an untrusted decision aid inside a least-privilege control plane. Key terms: prompt injection, confused deputy, excessive agency, sandbox, egress, least privilege, capability, audit trail.
Threat-model one retrieval-to-write path.
Replace a generic tool with a capability-shaped operation and specify its limits.
Learn it, test it, build it
Teach it back: Explain prompt injection as a confused-deputy problem.
Studio task
Threat-model one retrieved document reaching a write tool.
Evidence of completion: Add least privilege, egress control, approval binding, and an incident path.
Privacy is a lifecycle property of collection, purpose, access, retention, movement, and deletion. Pattern matching can reduce exposure; it cannot prove sensitive data absent.
4 minComplete
Audio not available in this edition.
What you will learn: minimization, retention, de-identification, residency, consent, auditability, PHI/PII limits, and human accountability in high-stakes domains.
Start with the data map
For every field, record why it is collected, lawful or policy basis, owner, users, processors, locations, retention, deletion path, and downstream derivatives. Send the model only the minimum slice required. “The provider does not train on our data” does not answer logging, abuse monitoring, subprocessors, backups, residency, or deletion.
De-identification is contextual
Removing names does not guarantee anonymity. Rare attributes, free text, timestamps, and linked datasets can re-identify people. Regex can catch common patterns but misses paraphrases and context; it also creates false positives. Describe such filtering as heuristic screening, then combine it with source controls, minimization, access restrictions, and tested deletion.
Consent and purpose
Consent must be meaningful for the specific use where required; it is not a universal permission token. Reusing support conversations to train a model or populate long-term memory can be a new purpose. Product design should support refusal, correction, export, and deletion consistent with applicable policy and law.
Regulated judgments
Medical, legal, and financial systems have different jurisdictions and obligations. This book gives no jurisdiction-specific legal conclusion. Keep source evidence, uncertainty, and human accountability visible. Separate administrative assistance from professional judgment. A clinic scheduling assistant may find slots and collect synthetic intake fields; it should not infer diagnosis, alter clinical records, or override triage policy without an authorized clinical workflow.
Production ruleWrite the retention and deletion design before enabling persistent memory. If you cannot trace derivatives and backups, you cannot make a precise erasure claim.
Auditability without surveillance
Logs should prove security and operational events while minimizing raw content. Prefer structured action metadata, hashes, reason codes, and scoped evidence pointers. Protect audit logs from alteration and unnecessary readers. Observability data is itself sensitive.
Summary: privacy is not a prompt instruction or regex. It is governed data movement across the complete lifecycle. Key terms: data minimization, purpose limitation, retention, deletion, de-identification, residency, consent, PHI, PII.
Create a data map for one model request, including logs and evaluation copies.
Rewrite “our filter removes PII” as an evidence-calibrated claim.
Learn it, test it, build it
Teach it back: Explain why regex cannot prove sensitive data absent.
Studio task
Trace one field through request, logs, evaluation, backup, and deletion.
Evidence of completion: State purpose, owner, retention, location, and residual copies.
AI cost is a workload property: model, tokens, calls, retrieval, tool latency, retries, observability, and human correction. Optimize the outcome per unit cost, not the model call in isolation.
4 minComplete
Audio not available in this edition.
What you will learn: token accounting, model routing, caching, batching, context size, retrieval latency, parallelism, loop cost, and quality-cost frontiers.
Build a cost equation
Expected task cost includes input and output tokens across every call, retrieval and reranking, tool/API charges, compute, storage, traces, retries, evaluation sampling, and expected human correction. Divide by successful tasks, not attempted tasks. A cheap call that causes expensive correction can be the costly design.
Illustrative—not a vendor price. A five-step loop averages $0.03 per call, 1.4 attempts per successful task, $0.02 retrieval/tool cost per attempt, and $0.30 expected review cost. Expected cost is roughly (5×.03+.02)×1.4+.30 = $0.538 per success, before fixed infrastructure.
Model selection and routing
Use deterministic code for parsing, validation, policy, and exact calculations. Use smaller or specialized models for classification and extraction when they meet the measured threshold. Route hard or uncertain cases upward. Routing itself needs evaluation: a weak router can deny the stronger model the cases that need it.
Context, caching, and batches
Larger context raises token cost and can reduce focus. Retrieve and compress deliberately while preserving evidence. Cache only when inputs, model/version, policy, and acceptable freshness are bound; private caches require tenant isolation. Batch offline tasks when latency permits. Parallel calls reduce wall time but can increase peak load and total tokens, and shared rate limits create correlated failures.
Measure the frontier
Plot quality and severe-failure rate against cost and latency for candidate architectures. A design is dominated if another is no worse on all relevant dimensions and better on at least one. Recheck after model or price changes; the frontier moves.
Common mistakeQuoting only per-token price hides agent-loop amplification, failed attempts, tool charges, and human review.
Summary: cost optimization begins with the successful user outcome and its failure burden. Key terms: routing, cache key, batch, tail latency, cost per success, quality-cost frontier.
Write the full expected-cost equation for one AI workflow.
Design a small-versus-large model routing evaluation with false-route costs.
Learn it, test it, build it
Teach it back: Explain cost per successful outcome, not cost per call.
Studio task
Build a cost frontier for three architectures.
Evidence of completion: Report quality, severe failures, p50/p95 latency, and total cost per success.
Patterson et al., “Carbon Emissions and Large Neural Network Training” (2021), arXiv.
Part VI
Evaluation and research literacy
Evaluation is the bridge between a compelling example and a defensible operating claim.
Chapter 21
How to evaluate an AI system
An evaluation is a measurement argument: tasks represent use, metrics represent consequences, graders represent requirements, and uncertainty limits what the result can support.
4 minComplete
Audio not available in this edition.
What you will learn: offline and online evaluation, golden sets, rubrics, model judges, human review, pass@k, recall@k, abstention, safety gates, statistical uncertainty, adversarial tests, and reproducibility.
Start with an observable outcome
“Helpful” is not yet a metric. “The customer’s issue is correctly classified, the cited policy supports the resolution, no unauthorized write occurs, and the case reaches an allowed terminal state within two minutes” is testable. Decompose end-to-end success into stages so failures can be located without letting a strong average hide a safety breach.
Offline, shadow, and online
Offline evaluation uses frozen tasks and is reproducible. Shadow evaluation observes real traffic without letting the candidate act. Online evaluation measures live outcomes, but introduces risk and confounding. Move through these stages with explicit gates; do not A/B test safety-critical failures as if they were button colors.
Golden and adversarial sets
A golden set contains reviewed inputs, expected outcomes, allowed variants, evidence, and failure labels. Separate development from held-out or sealed tests. Include common cases, boundaries, rare high-cost cases, contradictory inputs, missing evidence, tool failures, injection attempts, and distribution slices. Version both tasks and graders.
Metrics that answer different questions
Task success: did the end state satisfy requirements?
Pass@k: did at least one of k attempts pass? Useful for search-like workflows, but not a reliability claim for one run.
Pass^k: did all k runs pass? Useful for repeated reliability.
Recall@k: did the top k retrieved candidates contain needed evidence?
Calibration: do probabilities match observed frequencies?
Abstention: does the system stop when evidence is insufficient?
Hard gates: count severe safety or authorization failures individually.
Interactive lab: the same predictions, four stories
Enter confusion-matrix counts. Accuracy, precision, recall, and false-positive rate answer different product questions.
Default example: accuracy 95.0%, precision 15.4%, recall 90.0%, and false-positive rate 5.0%. Accuracy hides the alert burden.
Model judges and humans
Model judges scale subjective grading but may prefer verbosity, share model biases, miss subtle unsupported claims, or change with version. Validate a judge against blinded human labels, report agreement and disagreement slices, and use deterministic checks whenever possible. Human review also needs a rubric, calibration examples, multiple raters for subjective tasks, and uncertainty.
Confidence interval intuition. A system succeeds on 18 of 20 tasks: 90%. The small denominator leaves wide uncertainty; one more failure changes the score five points. Report the count and an interval, not “90% reliable.” Repeated runs on the same 20 tasks measure variance, not broader task coverage.
Reproducibility binding
Save dataset version, split, task IDs, model and provider version, prompts, context construction, tool schemas and implementations, temperatures, seeds where supported, budgets, environment, graders, raw outputs, and analysis code. Report failed infrastructure separately from model failure and together as user-visible failure.
Production ruleA dashboard metric is meaningful only if its denominator, task population, version, and failure definition are recoverable.
Summary: evaluate the full system and its stages on representative held-out tasks, with severe failures as gates and uncertainty visible. Key terms: golden set, held-out, sealed set, pass@k, pass^k, model judge, rubric, abstention, adversarial test.
Write one end-to-end success predicate and three stage metrics.
Design a 50-task golden set with at least five adversarial categories.
Learn it, test it, build it
Teach it back: Explain why an evaluation is a measurement argument.
Studio task
Freeze a 30-task golden set before revising a prompt.
Evidence of completion: Version tasks, graders, model, tools, budget, and raw outputs.
Primary sources and further reading
Liang et al., “Holistic Evaluation of Language Models” (2022), arXiv.
Zheng et al., “Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena” (2023), arXiv.
Guo et al., “On Calibration of Modern Neural Networks” (2017), PMLR.
Chapter 22
Evaluating agents and memory
Final-answer accuracy can hide whether failure began in stored memory, retrieval, state resolution, planning, tool execution, or the environment. Evaluate each layer and the end state.
4 minComplete
Audio not available in this edition.
What you will learn: long-horizon tasks, repeated-run reliability, state mutation, staleness, contradiction, poisoning, forgetting, receipt invalidation, controlled comparisons, and sealed benchmarks.
An agent evaluation matrix
Layer
Question
Example metric
Memory bank
Was the right item stored with correct scope/time?
write precision, conflict retention
Retrieval
Was needed evidence nominated?
recall@k, stale retrieval rate
Resolution
Did current beat superseded state?
current-state accuracy
Planning
Were prerequisites and budgets respected?
valid next-action rate
Execution
Did tools reach the required end state?
deterministic state assertions
Governance
Were writes authorized and receipts invalidated?
unsafe commit count, invalidation recall
Human burden
How much correction was required?
minutes and edits per success
Memory tests need time and mutation
Static question answering measures recall, not memory maintenance. Add updates, reversals, conflicting sources, scope changes, restart persistence, deletion, and delayed queries. Test what was true at time T and what is current now. Insert a canary memory, delete its privacy root, then search primary tables, indexes, caches, logs, and supported backups according to the claimed deletion contract.
Poisoning and safe action
Adversarially insert instructions disguised as successful experience, manufacture corroborating summaries, and test whether authority is laundered through trusted tools. The most important outcome is downstream consequence: did poisoned recall change a privileged action? Reauthorization at execution should block it even if retrieval fails.
Same-model comparisons
Compare no memory, full history, simple retrieval, and the proposed memory under the same answering model, prompts, tools, tasks, and budget. Also report native-default configurations separately. Run multiple trials. For multi-agent systems, include equal-compute and equal-latency analyses where feasible.
What benchmarks actually cover
LoCoMo evaluates long synthetic conversations. LongMemEval separates extraction, multi-session reasoning, temporal reasoning, updates, and abstention. LongMemEval-V2 extends toward multimodal agent trajectories but is a 2026 preprint. STATE-Bench evaluates synthetic enterprise tool workflows and final state; its Agent Learning track tests held-out use of prior trajectories. SWE-bench uses real repository issues and tests; WebArena exercises functional websites; GAIA tests tool-assisted research. These results are complementary, not interchangeable.
WarningA benchmark number without dataset revision, model, prompt, judge, tools, budget, run count, cost, and date is not a comparable result.
Receipts and freshness
Create a receipt, mutate each bound source or policy field, and verify invalidation. Test unbound relevant changes to expose blind spots. A system that invalidates everything is safe but may be useless; measure verified utility, false acceptance, false rejection, latency, and evidence-collection burden together.
Summary: agent-memory evaluation must test layers, time, mutation, consequence, and repeatability. Key terms: stateful benchmark, ghost memory, sealed set, same-model comparison, receipt invalidation, correction burden.
Create a four-session preference reversal test with valid and transaction time.
Design an ablation that distinguishes retrieval gain from answer-model gain.
Learn it, test it, build it
Teach it back: Explain why final-answer accuracy cannot locate a memory failure.
Studio task
Create a four-session state-change benchmark.
Evidence of completion: Score bank, retrieval, resolution, action, and correction burden separately.
Primary sources and further reading
Maharana et al., “LoCoMo” (ACL 2024), ACL Anthology.
Read a paper as an argument with evidence, not as a collection of confident sentences. The key question is always: what conclusion does this experiment actually identify?
4 minComplete
Audio not available in this edition.
What you will learn: claim decomposition, methods, fair baselines, contamination, ablation, significance, reproducibility, preprints, demos, and a dramatic-claim checklist.
The three-pass read
Claim pass: extract the problem, claimed gap, method, results, and limitations. Rewrite each headline claim in testable form.
Method pass: inspect tasks, data construction, splits, baselines, model/tool budgets, graders, and exclusions.
Evidence pass: trace every conclusion to a table, figure, theorem, artifact, or cited source.
Mechanism versus utility
A system may implement exact lineage without improving answer quality. A memory benchmark gain may come from a stronger answer model. A safety filter may block attacks while blocking most useful work. Separate implemented mechanism, measured component behavior, end-task utility, and production guarantee.
Baselines and parity
Ask whether baselines received the same model, prompt effort, tools, context, time, and compute. Report closed-parity comparisons separately from native-default systems. A weak baseline can make any architecture look necessary. Ablations remove one component at a time to estimate which mechanism caused the change.
Contamination and judges
Public benchmarks may appear in training data, tutorials, or prompt libraries. Real repository tasks may have patches online. Look for date filtering, sealed tasks, contamination analysis, and artifact controls. If a model judges outputs, inspect judge validation, position or verbosity bias, and whether the judge sees the reference and evidence.
Statistics and missing denominators
Check sample size, repeated runs, uncertainty intervals, multiple comparisons, stopping rules, and exclusions. Statistical significance does not imply practical importance. A 1% average gain may hide catastrophic regressions on one subgroup; a 20% relative improvement may be two percentage points absolute.
Dramatic-claim checklistWho built and funded the system? Is the source peer reviewed or a preprint? Was the comparison independently reproduced? Are tasks held out? Are budgets equal? Are negative cases shown? Does the conclusion exceed the measured setting?
Demos are existence proofs
A demo shows that one selected run can happen. It does not estimate frequency, tail risk, robustness, cost, or maintenance. Treat it as a hypothesis generator. Ask for the task distribution and all attempts.
Summary: evaluate the identification strategy, not the adjectives. Key terms: baseline, ablation, contamination, statistical significance, reproducibility, preprint, artifact.
Take an abstract and label every sentence as measured, inferred, hypothesized, or background.
Design one ablation that could falsify a claimed mechanism.
Learn it, test it, build it
Teach it back: Turn one headline claim into a falsifiable statement.
Studio task
Audit one recent paper’s abstract against its tables.
Evidence of completion: Label implemented, measured, inferred, hypothesized, and vendor-reported claims.
Primary sources and further reading
Dodge et al., “Documenting Large Webtext Corpora” (2021), arXiv.
Mitchell et al., “Model Cards for Model Reporting” (2019), ACM.
Begin with a user outcome and an authoritative source. Earn every additional layer through evidence.
Chapter 24
Designing your first AI product
The first architecture is a falsifiable hypothesis about the smallest system that can create the outcome safely.
4 minComplete
Audio not available in this edition.
What you will learn: a twelve-step path from user problem to evaluation, with explicit gates before retrieval, tools, autonomy, memory, and multiple agents.
Define the user outcome. Describe the changed state, not “use AI.”
Identify authoritative data. Name owners, freshness, access, and conflicts.
Decide acceptable failure modes. Include rare severe outcomes and abstention.
Start with deterministic code. Establish a baseline and preserve invariants.
Add model judgment only where needed. Bound the ambiguous transformation.
Add retrieval for current knowledge. Evaluate recall, authority, and citation fidelity.
Add tools for action. Expose narrow capabilities with server-side authorization.
Add workflow state before autonomy. Make transitions, recovery, and ownership explicit.
Add memory only if repeated experience helps. Govern write, review, time, conflict, and deletion.
Add subagents after measuring a bottleneck. Require separability and merge criteria.
Add human approval where consequences justify it. Bind approval to exact action.
Build evaluation before scaling. Freeze held-out tasks and ship behind observability and rollback.
From requirement to contract
Northstar outcome. “Resolve routine return requests.” Authoritative sources: order service and policy registry. Hard failures: refund without ownership, wrong amount, unsupported policy claim. Baseline: deterministic eligibility workflow. Model role: classify free-text reason and draft explanation. Retrieval: current policy by region. Tool: create refund proposal, not execute refund. Human approval above a threshold. Success: correct terminal state, evidence-linked explanation, no unauthorized effect, cost and latency within budget.
Build a thin vertical slice
Use one real end-to-end path with synthetic or safely governed data. Include authentication, source query, one model decision, one failure, one approval, and observability. A broad mock hides integration risk. A thin slice reveals where state and authority actually live.
Release gates
Golden set meets task and subgroup thresholds.
Safety hard gates have zero tolerated critical failures in the defined test.
Unknown tool outcomes reconcile.
Data map, retention, deletion, and vendor terms are reviewed.
Model/provider change has a regression process.
Operators can disable writes and fall back safely.
Decision ruleIf a new layer does not improve a named metric enough to justify its cost and failure modes, remove it.
Summary: product design is progressive delegation under measurement. Key terms: user outcome, authoritative data, failure budget, baseline, vertical slice, release gate, fallback.
Write a one-page outcome-authority-failure contract for a product idea.
Identify the first layer you can remove while preserving most value.
Learn it, test it, build it
Teach it back: Explain progressive delegation in twelve steps.
Studio task
Write an outcome–authority–failure contract.
Evidence of completion: Include a deterministic baseline and the evidence needed to add each layer.
Primary sources and further reading
Sculley et al., “Hidden Technical Debt in Machine Learning Systems” (2015), NeurIPS.
Amershi et al., “Software Engineering for Machine Learning” (2019), IEEE.
Chapter 25
Reference architectures
Reference architectures are starting hypotheses. Copy the reasoning and controls, not the boxes.
4 minComplete
Audio not available in this edition.
What you will learn: components, data flow, storage, trust boundaries, evaluation, deterministic responsibilities, and autonomy limits for seven systems.
1. Document question-answering
Flow: identity → access-filtered hybrid retrieval → rerank → answer with claim-level citations → citation validator. Storage: versioned documents, derived index, evaluation set. Deterministic: access control, source/version display, citation existence. Do not automate: treating retrieved text as policy authority. Evaluate: recall@k, authority/freshness, citation entailment, abstention, leakage.
2. Coding agent
Flow: task → isolated checkout → plan → bounded search/edit/test loop → diff review → evidence-gated completion. Trust boundary: repository content is untrusted; sandbox has network-deny default and scoped credentials. Deterministic: file policy, command allowlist, test capture, source binding. Do not automate: production deploy or secret access by default. Evaluate: held-out issues, tests, patch review, scope compliance, repeated runs, cost.
3. Customer-support workflow
Flow: classify → query CRM/order state → retrieve current policy → draft → resolve routine read-only case or queue exact write for approval. Storage: ticket workflow, source records, audit events; preferences in scoped memory only. Failure modes: wrong identity, stale policy, duplicated refund, invented resolution. Evaluate: correct terminal state, escalation quality, correction burden, customer outcome.
4. Research agent
Flow: questions → source plan → parallel search lanes → primary-source inspection → claim ledger → synthesis → citation audit. Deterministic: URL/identifier checks, claim-source mapping, word limits, duplicate detection. Do not automate: declaring consensus from search rank or using citations not inspected. Evaluate: source coverage, claim support, contradiction preservation, expert review, time and cost.
5. Voice agent
Flow: audio stream → speech recognition → turn/state manager → bounded model/tool step → speech synthesis, with interrupt handling. Trust boundary: voice does not prove identity. Storage: minimum transcript or structured outcome according to consent and retention. Do not automate: high-consequence confirmation based on ambiguous speech. Evaluate: task success, interruption recovery, end-to-end latency, transcription slices, accidental activation, handoff.
6. Regulated scheduling/intake assistant
Synthetic-only example. Identity gate → read appointment inventory live → collect allowed fields → validate form schema → screen deterministic administrative rules → hold slot → explicit confirmation → write through idempotent API → audit. Clinical symptoms route to an authorized human workflow; the assistant does not diagnose. Evaluate: identity failures, booking correctness, consent, accessibility, handoff, deletion, and zero cross-record leakage.
7. Long-running personal assistant
Flow: event inbox → user policy → planner → narrow tools → approval queue → checkpoint → outcome verification. Memory: candidate preferences, reviewed procedures, expiring intentions, source-linked history. Do not automate: spending, publishing, account/security changes, or sensitive communication without consequence-specific policy. Evaluate: longitudinal usefulness, stale preference rate, safe refusal, notification burden, revocation, correction, and surveillance cost.
Cross-architecture ruleKeep model output advisory until deterministic code validates identity, authority, state version, schema, and consequence.
Summary: the same motifs recur: authoritative live data, narrow model judgment, explicit workflow state, least-privilege tools, evidence, recovery, and evaluation. Key terms: trust boundary, vertical architecture, end state, citation validator, approval queue.
Choose one architecture and remove all model components; identify the remaining baseline.
Add a threat boundary and a recovery path to each arrow that crosses a service.
Learn it, test it, build it
Teach it back: Explain the common skeleton across all seven reference architectures.
Studio task
Redraw one reference architecture for your domain.
Evidence of completion: Add data flow, trust boundaries, storage, evaluation, and non-autonomous actions.
Frameworks change faster than architecture principles. This dated map organizes categories and evaluation questions; it does not recommend a universal winner.
4 minCurrent to 22 August 2026Complete
Audio not available in this edition.
What you will learn: what major platform categories solve, when they are justified, where lock-in appears, and what to test before adoption.
Fast-changing chapterProduct names, interfaces, limits, and pricing can change after the research cutoff. Follow the linked official documentation and rerun your evaluation; no feature list here is a procurement warranty.
Category
Examples—not endorsements
Justified when
Lock-in / evaluation
Model APIs + structured tools
OpenAI Responses/Agents, Anthropic tool use, Google Gemini
Hosted inference and provider-native tools simplify delivery
Prompt/tool schema portability, data terms, version pinning, eval parity
Agent SDKs
OpenAI Agents SDK, Google ADK, Microsoft Agent Framework, PydanticAI, Letta
Sessions, tools, handoffs, traces, or memory abstractions save measured work
Runtime semantics, state ownership, export, provider coupling
Graph/workflow orchestration
LangGraph, Temporal, durable workflow engines
Long-running state, pause/resume, recovery, or explicit transitions matter
Standard discovery/transport reduces bespoke integration
Protocol compatibility does not confer trust, permissions, or semantic parity
How to evaluate a framework
Can durable state, prompts, tools, traces, and data be exported?
Are retries, cancellations, idempotency, and replay semantics explicit?
Can authorization be enforced outside model decisions?
How are tenant isolation, secrets, and retention handled?
Can one component be replaced without rewriting the product?
Does the framework beat a small internal workflow on held-out tasks and total cost?
MCP and interoperability
MCP standardizes how hosts discover and invoke server-provided tools, resources, and prompts through a client-server protocol. It reduces adapter work. It does not certify a server, make tool output trustworthy, or replace host authorization. Treat installation and connection as supply-chain decisions; review permissions and constrain server reach.
Workflow engines and model-native orchestration
A durable workflow engine is valuable when replay, timers, signals, and recovery dominate. An agent graph library is convenient when model-aware branching and state views dominate. They can be combined: durable orchestration owns lifecycle; model components run as bounded activities. Avoid allowing nondeterministic inference inside code that must replay deterministically.
Procurement ruleBuy or adopt a framework for a measured operational capability—not to outsource architecture judgment.
Summary: choose categories by problem and exit cost. Protocols create compatibility, not trust. Key terms: SDK, orchestrator, vector store, observability, local inference, realtime, computer use, MCP, A2A, lock-in.
Score two frameworks on export, state, recovery, authorization, evaluation, and total cost.
Identify which component should remain portable if the model provider changes.
Learn it, test it, build it
Teach it back: Explain why protocol compatibility is not trust.
Studio task
Score two frameworks without using feature-count marketing.
Evidence of completion: Compare state, durability, exit, security, evaluation, and cost.
The frontier is not a list of larger models. It is the set of unresolved questions between impressive capability and dependable, governable participation in a changing world.
10 minComplete
Audio not available in this edition.
What you will learn: the central open questions in continual learning, memory, world models, identity, verification, authorization, coordination, privacy, evaluation, interpretation, alignment, governance, economics, and society.
Intelligence is not the same as accumulated skill
A system can display extraordinary skill because it received vast data, compute, demonstrations, tools, and engineered scaffolding. That achievement matters, but it does not isolate the system’s ability to acquire a genuinely new skill efficiently. Chollet’s proposed measure emphasizes skill-acquisition efficiency across a scope of tasks, relative to priors and experience. Other frameworks emphasize achieved performance across breadth. These are competing lenses, not a settled unit called an “intelligence point.”
This difference matters for forecasting. More memorized domains, better search, and larger inference budgets can produce broader useful performance without proving human-like generalization. Conversely, a system that learns unfamiliar tasks from little evidence might appear less polished on familiar benchmarks while exhibiting an important form of intelligence. A serious evaluation reports what experience was available, not only the final score.
AGI is a research target, not a binary product badge
Artificial general intelligence has no universally accepted test. The “Levels of AGI” position paper offers a useful matrix: performance depth ranges from emerging to superhuman; generality distinguishes narrow from broad competence; autonomy is treated separately. This prevents three common errors:
superhuman narrow performance does not imply broad general intelligence;
broad competence does not imply high autonomy; and
high autonomy does not imply high competence.
Any declaration that “AGI has arrived” must therefore state a definition, task scope, human comparison population, tool and data access, reliability requirement, and date. Without those fields, disagreement may be about vocabulary rather than evidence.
Superintelligence: a scenario class, not a date
Artificial superintelligence usually denotes broadly superhuman cognitive capability, not isolated excellence. The term bundles unresolved questions: breadth across which domains; performance against which humans; ability to learn new tasks; capacity for research or self-improvement; access to tools, capital, laboratories, robots, or institutions; and degree of autonomy. A model can be exceptionally capable while a constrained system around it remains unable to create large external effects. A weaker model connected to powerful institutions can have enormous effects.
No inspected source supplies an accepted ASI test or reliable arrival date. Forecasts should be scenarios with assumptions rather than countdown clocks. Builders can still prepare by measuring dangerous capabilities, strengthening model-weight and infrastructure security, binding actions to authority, running independent evaluations, and defining governance before thresholds are crossed. Frontier safety frameworks published by laboratories are first-party governance commitments; they describe those organizations’ intended processes and are not independent proof that the controls work.
Forecast disciplineSeparate “possible,” “plausible under stated assumptions,” “demonstrated in a controlled setting,” and “deployed reliably.” Never convert a capability trend into a precise timeline without a model of bottlenecks and uncertainty.
Four futures worth designing for now
Future
Opportunity
Failure to solve first
Personal intelligence
A lifelong teacher, planner, advocate, and creative partner controlled by one person
The most important artifact in a personal system may not be its model; it may be its constitution. That constitution should define who the system serves, which values are user-chosen versus legally or platform constrained, which memories may cross contexts, which actions require confirmation, how conflicts are surfaced, and how the relationship ends.
A practical design separates at least five layers:
Private source layer: user-controlled documents, calendar, communication, health or financial records under explicit permissions.
Identity and policy layer: authenticated user, roles, jurisdictions, consent, and action limits.
Personal memory layer: candidate preferences, reviewed facts, expiring intentions, past outcomes, and correction history.
Reasoning and simulation layer: models compare options, identify conflicts, and explain uncertainty without owning truth.
Action layer: narrow capabilities, consequence-specific approval, receipts, and reconciliation.
The system should allow compartments: work preferences need not enter health conversations; a surprise gift should not become a permanent inferred financial preference. The user needs a “why did you remember this?” path, a correction path, and meaningful deletion. Portability must preserve provenance and scope rather than exporting one opaque personality blob.
Scientific agents: output is not discovery
AI can already assist literature search, code, theorem proving, simulation, experimental planning, and data analysis. Integrated “AI scientist” systems attempt longer portions of the research cycle. The durable evaluation standard remains demanding: a hypothesis must be novel relative to inspected literature, a method must be valid, an experiment must be ethically and physically admissible, results must reproduce, and conclusions must match evidence. An automated reviewer sharing the generator’s blind spots is not independent replication.
A 2026 Nature paper reports an end-to-end AI-research pipeline and an experiment involving real peer review. That is important artifact evidence for a particular pipeline; it does not establish autonomous science in general. The safer near-term architecture makes models high-throughput proposers and analysts while humans and deterministic systems control experimental authority, biosafety, data governance, and claims.
Embodied systems and world models
A world model represents how an environment changes and how actions affect it. In a robot or autonomous laboratory, fluent text is insufficient: the system must track objects, dynamics, uncertainty, other agents, and delayed consequences. ICML 2025 work formally argues that flexible goal-directed general agents require increasingly accurate world models under its assumptions. This does not imply one particular neural architecture is sufficient, but it clarifies why action without predictive environmental structure becomes brittle.
Embodiment adds failure energy. A hallucinated sentence may mislead; a hallucinated motor command may collide. Systems need layered control: learned perception and planning, deterministic safety envelopes, low-level feedback control, emergency stops, simulation, staged deployment, and incident reconstruction.
Capability can advance while reliability remains jagged
The International AI Safety Report 2026 synthesizes evidence from more than 100 experts and describes rapid but uneven capability growth. Standardized reasoning, coding, science, and multimodal performance can improve while long workflows, physical reasoning, error recovery, and robust control remain weak. This is why the central architecture decision survives future model progress: stronger models may move the boundary of what can be delegated, but evidence, authority, state, and consequence still need explicit owners.
Learning and memory over time
Continual learning must acquire useful behavior without catastrophic forgetting, contamination, or unreviewed policy change. Long-term memory must resolve evolving state, preserve provenance, resist poisoning, honor deletion, and demonstrate utility beyond longer context. No evidence reviewed for this edition establishes an end-to-end memory that is simultaneously truthful, conflict-correct, poison-resistant, safely actionable, and physically erasable.
World models and identity
Agents need representations of how actions change environments, including uncertainty and other actors. Persistent identity raises harder questions: which goals, permissions, memories, and liabilities remain across model upgrades, devices, and organizations? A stable name is not a stable policy or person.
Verifiable reasoning and formal guarantees
Tests, citations, receipts, formal proofs, cryptographic attestations, and calibrated uncertainty certify different properties. Research must make more reasoning produce externally checkable artifacts while acknowledging incomplete specifications. Formal guarantees are powerful only for the property and model actually formalized.
Secure authorization and coordination
Natural-language intent is a weak basis for delegating power. Open problems include consequence-aware capabilities, compositional delegation across agents, revocation, approval binding, and safe recovery after partial effects. Multi-agent systems add incentives, communication manipulation, shared-memory integrity, and accountability.
Personalization without surveillance
Useful assistants benefit from context; pervasive retention threatens autonomy and privacy. Promising directions include local processing, minimized and inspectable memory, purpose-specific access, expiration, user-controlled correction, privacy-preserving learning, and evaluations that count surveillance and deletion burden as costs.
Evaluation in changing environments
Static benchmarks decay as models train on them and environments change. Future evaluation needs sealed rolling tasks, executable end states, repeated runs, adversarial mutation, cross-domain slices, cost and carbon, human correction, and post-deployment incident evidence. Governance must respond to uncertainty without turning every decision into paperwork or every risk into an average.
Interpretability, alignment, and social effects
Mechanistic interpretability seeks causal understanding of learned representations and computations; explanations generated by the same model are not equivalent. Alignment spans training objectives, product incentives, institutional controls, and contested human values. Economic effects depend on task redesign, labor power, access, concentration, environmental cost, and distribution—not capability alone.
Open questionHow can a system remain helpful across years while allowing a person to see, contest, compartmentalize, and truly remove what it retained—and still prove that consequential actions used current evidence and valid authority?
A research discipline for builders
Date fast-changing claims. Preserve negative results. Test the simplest rival. Separate proposal from permission and memory from evidence. Publish task definitions and failure cases. Prefer mechanisms that fail closed without making useful work impossible. The frontier will move; these habits remain.
Summary: advanced capability expands both opportunity and unresolved systems questions. Honest boundaries are a feature of mature engineering. Key terms: continual learning, catastrophic forgetting, world model, attestation, interpretability, alignment, governance.
Choose one frontier claim and specify the evidence that would move it from hypothesis to established result.
Design an evaluation where privacy and correction burden appear on the same frontier as quality.
Learn it, test it, build it
Teach it back: Explain AGI, ASI, personal intelligence, and autonomy as separate concepts.
Studio task
Write three 2030 scenarios without predicting a date.
Evidence of completion: For each, state assumptions, early indicators, controls needed now, and what would falsify it.
Primary sources and further reading
Chollet, “On the Measure of Intelligence” (2019), arXiv.
Is the outcome observable and the environment genuinely changes the useful next step?
Can allowed tools, data, iterations, cost, and time be bounded?
Can a workflow or deterministic program meet the requirement?
Can every consequential action be authorized and reconciled outside the model?
Is there a held-out evaluation and safe fallback?
Should this use memory?
Does retained experience improve repeated tasks beyond live queries or bounded context?
Are write, review, origin, scope, valid time, transaction time, conflict, and expiration explicit?
Can recalled content remain advisory?
Can a person inspect, correct, supersede, and delete the item and its derivatives?
Will the benefit be measured against no-memory and simple-retrieval baselines?
Do we need an ontology or graph?
Do shared semantics or variable-depth relationships answer named requirements?
Are SQL and schema mappings demonstrably insufficient?
Are entity resolution, provenance, temporal edges, and ontology versions owned?
Does a query benchmark justify ingestion and curation cost?
Evaluation checklist
Outcome and severe failures defined; denominators shown.
Development, held-out, and sealed tasks separated.
Representative slices, adversarial cases, updates, and abstention included.
Models, prompts, tools, data versions, budgets, graders, and raw outputs bound.
Repeated-run reliability, latency, cost, human correction, and uncertainty reported.
Model judges validated against humans; deterministic graders preferred.
Security checklist
Threat model identifies assets, adversaries, inputs, tools, trust boundaries, and externalities.
Untrusted content cannot grant privileges; authorization lives in deterministic code.
Tools are narrow, tenant-scoped, idempotent, auditable, and revocable.
Secrets remain in execution services; sandbox and egress are deny-by-default where appropriate.
Approvals bind exact action, destination, evidence, and expiry.
Incident response, rollback, reconciliation, and deletion are tested.
Paper-reading checklist
Rewrite the claim; classify it as implemented, measured, inferred, hypothesized, or externally reported.
Inspect task construction, splits, leakage, baselines, parity, judge, and exclusions.
Check absolute and relative effects, uncertainty, repeated runs, and severe regressions.
Read limitations and artifact; distinguish preprint, reviewed paper, official docs, and vendor report.
The complete project ladder
Projects turn recognition into transferable skill. Use synthetic, public, or deliberately created data. Every project produces an inspectable artifact and an evaluation; a working demo without evidence is incomplete.
Project 1 · Beginner
Base-rate laboratory
Build a spreadsheet or small webpage that converts prevalence, sensitivity, and false-positive rate into a 10,000-case confusion matrix. Add two domains with different error costs.
Evidence: correct arithmetic, plain-language explanation, threshold choice, and one example where accuracy misleads.
Project 2 · Beginner
Model versus rules bake-off
Choose a classification task with 50 synthetic examples. Implement a rules baseline and a model-assisted approach. Freeze 15 held-out cases before tuning.
Evidence: task definition, confusion matrices, failure slices, latency/cost, and a conclusion that may favor the rules.
Project 3 · Builder
RAG truth probe
Create a ten-document corpus containing one superseded policy, one contradiction, rare identifiers, and one malicious instruction. Compare lexical, dense if available, and hybrid retrieval.
Evidence: recall@k, authority and freshness labels, citation-support audit, injection outcome, and abstention cases.
Project 4 · Builder
A tool that is safe to retry
Design a synthetic appointment-hold or refund-proposal API. Specify schema, authorization, idempotency key, timeout, unknown outcome, reconciliation, and audit fields.
Evidence: duplicate and stale-state tests, rejected unauthorized calls, and a sequence diagram for partial failure.
Project 5 · Engineer
Workflow before agent
Implement a state machine for a support or scheduling flow. Put a model inside only one ambiguous step. Then compare it with an agent allowed to choose the next step.
Build a tiny bitemporal memory store with candidate/reviewed status, origin, scope, valid time, transaction time, supersession, and deletion. Insert preference reversals and poisoned experience.
Threat-model a retrieval-to-write agent, then run synthetic incidents: indirect prompt injection, cross-tenant query, stolen tool result, response-lost-after-commit, and stale approval.
Evidence: attack traces, deterministic control results, residual risk, recovery time, and one control that failed usefully closed.
Project 8 · Capstone
Constitutional personal intelligence
Design—but do not deploy—a personal research and planning agent. Define its user constitution, data compartments, memory lifecycle, source-of-truth map, narrow tools, approvals, portability, deletion, and evaluation.
Evidence: architecture and trust-boundary diagrams, 100-task sealed plan, privacy threat model, longitudinal correction metric, cost frontier, incident playbook, and a list of actions that remain human-only.
Capstone review board
Review the capstone six times, changing the reviewer’s lens:
Beginner: can every term and arrow be explained without jargon?
User: can I see, correct, compartmentalize, export, and delete what it knows about me?
Engineer: can every state transition recover after failure?
Security reviewer: can untrusted text influence privileged action?
Researcher: do comparisons isolate the claimed mechanism?
Founder: does this create enough outcome value to justify its cost and liability?
Portfolio standardPublish the task definition, architecture, synthetic fixtures, evaluation harness, negative results, and limitations. A polished video is optional; reproducible evidence is not.
Glossary
Agent
A system in which a model helps choose actions from observations in a loop.
Attention
A learned mechanism that mixes representations according to query-key compatibility.
Calibration
Agreement between stated probabilities and observed frequencies.
Context window
The bounded token sequence available to a model during an inference.
Embedding
A vector representation learned or constructed for useful geometric comparison.
Evidence receipt
A record binding a claim to specified evidence state, policy, verifier, and time.
Grounding
Supplying external evidence or observations to constrain an output; not automatic truth.
Idempotency
The property that repeating the same logical operation does not duplicate its effect.
Knowledge graph
Entities and relations intended to represent domain knowledge, usually with schema or provenance.
Memory
Retained, selected experience made available to later tasks under a lifecycle policy.
Model
A learned function mapping inputs to outputs or probability distributions.
Ontology
An explicit specification of domain concepts, relations, and sometimes logical constraints.
Provenance
Information about the origin and transformation history of data or claims.
Retrieval-augmented generation (RAG)
A pipeline that retrieves external context for a generative model.
Reranker
A second-stage model that scores retrieved candidates more precisely.
State
Information describing the current condition of a request, workflow, or system.
Token
A vocabulary unit processed by a language model.
Tool
A host-executed operation a model may propose through a structured interface.
Valid time
The interval in the represented world during which a fact applies.
Workflow
An explicit set of states, transitions, and responsibilities for completing a process.
General-purpose AI
A system intended to perform a broad range of tasks; breadth does not imply uniform competence, autonomy, or AGI.
Personal intelligence
This book’s design category for systems that build a governed, longitudinal working relationship with one person. It is not a standard capability tier.
Artificial general intelligence (AGI)
A proposed class of broadly capable systems. Any serious claim must state its task breadth, performance threshold, learning conditions, and autonomy.
Artificial superintelligence (ASI)
A hypothetical system exceeding human performance across a broad, consequential range of cognitive tasks. There is no accepted test or arrival date.
Embodied intelligence
Intelligence expressed through perception and action in a physical or simulated environment, where dynamics and consequences matter.
World model
An internal representation used to predict how an environment may change under actions; its adequacy is task- and distribution-dependent.
Collective intelligence
Problem-solving capacity emerging from coordinated people, models, institutions, and tools—not merely from increasing agent count.
Turing (1950); Vaswani et al. (2017); Devlin et al. (2018); Brown et al. (2020); Ouyang et al. (2022); Guo et al. (2017).
Prompting, retrieval, and tools
Wei et al. (2022); Lewis et al. (2020); Karpukhin et al. (2020); Yao et al. (2022); Schick et al. (2023); Greshake et al. (2023).
Agents and planning
Shinn et al. (2023); Madaan et al. (2023); Yao et al. (2023); Wu et al. (2023); Li et al. (2023).
Memory and knowledge
Park et al. (2023); Packer et al. (2023); Maharana et al. (2024); Wu et al. (2024, 2026); Xu et al. (2025); Rasmussen et al. (2025); Hogan et al. (2021); W3C RDF, OWL, and PROV recommendations.
Production, security, and evaluation
Garcia-Molina and Salem (1987); Sculley et al. (2015); NIST AI RMF (2023); OWASP GenAI project; AgentBench, WebArena, GAIA, SWE-bench, HELM.
Emerging evidence and memory safety—preprints at cutoff
Proof-or-Stop (2026); SafeCommit (2026); Proof-Carrying Agent Actions (2026); TMA-NM (2026); TEPA (2026); TOKI (2026); A-TMA (2026). These works were not independently reproduced for this edition.
What this edition deliberately does not claim
It does not name a universal best model, framework, agent architecture, or memory system. It does not provide jurisdiction-specific legal advice. It does not claim that prompting prevents injection, that provenance proves truth, that tests prove total correctness, or that de-identification regex proves privacy. Framework details are dated; all product decisions require a current official-doc and evaluation pass.