Core Guides

Evolve a harness: the GEPA example

GEPA improves the instruction texts of a program by reflection. On Reef, the program is an agent's harness tree, and the texts are its rules, skills and commands. In each iteration GEPA takes one tree that it made before, the parent. It shows a model how the parent did on a few tasks, and the model rewrites one text. GEPA accepts the new tree, the child, when it scores higher than the parent on those tasks. An accepted child then runs every evaluation task. This is GEPA's validation pass. The child serves when its mean score is above the served tree's.

This page shows the four classes of the GEPA recipe (recipes/gepa/). Write a recipe defines each class.

The ideas of GEPA at the steps of the loop. The agent runs a task with the served tree and reports the run with its score. Control: the report is the default report type. Samples: TraceSamples makes one trace of the run and its score. Control: jobs.py makes one job of one minibatch. Training, in job N: GEPA.run reflects on the minibatch and accepts a child that beats its parent. Evaluation, in the same job N: evaluation.py runs the validation pass and keeps the child by the mean score. Control commits the tree when it is kept, and the agent pulls it. Training, in job N+1: archive_for_job updates the archive and its Pareto fronts with the validation scores of job N. The ideas of GEPA at the steps of the loop. The agent runs a task with the served tree and reports the run with its score. Control: the report is the default report type. Samples: TraceSamples makes one trace of the run and its score. Control: jobs.py makes one job of one minibatch. Training, in job N: GEPA.run reflects on the minibatch and accepts a child that beats its parent. Evaluation, in the same job N: evaluation.py runs the validation pass and keeps the child by the mean score. Control commits the tree when it is kept, and the agent pulls it. Training, in job N+1: archive_for_job updates the archive and its Pareto fronts with the validation scores of job N.

The four classes of GEPA #

A recipe is four classes. GEPA writes two of them, the algorithm and the evaluation, and takes two from Reef. It also writes a jobs class, which arranges the samples of a job:

Attribute

GEPA's class

Written by

What it does in GEPA

report

ScoredRolloutReport

Reef

A report holds the score of one run of the served tree

samples

TraceSamples, with MinibatchJobData for the data of a job

Reef, and GEPA for the jobs class

One reported run becomes one trace: a task, a reply and a score. One job holds one minibatch: minibatch_size traces

algorithm

GEPA

GEPA

run(job) selects a parent, asks a model to rewrite one text of it, and accepts the child when it beats the parent on the minibatch

evaluation

ValidationMeanPolicy

GEPA

It runs the child on every evaluation task, and keeps the child when its mean score is above the served tree's

The recipe class names them (recipe.py):

Python
# control: a report holds the score of one run of the served tree, and names the run by its references.
report = ScoredRolloutReport
# samples: one reported run becomes one trace with its score: one example of a minibatch. The feedback text
# that reflection reads about the example is made later, in the job (feedback.py says why).
samples = TraceSamples
# samples, the data of one job: one minibatch. MinibatchJobData starts a job when minibatch_size runs wait,
# and the job holds exactly those runs.
jobs = MinibatchJobData
# training: GEPA.run makes the job's tree. It first folds the validation of the job before into the archive
# (the Pareto fronts). Then it samples a parent from the fronts, reflects on the minibatch to rewrite one
# component of the parent, and accepts the child only when it scores strictly higher than the parent on the
# minibatch.
algorithm = GEPA
# evaluation: GEPA's validation pass, in the same job after GEPA.run. ValidationMeanPolicy scores the child on
# every evaluation task and keeps it when its mean score is above the served tree's.
evaluation = ValidationMeanPolicy

Reef calls the classes in this order. The names are short for the real ones:

Text
# control, for each report of a run
report = ScoredRolloutReport.from_dict(body)                 # 1. report

# samples service, for each stored report
trace = TraceSamples.make_sample(context)                    # 2. samples

# control, when minibatch_size traces wait
data = MinibatchJobData.make_job_data(traces, data_id)       #    samples, the data of a job

# training service, job N
GEPA.run(job)                                                # 3. algorithm: leaves the child as the job's tree
evaluation = ValidationMeanPolicy.evaluate(child)            # 4. evaluation: the validation pass
decision = ValidationMeanPolicy.decide(child, evaluation)    #    keep the child?

# training service, job N+1
GEPA.run(job)                                                # 3. first reads the scores of job N

In a harness job, the method makes a tree, and then the policy evaluates it. So GEPA.run reads the scores of its validation pass when the next job starts.

1. The report (control) #

Class: ScoredRolloutReport (scored_rollout.py), a class that Reef has.

Implements: one field, score (definition).

GEPA learns from runs of the served tree on training tasks. A client pulls the tree, runs a task with it through Reef, and reports the run with its score. The report names the model calls of the run in references. Control refuses a report without a score.

