Skip to content
E
Educatum

Chapter 9: Agent Optimization — Prompts vs. Weights

By Educatum AI teamLast updated:
Key Intuition

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 θ\theta and non-parametric system parameters ϕ\phi (system instructions, few-shot demonstrations, tool descriptions, and orchestration structure).

Formally, given a task distribution D\mathcal{D}, trajectory rollout generator Pθ,ϕ(τ∣x)P_{\theta, \phi}(\tau \mid x), and verifier/reward function R(x,τ)R(x, \tau), agent optimization seeks:

max⁡θ,ϕ  Ex∼D,  τ∼Pθ,ϕ(⋅∣x)[R(x,τ)]−λ Cost(τ)\max_{\theta, \phi} \; \mathbb{E}_{x \sim \mathcal{D},\; \tau \sim P_{\theta, \phi}(\cdot \mid x)} \big[ R(x, \tau) \big] - \lambda \, \text{Cost}(\tau)

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 (ϕ\phi) and trajectory fine-tuning & reinforcement learning (θ\theta).


1. Optimizing ϕ\phi: 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:

  1. 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.
  2. 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.
  3. Bayesian Surrogate Search: Evaluating every combination of instructions and demonstration sets across MM 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 (instructionm,demosm)m=1M(\text{instruction}_m, \text{demos}_m)_{m=1}^M 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 0/10/1 score. GEPA (Agrawal et al., 2025) preserves that diagnostic signal through reflective prompt evolution and Pareto frontier selection:

  1. 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.
  2. 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.
  3. 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 Ltext\mathcal{L}_{\text{text}} (from a test suite, verifier, or rubric judge).
  • Textual Backward Pass: At each node vv in the graph, an LLM computes a “textual gradient”—actionable natural-language feedback describing how vv‘s output or prompt should change to improve downstream nodes:
∂Ltext∂v  ≈  LLMcritique ⁣(v,  downstream inputs,  ∂Ltext∂child(v))\frac{\partial \mathcal{L}_{\text{text}}}{\partial v} \;\approx\; \text{LLM}_{\text{critique}}\!\left(v,\; \text{downstream inputs},\; \frac{\partial \mathcal{L}_{\text{text}}}{\partial \text{child}(v)}\right)
  • 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 (ϕ\phi)

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 θ\theta: 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 (7B7\text{B}–32B32\text{B}), you must update weights θ\theta.

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:

  1. 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.
  2. Outcome Filtering (Rejection Sampling): Retain only trajectories that pass deterministic ground-truth verification, discarding hallucinated tool calls or lucky guesses with broken intermediate steps.
  3. 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 (mt=0m_t = 0 for observation tokens, mt=1m_t = 1 for model-generated tokens):
LSFT(θ)=−∑(x,τ)∈Dpass∑t=1∣τ∣mtlog⁡πθ(τt∣x,τ<t)\mathcal{L}_{\text{SFT}}(\theta) = -\sum_{(x, \tau) \in \mathcal{D}_{\text{pass}}} \sum_{t=1}^{|\tau|} m_t \log \pi_\theta(\tau_t \mid x, \tau_{<t})

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 VψV_\psi 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 GG rollouts {τ1,τ2,…,τG}\{\tau_1, \tau_2, \dots, \tau_G\} for the same prompt xx from the old policy πθold\pi_{\theta_{\text{old}}}, scoring each rollout with a deterministic verifier ri=R(x,τi)r_i = R(x, \tau_i), and computing a group-normalized advantage:

A^i,t=ri−mean({r1,…,rG})std({r1,…,rG})+ϵ\hat{A}_{i,t} = \frac{r_i - \text{mean}\big(\{r_1, \dots, r_G\}\big)}{\text{std}\big(\{r_1, \dots, r_G\}\big) + \epsilon}

The policy maximizes the clipped surrogate objective with an explicit KL-divergence regularizer toward a reference policy πref\pi_{\text{ref}}:

JGRPO(θ)=Ex∼D, {τi}i=1G∼πθold[1G∑i=1G1∑t=1∣τi∣mi,t∑t=1∣τi∣mi,t(min⁡ ⁣(ρi,t(θ)A^i,t,  clip(ρi,t(θ), 1−ε, 1+ε)A^i,t)−β DKL(πθ ∥ πref))]\mathcal{J}_{\text{GRPO}}(\theta) = \mathbb{E}_{x \sim \mathcal{D},\, \{\tau_i\}_{i=1}^G \sim \pi_{\theta_{\text{old}}}} \left[ \frac{1}{G} \sum_{i=1}^{G} \frac{1}{\sum_{t=1}^{|\tau_i|} m_{i,t}} \sum_{t=1}^{|\tau_i|} m_{i,t} \left( \min\!\left( \rho_{i,t}(\theta) \hat{A}_{i,t},\; \text{clip}\big(\rho_{i,t}(\theta),\, 1-\varepsilon,\, 1+\varepsilon\big) \hat{A}_{i,t} \right) - \beta \, D_{\text{KL}}\big(\pi_\theta \,\|\, \pi_{\text{ref}}\big) \right) \right]

where ρi,t(θ)=πθ(τi,t∣x,τi,<t)πθold(τi,t∣x,τi,<t)\rho_{i,t}(\theta) = \frac{\pi_\theta(\tau_{i,t} \mid x, \tau_{i,<t})}{\pi_{\theta_{\text{old}}}(\tau_{i,t} \mid x, \tau_{i,<t})} is the token-level probability ratio, mi,t∈{0,1}m_{i,t} \in \{0, 1\} masks out environment observation tokens from the policy gradient update, ε\varepsilon is the clipping range, and β\beta controls drift from πref\pi_{\text{ref}}.

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 GG rollouts requires spinning up GG 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 (ri=0r_i = 0 for all GG) or too easy (ri=1r_i = 1 for all GG), A^i,t=0\hat{A}_{i,t} = 0 and the group produces zero gradient. Dynamic curriculum filtering (sampling tasks near the 20%20\%–80%80\% 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 (ϕ\phi) vs. Weights (θ\theta)

In practice, ϕ\phi-optimization and θ\theta-optimization form a staged ladder, not an either/or choice:

Dimension Prompt / Program Optimization (ϕ\phi: MIPROv2, GEPA, TextGrad) Trajectory SFT (θ\theta: FireAct) Agentic RL (θ\theta: 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 7B7\text{B}–32B32\text{B} 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 max⁡θ,ϕ\max_{\theta, \phi} over both model weights and prompts/topology; never tune one module prompt without re-evaluating downstream modules.
  • Automate ϕ\phi 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.

More in Engineering AI Agents (CS329Z)

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.