Intermediate

Can a prompt rewrite itself? TextGrad, AdalFlow and GEPA compared

On this page

Automatic prompt optimization. If you have ever fixed a prompt for one failing case and watched two others break, you already know why people want a program to do this job, one that runs the prompt against examples, reads what went wrong, and writes the next version for you.

Three names come up whenever the subject does: TextGrad, AdalFlow and GEPA. They share the same core move, an LLM reads the failures and edits the prompt, and they disagree on how to search for the better prompt and on how much of your application they need to own. This post goes through what one iteration of each looks like on the same small example, then through two things that apply to all of them: the result depends on the models involved, and a prompt can overfit a dataset the same way a trained model does. As usual I won’t reproduce the papers, I’ll tell you what each is good for and leave you the links.

One note before we start. The traces in the grey boxes are illustrations that I wrote to show the shape of each step, they are not output from a real run, and for runnable code I link each project’s own examples.

What does "optimizing a prompt" even mean?

It means treating the prompt as a parameter and the evaluation as the training signal. You need a set of examples, a metric that scores an output, and a budget, usually counted in rollouts, where a rollout is one full run of your system on one example.

The idea is older than the three libraries. APE showed in 2022 that a model can propose instructions and pick the best by score, ProTeGi coined the gradient metaphor by having a model describe in words what is wrong with the prompt and then edit against that description, and OPRO got results by simply showing the optimizer model the previous prompts next to their scores. DSPy then moved the problem from one prompt to a whole pipeline, with optimizers that tune the instructions and the few-shot examples of each step.

Here is the example for the rest of the post. A support desk wants every incoming ticket labelled as billing, technical or account, and the starting prompt is the one anybody would write first:

Classify the support ticket as billing, technical or account.

One ticket it gets wrong reads "I was charged twice after resetting my password", which the model labels account because of the password, when the customer wants a refund.

Further reading

"The Shift from Models to Compound AI Systems" explains why the target moved from a single prompt to a pipeline of calls, which is the setting all three tools were built for.

TextGrad: feedback as a gradient

TextGrad built a library on the analogy with neural network training, to the point that the API mirrors PyTorch, with variables, a loss, a backward pass and an optimizer step. A "textual gradient" is feedback in plain language that plays the role of the numeric gradient, and one step has four parts:

  1. Forward. The system runs on an example and the library records which text went into which call, the prompt being marked as the variable to optimize.
  2. Loss. A critic model receives the output together with an evaluation instruction that you wrote, and answers with a critique.
  3. Backward. For each variable upstream of the output, the critic is asked how that variable should change given the critique, and this is repeated call by call until it reaches the prompt.
  4. Step. An optimizer model receives the current prompt and the feedback collected for it, writes a new prompt, and the new prompt replaces the old one.

On our ticket it would look like this:

Prompt v0   Classify the support ticket as billing, technical or account.
Ticket      I was charged twice after resetting my password.
Output      account
Loss        Wrong, the expected label is billing. The answer followed the word
            "password" and ignored that the customer is reporting a double charge.
Gradient    The prompt gives no rule for tickets that mention two topics. It
(on prompt) should say that the label comes from what the customer is asking for.
Prompt v1   Classify the support ticket as billing, technical or account. Choose
            the label by what the customer is asking you to do, even when the
            ticket mentions other topics.

The README has a runnable version of this loop on a counting question, where a single step turns "You are a concise LLM. Think step by step." into a prompt that tells the model to count each item and verify the total.

What makes TextGrad different from the other two is that the variable does not have to be a prompt. The same four parts can improve one answer, a piece of code or a molecule, and the headline results in the paper come from that use: GPT-4o went from 51% to 55% zero-shot on Google-Proof Question Answering, and solutions to LeetCode-Hard problems gained 20% in relative terms, both by refining the output at test time with the prompt left alone.

Notice what step 4 does not do. The new prompt replaces the old one without any test of whether it is better, the old one is gone, and that check is yours to write, as the project’s prompt optimization tutorial does by reverting any step that lowers the validation score.

AdalFlow: the same gradient, across a pipeline

The TextGrad trace had one prompt and one call, and real systems rarely stay that small. Suppose the classifier grows: one call summarizes the ticket, a retriever fetches similar past tickets, and a second call picks the label. When the label is wrong, which of the two prompts gets the blame, and how does feedback cross a retriever that has no prompt at all?

This is the gap AdalFlow set out to close. Its paper, LLM-AutoDiff, keeps the textual gradient and extends it so that feedback passes through non-LLM steps, repeated calls in a loop keep their order, and gradients are computed only for the samples that failed. The library around it is a full application framework, in which every piece of a prompt is declared as a parameter with a flag that says whether to train it, and its trainer wraps the TextGrad step in the discipline that TextGrad leaves to you:

  1. Batch. The pipeline runs on a batch of training examples and each one is scored.
  2. Backward on failures. Feedback is generated only for the failed examples and carried back through every step, the retriever included, to the prompts marked as trainable.
  3. Propose and gate. The optimizer writes a new prompt, and in the strategy the library calls constrained it gets up to five attempts, each of which must beat the current prompt on a sample of recent examples before it is allowed a full validation run.
  4. Validate or revert. A proposal that does not improve the validation score is thrown away and the previous prompt is restored.
  5. Demonstrations. A second optimizer fills a few-shot slot in the prompt with worked examples produced by a stronger teacher model, the bootstrap idea that comes from DSPy.