2. The samples (samples service) #

Class: TraceSamples (traces.py), a class that Reef has.

Implements: make_sample(context) (definition).

GEPA needs each run as one example of a minibatch. TraceSamples makes one sample of each report: the calls that the report references, as Reef served them, with the reported score. The method reads the sample as a trace: a task, a reply and a score. Reflection also reads a feedback text about each example. The method makes that text in the job, in step 5 of run; feedback.py says why.

The data of a job: one minibatch #

Class: MinibatchJobData (jobs.py), written by GEPA. It is the attribute jobs, the second step of the samples.

Implements: the constructor. It keeps the make_job_data(samples, data_id) of Reef's TraceJobData (definition).

A GEPA iteration compares a parent and its child on one minibatch, so a job must hold exactly one minibatch. TraceJobData, the jobs class that a harness recipe has by default, starts a job for each trace. MinibatchJobData starts a job when job_samples traces wait, and the job holds exactly those traces. Its constructor gives that one size to TraceJobData twice, as the most traces that a job takes and as the fewest:

Python
super().__init__(
    context, job_samples, job_samples, max_job_samples=max_job_samples, evaluation_split=evaluation_split
)

A deployment sets the size once, as minibatch_size in the method's config. The default is 3. GEPARecipe.stages gives that value to the jobs class as job_samples.

3. The algorithm (training): one GEPA iteration #

Class: GEPA (algorithm.py), written by GEPA.

Implements: run(job) (definition).

GEPA needs a search that continues from job to job. It keeps the search in one file of the method's state, state/archive.json, which Reef commits with each job. The archive holds every candidate: the texts of one tree that GEPA accepted, with its validation scores, one for each evaluation task (evolution.evaluation.tasks).

run has seven steps, and the code has a comment for each one.

Step 1: the archive update of the job before. The archive that the last job committed can hold a pending candidate: an accepted child without validation scores. The policy of section 4 scored that child after run returned. So run now reads the policy's decision and the scores of both trees from the scenario's history (archive_for_job). Archive.settle gives the pending candidate its validation scores. When the policy kept the child, the candidate becomes the served one (archive.py):

Python
pending = self.pending
if pending is not None:
    self.record_validation(pending, candidate_scores)
    self.charge(len(candidate_scores) * repeats)
if self.served is not None and self.candidates[self.served].val_scores is None:
    self.record_validation(self.served, served_scores)
if selected and pending is not None:
    self.served = pending
self.clear_pending()

Step 2: the budget. Each scored run is one metric call. The search stops when the archive has spent its budget, max_metric_calls:

Python
if settings.max_metric_calls is not None and archive.metric_calls >= settings.max_metric_calls:
    reason = f"the budget of {settings.max_metric_calls} metric calls is spent"
    return self.finish(workspace, archive, reason, {"stopped": reason})

The archive counts the validation of the first tree, each minibatch of a parent and of a child, and the validation of each accepted child.

Step 3: a parent from the Pareto front. For each evaluation task, the front holds the candidates with the best score on that task. Archive.select_parent first drops each candidate that other candidates cover on all its fronts. It then samples one of the others from a list. A candidate is in the list once for each front that holds it, so a candidate on more fronts is more likely:

Python
survivors = remove_dominated(self.fronts(), [self.mean_val(index) for index in range(len(self.candidates))])
frequency: dict[int, int] = {}
for task in sorted(survivors):
    for index in sorted(survivors[task]):
        frequency[index] = frequency.get(index, 0) + 1
sampling = [index for index, count in frequency.items() for _ in range(count)]

A candidate that is the best on one task only can thus still be a parent.

Step 4: the minibatch. The job's traces are runs of the served tree. When the parent is the served candidate, the traces are the parent's minibatch, and the job starts no run. Another parent runs the same tasks in the job (GEPA.minibatch):

Python
if parent == archive.served:
    archive.charge(len(traces))
    return [
        Example(task, trace.reply or "", 0.0 if trace.score is None else trace.score, trace.failure or "")
        for task, trace in traces
    ]
tasks = [task for task, _ in traces]
task_runs = services.evaluate(candidate_tree(head, archive.candidates[parent].texts), tasks)
archive.charge(len(task_runs))

services.evaluate is Reef's: it runs a tree on tasks with the worker pool and the scorer of the deployment's evaluation.

Step 5: the reflective mutation. The method takes one text of the parent: a file of the tree with rules, a skill or a command. The texts of a candidate take turns. A reflection model reads that text and one record for each example of the minibatch, and writes a new text:

Python
prompt = render_prompt(parent_texts[component], reflective_dataset(minibatch, self.feedback))
reflection = services.models.get(settings.reflection_model, services.models.served)
reply = reflection.chat([{"role": "user", "content": prompt}])
new_text = extract_new_text(reply)

