Engineering AI Agents: The Stanford CS329Z Field Guide
An independent, first-principles field guide aligned with Stanford CS329Z: Engineering AI Agents (Diyi Yang, Michael Ryan, John Yang). Ten deep-dive chapters with math derivations, system diagrams, and production checklists covering Compound AI Systems, Context Engineering, Agentic RAG, MCP, CodeAct, hierarchical memory, multi-agent coordination, prompt vs. weight optimization, and empirical evaluation on Terminal-Bench.
The Engineering Shift to Compound AI Systems
Classical software relied on deductive, deterministic rules. Modern LLMs usher in inductive software engineering—stochastic function approximators that cannot reliably solve long-horizon tasks in a single forward pass. Engineering autonomous agents means abandoning the "all-knowing monolithic model" and building Compound AI Systems: modular cognitive cores embedded inside memory streams, execution sandboxes, context managers, and empirical verifiers.
Chapter 1: The Agentic Stack & The Spectrum of Agency
Autonomous AI agents replace static, deductive control flows with inductive Compound AI Systems where an LLM policy iteratively observes environment state, invokes external tools, and verifies side effects. Because per-step errors compound exponentially over long horizons, production systems deliberately navigate the spectrum of agency—favoring deterministic workflows (chaining, routing, parallelization, evaluator-optimizer) when paths are known, and reserving open-ended ReAct, planning, and tree-search loops for dynamic tasks with verifiable feedback.
Chapter 2: Context Engineering & Transformer Limits
Context Engineering treats the LLM context window as scarce, stateful working memory rather than an unlimited prompt string. Because Transformer attention scales quadratically in prefill compute, KV cache memory grows linearly with sequence length and batch size, and softmax dilution degrades recall in the middle of long contexts, reliable agents decouple the ground-truth event log from the projected LLM context—enforcing append-only KV prefix stability alongside observation masking, compaction, progressive disclosure, and subagent isolation.
Chapter 3: From BM25 to Agentic RAG
Production retrieval grounds AI agents in live, verifiable knowledge that parametric weights cannot store reliably. Modern retrieval pipelines combine sparse lexical matching (Okapi BM25) with dense semantic embeddings via Reciprocal Rank Fusion (RRF) and cross-encoder reranking, then elevate retrieval from a brittle single-pass pipeline into Agentic RAG—where the agent iteratively formulates queries, inspects results, traverses filesystems with CLI tools like ripgrep or GraphRAG, and verifies evidence sufficiency.
Chapter 4: Tool Use and Model Context Protocol (MCP)
Tools bridge stateless next-token predictors with live environments, deterministic computation, and external side effects. Modern tool-use engineering evolved from self-supervised token-level training (Toolformer, ToolkenGPT) and retrieval-augmented API synthesis (Gorilla, ToolLLM) evaluated via Abstract Syntax Tree (AST) matching, into standardized runtime protocols—progressing from brittle REST prompt parsing and vendor-locked Function Calling to the Model Context Protocol (MCP), which decouples agent hosts from tool servers with isolated credentials and progressive schema discovery.
Chapter 5: Agent Control Flow — ReAct, Reflexion, CodeAct & Execution Graphs
Agent control flow governs how an LLM alternates between thinking, acting, observing, and recovering across multi-step horizons. ReAct interleaves natural-language thoughts with discrete actions; Reflexion and CRITIC add episodic or tool-grounded verification loops; CodeAct unifies action spaces into executable Python code to express loops and composition in a single turn; and ReWOO/LLMCompiler decouple planning from execution via symbolic placeholders and parallel DAGs to slash latency and token costs.
Chapter 6: Frameworks, Scaffolding, and Durable Execution — DSPy vs. LangGraph & Temporal
Agent frameworks solve fundamentally different layers of the stack. Choosing the wrong abstraction incurs the 'Harness Tax'—hidden prompt bloat, debugging opacity, and rigid scaffolding that breaks as foundation models evolve. DSPy treats LLM pipelines as declarative computational graphs whose instructions and demonstrations are automatically compiled against a metric; LangGraph models explicit cyclic state machines with checkpointers and human-in-the-loop interrupts; and Temporal provides durable event-sourced execution so long-horizon agent workflows survive crashes, timeouts, and retries without duplicating side effects.
Chapter 7: Agent Memory Architectures
Long-lived agents cannot rely on unbounded context stuffing. Production memory architectures mirror cognitive science—separating working context, episodic logs, semantic knowledge graphs, and procedural skill libraries—implemented across systems like Voyager, MemGPT, Mem0, and Zep, alongside sleep-time compute to resolve the retrieval paradox.
Chapter 8: Multi-Agent Systems & Coordination Failures
Multi-agent systems trade higher token overhead and coordination risk for context isolation, parallel exploration, and independent verification. Because empirical studies show most multi-agent failures stem from specification ambiguity, misaligned handoffs, and cascading errors rather than single-model intelligence, teams should benchmark a strong single-agent baseline before adopting hierarchical, pipeline, or debate topologies.
Chapter 9: Agent Optimization — Prompts vs. Weights
Optimizing an AI agent means solving a joint maximization problem over model weights theta and system-level parameters phi (prompts, few-shot traces, tool schemas, and control flow). Automated prompt compilers like MIPROv2, GEPA, and TextGrad unlock huge gains on frozen APIs without gradient access, while FireAct SFT and critic-free GRPO distill and reinforce multi-turn agentic policies directly into open weights.
Chapter 10: Empirical Agent Evaluation, Benchmarks & Production Playbook
Evaluating stochastic agents requires inspecting physical environment side-effects rather than grading prose. Stanford CS329Z formalizes every evaluation task as a 4-tuple <Request, Environment, Termination, Scorer>, exemplified by Terminal-Bench and Harbor—which physically isolate verification scripts from the agent container to stop reward hacking—and closes the loop with the Agent Data Funnel and a 9-point production engineering checklist.
The AI Agent Engineering Checklist
Frequently Asked Questions
How does this playbook align with Stanford CS329Z?
Every chapter maps directly to Stanford CS329Z lectures (Lectures 1–12 by Diyi Yang, Michael Ryan, John Yang, and guest speakers Alex Shaw & Ryan Marten), covering the full stack from ReAct and Context Engineering to MCP, DSPy/LangGraph, MemGPT, GRPO, and Terminal-Bench.
What is the difference between MCP, Function Calling, and CodeAct?
Function Calling binds static JSON schemas per model provider; Model Context Protocol (MCP) standardizes dynamic Host-Client-Server tool discovery and credential isolation; CodeAct replaces multi-turn JSON calls with executable Python/Bash actions for single-turn loops and state management.
Why does Stanford CS329Z emphasize Terminal-Bench and Harbor?
Autonomous agents are non-deterministic, so deductive unit tests fail. Terminal-Bench and Harbor evaluate agents inside isolated Docker containers by inspecting physical environment state side-effects and separating verifier scripts from the agent container to prevent reward hacking.