Stanford CS 329Z Lecture 9 Outlines the Selection of Agent System Optimization Methods
CS 329Z: Engineering AI Agents
Lecture 9 of Stanford's CS 329Z course presents a selection diagram for Agent system optimization: the prerequisite for optimization is having data, a system, and evaluation metrics all in place; generally, context optimization (prompts and few-shots) is done first because it is cheap, fast, and sample-efficient; when context optimization is insufficient, or when you want to distill capabilities into a small model, or when prompts grow longer and longer, then you move on to changing the weights. The lecture notes also review reflective prompt optimization methods such as OPRO, MIPROv2, TextGrad, and GEPA; weight optimization paths such as SFT, RL (PPO vs. GRPO), and on-policy distillation; and approaches that let agents self-optimize, such as the Darwin Gödel Machine, Meta-Harness, and karpathy's autoresearch. They also point out that agents are already decent optimizers, making evaluation metrics the link that most needs to be controlled.
Why read this
AI score 57
The Stanford course breaks Agent optimization into three paths—context, weights, and self-optimization—and provides the criteria for deciding when to choose which.
Topics
View original postCS 329Z: Engineering AI Agents Stanford / Fall 2026 @stanfordnlp https://t.co/ynvpE8PKFE Course positioning: the engineering discipline from "models" to "systems" Coverage: simple LLM pipelines → compound AI systems → autonomous Agents. The backgrounds of the three instructors are also highly complementary: @Diyi_Yang (Stanford NLP professor, human-computer interaction and social computing) @michaelryan207 (core contributor to DSPy, author of the automatic evaluation AutoMetrics) @jyangballin (author of SWE-agent / SWE-bench / SWE-smith, one of the most important researchers in the field of software engineering Agents) # Course main thread: three major engineering challenges Three core questions run through the entire course—decomposition, data, and evaluation. The 11 weeks of content basically unfold around these three threads and can be divided into five modules: Module 1: Building primitives (Week 2–3) · LLMs as building material: API/SDK (litellm), structured output, constrained generation, decoding strategies, test-time compute, context engineering, model selection and cost/latency trade-offs · RAG: embeddings, vector stores, chunking strategies, hybrid retrieval, cross-encoder and ColBERT late interaction · Tool calling: function calling APIs, MCP (Model Context Protocol), tool design, code sandboxes, error handling and retries Module 2: Frameworks and design patterns (Week 3–5) · Framework layer: DSPy (signature / module / optimizer), LangChain/LangGraph, LlamaIndex, with the focus on "what the framework abstracts vs. what you hand-write" · Design patterns: the taxonomy of workflow vs. agent, five composable workflow patterns, ReAct / plan-and-execute / reflection, "the scaffold itself is a design decision" · Memory architecture: short-term/long-term memory, memory as tool actions, the file system as externalized memory, cross-Agent memory (MemGPT, Mem0, Generative Agents) · Multi-Agent systems: orchestration patterns, handoff and state passing, and a very opinionated pair of contrasting readings—reading both AutoGen and "Why Do Multi-Agent LLM Systems Fail?" as well as Neubig's "Don't Sleep on Single-agent Systems" Module 3: Optimization (Week 5) · A panorama from prompts to fine-tuning: GEPA, MIPROv2, OPRO, TextGrad (prompt optimization); LoRA/QLoRA, distillation, RLHF/DPO (weight optimization); test-time scaling (inference compute) · The core issue is the decision framework: when to optimize prompts, when to optimize weights, and when to throw inference compute at it Module 4: Data and evaluation (Week 6–8)—the most substantial part · Data: three types of data—trace, demonstration, and feedback; training data vs. evaluation data; the data flywheel; synthetic data; building datasets from Agent trajectories (SWE-smith) · Evaluation fundamentals: why eval is hard; the 4-tuple framework (request / environment / stopping criteria / scorer); properties of a good benchmark; tinyBenchmarks · Evaluation infrastructure: three types of graders, prompt design for LLM-as-judge and known biases, pairwise vs. pointwise, non-deterministic metrics pass@k vs. pass^k, harness design Module 5: Safety and frontiers (Week 8–11) · Safety: privacy risks of tool access, prompt injection (including indirect injection), red teaming, sandboxing and permission models, output guardrails, human-in-the-loop · Coding Agents: end-to-end architecture comparison of SWE-agent, Claude Code, and OpenHands · Proactive Agents: from reactive to proactive, General User Models (GUM), Next Action Prediction, and the mixed-initiative question of "when should an Agent act proactively and when should it wait" · Open problems: multimodal/web/computer-use Agents, scientific Agents, long-running architectures, production observability (tracing, monitoring, cost management) # Assignment design: build with one hand, evaluate with the other HW1: Build an Agent system from scratch (10%) Given a paper library, build an Agent that can retrieve and reason to answer scientific questions. · Part A: Use only litellm to hand-write RAG + tool calling + a ReAct-style Agent loop · Part B: Rebuild the key components with DSPy and reflect on what the framework abstracts HW2: Evaluate an Agent (10%) Given a pre-built Agent, design a complete evaluation suite: code-based graders, at least one LLM-as-judge, benchmark tasks built with the 4-tuple framework, and error analysis.
View original
CS 329Z: Engineering AI Agents Stanford / Fall 2026 @stanfordnlp https://t.co/ynvpE8PKFE 课程定位:从"模型"到"系统"的工程学 覆盖:简单 LLM 流水线 → 复合 AI 系统 → 自主 Agent。三位讲师的背景也高度互补: @Diyi_Yang(斯坦福 NLP 教授,人机交互与社会计算方向) @michaelryan207(DSPy 核心贡献者,自动评估 AutoMetrics 作者) @jyangballin(SWE-agent / SWE-bench / SWE-smith 作者,软件工程 Agent 领域最重要的研究者之一) # 课程主线:三大工程挑战 贯穿全课的三个核心问题——分解(decomposition)、数据(data)、评估(evaluation)。11 周的内容基本围绕这三条线展开,可以分为五个模块: 模块 1:构建基元(Week 2–3) · LLM 作为构建材料:API/SDK(litellm)、结构化输出、约束生成、解码策略、test-time compute、上下文工程、模型选型与成本/延迟权衡 · RAG:embedding、向量库、分块策略、混合检索、cross-encoder 与 ColBERT 后期交互 · 工具调用:函数调用 API、MCP(Model Context Protocol)、工具设计、代码沙箱、错误处理与重试 模块 2:框架与设计模式(Week 3–5) · 框架层:DSPy(signature / module / optimizer)、LangChain/LangGraph、LlamaIndex,重点是"框架抽象了什么 vs. 你手写了什么" · 设计模式:workflow vs. agent 的分类学,五种可组合 workflow 模式,ReAct / plan-and-execute / reflection,"scaffold(脚手架)本身就是设计决策" · 记忆架构:短期/长期记忆、记忆作为工具动作、文件系统作为外化记忆、跨 Agent 记忆(MemGPT、Mem0、Generative Agents) · 多 Agent 系统:编排模式、handoff 与状态传递,以及一个很有态度的对照阅读——既读 AutoGen,也读《Why Do Multi-Agent LLM Systems Fail?》和 Neubig 的《Don't Sleep on Single-agent Systems》 模块 3:优化(Week 5) · 从提示词到微调的全景:GEPA、MIPROv2、OPRO、TextGrad(提示优化);LoRA/QLoRA、蒸馏、RLHF/DPO(权重优化);test-time scaling(推理算力) · 核心问题是决策框架:什么时候优化 prompt、什么时候优化 weights、什么时候堆推理算力 模块 4:数据与评估(Week 6–8)——最有分量的部分 · 数据:trace、demonstration、feedback 三类数据;训练数据 vs. 评估数据;数据飞轮;合成数据;从 Agent 轨迹构建数据集(SWE-smith) · 评估基础:为什么 eval 难;4 元组框架(request / environment / stopping criteria / scorer);好 benchmark 的性质;tinyBenchmarks · 评估基础设施:三类 grader、LLM-as-judge 的 prompt 设计与已知偏差、pairwise vs. pointwise、非确定性指标 pass@k vs. pass^k、harness 设计 模块 5:安全与前沿(Week 8–11) · 安全:工具访问的隐私风险、prompt injection(含间接注入)、红队、沙箱与权限模型、输出护栏、human-in-the-loop · Coding Agent:SWE-agent、Claude Code、OpenHands 的端到端架构对比 · 主动式 Agent:从 reactive 到 proactive,General User Models(GUM)、Next Action Prediction,以及"Agent 何时应主动、何时应等待"的 mixed-initiative 问题 · 开放问题:多模态/web/计算机使用 Agent、科学 Agent、长时运行架构、生产可观测性(tracing、monitoring、成本管理) # 作业设计:一手建、一手评 HW1:从零构建 Agent 系统(10%) 给定论文库,构建能检索并推理回答科学问题的 Agent。 · Part A:只用 litellm 手写 RAG + 工具调用 + ReAct 式 Agent 循环 · Part B:用 DSPy 重建关键组件,并反思框架抽象了什么 HW2:评估一个 Agent(10%) 给定一个预构建 Agent,设计完整评估套件:代码型 grader、至少一个 LLM-as-judge、用 4 元组框架构建 benchmark 任务、错误分析。
Body
CS 329Z: Engineering AI Agents Stanford / Fall 2026 @stanfordnlp https://t.co/Ko6UarsQff
第 9 讲:Agent 系统优化方法的选型图 优化的前提是数据、系统和评估指标三样都有。一般先做上下文优化(prompt 和 few-shots),因为便宜、快、省样本。上下文优化不够用、想把能力蒸馏到小模型、或者 prompt 越写越长时,再改权重。让 agent 自己去优化也已经可行,这时最需要把控的是评估指标本身。 https://t.co/Rn4sY872KG
什么时候值得优化 · 三根支柱缺一不可:数据(训练数据、轨迹、示范、人类反馈)、系统(模型、工作流、agent)、指标(通过率、LLM 评判、成本和延迟)。 · 优化解决的是“最后一公里”问题。模型给的是通用能力,优化是让它贴合你的具体场景。有些需求很难用 prompt 写清楚,用示例和评估反而更能把意图表达出来。 · 收益包括更可靠、适配特定领域、用更小的模型或更短的 prompt 降低成本,以及把成功和失败的经验沉淀下来。 · 开场用了一个投票例子:在 PaLM 2 上,“Take a deep breath and work on this problem step-by-step”的准确率是 80.2%,“Let's think step by step”是 71.8%。说明措辞的细微差别就会带来明显的效果差距,靠人手调很难找到最优。
上下文优化 1. 少样本示例优化 · 示例的排序会影响结果(Lu et al. 2022)。用探测集上的熵来选排序,可以接近穷举所有排序后的最优效果。 · 自举推理:STaR 用拒绝采样挖出正确的推理过程;DSPy 不需要微调,直接保留指标得分高的推理轨迹当示例,再搜索最佳组合。这种方式有时比人工写的推理或标准答案还好。
2. 反思式优化 · OPRO:把历史 prompt 和对应得分给 LLM 看,让它写出新的 prompt。“Take a deep breath”就是这样被找到的。 · MIPROv2 分三步:先自举出示例;再结合程序结构、数据特征、成功轨迹和写作技巧,生成多条候选指令;最后用贝叶斯代理模型在小批量数据上搜索“指令 + 示例”的最优组合。 · TextGrad:让 LLM 对输出提出改进意见,像梯度一样沿系统里的各个 prompt 反向传递。 · GEPA:基于反思做 prompt 进化,并保留帕累托前沿上的候选。讲义的结论是它在多个任务上优于基线,而且比 RL 省样本得多。
权重优化 · SFT:用强教师模型跑 agent 任务,把轨迹拿来训练学生模型,也可以先验证结果、只保留正确的。例如 FireAct 用 GPT-4 的轨迹微调 Llama2-13B,效果超过了直接 prompt 的 GPT-3.5。关键在于任务和环境要足够多样。 · RL:让学生模型自己跑任务,按任务是否完成给奖励,前提是结果可验证。讲义对比了 PPO 和 GRPO:PPO 要在内存中保留 4 个模型、每步训练 2 个;GRPO 只需 3 个、每步训练 1 个,优势值直接用组内奖励的 z-score 计算,DeepSeek-R1 用的就是 GRPO。 · On-policy 蒸馏:学生模型自己采样生成,教师逐 token 打分,好比“复盘自己下过的棋”。引用的 Thinking Machines 结果是,它比 RL 更高效,训出的模型也更好。
让 agent 自己做优化 · Darwin Gödel Machine:agent 修改自己的代码。选哪个版本当“父代”时,表现越好越优先,已有子代越多越靠后。消融实验显示,“自我修改”和“回到早期版本重新探索”这两点都不可或缺。 · Meta-Harness:让一个元 agent 看到全部历史经验,由它决定下一步改什么,逐步改出更好的 harness。 · autoresearch(karpathy):给 agent 一个代码仓库,它自己提想法、改代码、跑实验,指标变好就保留,变差就回退,并把结果记下来。讲义还引用了 Cerebras 关于“如何防止这类循环作弊”的文章。 · 讲义的总结:agent 已经是不错的优化器,因此评估指标成了最需要把控的环节。
选型建议
适合上下文优化的情况 · 只能通过 API 调用、无法微调的强模型。 · 需要频繁、快速地重新优化。 · 环境交互成本高,需要省样本。
适合权重优化的情况 · 上下文优化不起作用,尤其是指令遵循能力弱的小模型。 · 手上有强教师模型,想换成更便宜的模型。 · prompt 已经膨胀得太长。 · 权重优化更吃数据,但能随数千、上万条样本持续提升(OpenThoughts-Agent)。
组合使用:BetterTogether 指出,有时最好的顺序是先优化 prompt,再优化权重,最后再回头优化一次 prompt。