More Guides

Evolve a harness: the ReasoningBank example (memory)

ReasoningBank gives an agent a memory that the agent builds from its own runs, without ground truth. After each run, a model judges whether the run succeeded. A model then writes short memory items from the run: strategies from a success, and lessons from a failure. On a later task, the agent reads the items that fit the task. On Reef, each memory item is one skill of the agent's harness tree.

This page shows the four classes of the ReasoningBank recipe. Write a recipe defines each class.

The ideas of ReasoningBank at the steps of the loop. The agent runs a task and calls the model through Reef. Inference stores each call. Samples: samples.py makes one sample of a finished run; no client reports. Control: one run is one job, the default job data. Training: algorithm.py labels the run with the judge and extracts memory items with the extractor, and memory.py writes one skill for each item. Evaluation: the default policy keeps the tree, and no task runs. Control commits the tree. The agent pulls the tree, and opens the skills that fit its task. The ideas of ReasoningBank at the steps of the loop. The agent runs a task and calls the model through Reef. Inference stores each call. Samples: samples.py makes one sample of a finished run; no client reports. Control: one run is one job, the default job data. Training: algorithm.py labels the run with the judge and extracts memory items with the extractor, and memory.py writes one skill for each item. Evaluation: the default policy keeps the tree, and no task runs. Control commits the tree. The agent pulls the tree, and opens the skills that fit its task.

The four classes of ReasoningBank #

A recipe is four classes. ReasoningBank writes two of them, and takes the other two from Reef:

Attribute

ReasoningBank's class

Written by

What it does in ReasoningBank

report

ScoredRolloutReport

Reef

It parses a report that holds a score. The example sends no report.

samples

RunSamples

ReasoningBank

It makes one sample of each finished run. Each sample starts one job, so one run is one job.

algorithm

ReasoningBank

ReasoningBank

It labels each run, extracts memory items from the run, and writes each item as one skill of the tree.

evaluation

NoEvaluationPolicy

Reef

It keeps every tree that passed validation. No task runs.

The recipe class names the four classes (recipe.py). In its comments, a step is one job:

Python
# control: what a report holds. The method needs no report: it learns from the recorded model calls. A
# deployment whose clients report a score for each run names reef.samples.traces:TraceSamples in
# pipeline.samples; a report then holds the score of the run that its references name.
report = ScoredRolloutReport
# samples: what the traffic becomes. RunSamples.make_samples makes one unscored trace sample of each model
# call that ends a run, and none of a call in the middle of a run. It gives the run no label: see algorithm.
# Each sample starts one job, so one finished run makes one step: the paper extracts the memory items when a
# task is completed. recipe.jobs.job-samples sets more runs.
samples = RunSamples
# training: ReasoningBank.run makes the step's tree. It labels each run a success or a failure (by its score,
# else by a judge model), extracts memory items from the run, screens them, consolidates the bank, and writes
# each item of the bank as one skill.
algorithm = ReasoningBank
# evaluation: every tree that passes validation is kept, and no task runs. The paper adds new items to the
# memory with "a simple addition operation", without a check of an item before it is kept.
evaluation = NoEvaluationPolicy

The class subclasses HarnessEvolutionRecipe. So the algorithm is a HarnessAlgorithm, which edits the tree, and the evaluation, an Evaluation as for weights, decides whether the job keeps the edited tree (A recipe that evolves a harness).

1. The report (control): no report is needed #

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

Implements: the field score (definition).

ReasoningBank learns from the model calls of a run. The agent calls the model through Reef, and inference stores each call. The example sends no report. The recipe keeps the report class of HarnessEvolutionRecipe for a deployment whose clients report a score for each run (Configuration).

2. The samples (samples service): one run, one sample #

Class: RunSamples (samples.py), written by ReasoningBank.

Implements: make_samples(record_set) (definition).

ReasoningBank needs one sample for each finished run. An agent sends one model call for each turn of a run, and each call holds the transcript before it. So the call that ends with a final reply holds the whole run, and a call that ends with a tool call is the middle of a run.

