Self-improving agents

GEPA: how it works, prompt optimization, implementation, and benefits

GEPA is an evolutionary prompt optimizer that uses written feedback and Pareto selection to rewrite prompts automatically. With just 20–100 examples it beats GRPO and MIPROv2.

Berca Akbayır

Member of Technical Staff7 min read

TL;DR

  • GEPA (Genetic-Pareto) optimizes prompts, tool schemas and agent rules as parameters, without touching model weights.
  • A reviewer model reads execution logs and written feedback on mistakes, then rewrites the instructions: revisions are reasoned, not random.
  • Pareto selection keeps versions with different strengths in play instead of only the best average.
  • It needs just 20–100 examples and matched GRPO (24,000 runs) with only 243–1,179 runs.
  • ~12% gain vs ~6% for MIPROv2 on GPT-4.1 Mini, with prompts up to 9.2x shorter and therefore cheaper on every call.
  • The output is readable, portable plain text, reusable when you switch models.
  • It's built into DSPy (`dspy.GEPA`) and MLflow. The key ingredient is a metric that explains errors in words.

Fundamentals of the GEPA algorithm

What is GEPA?

GEPA (Genetic-Pareto) is an evolutionary prompt and text optimization algorithm used in AI frameworks. It combines evolutionary optimization with multi-objective Pareto selection to systematically improve prompts while maintaining diversity across different problem types.

The role of GEPA in modern AI

In modern AI engineering, GEPA shifts teams away from manual prompt writing and costly model training toward self improving software systems. Instead of treating prompts as static text, GEPA treats instructions, tool schemas and agent rules as parameters that a machine can optimize automatically.

Adapting an LLM to a specialized business domain usually requires supervised fine tuning or reinforcement learning. Those methods demand tens of thousands of labeled examples, expensive GPU clusters and constant maintenance.

GEPA achieves equal or better accuracy using roughly 20 to 100 examples because it learns from rich text logs rather than simple numbers. Since the resulting prompts are plain text, teams can migrate to newer models without retraining weights.

GEPA has moved beyond academic research to become a core engine inside major developer tools. In DSPy, it acts as a primary compiler that tunes modular AI programs automatically.

Enterprise platforms like MLflow also integrate GEPA into prompt registries for LangGraph, LangChain and the OpenAI Agents SDK. Developers can version, test and optimize text artifacts across their entire stack using one standard workflow.

GEPA prompt optimization mechanisms

How does GEPA work?

A prompt is the set of written instructions that tells an AI model how to perform a task. GEPA (Genetic Pareto) is a method that improves these instructions automatically, in much the same way an editor improves a draft through repeated rounds of review and revision. Reported gains over GRPO average 6% with up to 35 times fewer trial runs while gains over MIPROv2 exceed 10%, both being established alternatives.

-

The available examples are divided once into practice tasks used for revision and a separate set of exam tasks on which every version in the pool is graded. GEPA does not simply keep the single version with the best average grade. A version is more likely to be picked for further revision the more exam tasks it handles better than any other, so versions with different strengths all remain in play.

Reflective prompt refinement

The distinctive feature of GEPA is that revisions are reasoned and not random. A second AI model acts as a reviewer that reads the current instructions together with a record of what the system did, the grade it received and written comments on its mistakes, then proposes improved instructions. GEPA can also combine two successful versions into one so that the strengths of both are retained.

As an illustration, consider an assistant that summarises customer emails. If the comment reads "the summary left out the delivery date the customer asked about", the reviewer may add the rule "always state any dates or deadlines mentioned in the email".

Execution feedback loops

The quality of each revision depends on the quality of the feedback. Written comments drawn from logs, automated checks or an AI judge let the reviewer understand why a grade was low and not merely that it was low. This is comparable to a teacher who explains each error instead of returning only a mark, which is why GEPA needs relatively few trials to improve.

Every revision must also prove itself before it is kept. A new version joins the pool only if it performs better on the same practice tasks that exposed the weaknesses of its predecessor, after which it is graded on the exam tasks. This simple check discards unhelpful changes early and ensures that the pool improves steadily.

Implementing the GEPA optimizer in DSPy

Configuration of DSPy modules with GEPA

DSPy is a framework in which an AI application is written as a program made of modules, each carrying its own instructions. GEPA is available there as a built in optimizer that takes such a program and returns a copy with improved instructions, leaving the program logic untouched. The configuration requires four ingredients, namely the program, a metric, a reflection model and two sets of examples.

-

