# Write prompts and reward functions

Turn each row of a reasoning dataset into a prompt, and score what the model writes back, so a reinforcement learning run such as CISPO or GRPO can learn from it.

You need a [reasoning dataset](upload-a-dataset.md#reasoning). The examples use GSM8K from the [Quickstart](../get-started/quickstart.md).

## How the prompt is built

In a manifest, `environment.prompt_template` holds the chat messages. In the experiment wizard, the **Prompts** step writes the same thing from its system prompt and **User prompt** fields.

```yaml
prompt_template:
    system_0: Solve the problem. Put the final number in <answer></answer> tags.
    user_1: '{question}'
```

For each row, Arena:

1. **Turns each key into one chat message.** The text before the first `_` is the role: `system_0` is a system message, `user_1` a user message, `assistant_2` an assistant message.
2. **Orders the messages by the number at the end of each key.** Number every key. Arena doesn’t keep the order you wrote them in, so keys without a number come out alphabetically. Numbering only some keys, or using a number twice, is an error.
3. **Fills `{question}` and `{answer}`** from the row’s mapped columns. Nothing else is filled: other braces, such as `{"n": 1}`, stay as written. Putting `{answer}` in the prompt shows the model the answer.
4. **Applies the model’s chat template**, with `chat_template_kwargs` from the manifest’s `environment` section.

The chat template decides the rest:

- **System prompt.** There is one only if you add a `system_*` key, or the model’s template adds its own. `Qwen/Qwen2.5-0.5B-Instruct` adds one; Qwen3.5 models don’t.
- **Thinking.** For Qwen3.5 the template opens the assistant turn with a thinking block. `Qwen/Qwen3.5-0.8B` and `Qwen/Qwen3.5-2B` close it at once (thinking off); `Qwen/Qwen3.5-4B` and `Qwen/Qwen3.5-9B` leave it open (thinking on). Set `chat_template_kwargs: {enable_thinking: true}` or `false` to choose.
- **Assistant prefill.** When the last message is an assistant message with text, the model continues that text. The prefill is part of the prompt, not the completion.

## What the reward function receives

Arena calls your function once per completion, passing arguments by name, and expects a number back:

```python
def reward_fn(completion: str, answer, question) -> float: ...
```

- **`completion`** is everything the model wrote in its turn: reasoning, the `</think>` that ends it, and the answer. The end-of-turn token is dropped and surrounding whitespace is stripped. It starts where the prompt ends, so anything already in the prompt, such as Qwen3.5’s opening `<think>` or an assistant prefill, is not in it.
- **`answer`** is the row’s answer column, unchanged. For GSM8K that is the whole worked answer ending `#### 72`. Columns keep their types, so a numeric answer arrives as a number.
- **`question`** is the row’s question column, unchanged. It is not the rendered prompt.

A completion counts as solved when its reward reaches `max_reward` in the manifest, or **Maximum reward** in the wizard. The default is 1. Set it to the most your function can return.

For the same prompt and the row `question: What is 2 + 3?`, `answer: '#### 5'`, here is what `completion` looks like:

| Model and setting                                      | `completion`                                        |
|--------------------------------------------------------|-----------------------------------------------------|
| `Qwen/Qwen3.5-0.8B`, `enable_thinking: true`           | `2 plus 3 is 5.\n</think>\n\n<answer>5</answer>`    |
| `Qwen/Qwen3.5-0.8B`, thinking off (the default)        | `2 plus 3 is 5.\n<answer>5</answer>`                |
| `Qwen/Qwen2.5-0.5B-Instruct`, asked for `<think>` tags | `<think>2 plus 3 is 5.</think>\n<answer>5</answer>` |

## Write a reward that fits

- **Score the answer after the reasoning**, so a number the model tries while thinking doesn’t count. Take the text after the last `</think>`, or the last `<answer>` match.
- **Match what your model and template produce.** With Qwen3.5 thinking on, the opening `<think>` is in the prompt and `</think>` is followed by a blank line. A pattern that needs `<think>` at the start of `completion`, or one newline after `</think>`, never matches.
- **Ask for every tag you check.** A reward that needs `<answer>` tags scores 0 when the prompt never asks for them.

The Quickstart’s [`reward.py`](/_downloads/549fc2d8943f592c34a27a56fb413b12/reward.py) follows all three: one point for the right number, one for the format.

## Check a template before you submit

Render the prompt on your own machine with the model’s tokenizer. This builds the same messages Arena does for a two-key template:

```python
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3.5-0.8B")
row = {"question": "What is 2 + 3?", "answer": "#### 5"}
messages = [
    {"role": "system", "content": "Solve the problem. Put the final number in <answer></answer> tags."},
    {"role": "user", "content": row["question"]},
]
print(tokenizer.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True, enable_thinking=False,
))
```

Then call your reward function with completions shaped like the table above.

## Validate the reward function

### Web app

In the wizard’s **Environment** step, a reasoning dataset has two required steps: **Prompts** and **Reward Function**. **Next** stays disabled until both are done.

1. Under **Reward Function**, write `reward_fn` in the **Editor**, or click **Generate** to have Arena draft one from your prompt and some sample rows.
2. Set **Maximum reward**.
3. **Sample row** shows one row of your dataset, with the rendered prompt in the question cell. The **Answer** cell is the completion the check scores. It starts as the row’s answer; edit it to try other replies, and click **Reset** to go back. Your dataset is not changed. The shuffle button picks another row.
4. Click **Validate**. **Validation Results** shows the **Syntax check** and **Execution test**, and **Calculated reward** shows the score.

### CLI

`arena experiments submit` runs the reward file once before it starts the run, using the reference answer from the dataset’s first row as the completion. Pass `--completion` to test with your own text instead:

```bash
arena experiments submit gsm8k_cispo.yaml --reward-file reward.py --completion "<answer>72</answer>"
```

If the reward file fails to import or doesn’t return a number, nothing is submitted. `--dry-run` runs the same check before it prints the price, so a broken reward file shows up there too.

Leave `environment.rubric_file_path` out of the manifest and the CLI fills it in from `--reward-file`. If you set it, it must name the same file.

## Use an LLM as the judge

A judge is another LLM, called through its provider’s API, that reads each completion and scores it against criteria you write. It suits rewards that are hard to code, such as whether the working is clear. Keep a code check for the parts you can verify exactly.

The example keeps GSM8K and CISPO and scores each completion as 0.6 × correctness plus 0.4 × the judge’s score for the working. Judges are set up from the CLI. The files:

- [`reward.py`](/_downloads/65a2e6d80294f0d99dc52c6d7b0990b6/reward.py)
- [`manifest.yaml`](/_downloads/15a0331d57e72fa638141d3cfbaf30b2/manifest.yaml)
- [`manifest_ruler.yaml`](/_downloads/67e8064db5100e19d4e4604a3851b08e/manifest_ruler.yaml)

### Store the judge’s API key

The training job calls the judge, so it needs your provider key. Store it as an organization secret: the manifest names the secret, and Arena passes it to the job as an environment variable of that name. The key never goes in the manifest.

```bash
arena secrets set OPENAI_API_KEY --from-env OPENAI_API_KEY
arena secrets list
```

Without `--from-env`, `arena secrets set` prompts for the value. In the web app, add secrets under **Settings** → **Organization**; see [Organization secrets](../account/account.md#organization-secrets).

### The reward file

A judge needs the reward written as an OpenEnv `Rubric` class instead of a `reward_fn`. Arena calls it on every turn with the model’s reply (`action.message`) and the dataset row (`observation.question`, `observation.answer`).

```python
# Copyright 2026 AgileRL
# SPDX-License-Identifier: Apache-2.0

import re

from openenv.core.rubrics.base import Rubric
from openenv.core.rubrics.containers import WeightedSum

from agilerl.llm_envs.rubrics import LLMGroupJudgeRubric, LLMJudgeRubric

CRITERIA = """\
The reply solves the math word problem. Each step of the working follows from
the problem or the step before it, and a student could follow it. The reply
ends with one final number inside <answer></answer> tags, and that number
matches the reference answer. Penalise wrong arithmetic, skipped steps,
repetition and padding."""


def extract_gold_answer(answer: str) -> str | None:
    """Return the final numeric answer from a GSM8K answer (the value after ``####``)."""
    match = re.search(r"####\s*(-?[\d,]+)", answer)
    return match.group(1).replace(",", "").strip() if match else None


def extract_model_answer(completion: str) -> str | None:
    """Return the final number inside the model's last ``<answer>...</answer>`` block."""
    blocks = re.findall(r"<answer>([\s\S]*?)</answer>", completion)
    if not blocks:
        return None
    number = re.search(r"-?[\d,]+", blocks[-1])
    return number.group(0).replace(",", "").strip() if number else None


class Correctness(Rubric):
    """1.0 when the number in ``<answer>`` matches the GSM8K gold answer."""

    component_name = "correct"

    def forward(self, action, observation) -> float:
        gold = extract_gold_answer(str(observation.answer))
        predicted = extract_model_answer(action.message)
        if gold is None or predicted is None:
            return 0.0
        return 1.0 if predicted == gold else 0.0


class RUBRIC(WeightedSum):
    """Correct final answer, plus a judge's score for the working."""

    def __init__(self, judge) -> None:
        super().__init__(
            [Correctness(), LLMJudgeRubric(judge, CRITERIA)],
            weights=[0.6, 0.4],
        )


class RULER(LLMGroupJudgeRubric):
    """One judge call ranks every completion in a group against the criteria."""

    def __init__(self, judge) -> None:
        super().__init__(judge, CRITERIA)
```

- `Correctness` is a plain rubric: 1.0 when the number in `<answer>` matches the number after `####`. Its `component_name` names its metric.
- `LLMJudgeRubric` shows the judge the question, the reply and the row’s answer, with your criteria, and asks for a score from 0 to 1. A reply it can’t read scores 0.
- `RUBRIC` adds them with `WeightedSum`. The weights must add up to 1.
- `RUBRIC` takes a `judge` argument in `__init__`. Arena builds the class with the run’s judge client, so it must be a class, not an instance made when the file is imported.

Write the criteria the way you would brief a human grader: what a good reply does, and what to mark down. The judge sees the reply without its reasoning. Pass `include_reasoning=True` to `LLMJudgeRubric` to show it the reasoning too; that trains the model to write reasoning the judge likes.

### The manifest

```yaml
---
algorithm:
    name: CISPO
    batch_size: 16
    beta: 0.001
    lr: 0.0000005
    clip_coef: 0.2
    max_grad_norm: 0.1
    update_epochs: 1
    group_size: 8
    temperature: 0.9
    calc_position_embeddings: true

environment:
    name: gsm8k
    env_type: rollout
    dataset: gsm8k
    rubric_file_path: reward.py
    rubric_name: RUBRIC
    judge:
        provider: openai
        model: gpt-4.1-mini
        api_key_env: OPENAI_API_KEY
        max_tokens: 512
    prompt_template:
        system_0: >-
            Solve the problem. Show your working step by step, then give the
            final number inside <answer></answer> tags.
        user_1: '{question}'

replay_buffer:
    kind: llm

training:
    max_steps: 100_000
    metrics_interval: 5
    eval_loop: 1
    evaluation_interval: 5

network:
    pretrained_model_name_or_path: Qwen/Qwen3.5-0.8B
    max_context_length: 1024
    lora_config:
        lora_r: 16
        lora_alpha: 64
        task_type: CAUSAL_LM
```

Three things in `environment` set up the judge:

- `rubric_name: RUBRIC` is the class to load from the reward file. Without it, Arena looks for `reward_fn`.
- `judge.provider` is `openai`, which covers any OpenAI-compatible endpoint, or `anthropic`. `judge.model` is the judge’s model id.
- `judge.api_key_env` is the name of the organization secret, not the key.

`judge.max_tokens` is the judge’s reply budget. A judge that thinks before it answers spends this budget on thinking too, so raise it for thinking models. To reach a judge somewhere other than OpenAI, such as OpenRouter or your own vLLM server, set `judge.base_url`. The [manifest schema](../cli/manifest-schema.md) lists every judge field and its default.

Submit it like any other run:

```bash
arena experiments submit manifest.yaml --reward-file reward.py --experiment-name gsm8k-judge
```

Every completion now costs a judge call, so each prompt costs `group_size` calls. Check your provider’s rate limits and spend before a long run. A judge call that still fails after the provider SDK’s retries drops that group, and the run stops after 8 failed episodes in a row.

### Watch the judge

Besides the usual metrics, a judge run logs `reward_correct` and `reward_judge` (each part before weighting), `judge_calls`, `judge_parse_failure_rate` (replies with no readable score, each scored 0) and `judge_mean_latency_s`. If the parse failure rate is high, raise `max_tokens` first. If latency climbs, the judge is slowing training: raise `judge.max_concurrency` or use a faster model.

Accuracy counts a completion as solved when its reward reaches `max_reward`, which here only a correct answer the judge also scores 1 can reach. Read `reward_correct` for how often the model gets the number right.

To see why the judge gave a score, open the project’s **Results** tab and click **View sampled outputs** on the experiment. The **Judge notes** column shows the judge’s one-sentence reason for each completion. Read some early in the run. If the judge rewards something you didn’t mean, such as long answers, tighten the criteria and resubmit.

### Score a group together with RULER

CISPO already compares the completions in a group. **RULER** gives the judge the same view: one call shows the judge every completion for a prompt and asks for a score for each. Comparing replies side by side is often easier for a judge than scoring each alone, and a group costs one call instead of one per completion.

`reward.py` already defines `RULER`, a subclass of `LLMGroupJudgeRubric` with the same criteria. To use it, name it as `group_rubric_name` and point `rubric_name` at `Correctness` alone:

```yaml
environment:
    rubric_file_path: reward.py
    rubric_name: Correctness
    group_rubric_name: RULER
    max_reward: 2.0
```

```bash
arena experiments submit manifest_ruler.yaml --reward-file reward.py --experiment-name gsm8k-ruler
```

How it differs from the per-completion judge:

- The group score is added to `Correctness`, so a completion can score up to 2; set `max_reward` to match. It is logged as `reward_group_judge`, and its judge notes are labelled `group_judge`.
- Leave `rubric_name` out and the group score is the whole reward.
- The judge sees the completions in a new random order on every call, so a judge that favours one position adds noise rather than bias.
- A reply it can’t read, or with the wrong number of scores, scores the whole group 0.
- The judge writes one reason per completion, so raise `max_tokens` with `group_size`.
- Held-out evaluation episodes get no group score.