The class reads the model calls and no report. Its base class is thus InferenceSamples, and Reef calls make_samples once for each stored model call:

Python
sample = make_trajectory((record_set.record,))
if prompt_of(sample) is None or not reply_of(sample):
    return SampleResult.skipped()
return SampleResult.ready((sample,))

prompt_of is the last user message of the call, and reply_of is its final reply. A call with both makes one sample: the whole run. Every other call makes no sample. The sample has no score and no label: the algorithm labels the run.

The data of a job. The paper extracts the memory items when a task is completed. The recipe keeps the default of a harness recipe (definition): a job holds its samples as they come, and the default job size is 1. Each finished run thus starts one job. To learn from more runs in one job, set recipe.jobs.job-samples.

3. The algorithm (training): runs become memory items #

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

Implements: run(job) (definition).

One job turns its runs into memory items. An item has a title, a description and a content. The memory is in two places, which change together:

  • The bank is the file state/memory.json of the method's state: the items, oldest first. The next job reads it.

  • The skills are in the tree, one file for each item: skills/rb-<slug>/SKILL.md. The agent reads them.

run reads the bank from the state and the runs from workspace.traces(). Then it does four steps for each run. The comments count from 2, because step 1 chooses the runs:

Python
for trace in runs:
    text = trace_text(trace)
    try:
        # 2. Label the run a success or a failure: by its score, else by the judge model. The label is the
        #    samples service's concern; label() says why it stays in the method.
        outcome = self.label(trace, text, judge)
        outcomes[outcome] += 1
        # 3. Extract: the extractor model writes the memory items of the run, at most max_items_per_trace.
        items = self.extract(text, outcome, bank, extractor, step=workspace.step)
    except ReplyError as error:
        skipped.append({"record": trace.record, "reason": str(error)})
        continue
    # 4. Screen: an item with a credential or an instruction override stays out of the bank.
    safe = screen(items)
    skipped.extend({"record": trace.record, "reason": SCREEN_REFUSAL} for _ in range(len(items) - len(safe)))
    # 5. Consolidate: an item replaces the bank's item of the same slug, so the next run's extractor reads
    #    the new titles.
    bank = consolidate(bank, safe)
    learned.extend(item.slug for item in safe)
  • Label. A run with a score of at least success_score is a success. The judge model labels a run without a score, from the run alone (judge.md). The judge is a model of the job, services.models, and that is why the job makes the label.

  • Extract. The extractor model writes strategies from a success and lessons from a failure (extract.md). The prompt lists the titles of the bank, so the extractor can use a title again to replace that item.

  • Screen. The tree is served to every session, so an item with a credential or an instruction override stays out of the bank.

  • Consolidate. The slug of an item comes from its title. A new item replaces the bank's item with the same slug, or else joins the end of the bank. At the end of the job, the bank keeps its newest max_items items.

A reply of the judge or of the extractor that is not the asked JSON skips its run.

The last step writes the bank as the skills of the tree:

Python
candidate = skills_tree(workspace.tree(), bank)
validation = services.check(candidate)
if not validation.passed:
    summary = f"the memory skills fail validation, so the bank stays as it was: {validation.message()}"
    workspace.write_output(summary, {**notes, "problems": list(validation.problems)})
    return
workspace.write_tree(candidate)
write_bank(bank_path, bank)

skills_tree makes the skills/rb-* skills of the tree exactly the items of the bank, and keeps every other file of the tree. services.check validates the new tree for the agent's harness. Only a tree that passes is written, with its bank, so the next job starts from a bank that can be served.

MemoryItem.skill writes the file of one item (memory.py): a header with the name and the description, then the title and the content:

Python
header = yaml.safe_dump(
    {"name": SKILL_PREFIX + self.slug, "description": self.description},
    sort_keys=False,
    allow_unicode=True,
    width=4096,
)
return f"---\n{header}---\n\n# {self.title}\n\n{self.content}\n"

4. The evaluation (training, after the method): every valid tree is kept #

Class: NoEvaluationPolicy (policy.py), a class that Reef has.