The reflection model is the model that the deployment declares as evolution.models.reflection. Without it, the served model reflects. The prompt is GEPA's own (reflection_prompt.md). A record holds the task, the reply and a feedback text (feedback.py):

Python
return [
    {
        INPUTS_KEY: example.task,
        OUTPUTS_KEY: example.output,
        FEEDBACK_KEY: example.error or feedback.feedback(example.task, example.output, example.score),
    }
    for example in minibatch
]

The feedback text is the whole signal that reflection gets. The default Feedback class only restates the score. A deployment that can say why an answer is wrong names its own class in evolution.method.config.feedback.

The child is the served tree with the child's texts in place of its own:

Python
child_texts = {**parent_texts, component: new_text}
child = candidate_tree(head, child_texts)

Step 6: the acceptance on the minibatch. The child runs the tasks of the minibatch, with services.evaluate. The method accepts the child only when the sum of its scores is strictly higher than the parent's:

Python
parent_total, child_total = sum(record["parent_scores"]), sum(child_scores)
if child_total <= parent_total:
    # The one ending GEPA counts as a spent iteration: a child that lost the minibatch comparison.
    archive.reject()
    archive.log_proposal(record)
    summary = f"the child scored {child_total:g} on the minibatch and its parent {parent_total:g}"
    return self.finish(workspace, archive, summary, record)

record is the record of the iteration: the parent, the text that changed, and the scores of both sides. It goes into the archive and into the job's notes. After a rejected child, run leaves the tree as it was, and Reef skips the job: the job has no evaluation and no new version.

Step 7: the candidate. An accepted child joins the archive as the pending candidate, and it becomes the tree of the job:

Python
record["accepted"] = True
record["candidate"] = archive.add(child_texts, parent, child_scores, workspace.step)
archive.log_proposal(record)
workspace.write_tree(child)

Every ending of run writes the archive to state/ (GEPA.finish).

4. The evaluation (training, after the method): the validation pass #

Class: ValidationMeanPolicy (evaluation.py), written by GEPA.

Implements: setting_defaults. It keeps the decision of Reef's ComparePolicy, an Evaluation that reads the scores of the child and of the served tree (definition).

GEPA needs a validation pass, so that the tree with the highest mean score on the evaluation tasks serves. When run leaves a child, the training service calls the policy in the same job. evaluate runs the child on every evaluation task. The scores of the served tree usually come from the score cache of the scenario's history. decide keeps the child when its mean score is above the served tree's.

The class is ComparePolicy with one fixed setting, the statistic:

Python
setting_defaults = MappingProxyType({"statistic": MEAN})

def __init__(self, evaluator: HarnessCandidateEvaluator, *, statistic: str = MEAN, min_margin: float = 0.0):
    self.check_statistic(statistic)
    super().__init__(evaluator, statistic=statistic, min_margin=min_margin)

ComparePolicy.decide compares the two means (policy.py):

Python
metrics.update({"candidate_mean": candidate_mean, "current_mean": current_mean})
selected = candidate_mean - current_mean > self.min_margin

A child that the policy rejects still gets its validation scores in the archive, in step 1 of the next job, and can be a parent.

Control commits a kept tree as a new version. With the default activation rule the version serves, and a client pulls it with GET /reef/harness.

Run it #

The example runs GEPA on AIME math problems, as the GEPA project's own example does: it evolves the system prompt of a pi agent, rules.md. It needs no GPU. It needs:

  • the pi harness, version 0.84.2, as REEF_PI_BINARY;

  • OPENAI_API_KEY. A live run calls two paid models: gpt-4.1-mini-2025-04-14 solves the problems, and gpt-5-2025-08-07 reflects;

  • network access to Hugging Face, where the driver loads the AIME problems.

The driver, run.py, takes the place of reef serve. It loads the deployment file and starts a Reef server in its own process. The driver is also the client: it runs each minibatch as pi runs through that server, and reports each score.

The deployment file (gepa.yaml) selects the recipe. The recipe class names the method, the jobs class and the policy:

YAML
recipe:
  implementation: recipes.gepa.recipe:GEPARecipe

The file gives the settings of the method under recipe.config.evolution.method.config:

YAML
minibatch_size: 3
seed: 0
skip_perfect_score: true
perfect_score: 1.0
max_metric_calls: 150
# The evolvable parts of the tree. run.py appends "skill" under REEF_GEPA_MULTI=1.
components: [rules]
# The wording GEPA's own default evaluator writes into the reflective
# records, in the harness/ package.
feedback: harness.aime:AIMEFeedback

evolution.evaluation.scorer names the scorer of the example. evolution.evaluation.tasks is empty in the file: the driver fills it with the 45 validation problems.