The metric is the most important element of the setup because it supplies the written comments on which reflection depends. In DSPy it is an ordinary function that receives the expected answer and the produced answer and hands back a score with optional text feedback. The documentation advises assigning a stronger model to reflection than to the task itself, since the reviewer is consulted only a few times and its cost stays modest.

The example below configures GEPA for the email summariser introduced earlier. The model names are placeholders and should be replaced with the models in use.

Python
import dspy

# 1. Model that performs the task
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))

# 2. Program to be optimised
summariser = dspy.ChainOfThought("email -> summary")

# 3. Metric that returns a score and written feedback
def metric(gold, pred, trace=None, pred_name=None, pred_trace=None):
    missing = [d for d in gold.dates if d not in pred.summary]
    if missing:
        return dspy.Prediction(
            score=0.0,
            feedback=f"The summary omits these dates {missing}.",
        )
    return dspy.Prediction(score=1.0, feedback="All dates are present.")

# 4. Optimiser with a stronger model as reviewer
optimizer = dspy.GEPA(
    metric=metric,
    reflection_lm=dspy.LM("openai/gpt-4o"),
    auto="light",
    num_threads=4,
)

# 5. Run the optimisation and save the result
optimised = optimizer.compile(summariser, trainset=train, valset=val)
optimised.save("summariser_gepa.json")

Two settings govern cost and reliability. The auto budget controls how many versions are tried, with "light" covering roughly six candidates and "medium" or "heavy" extending the search. Most examples should go to the training set while the validation set stays small but representative, and leaving it out makes GEPA grade on the training data, which risks overfitting.

A final test set that played no part in either revision or grading should be held back to report performance on unseen data. One note on the source is that the referenced page does not show the task model setup, so step 1 follows standard DSPy usage.

Practical benefits of GEPA optimization

  1. Efficiency: Because every trial yields written feedback and not only a grade, GEPA learns from far fewer attempts than methods that retrain the model itself. In the original experiments it matched the best validation scores of GRPO, a reinforcement learning baseline given 24,000 trial runs, with only a few hundred to roughly 1,200 runs depending on the task.
  2. Quality: Across every benchmark and model tested GEPA surpassed MIPROv2, with an aggregate improvement of about 12% on GPT 4.1 Mini against roughly 6% for that optimizer. It achieves this by refining the instructions alone, without attaching worked examples to the prompt.
  3. Cost Reduction: The resulting prompts were about 33% shorter on average than the example laden prompts of MIPROv2 and up to 9.2 times shorter in the best case. A shorter prompt is cheaper and faster on every subsequent call, so the saving accumulates for as long as the system is in use.
  4. Portability and Transparency: The output is plain text that a person can read, audit and edit, and it requires no access to the internal parameters of the model. Prompts tuned on the small open model Qwen3 8B also raised the performance of GPT 4.1 Mini by 9% on average, which suggests that an optimised prompt can be reused when the underlying model changes.
-

FAQs

What is GEPA in LLM development?

GEPA in LLM development is an automatic prompt optimizer whose name stands for Genetic Pareto. It improves the written instructions of an AI system by running the system, reviewing what went wrong and rewriting the instructions over repeated rounds. Any AI system that contains one or more LLM prompts can be optimised with it.

How does the GEPA optimizer avoid reinforcement learning?

The GEPA optimizer avoids reinforcement learning by leaving the model itself unchanged and editing only the text of its prompts. Reinforcement learning adjusts the internal parameters of a model through thousands of scored trials, whereas GEPA asks a second model to read the record of each trial and explain in plain language how the instructions should improve. This is why it reached the best validation scores of the GRPO reinforcement learning baseline, which was given 24,000 trial runs, with as few as 243 to 1,179 runs.

Can GEPA optimize code generation tasks?

Yes, GEPA can optimize code generation tasks and the original paper presents early evidence of this. Compiler errors, test results and performance measurements serve as the written feedback that guides each revision of the code. On the NPUEval benchmark this approach lifted mean vector utilisation from 4.25% to 30.52%, although the authors themselves label these findings as preliminary.

How does GEPA compare to other DSPy optimizers?

GEPA compares favourably to other DSPy optimizers in accuracy, prompt length and the amount of data it needs. Optimizers such as MIPROv2 search over combinations of instructions and worked examples guided by scores alone, while GEPA rewrites the instructions based on written feedback about specific failures. The paper's experiments on GPT 4.1 Mini show an aggregate gain of roughly 12% for GEPA against about 6% for MIPROv2, with prompts up to 9.2 times shorter. The trade off is that GEPA requires a metric able to explain errors in words, which the other optimizers do not need.