Implements: accepts(scores), with no sides (definition).

The paper adds new items to the memory with "a simple addition operation". So ReasoningBank names the policy that keeps every tree that passed validation. The training service calls the policy in the same job, after run returns. No task runs, so the deployment needs no evaluation tasks and no scorer.

Control commits the tree as a new version. With the default activation rule the version serves, and a connected client installs it at the start of its next session.

What the agent loads: retrieval #

The agent's harness lists the name and the description of each skill to the agent, and the agent opens the skills that fit its task. The description of an item is thus the key by which the agent finds it. So the extractor's prompt asks for one sentence that tells when the item applies: the type of task or situation.

The paper retrieves the most similar items by embedding, and puts them into the system prompt.

Run it #

The example learns from the live sessions of pi clients. It needs:

  • an OpenAI-compatible model endpoint. The example expects qwen3-8b at http://127.0.0.1:8000, with its key in REEF_UPSTREAM_API_KEY. Edit the inference section of the file for another model;

  • the pi harness on the host of each client.

The deployment file selects the recipe and sets the options of the method (serve.yaml). The recipe class names the four classes, so the file names none of them:

YAML
recipe:
  implementation: recipes.reasoning_bank.recipe:ReasoningBankRecipe
  config:
    evolution:
      adapter: pi
      method:
        config:
          # The served model judges and extracts, as in the paper. To use another model, declare it under
          # evolution.models (url, model, api_key_env) and give its name here.
          judge_model: served
          extract_model: served
          max_items_per_trace: 3
          max_items: 50
      state_dir: .reef/reasoning-bank/harness

Start Reef from the repository root:

Shell
reef serve -c recipes/reasoning_bank/examples/serve.yaml

Connect a pi client in a second terminal. The command installs the served tree and makes the pi command run through Reef (A coding agent):

Shell
reef-client harness connect --reef http://127.0.0.1:8900

Then work with pi. Each call that ends with a final reply starts one job. The job makes at most two model calls for the run: one to the judge and one to the extractor. A job that changes the bank makes a new version, whose skills/rb-* skills are the bank.

To check it, read GET /reef/harness/artifacts. It lists the versions and the jobs that made none, and each row names its page (page_path). The page of a job shows its patch and the summary that run writes:

Python
summary = (
    f"learned from {len(runs)} run(s) ({outcomes['success']} success, {outcomes['failure']} failure); "
    f"{len(notes['added'])} item(s) added, {len(notes['replaced'])} replaced and {len(dropped)} dropped; "
    f"the bank holds {len(bank)}"
)

Test it without a model #

The tests run in memory, with canned replies for the judge and the extractor:

Shell
python -m pytest tests/recipes/reasoning_bank -q

One test sends the two model calls of one run through every service, with the deployment file of the example (test_reasoning_bank_recipe.py). These are its checks:

Python
# training: the job labels the run with the judge, and writes the extractor's item as a skill.
notes = step.metrics["method_notes"]
assert (notes["traces"], notes["runs"], notes["judged"], notes["added"]) == (1, 1, 1, ["run-the-tests"])
assert (len(judge.prompts), len(extractor.prompts)) == (1, 1)
assert list(step.metrics["patch"]) == ["skills/rb-run-the-tests/SKILL.md"]
# evaluation: the tree is kept without a task run.
assert (step.metrics["selected"], step.metrics["selection"]["policy"]) == (True, "none")
assert step.metrics["evaluation_task_count"] == 0

Two calls and no report give one sample, one job, one call to each model, and one new skill in a tree that Reef keeps. test_reasoning_bank.py tests each step of run alone.

Limits #

  • The recipe differs from the paper. The agent chooses the items from the skill list, an item with a known title replaces the old item, and the bank has a size limit. The README lists every difference.

  • A long run loses its middle. The judge and the extractor read at most 30,000 characters of one run.

  • The bank keeps what a policy rejects. With the policy compare or floor, the bank keeps the items of a job whose tree the policy rejected, and each job proposes the whole bank again.

  • No measured results. The repository holds no measured result of this recipe.

Next steps #