Check the setup first. The dry run checks the pi version and the pinned problems, loads the recipe from the deployment file, and prints its plan as JSON. It calls no model:

Shell
cd recipes/gepa/examples/aime
uv pip install -e .
REEF_PI_BINARY=/path/to/pi ./run.sh --dry-run

Then run the search:

Shell
export OPENAI_API_KEY=...
REEF_PI_BINARY=/path/to/pi REEF_GEPA_WORKERS=4 ./run.sh

A live run is about 150 search runs and the validation passes, and then 300 test runs. REEF_GEPA_WORKERS is the count of runs at once; the default is 128 worker processes.

In each round, the driver pulls the served tree, runs the three problems of the minibatch, and reports the three scores. The third report starts the job. The driver prints one line for each round:

Python
print(f"round {step}: {calls}/{budget} metric calls, {len(search_archive.candidates)} candidates")

When the budget is spent, the driver scores the first tree and the served tree on 150 test problems. It prints both scores, and writes them with the validation means to work/summary.json.

The repository keeps the records of two runs of this recipe, with the seeds 0 and 1. The first tree scored 26.67% and 24.00% on the test problems, and the served tree 46.67% and 36.00%. Both runs predate the current driver. The AIME example compares them with the GEPA project's own optimizer.

Test it without a model #

The recipe's tests run whole jobs on Reef's harness backend with no model and no pi (test_gepa.py). A canned reply is the reflection model, and a script that answers with its rules is the agent.

Shell
python -m pytest tests/recipes/gepa/test_gepa.py -q

One test runs a GEPA iteration through its two jobs. A step of the test is one job. Job 1 accepts a child, and the policy keeps it. The archive that job 1 commits holds the child as the pending candidate:

Python
assert notes["accepted"] is True and notes["candidate"] == 1
# GEPA's count: the seed's validation (2 tasks), the served minibatch (1, from the traces) and the child's (1).
assert notes["metric_calls"] == 4
# The child is the step's candidate, and its validation mean beats the seed's.
assert first.metrics["selected"] is True and first.metrics["patch"] == {"rules.md": REFLECTED}
archive = archive_of(first)
assert (archive.pending, archive.pending_step) == (1, 1)

Job 2 starts with the archive update. The child gets its validation scores and becomes the served candidate:

Python
artifacts.publish("r1", HarnessTree.read(first.artifact.local_path))
second = step(backend, 2, first.state, sample("a2", 1.0))
# The next step folds the validation in from the history; the task that could not run is a zero, not a gap.
settled = archive_of(second)
assert (settled.served, settled.pending) == (1, None)
assert (settled.candidates[1].val_scores, settled.candidates[0].val_scores) == ([1.0, 0.0], [0.0, 0.0])

test_gepa_fidelity.py runs the gepa package and this recipe from one seed, when the package is installed. It requires the same parents and candidates at each iteration. test_gepa_aime_harness.py tests the AIME example.

Other sources of runs #

Every harness recipe can also take its runs from these two sources.

Unscored traffic. Set pipeline.samples.module: reef.samples.traces:InferenceSamples: each model call becomes one trace without a score. To give explicit instructions, send a manual training request.

Uploaded tasks. To train and evaluate on Harbor task directories, set recipe.config.evolution.evaluation.imported_tasks: true with the scorer reef.evaluation.harness:VerifierRewardScorer, and name the jobs class reef.train.sample2job.traces:TrainTaskJobData in pipeline.sample2job.module. Upload the task directories with a train or eval assignment, evaluation tasks first. Reef runs each train task once, in upload order. Task directories need Docker and evolution.executor: local.

To check either source, GET /reef/harness/artifacts has a row for each job, and the page of a job shows its request, patch, metrics and result.

Review a tree before it serves #

The code of a tree runs with your privileges. To review each new version first, set activation.module: never and activate the versions that you accept. A version that does not serve shows active: false in GET /reef/scenarios/{scenario}/artifacts. evolution.state_dir holds the history of each scenario, with the runs and the traces of clients: protect it.

Limits #

  • Text parts only. GEPA rewrites the text files of the tree: the rules, the skills and the commands. components names the parts that it rewrites; the default is [rules, skill].

  • No merge. Each child comes from one parent by reflection. GEPA's merge of two candidates is not implemented.

  • The archive is one job behind. The last child of a search gets its validation scores in the archive only when one more job runs.

  • One policy and one job size. GEPARecipe accepts only the policy compare with the statistic mean, and only minibatch_size as the job size. For another policy or job size, use reef.recipe.harness:HarnessEvolutionRecipe with evolution.method: recipes.gepa:GEPA.

  • Traces that you trust. The reflection prompt holds the text of the traces as it is. Use traffic that you trust, or the never activation rule, so that a person activates each version.

Next steps #