On the two-prompt ticket pipeline, one training step could read:

Batch        4 tickets, 3 labelled correctly, 1 wrong (the double charge)
Feedback     Classifier prompt: the summary it received never mentioned a charge.
             Retriever: passed through, nothing to change.
             Summarizer prompt: it kept "password reset" and dropped "charged
             twice". It should keep every request the customer makes.
Proposal 1   New summarizer prompt, validation 0.78 against a current 0.80: revert
Proposal 2   New summarizer prompt, validation 0.84: keep
Demos        One teacher-written example added to the classifier prompt,
             validation 0.86: keep

The blame landed on the first prompt even though the wrong label came out of the second, which is the part a single-prompt optimizer cannot do. The few-shot slot matters too, since there is evidence that how the examples in a prompt are selected can outweigh how the instructions are optimized. You can watch the real thing in the classification tutorial, where a step that fails validation ends its log line with the word "revert".

The price is the framework itself: your pipeline has to be written with AdalFlow’s components before its trainer can touch it.

Look back at the two traces. In TextGrad, prompt v1 took the place of v0, and in AdalFlow each proposal was either kept as the new current prompt or reverted. AdalFlow is the more careful of the two, yet both hold a single prompt at any moment, and every step is a decision about that one prompt: replace it or keep it.

Optimization people call this a greedy search, because it always takes the best move available right now and keeps no memory of the alternatives. It never returns to an earlier version and it never follows two ideas at once.

To see what that costs, take ten validation tickets and three candidate prompts, A being the current one and B and C two rewrites proposed along the way:

PromptTickets it gets rightScore
A (current)1 to 66/10
B1 to 5, and 76/10
C7 to 104/10

A greedy optimizer compares the averages, B ties and C loses, so both are discarded. Yet C is the only prompt that solves tickets 8 to 10, perhaps it learned to read refund requests, and that lesson is gone while the optimizer keeps polishing A. We’d say the search is stuck in a local optimum, every single edit to A looks equal or worse even though a better prompt exists.

GEPA: a pool of prompts in place of one

GEPA, short for Genetic-Pareto, is the answer to that problem. It keeps a pool of prompts in place of a single one, and any candidate that is the best on at least one validation example stays in the pool. In the table above A, B and C all survive, and the set they form is called the Pareto frontier. One iteration goes like this:

  1. Select. A parent is drawn from the frontier, with a probability proportional to the number of examples on which it is the best.
  2. Run. The parent runs on a small batch of training examples, and the full trace of each run is kept along with the score and whatever text your metric returned.
  3. Reflect. A reflection model reads the parent’s prompt, the traces and the feedback, and writes a new prompt for one module of the system, the modules taking turns across iterations.
  4. Accept. The child runs on the same small batch and is dropped unless it scores higher than the parent did.
  5. Score. A child that passed is scored on the whole validation set and joins the pool, and candidates that no longer win any example leave the frontier.

An optional sixth step, merge, combines two candidates that descend from the same ancestor and improved different modules. Continuing the table:

Select    C is drawn (it is the only candidate that solves tickets 8, 9 and 10)
Run       3 training tickets, C gets 1 right
Feedback  "Expected technical. The customer cannot log in after an update, and
          no charge is mentioned."
Reflect   C learned to spot refund requests but now sends anything that mentions
          an account to billing. New prompt D keeps the refund rule and adds
          that login and update problems are technical.
Accept    D gets 3 of the same 3 right, against 1 for C: continue
Score     D solves tickets 1 to 4 and 7 to 10, 8/10
Pool      D joins. C leaves, because D wins every ticket C won. A and B stay,
          because each still solves a ticket that D misses.

Greedy search would have thrown C away two steps earlier, and D is built on what C knew.

The feedback line is the other half of the idea. GEPA wants your metric to return text along with the score, and a metric that returns only a number leaves the reflection model with the sentence "This trajectory got a score of…" and nothing else.

Does the frontier earn its bookkeeping? The paper’s ablation says yes: on four tasks with a small open model, always mutating the best candidate took the aggregate score from 48.8 to 54.9, and selecting from the Pareto frontier took it to 61.3. Against the optimizer that DSPy users would otherwise reach for, GEPA reached 65.2 on GPT-4.1 Mini where MIPROv2 reached 58.7 from a baseline of 53.0.

GEPA is an optimizer and nothing else. It ships inside DSPy as dspy.GEPA, the quickstart in its own README optimizes a system prompt on competition math problems, and for a system written in anything else you implement an adapter with two methods, one that runs a candidate and one that turns traces into feedback.

