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.
The Compound System Optimization Objective
Once an agent’s architecture, tool interfaces, and evaluation metric are built, improving reliability reduces to an optimization problem. In a Compound AI System composed of interacting LLM modules, retrievers, and tools, performance depends on both parametric model weights and non-parametric system parameters (system instructions, few-shot demonstrations, tool descriptions, and orchestration structure).
Formally, given a task distribution , trajectory rollout generator , and verifier/reward function , agent optimization seeks:
Notice why manual prompt engineering fails at scale: when an agent pipeline has 4 modules (Planner, Retriever Query Writer, Tool Caller, Verifier), editing Module 1 shifts the input distribution seen by Modules 2–4. Hand-tuning one prompt in isolation easily causes cross-module regression. Modern agent optimization therefore splits into two complementary toolkits: automated prompt/program optimization () and trajectory fine-tuning & reinforcement learning ().
1. Optimizing : Declarative Pipelines and Automated Prompt Compilers
The DSPy paradigm (Khattab et al., 2023) treats LLM calls as typed declarative modules (Predict, ChainOfThought, ReAct) rather than brittle f-string templates. A compiler then searches the joint space of instructions and bootstrapped few-shot demonstrations against a concrete evaluation metric.
MIPROv2 (Multiprompt Instruction Proposal Optimizer v2)
MIPROv2 (Opsahl-Ong et al., 2024) jointly optimizes instructions and few-shot demonstrations across every module in a multi-stage agent program:
- Bootstrap Candidate Traces: Run the unoptimized program on training examples and collect trajectories that pass the evaluation metric. Each module receives validated input-output demonstrations drawn from successful end-to-end runs.
- Grounded Instruction Proposal: A proposer LM inspects:
- Summarized dataset patterns and failure cases,
- The program’s control-flow graph and each module’s specific role,
- Bootstrapped trace examples, generating diverse candidate instructions grounded in actual data rather than generic advice.
- Bayesian Surrogate Search: Evaluating every combination of instructions and demonstration sets across modules is combinatorially explosive. MIPROv2 fits a Tree-structured Parzen Estimator (TPE) / Bayesian surrogate model over mini-batches, efficiently balancing exploration and exploitation to select the highest-scoring assignment before full validation.
GEPA (Genetic-Pareto / Reflective Prompt Evolution)
Scalar optimization methods often discard why a trajectory failed, compressing rich error logs (stack traces, wrong SQL joins, violated constraints) into a single score. GEPA (Agrawal et al., 2025) preserves that diagnostic signal through reflective prompt evolution and Pareto frontier selection:
- Trace Reflection: When a candidate prompt fails on a validation instance, a reflector LM reads the full multi-turn execution trace—tool outputs, error messages, and metric feedback—and diagnoses the concrete behavioral gap in natural language, proposing a targeted prompt mutation.
- Pareto Frontier Maintenance: Instead of keeping only the single prompt with highest average score (which can lose niche capabilities), GEPA tracks a Pareto frontier of prompt variants that are non-dominated across individual evaluation tasks or failure modes, recombining complementary strengths via crossover mutations.
- Sample Efficiency: Because every mutation is guided by causal trace diagnosis rather than blind perturbation, GEPA achieves strong gains with far fewer rollout evaluations than black-box evolutionary search.
TextGrad: Automatic Differentiation via Text
TextGrad (Yuksekgonul et al., 2024) generalizes backpropagation from tensor computation graphs to arbitrary compound AI computation graphs:
- Forward Pass: Inputs flow through LLM calls, Python tools, and evaluators to produce an output and a natural-language critique (from a test suite, verifier, or rubric judge).
- Textual Backward Pass: At each node in the graph, an LLM computes a “textual gradient”—actionable natural-language feedback describing how ‘s output or prompt should change to improve downstream nodes:
- Textual Optimizer Step (
TGD.step): An update operator applies the accumulated textual gradient to rewrite the target prompt, system instruction, or generated artifact (such as code or molecular/math solutions) iteratively.
Comparing Prompt Optimization Methods ()
| Method | Optimization Mechanism | Feedback Signal Used | Best Use Case | Key Limitation |
|---|---|---|---|---|
| MIPROv2 | Grounded proposal + Bayesian TPE search over instructions & demos | Scalar task metric on mini-batches | Multi-module DSPy pipelines needing joint instruction + few-shot tuning | Ignores rich trace diagnostics; needs enough examples for few-shot bootstrapping |
| GEPA | Natural-language trace reflection + Pareto genetic recombination | Full execution traces + per-task scores | Complex multi-turn agents with rich error logs and diverse task subsets | Relies on a strong reflector model to diagnose failure causes accurately |
| TextGrad | Reverse-mode textual gradient propagation through computation graphs | Textual critiques from evaluators or unit tests | Optimizing both system prompts and intermediate artifacts (code, plans, answers) | Multi-step graph backprop can drift without validation gating on every update |
2. Optimizing : Weight Tuning for Agentic Policies
Prompt optimization cannot fix everything. When a model lacks fundamental tool-use formatting habits, struggles with domain-specific APIs, incurs prohibitive prompt token latency from long few-shot examples, or needs to run on compact open-weight models (–), you must update weights .
FireAct: Trajectory Supervised Fine-Tuning (SFT)
FireAct (Chen et al., 2023) established the blueprint for fine-tuning language models into capable multi-turn agents using heterogeneous trajectory distillation:
- Multi-Method Trajectory Synthesis: Collect successful tool-use trajectories from a strong teacher model across multiple task families and reasoning formats (e.g., ReAct, Reflexion, Chain-of-Thought) rather than locking into a single rigid template.
- Outcome Filtering (Rejection Sampling): Retain only trajectories that pass deterministic ground-truth verification, discarding hallucinated tool calls or lucky guesses with broken intermediate steps.
- Loss Masking on Environment Observations: During SFT, compute cross-entropy loss only on the agent’s own reasoning and action tokens, masking out injected environment/tool observations ( for observation tokens, for model-generated tokens):
Masking environment tokens prevents the model from wasting capacity memorizing unpredictable external tool outputs (stdout, HTML, database rows). FireAct-tuned smaller models dramatically outperform zero-shot prompting and become robust to noisy tool outputs—though pure SFT remains bounded by imitation ceiling and can overfit to teacher style.
GRPO: Critic-Free Agentic Reinforcement Learning
To surpass teacher demonstrations and learn autonomous error recovery (backtracking, trying alternative hypotheses after a failing command), modern agent training uses Reinforcement Learning with Verifiable Rewards (RLVR)—most notably GRPO (Group Relative Policy Optimization) (Shao et al., 2024; DeepSeek-R1).
Standard PPO requires training a separate value/critic network matching the policy size—doubling GPU memory and struggling with high-variance long-horizon credit assignment. GRPO eliminates the critic network entirely by sampling a group of rollouts for the same prompt from the old policy , scoring each rollout with a deterministic verifier , and computing a group-normalized advantage:
The policy maximizes the clipped surrogate objective with an explicit KL-divergence regularizer toward a reference policy :
where is the token-level probability ratio, masks out environment observation tokens from the policy gradient update, is the clipping range, and controls drift from .
Unique Engineering Challenges in Multi-Turn Agentic RL
Training GRPO on multi-turn tool-using agents (coding, terminal tasks, search) is far harder than single-turn math RL:
- Environment Rollout Bottleneck: Each group of rollouts requires spinning up isolated Docker/sandbox containers and waiting on real compilers, browsers, or databases. Async rollout engines and lightweight container snapshots dominate throughput.
- Zero-Variance Groups: If a task is too hard ( for all ) or too easy ( for all ), and the group produces zero gradient. Dynamic curriculum filtering (sampling tasks near the – pass band) is essential.
- Credit Assignment & Reward Hacking: Sparse terminal rewards cannot distinguish a clean 4-turn fix from a messy 25-turn flailing trajectory that stumbled onto passing tests—or worse, deleted the test suite. Process shaping (penalizing invalid tool syntax or excessive turns) and isolated verifiers are mandatory.
3. Decision Matrix: Prompts () vs. Weights ()
In practice, -optimization and -optimization form a staged ladder, not an either/or choice:
| Dimension | Prompt / Program Optimization (: MIPROv2, GEPA, TextGrad) | Trajectory SFT (: FireAct) | Agentic RL (: GRPO / RLVR) |
|---|---|---|---|
| Model Access | Works on closed frontier APIs and open models | Requires open weights / fine-tuning API | Requires open weights + custom RL rollout infra |
| Data Needed | 20–300 labeled eval examples + metric | 500–50,000 verified successful trajectories | Thousands of verifiable sandbox environments |
| Latency & Token Cost | Often increases input tokens via few-shot demos & detailed instructions | Reduces prompt overhead; distills frontier behavior into fast – models | Best accuracy-per-token at runtime once trained |
| Error Recovery & Discovery | Limited to base model’s latent capabilities | Bounded by teacher trajectory ceiling | Discovers novel search, verification, and recovery strategies |
| Iteration Speed | Minutes to hours | Hours to days | Days to weeks (sandbox infra intensive) |
| Recommended Order | Stage 1 (Always start here) | Stage 2 (Distill once task & eval stabilize) | Stage 3 (Push frontier beyond teacher ceiling) |
Key Takeaways
- Optimize the whole compound system: View agent tuning as over both model weights and prompts/topology; never tune one module prompt without re-evaluating downstream modules.
- Automate before touching weights: Use MIPROv2 for joint multi-module instruction + demo compilation, GEPA for trace-driven reflective evolution, and TextGrad for computation-graph critique propagation.
- Mask observations in weight updates: Whether running FireAct SFT or GRPO, mask environment/tool observation tokens so optimization shapes only agent reasoning and actions.
- GRPO unlocks critic-free agentic RL: Group-normalized advantages avoid expensive value networks, provided you solve sandbox rollout parallelism, zero-variance task filtering, and reward-hacking isolation.