AI Agent Assurance for Your Agent Deployments
Agent Assurance Tests How Your Agent Actually Behaves across Workflows, Tools, and Actions to Catch Failures and Vulnerabilities.
npm install -g @testmuai/rook@latest
What Is Prompt Optimization? Techniques, Automatic Methods and Real Gains
Prompt optimization tunes an LLM prompt against a measured score. Compare manual, APE, OPRO and DSPy methods, then check that a gain is real before you ship it.
OVERVIEW
A team building a calendar-scheduling agent edits its system prompt so the agent stops offering meeting slots outside working hours. On its 100-case eval set the pass count climbs from 70 to 76, and the pull request calls the edit a prompt optimization win.
Whether it is a win depends on which cases moved: if the new prompt fixed 9 cases and broke 3, an exact McNemar test on those 12 changed cases gives p = 0.146. If the two prompts were equally good, a split at least that lopsided, in either direction, would still turn up about 15% of the time. The script behind this hub, executed on 2026-12-01, prints that result and two more checks, shown in full below.
Overview
Prompt optimization is the process of changing an existing prompt's instructions, few-shot examples or format to raise a measured score on a set of test cases. A person or an optimizer model proposes and scores candidate prompts, and a gain counts only when it holds on held-out cases and survives a paired comparison.
What Are the Main Prompt Optimization Techniques?
- Manual iteration: In manual prompt optimization, a person edits one part of the prompt, reruns a fixed eval set and keeps the edit only if the score holds. Needs an optimizer model: no. Each edit is a new comparison, so the eval set must be large enough to separate a fix from noise.
- Few-shot example selection: Few-shot example selection chooses which labeled demonstrations go into a prompt and in what order. Changes the instruction wording: no. Order is part of the search, because Lu et al. found that the order of the same examples can separate near state-of-the-art from random guess performance.
- Instruction search (APE and OPRO): APE and OPRO use an optimizer model to propose candidate instructions and keep the one that scores best on training examples. Uses an optimizer model: yes. OPRO also feeds earlier instructions and their scores into each new proposal, and its default run scores up to 1,600 candidates.
- Text feedback optimization (ProTeGi and TextGrad): ProTeGi and TextGrad ask a model to criticize the current prompt in words, then edit the prompt in response, treating the written critique the way gradient descent treats a numeric gradient. ProTeGi reported up to 31% over its initial prompt in preliminary results.
- Reflective prompt evolution (GEPA): GEPA reads execution traces, writes a natural-language diagnosis of what went wrong and proposes new prompts from the Pareto frontier of its own attempts. Needs execution traces: yes. Its paper reports beating GRPO by 6% on average with up to 35x fewer rollouts.
- DSPy optimizers (MIPROv2): DSPy optimizers such as MIPROv2 tune the instructions and few-shot demonstrations of every module in a multi-step program against a metric you write. Can tune model weights: yes, through BootstrapFinetune. The DSPy guide puts a typical simple run at a few dollars and about ten minutes.
- Agent Assurance re-testing: Agent Assurance from TestMu AI re-runs the same scenario suite after a prompt change and lists which scenarios newly fail or were fixed, checking tool calls, files and records against evidence. Rewrites prompts: no. It tests agents that act through tools, files and APIs.
What Is Prompt Optimization?
Prompt optimization is the work of changing a prompt that already exists so it scores better on a defined objective, measured on a set of examples. AWS Prescriptive Guidance calls it "the iterative process of refining prompts to improve the quality, accuracy, and reliability of LLM outputs." Its methods run from manual heuristics to automated ones that "treat prompt design as a formal optimization problem."
Research papers state the goal in measurable terms. The MetaSPO paper by Choi, Baek and Hwang (KAIST, May 2025) describes the objective as automatically discovering prompts "that maximize task performance through iterative refinement processes." Every LLM prompt optimization effort, manual or automatic, needs the same inputs:
- A starting prompt - the version in use today, whose score is the baseline every candidate must beat.
- An objective - a function that scores each output, such as exact match, a rule or a model judge.
- Development cases - the examples the score is computed on while candidates are compared.
- Held-out cases - examples the search never sees, used once to judge the prompt it picked.
How Prompt Optimization Differs From Writing a Prompt
Prompt engineering is how a prompt gets written in the first place: its role, instructions, examples and reasoning pattern. Prompt optimization starts after that, from a working prompt plus a score, and keeps a change only when the score moves on cases.
The Amazon Bedrock guide to optimizing a prompt draws the same line: its simple option "performs a fast, heuristic rewrite of a single short prompt for one model" and "does not use evaluation data." Its advanced option is the one where "your evaluation steers the prompt rewriting." A rewrite that no eval set ever scored is closer to prompt engineering, because nothing measured whether it helped.
What Can Prompt Optimization Change?
An optimizer can change any part of the text the model receives, and some frameworks reach past the prompt into the model itself. Each target below has its own evidence that it moves scores:
- Instructions - the task description and rules, which APE, OPRO and ProTeGi search over directly.
- Few-shot demonstrations - which labeled examples appear. The DSPy optimizers guide groups four optimizers for this job, listed in the DSPy section below.
- Example order - the sequence of the same demonstrations. Lu et al. (ACL 2022) found that order alone can separate "near state-of-the-art and random guess performance," and their ordering method gave a 13% relative improvement for GPT-family models across eleven text classification tasks.
- Format - separators, spacing and casing. Sclar, Choi, Tsvetkov and Suhr measured few-shot accuracy differences of up to 76 points on LLaMA-2-13B from formatting choices alone, and they advise reporting a range across plausible formats.
- System prompt - the standing instructions an agent carries into every task. The MetaSPO paper optimizes this layer directly, because user prompts tuned per task have to be tuned again for every new task.
- Model weights - outside prompt optimization proper, but in scope for DSPy, whose optimizers guide says an optimizer tunes "the prompts and/or the LM weights" (BootstrapFinetune does the second).
A candidate that wins by a few points may have won on spacing, so compare finalists across more than one format before crediting the instruction text.
Prompt Optimization Techniques From Manual to Automatic
The methods differ in what they edit, what they need from you and what their authors measured. Each reported result comes from that paper's own benchmarks and baselines, so read the numbers as evidence that a method works, not as a forecast for your prompt. Agent benchmarks such as AgentBench carry the same caveat, since they score models in fixed environments rather than the agent you ship.
| Method | What it changes | What it needs | Reported result |
|---|---|---|---|
| Manual iteration | Any part of the prompt, one edit per run | An eval set and a reviewer's time | No published figure; depends on your cases |
| APE (Zhou et al., 2022) | The instruction | Demonstrations, a proposing LLM and a scoring LLM | Better than or comparable to human-written instructions on 19 of 24 tasks |
| OPRO (Yang et al., 2023) | The instruction | A scorer, a training subset and many optimizer calls | Up to 8% above human prompts on GSM8K and up to 50% on Big-Bench Hard tasks |
| ProTeGi (Pryzant et al., 2023) | The instruction, edited from written critiques | Labeled minibatches and a beam search | Up to 31% over the initial prompt in preliminary results on four tasks |
| TextGrad (Yuksekgonul et al., 2024) | Prompts and other parts of a compound AI system | An LLM that writes feedback | GPQA with GPT-4o: 51% to 55%, from optimizing answers, not prompts |
| GEPA (Agrawal et al., 2025) | Each module's prompt, rewritten from trace reflection | Execution traces and a metric | Beats GRPO by 6% on average with up to 35x fewer rollouts; over 10% above MIPROv2 |
| MIPRO (Opsahl-Ong et al., 2024) | Instructions and demonstrations of every module | A program, a metric and training inputs | Beat baseline optimizers on 5 of 7 programs with Llama-3-8B, by up to 13% accuracy |
Manual Iteration Against an Eval Set
Manual iteration is the method most teams start with: read the failing cases, form a hypothesis, change one thing in the prompt and rerun the same set. The edits themselves come from the prompting techniques you already know; what makes it optimization is the fixed set and the recorded score per prompt version.
- Change one element per run, so a score change can be traced to it.
- Store the prompt version next to every score, along with the model and its settings.
- Write the eval before the edit, the order eval-driven development follows, so the target cannot drift toward whatever the new prompt happens to do well.
Few-Shot Example Selection and Ordering
Few-shot selection searches over demonstrations instead of wording, and DSPy groups four optimizers under automatic few-shot learning for it. The DSPy optimizers guide advises starting with BootstrapFewShot when you have very few examples (around 10), and moving to BootstrapFewShotWithRandomSearch with 50 examples or more.
Because Lu et al. found that order alone can move a prompt from near state of the art to random guessing, treat each ordering of the chosen examples as its own candidate.
Instruction Search With an Optimizer Model: APE and OPRO
APE (Automatic Prompt Engineer) treats the instruction as something to search for "over a pool of instruction candidates proposed by an LLM." It then measures how well another LLM performs zero-shot when following each candidate, and keeps the instruction with the best score.
OPRO, from Google DeepMind, adds memory to that search. In each optimization step, the optimizer model "generates new solutions from the prompt that contains previously generated solutions," and then "the new solutions are evaluated and added to the prompt for the next optimization step." The optimizer therefore sees which earlier wording scored well before it writes the next batch.
Text Feedback as a Gradient: ProTeGi and TextGrad
ProTeGi uses "minibatches of data to form natural language "gradients" that criticize the current prompt," then edits the prompt "in the opposite semantic direction of the gradient." The search over edited prompts is "guided by a beam search and bandit selection procedure."
TextGrad generalizes the idea to a whole pipeline: it "backpropagates textual feedback provided by LLMs to improve individual components of a compound AI system." The 51% to 55% GPQA figure for GPT-4o in the TextGrad abstract comes from optimizing answers rather than prompts, so it says little about prompt gains.
Reflective Prompt Evolution With GEPA
GEPA reads a program's execution traces and "reflects on them in natural language to diagnose problems," then proposes prompt updates. It combines lessons from "the Pareto frontier of its own attempts" when it writes each new candidate.
Its authors compare it with reinforcement learning methods, which they say "often require thousands of rollouts to learn new tasks." The GEPA paper reports that GEPA beat GRPO by 6% on average and up to 20% while using up to 35x fewer rollouts, and that it outperformed MIPROv2 by over 10%.
Compiled Pipelines: DSPy Optimizers
DSPy turns a multi-step pipeline into a program whose prompts are parameters, and an optimizer tunes them "to maximize the metrics you specify, like accuracy." The DSPy optimizers guide groups its optimizers this way:
- Automatic few-shot learning - LabeledFewShot, BootstrapFewShot, BootstrapFewShotWithRandomSearch and KNNFewShot.
- Automatic instruction optimization - COPRO, MIPROv2, SIMBA and GEPA.
- Automatic finetuning - BootstrapFinetune.
- Program transformations - Ensemble.
- Meta-optimizers - BetterTogether, which combines prompt optimization and fine-tuning.
MIPROv2 "Generates instructions and few-shot examples in each step" and searches the combinations with Bayesian Optimization. The DSPy optimizers guide also reports a run on DSPy 2.5.29 in which MIPROv2 in light mode, trained on 500 HotPotQA question-answer pairs, raised a ReAct agent's score from 24% to 51%. The guide calls that run informal, so treat it as an illustration.
How Does Automatic Prompt Optimization Work?
Automatic prompt optimization runs a propose, score and select loop until a budget runs out. The OPRO paper's default setting shows the scale: the optimizer model is prompted 8 times per step to generate 8 instructions, for 200 steps, which is up to 1,600 candidate instructions scored in one run.
- Propose - an optimizer model writes new candidates from the current best prompts, their scores or a critique of their failures.
- Score - each candidate runs on a minibatch or training subset, and the metric scores every output.
- Select - the top candidates survive into the next round, by rank, beam search, a bandit rule or a Pareto frontier.
- Stop and pick - when the step budget ends, the best candidate on the development set is returned.
In the DSPy optimizers guide, MIPROv2 runs this loop in three stages: a "bootstrapping stage" collecting traces, a "grounded proposal stage" drafting instructions and a "discrete search stage" scoring candidates on mini-batches. The guide says training inputs "may be very small (i.e., only 5 or 10 examples)." The OPRO authors list the need for a training set as a limitation of their method, and say theirs "at least contains tens of samples" so the optimized prompt does not severely overfit.
Choosing the Metric a Prompt Optimizer Maximizes
An optimizer improves exactly what its metric rewards. The DSPy optimizers guide defines the metric as "a function that evaluates the output of your program, and assigns it a score (higher is better)." Every candidate is ranked on that number alone, so a loose metric produces a prompt that is good at the loose metric.
- Exact match and rules - cheap and stable, and the right choice when the output has a correct form such as a label, a JSON field or a time slot.
- Overlap metrics - an n-gram target such as the BLEU score rewards surface overlap with a reference, so an optimizer can learn to echo reference wording. The ROUGE score does the same for summaries, counting the words and word sequences a summary shares with human-written references.
- Model judges - an LLM-as-a-judge can score open answers, but the optimizer then climbs the judge's preferences too, so check the judge against human labels first.
Hamel Husain and Shreya Shankar state the limit in their evals FAQ on automated prompt tools. An automated tool, they write, "can refine a prompt to perform better on known failures, but it cannot discover new ones." Choose the metric from the LLM evaluation metrics that match your failure analysis, and expect the optimizer to fix only the failure types your cases contain.
How Big Must the Eval Set Be Before a Prompt Gain Is Real?
Large enough that the gain is wider than the interval around the old score. In the script below, at 100 cases, an observed 70% pass rate has a 95% Wilson interval of 60.4% to 78.1%, so a new prompt scoring 76% sits inside the old prompt's own range. At 400 cases the interval narrows to 65.3% to 74.3%.
Those figures come from prompt_gain_check.py, a Python script that uses only the standard library and makes no model or network calls, run on 2026-12-01 for this hub. It uses the Wilson method for proportions, which the NIST/SEMATECH e-Handbook presents as recommended by Brown, Cai and DasGupta (2001), among others. The two functions the first two checks rely on:
import math
import random
Z = 1.959964 # two-sided 95%
def wilson(k, n, z=Z):
p = k / n
den = 1 + z * z / n
mid = (p + z * z / (2 * n)) / den
half = (z / den) * math.sqrt(
p * (1 - p) / n + z * z / (4 * n * n))
return mid - half, mid + half
def mcnemar_exact(fixed, broken):
"""Two-sided exact McNemar p:
binomial(fixed+broken, 0.5)."""
n = fixed + broken
k = min(fixed, broken)
tail = sum(math.comb(n, i)
for i in range(k + 1)) / 2 ** n
return min(1.0, 2 * tail)Running it printed the following output, unedited. The next two sections read its second and third parts.
prompt_gain_check.py (stdlib, seed 7)
1. Wilson 95% CI, observed pass rate 70%
----------------------------------------
n passes low high width
20 14 0.481 0.855 0.373
30 21 0.521 0.833 0.312
50 35 0.562 0.809 0.246
100 70 0.604 0.781 0.177
200 140 0.633 0.759 0.126
400 280 0.653 0.743 0.089
2. Paired check, 100 cases (illustrative)
-----------------------------------------
prompt A passes 70/100
prompt B passes 76/100
fixed by B (F->P) 9
broken by B (P->F) 3
exact McNemar p 0.146
Same 9 fixes, fewer breaks:
broken net gain p
3 6 0.146
2 7 0.065
1 8 0.021
0 9 0.004
3. Best of K prompts on one dev set
-----------------------------------
All candidates truly pass 70%. Dev set n=50,
held-out set n=200, 2,000 trials per row.
K winner dev winner held
1 0.701 0.701
8 0.790 0.700
32 0.828 0.699
128 0.857 0.701
The held-out column stays near 0.700 because
the winner was never better; the dev column is
the optimizer's selection bias.The width column is the practical guide: halving it takes four times the cases. Reuse one fixed golden dataset for every candidate. When the agent's outputs vary between runs of the same prompt, run each case several times and read the repeat-run measures in pass@k vs pass^k before reading a single pass rate.
Comparing Two Prompts on the Same Cases
When both prompts run on the same cases, compare them case by case instead of comparing two pass rates. Cases that pass or fail under both prompts carry no information about the difference. The statsmodels McNemar documentation computes its statistic only from cases "that are zero in one sample but one in the other sample," and its exact version uses the binomial distribution.
In the script's illustrative case, prompt B fixed 9 cases and broke 3 for a net gain of 6, and the exact test gives p = 0.146. Holding the 9 fixes constant, the result crosses the usual 0.05 line only when B breaks one case or none:
| Cases broken by B | Net gain (of 100) | Exact McNemar p |
|---|---|---|
| 3 | 6 | 0.146 |
| 2 | 7 | 0.065 |
| 1 | 8 | 0.021 |
| 0 | 9 | 0.004 |
Pairing costs nothing extra once both prompts have run. Evan Miller's paper on adding error bars to evals describes paired differences as a "free" reduction in estimator variance when comparing two models, and the same logic applies to two prompts on one model.
How Prompt Optimizers Overfit the Dev Set: Selection Bias and Held-Out Data
An optimizer that scores many candidates on one development set and keeps the top scorer reports an inflated winner, even when no candidate is better. In the script's third check, every candidate prompt has a true pass rate of 70%. Picking the best of 128 on a 50-case dev set reported 85.7%, while the same winner scored 70.1% on 200 held-out cases, averaged over 2,000 trials.
rng = random.Random(7)
TRIALS, DEV, HOLD, TRUE = 2000, 50, 200, 0.70
def score(n, p):
return sum(rng.random() < p for _ in range(n)) / n
for K in (1, 8, 32, 128):
dev_sum = held_sum = 0.0
for _ in range(TRIALS):
best = max(score(DEV, TRUE) for _ in range(K))
dev_sum += best
held_sum += score(HOLD, TRUE)
print(f"{K:>4} {dev_sum / TRIALS:>11.3f} "
f"{held_sum / TRIALS:>12.3f}")The script's 15.6-point gap is pure selection, and it grows with the number of candidates. A code comment in the DSPy optimizers guide describes the same step: BootstrapFewShotWithRandomSearch repeats its bootstrapping 10 times, plus some initial attempts, "before selecting its best attempt on the devset." The OPRO paper's default run selects among up to 1,600 instructions.
The OPRO authors report the effect in their own results: training accuracies "are often 5%-20% higher than our test accuracies." In one experiment set they optimize on a 20% subset of each task and test on the rest, and for GSM8K they sample 3.5% of the training set. They state that "we do not set aside a validation set in our default setting," and suggest a larger training set and fewer steps to reduce the gap.
- Split cases into a development set the optimizer may see and a held-out set it never sees.
- Score the chosen prompt on the held-out set once, at the end, and report that number.
- Scale the data with the search, as the DSPy optimizers guide does when it suggests 200 examples or more for MIPROv2 runs of 40 trials or more "to prevent overfitting."
How Much Does a Prompt Optimization Run Cost?
A small run is cheap and a large one is not. The DSPy optimizers guide puts a typical simple optimization run at a few dollars and about ten minutes. It says runs range from a few cents to tens of dollars "depending on your LM, dataset, and configuration," and warns to be careful when running optimizers with very large models or very large datasets.
- Candidate count - each of OPRO's default candidates needs scoring calls on the training subset, plus one optimizer output.
- Rollouts - GEPA's rollout savings against GRPO (above) show how much the method choice moves the bill.
- Repeat runs per task - the MetaSPO authors call re-optimizing user prompts for each new task "computationally expensive and time-consuming."
- Evaluation passes - every held-out check and every repeated case in the sections above is another full set of model calls.
Know when to stop. AWS Prescriptive Guidance warns that "evaluation metrics sometimes plateau below acceptable thresholds" and lists "Quality metrics plateauing significantly below success criteria despite multiple optimization iterations" as the signal to consider changing the model instead.
A Regression Gate for an Optimized Prompt
A net gain can hide new failures, so gate the prompt on the cases it broke as well as on its score. Apple researchers working on model updates in the MUSCLE paper name these negative flips: "previously correct instances are now predicted incorrectly." The term fits a prompt change equally well, and the 3 broken cases in the scheduling example are three negative flips.
- Held-out score - the new prompt's held-out pass rate with its interval, never the dev score the optimizer chose it on.
- Break list - every negative flip by case id, read by a person; a broken case on a must-pass path blocks the release whatever the net gain.
- Paired result - fixes and breaks with the exact McNemar p, so a 9-to-3 split is not shipped as a proven gain.
- Version record - the prompt version, model and settings stored with the run, so the result can be traced after release.
For gates that also survive a model upgrade, see LLM regression testing; for tracking prompt versions once they serve traffic, see LLM prompt monitoring.
Re-Testing an Agent After a Prompt Change With Agent Assurance
An optimizer reports a better score on text, but an agent that acts follows its prompt when it picks tools, so a prompt edit is a release of the agent. The edit can change the tools the agent calls and the records it writes. Agent Assurance from TestMu AI tests agents that act through tools, files and APIs; the product does not optimize or rewrite prompts.
It tests the agent you built rather than ranking models: scenarios come from that agent's code, PRD or spec, and discovery reads its manifests, prompts, tool tables and MCP servers. Most eval and observability tools score what your agent said and recorded. Agent Assurance checks what the run changed, and reports what it could not verify.
After the edit, re-run the same suite and read which scenarios newly fail or were fixed and the pass-rate change between the last two runs, the run-level form of the paired count above. An agent version pins its specification, features and scenarios, and a run pins the agent version and the profile revision it used (see the Agent Assurance features documentation). The hosted Runs page has no side-by-side diff, so open each run and confirm its version, profile revision and scenario selection before comparing.
Before calling a newly failing scenario a regression, repeat it unchanged and compare scenario definitions, profile revisions and coverage across the two runs. A criterion can pass, fail or come back Unable to Verify, and that last verdict stays outside the pass rate rather than counting as a failure. In CI, the Agent Assurance CI/CD guide gates on verdict totals, not the exit code, and its strict gate blocks the job on Unable to Verify without relabelling it as Fail.
Install Rook CLI with the npm command below (Node.js 20 or later); Homebrew and the shell installer need no Node, while npx @testmuai/rook-skill, the skill installer, wants Node.js 22 or later. The Agent Assurance free trial runs 7 days with 10,000 credits, and the Agent Assurance pricing page lists the plans after it.
npm install -g @testmuai/rook@latestWhere Should You Start With Prompt Optimization?
Before running any optimizer, split your cases into a development set and a held-out set, and record the current prompt's held-out pass rate with its Wilson interval. Then make one change, compare the two prompts case by case, and ship only when no must-pass case is on the break list and the held-out score holds.
npm install -g @testmuai/rook@latest, or for a full walkthrough of the product.Was this helpful?
Authors