The result belongs to the models that produced it

The three traces above left out a detail that changes the outcome of all of them, which models are doing the work. There are at least two in every one of these loops: the task model that runs your prompt, and the model that criticizes and rewrites it, which the tools call the backward engine, the optimizer or the reflection model.

The rewriting model leaves its fingerprint on the prompt. OPRO ran the same math task with different optimizer models and the winners don’t look alike: one model family converged on short instructions such as "Take a deep breath and work on this problem step-by-step." and "Break this down.", the GPT models on longer and more detailed ones, and the accuracy of the same task model ranged from 74.5 to 80.2 depending on who wrote its prompt. The rewriting model can also simply fail at the job, and TextGrad’s optimizer has an error message for the case in which the model does not return the new prompt in the expected format, with the advice to try a stronger one.

The task model decides how much there is to gain. In the GEPA paper the same optimizer on the same six benchmarks added 9.6 points to a small open model and 12.2 to GPT-4.1 Mini, and the merge step raised the aggregate on the second while lowering it on the first.

In our example, picture two task models that both mislabel the double-charge ticket. One of them is fixed by the single rule about what the customer is asking for, and the other needs the three labels defined and a worked example before it stops following the word "password". The optimizer will find a different prompt for each, so I treat an optimized prompt as belonging to the model it was tuned on, and when the model changes I run the optimization again from the original prompt.

A prompt can overfit too

The models are one thing an optimized prompt is tied to, and the dataset is the other. A prompt can overfit for the same reason a trained model does: the optimizer is rewarded for the score on your examples, and some ways of raising that score don’t carry over to new inputs. Here is what it looks like on the tickets, a prompt after too many steps on a small training set:

Classify the support ticket as billing, technical or account. Choose the label
by what the customer is asking you to do. Tickets that mention "charged twice"
or "invoice 4471" are billing. If the customer mentions the mobile app and a
password in the same message, answer technical. Messages that start with
"Hi team" are usually account.

The first two sentences are a rule, and the rest is the training set written out as instructions. This prompt scores very well on the tickets it was tuned on and will mislabel the next customer who writes "Hi team" about an invoice.

The effect has been measured. OPRO’s authors found training accuracy often 5 to 20 points above test accuracy, and suggest a larger training set and fewer optimization steps. Each of the three tools has a place where the problem shows:

The defence is the one from machine learning. Keep a test set that no optimizer and no selection step ever sees, score the original prompt and the optimized one on it, and read the optimized prompt yourself, because a rule that names an invoice number is easy to spot.

The three side by side

With the mechanics, the models and the dataset covered, here is the whole comparison in one table.

TextGradAdalFlowGEPA
What you installAn optimizer with a PyTorch-style APIAn application framework with a trainerAn optimizer with adapters
SearchGreedy, one prompt, overwritten each stepGreedy, a rewrite is kept only if validation improvesA pool of candidates, selected from a Pareto frontier
What it tunesAny text: a prompt, an answer, codeInstructions and few-shot examplesInstructions of each module, or any text component
Feedback comes fromA critic prompt you write as the lossThe same, computed for failed samplesYour metric’s score and the text it returns
Multi-step pipelinesSupported as a graph of callsThe main design goal, retrievers and loops includedThe main design goal, one module per iteration
Guard against overfittingNone in the step, you add a validation checkValidation gate on every stepAcceptance on the batch, then selection on a separate set
Cost of adoptionWrap inputs and prompts as variablesRewrite the pipeline with its componentsWrite a metric and, outside DSPy, an adapter

As a developer, what does this mean for me?

Start with the evaluation, because all three tools amplify whatever the metric rewards. A few dozen labelled examples split into training, validation and test, and a metric you trust, are worth more than the choice of optimizer, and if the metric is an LLM judge then its own flaws become the target the optimizer learns to hit.

Make the metric explain itself. A critique that says what was misread gives the rewriting model something to act on, and a bare 0 gives it nothing, whichever of the three you use.

Choose by what you already have. If the system exists and you only want better prompts, GEPA asks the least of your code. If you are starting a pipeline and want few-shot examples tuned along with the instructions, AdalFlow gives you both in one trainer, and DSPy with dspy.GEPA is the alternative I would compare it with. If what you want to improve is a single output, a solution or a snippet of code at inference time, that is TextGrad’s home ground.

Write down which models were in the loop. The optimized prompt is a result for one task model and one rewriting model, and a model upgrade is a reason to run the optimization again.

Conclusion

The three tools agree that a model can read failures and write a better prompt, and the choice between them is the search around that step: one prompt overwritten, one prompt gated by validation, or a pool in which a prompt that is good at one thing survives until its lesson can be used. Whichever you pick, the optimizer is fitting your examples with your models, so the result is as good as the examples, the feedback and the test set you kept out of its reach.

I’ve left some more links in the references for whoever is curious.

References:

We want to work with you. Check out our Services page!

We want to work with you

The engineers who write here are the same ones who join client teams. Let’s build something that grows with your business.

Book a call