Use Reef ======== Reef sits between an agent and its model. It records each model call, takes your feedback on the call, trains the model on that feedback, and serves the new version on the same endpoint. .. figure:: ../assets/reef-loop-light.svg :alt: One model call and its report through Reef. The agent calls the model, and inference answers, stores the call and returns its receipt. The agent reports on the run. Control checks the report, samples makes samples, control makes a job, training trains it, and control commits the new version. With the activation rule evaluated, evaluation scores the version on tasks. Control activates the version by the activation rule, and inference serves it. This page takes one workload through the whole loop. You will: #. start Reef with a recipe; #. call the model through Reef; #. report on the call; #. run the whole loop, and watch Reef train and serve a new version; #. read the versions and choose which one serves; #. change the settings; #. use the loop for your own workload: your agent, your model, your recipe. Before you start ---------------- You need a `Reef checkout <../getting-started/installation.rst>`__. Reef itself needs no GPU: what else you need depends on what Reef improves. - **The model's weights**, as on this page. You need one of these: - Two GPUs: one serves the model (inference), and the other trains it. They run inside the `Reef GPU image <../getting-started/installation.rst#build-the-gpu-image-for-weight-training>`__, with ``Qwen/Qwen2.5-1.5B-Instruct`` in ``~/models/``. The steps below use this path. - A Tinker API key, on a host without GPUs. Step 1 gives the commands that differ. - **The agent's harness**, such as the rules and the skills of a coding agent. You need only a model endpoint, and no GPU. The loop is the same; `Update a coding agent's rules `__ runs it. - **Nothing yet.** The `quickstart `__ records calls and reports with a hosted model, and trains nothing. The example of this page ------------------------ This page walks through one example that is in the repository: the recipe with the name ``minimal``, in `recipes/minimal/ <../../recipes/minimal/README.md>`__. It is a real recipe, not a placeholder: it fine-tunes the model on the runs that pass your own check. The example has three parts. The page shows the core lines of each, and each file holds the complete code. .. list-table:: :header-rows: 1 * - Part - File - What it is * - The recipe - `recipes/minimal/recipe.py <../../recipes/minimal/recipe.py>`__ - The training method: a Python class that names what each Reef service does. About 40 lines, with its report type and its samples class in two files beside it. * - The deployment file - `examples/slime/serve.yaml <../../recipes/minimal/examples/slime/serve.yaml>`__ - What Reef runs: the model, the recipe, the training backend and the storage. * - The client - `examples/client.py <../../recipes/minimal/examples/client.py>`__ - Your side: about 60 lines that call the model through Reef and report on each run. The recipe class names four classes, one for each step of the loop that the recipe defines (`Write a recipe <../developer-guide/write-a-recipe.rst>`__ defines each one): .. code:: python # control: what a report holds. Control refuses a report that this type does not parse. report = RunReport # samples: what a report becomes. The samples service calls PassedRuns.make_sample once for each report. samples = PassedRuns # training: the built-in sft algorithm. Every job trains, with cross-entropy on each reply of the model. algorithm = "sft" # evaluation: every new version serves at once. The deployment's activation section can name another rule. evaluation = AlwaysActivate The deployment file selects that class by its module and name, and sets two of its settings: .. code:: yaml recipe: implementation: recipes.minimal.recipe:MinimalRecipe samples: # A run trains when its check scores it 1 or more. min-score: 1.0 jobs: # A job starts when four runs that passed wait: one optimizer step. job-samples: ${training.config.global_batch_size} - ``implementation`` is ``:``: the class ``MinimalRecipe`` of the file ``recipes/minimal/recipe.py``. To use another recipe, name another class here. - ``samples`` and ``jobs`` configure the classes that the recipe names in ``samples`` and ``jobs``. The client is the other side of the loop. Its core is two calls: .. code:: python body, receipt = client.inference_with_record(SCENARIO, "/v1/chat/completions", request) .. code:: python client.report(SCENARIO, {"score": score}, references=[receipt]) Reef does the rest: it trains the model on the reported runs, and serves the new version. 1. Start Reef with a recipe --------------------------- Start Reef with the deployment file of the example. It names the recipe ``minimal`` and a model: .. code:: bash hf download Qwen/Qwen2.5-1.5B-Instruct --local-dir ~/models/Qwen2.5-1.5B-Instruct export REEF_TOKEN=reef-local export REEF_MINIMAL_STATE_DIR="$PWD/work/minimal" reef serve -c recipes/minimal/examples/slime/serve.yaml ``reef serve`` starts the inference engine and the Reef services, and stays in the foreground. In a second terminal, check that Reef answers: .. code:: bash curl -f http://127.0.0.1:8900/healthz .. code:: text {"ok": true} Each section of the deployment file is for one part of Reef: - ``reef``: the address and the token of the Reef server. - ``inference``: the model, and the engine that serves it. Here one SGLang engine on one GPU. - ``recipe``: the training method and its settings. - ``training``: the backend that trains, and its options. Here Slime on the other GPU. - ``storage``: where Reef keeps the records and the versions. **On Tinker**, install the Tinker extra, give the key, and start the other deployment file of the recipe. Every later step is the same: .. code:: bash uv pip install -e '.[tinker]' -e ./third_party/reef-client export TINKER_API_KEY="..." export REEF_TOKEN=reef-local export REEF_MINIMAL_STATE_DIR="$PWD/work/minimal" reef serve -c recipes/minimal/examples/tinker/serve.yaml 2. Call the model through Reef ------------------------------ Steps 2 and 3 show the two calls that a client makes. Step 4 runs them in one script. A client first makes a **scenario**: one workload, with its own records, samples and versions. .. code:: python client.post("/reef/scenarios", SCENARIO, {"name": SCENARIO}) A model call is an OpenAI chat completion, sent to Reef: .. code:: python request = {"model": "active", "messages": [{"role": "user", "content": question}], "max_tokens": 64} body, receipt = client.inference_with_record(SCENARIO, "/v1/chat/completions", request) - ``model: active`` asks for the version that the scenario serves now. - Reef stores the call as a record. The **receipt** is the record's ID. Reef returns it in the response header ``x-reef-agent-record-id``. Any OpenAI-compatible client works the same way: see `Connect an agent `__. 3. Report on the call --------------------- A **report** tells Reef how a run went. It is one call, with the receipt and your feedback: .. code:: python client.report(SCENARIO, {"score": score}, references=[receipt]) - ``references`` names the run by the receipt of its last model call. For a run of several calls, reference only the last one: Reef finds the earlier calls from it. - ``score`` is your own judgment of the run, as a number. Here it is 1 for a correct answer and 0 for a wrong one. - The recipe decides what a report holds. The ``minimal`` recipe requires a ``score``. Another recipe takes a demonstration, or the reward of a task, and Reef itself requires no score. Each `recipe's page `__ gives its report. - Reef refuses a report that the recipe does not take. With the ``minimal`` recipe, a report without a score gets 400 and the message ``score is required``. 4. Run the whole loop --------------------- One call and one report do not train yet. In this deployment a job trains four runs (``recipe.jobs.job-samples``), and the ``minimal`` recipe trains only the runs that score 1. So the client sends runs until four have scored 1. This loop is the core of `client.py <../../recipes/minimal/examples/client.py>`__: .. code:: python passed, left = 0, 0 while passed < RUNS_OF_A_JOB: answer, receipt = ask(f"What is {left} + 2?") score = float(str(left + 2) in answer) report(receipt, score) print(f"{left} + 2 -> {answer!r}: score {score}") passed, left = passed + int(score), left + 1 - ``ask`` is the model call of step 2, and ``report`` is the report of step 3. - ``score`` is the client's own check: 1 when the answer holds the right sum. Then the client waits for the version that Reef trains on the four runs, and calls the model again: .. code:: python while (commit := trained_version()) is None: time.sleep(10) print(f"a new version serves: commit {commit['commit_number']}, train/loss {commit['metrics'].get('train/loss')}") The file has the rest: the scenario, the two functions, and ``trained_version``, which reads the scenario's commits. Run it in the second terminal: .. code:: bash export REEF_TOKEN=reef-local python recipes/minimal/examples/client.py The client prints each run, then the version that Reef trained, then the answer of that version. On two GPUs with this model the run takes about five minutes: .. code:: text 0 + 2 -> '0 + 2 is equal to 2.': score 1.0 1 + 2 -> '1 + 2 equals 3.': score 1.0 2 + 2 -> '2 + 2 equals 4.': score 1.0 3 + 2 -> '3 + 2 is 5.': score 1.0 a new version serves: commit 2, train/loss 0.13790160417556763 20 + 2 -> '20 + 2 is 22.' From now on, ``model: active`` gets the new version. A job makes two commits: one when control submits it, and one that holds the new version. Between the fourth run that scored 1 and the line ``a new version serves``, steps 4 to 9 of the figure at the top happen: control makes the job, training trains it, control commits the new version and activates it, and inference serves it. Step 7 does not run here: the example keeps the default activation rule, which serves every new version at once. The task of this example is small on purpose: it shows the loop, not a gain. One job of four runs does not change what the model answers in a way that you can measure. For workloads with measured results, see `Recipes `__. 5. Read the versions and choose which one serves ------------------------------------------------ Reef keeps every version. A version is an **artifact**. A second script of the example reads the versions and serves the first one again (`versions.py <../../recipes/minimal/examples/versions.py>`__). It lists the artifacts of the scenario, newest first: .. code:: python artifacts = client.get(f"/reef/scenarios/{SCENARIO}/artifacts")["artifacts"] for artifact in artifacts: print(artifact["artifact_id"], artifact["operation"], "active" if artifact["active"] else "not active") - ``operation`` says what made the version: ``creation`` for the model that the scenario started with, and ``training`` for each version that a job made. - ``active`` marks the version that ``model: active`` gets. - Each artifact also has ``metrics``, the training metrics of its job, and ``parent_artifact_id``. To serve another version, give its ID and the share of the traffic that it takes: .. code:: python first = artifacts[-1]["artifact_id"] body, _ = client.post(f"/reef/scenarios/{SCENARIO}/update", SCENARIO, {"served": {first: 100}}) print("served:", body["served"]) Each model response names the version that answered, in the header ``x-reef-artifact-id``: .. code:: python _, headers = client.post("/v1/chat/completions", SCENARIO, request) print("answered by:", headers.get("x-reef-artifact-id")) Run the script after the client: .. code:: bash python recipes/minimal/examples/versions.py .. code:: text artifact:4e155d358de64bb1b1724d8eafe91b6e training active artifact:464477f295e240de9ad6b2249826a9d2 creation not active served: {'artifact:464477f295e240de9ad6b2249826a9d2': 100} answered by: artifact:464477f295e240de9ad6b2249826a9d2 The first two lines are the versions: the one that training made, which serves, and the one that the scenario started with. The last two lines show the change: the first version serves again, and it answers the next call. By default every new version serves at once. To hold new versions back, set an activation rule in the deployment file: ``never`` waits for you. With ``evaluated``, the evaluation service scores each new version on tasks, and control activates the version when its score reaches the minimum that you set (step 7 of the figure). `Operate a deployment `__ has these tasks, and the ones for checkpoints and recovery. 6. Change the settings ---------------------- Reef runs as seven `services <../reference/services.rst>`__. Each one reads its own part of the deployment file. A part that you leave out keeps its default. .. list-table:: :header-rows: 1 * - Service - What it does - You set - Default * - inference - Serves the model, and stores each call - ``inference``: the model and its engine - An SGLang engine on this host's GPUs * - control - Checks each report, makes a job when enough samples wait, and decides whether a new version serves - ``recipe.jobs`` (``job-samples``), ``recipe.config`` (``training-mode``), ``activation`` - Jobs start by themselves, and every new version serves. A weight recipe has no default ``job-samples``. * - samples - Turns each report into training samples - ``recipe.samples``: the settings of the recipe's sample stage - The recipe's defaults * - training - Trains each job and saves a checkpoint - ``training``: the backend and its options. ``recipe.algorithm``: the options of the recipe's algorithm - The Slime backend * - evaluation - Scores a version on tasks, when you start an evaluation - ``evaluation`` - No evaluation runs * - data - Stores the data that you upload, such as trajectories and tasks - ``storage`` - SQLite and local directories under ``.reef/`` * - harness - Gives agents the harness of a harness recipe - ``recipe.config.evolution`` - Not used by a weight recipe Check a file before you start it. The command prints each setting with its source, and starts no process: .. code:: bash reef serve -c recipes/minimal/examples/slime/serve.yaml --print-config `Recipe configuration <../reference/configuration-recipe.rst>`__ gives the keys of the ``recipe`` section, and the `settings reference <../reference/configuration-settings.rst>`__ gives every key. 7. Use it for your own workload ------------------------------- The steps above ran the example's client. Three changes make the loop yours: your agent, your model, and the recipe that fits your feedback. Connect your agent ~~~~~~~~~~~~~~~~~~ Your agent does two things: it sends each model call through Reef, and it sends one report for each run. Any OpenAI-compatible client works: set its base URL to ``http://:8900/v1``, its API key to the Reef token, and the header ``x-reef-scenario`` to the scenario's name. A run of several calls gets one report, with the receipt of its last call. `Connect an agent `__ has the settings, an agent of two calls, and the command that connects Claude Code, Codex, OpenCode or pi. Use your own model ~~~~~~~~~~~~~~~~~~ These lines of the deployment file name the model. Change them together: .. list-table:: :header-rows: 1 * - Backend - Line - What to set * - Slime - ``inference.model-path`` - The directory of a Hugging Face model on this host * - Slime - ``training.options``: the block below the comment ``architecture flags`` - The flags of the model's architecture, and ``padded-vocab-size``. Reef reads the layer sizes from the model's config. * - Slime - ``inference.num-gpus``, and ``actor-num-gpus-per-node`` and ``num-gpus-per-node`` of ``training.options`` - The GPUs that serve, the GPUs that train, and their sum * - Tinker - ``inference.model-path`` - The name of a model that Tinker offers, such as ``Qwen/Qwen3-8B`` The example files of the other recipes have these lines for larger models: ``Qwen3-4B`` in `OpenClaw-RL's <../../recipes/openclawrl/examples/openclawrl/serve.yaml>`__, and ``Qwen3-30B`` in `SAO's <../../recipes/sao/examples/imo_answerbench/serve-30b.yaml>`__. Check your file with ``--print-config`` before you start it. Use another recipe ~~~~~~~~~~~~~~~~~~ A recipe decides what your agent reports. Change three things together: #. ``recipe.implementation``: the recipe's class. #. The recipe's own sections of the deployment file: ``recipe.samples``, ``recipe.jobs`` and ``recipe.algorithm``. Copy them from the recipe's example file. #. The report that your agent sends. .. list-table:: :header-rows: 1 * - You have - Recipe - The report of one run * - A check that passes or fails a run - ``minimal`` - ``{"score": 1.0}`` * - A reward for each run - `SAO <../../recipes/sao/README.md>`__ - ``{"score": 0.7}`` * - A demonstration of a good answer - `SDFT <../../recipes/sdft/README.md>`__ - ``{"metadata": {"teacher_context": ""}}`` `Recipes `__ lists every recipe with the feedback that it needs. Common tasks ~~~~~~~~~~~~ .. list-table:: :header-rows: 1 * - Task - How * - See why nothing trains - ``GET /reef/status``: the scenario's ``pipeline`` gives the samples that wait (``ready_samples``) and the size of a job (``job_samples``). A report that the recipe skipped made no sample. * - Change the size of a job - ``recipe.jobs.job-samples``. On Slime, set it to the batch of one optimizer step, ``global_batch_size``, as the example file does. * - Train only when you ask - ``recipe.config.training-mode: manual``, then `POST /reef/train <../reference/http-api-training.rst#post-reef-train>`__. * - Hold each new version back until you choose it - The activation rule ``never``, then `set what the scenario serves `__. * - Serve a new version only when it passes an evaluation - The activation rule ``evaluated`` (`activation rule `__). * - Go back to an earlier version - `Set what the scenario serves `__ to its artifact ID, as in step 5. * - Run a second workload - Make a second scenario: ``POST /reef/scenarios``. Slime trains one scenario for each deployment, so a second workload on Slime is a second deployment. * - Keep the records in PostgreSQL - `Storage `__. * - Run the services on several hosts - `Split the services `__. Next steps ---------- - `Write a recipe <../developer-guide/write-a-recipe.rst>`__: define your own method as four classes, each with a base class that says what to implement. - `Evolve a model `__ and `Evolve a harness `__: one recipe of each kind, from its ideas to its code. - `Connect an agent `__: your own client, or a coding agent. - `Run Reef in production `__: your GPUs or Tinker, PostgreSQL, and sandboxes on E2B or Modal. - `Choose another recipe `__: the methods that ship with Reef, and what each one trains.