Samyak Goyal
Author · 05 hubs
Samyak Goyal is a Senior Member of Technical Staff at TestMu AI engineering Kane CLI, the command-line tool that runs browser automation from the terminal, where a flow described in natural language executes in a real Chrome browser and returns pass or fail with shareable proof. He is a backend engineer with 4+ years of experience, previously an SDE at Innovaccer, where he built APIs, introduced Kafka, and cut deployment from weeks to hours. Samyak also builds multi-agent systems, skill-orchestration frameworks, and a personal copilot that indexes 200+ microservice repositories.

Sirajuddin Khan
Reviewer
Sirajuddin Khan is Vice President of Product Management at TestMu AI, where he drives the company's agentic AI product strategy, building a suite of autonomous agents that includes Agentic Browsers and Agentic Visual Testing and shifting the unit of work from test execution to autonomous outcomes. One of the company's earliest product leaders, he has owned the roadmap for the high-performance execution cloud and grew the cross-browser testing products from early adoption to market leadership. He brings over a decade of experience across SaaS, B2B, and eCommerce, with earlier product roles at Wydr and ShopClues, where his catalog and search work cut delivery SLAs and lifted seller activity. Sirajuddin holds an MBA in Information Technology from Sikkim Manipal University and a B.Tech in Computer Science Engineering from Maharshi Dayanand University.
Prompt Optimization FAQs
TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance
- Advanced access controls
- Advanced data retention rules
- Advanced Local Testing
- Premium Support options
- Early access to beta features
- Private Slack Channel
- Unlimited Manual Accessibility DevTools Tests


