add-reward
Guide for adding a new reward function to AReaL. Use when user wants to create a reward function.
Best use case
add-reward is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Guide for adding a new reward function to AReaL. Use when user wants to create a reward function.
Teams using add-reward should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/add-reward/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How add-reward Compares
| Feature / Agent | add-reward | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Guide for adding a new reward function to AReaL. Use when user wants to create a reward function.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Add Reward
Add a new reward function to AReaL.
## When to Use
This skill is triggered when:
- User asks "how do I add a reward function?"
- User wants to implement custom rewards
- User mentions reward computation
## Step-by-Step Guide
### Step 1: Create Reward File
Create `areal/reward/<name>.py`:
```python
from typing import Any
from areal.utils import logging
logger = logging.getLogger("MyReward")
def <name>_reward_fn(
prompt: str,
completions: str,
prompt_ids,
completion_ids,
answer: str | None = None,
**kwargs: Any,
) -> float:
"""Compute reward for a single completion.
Args:
prompt: Prompt string
completions: Completion string (model output)
prompt_ids: Tokenized prompt IDs
completion_ids: Tokenized completion IDs
answer: Ground truth answer from dataset (optional)
**kwargs: Additional data from dataset
Returns:
Reward value (float), typically 0.0 or 1.0
"""
try:
# Extract answer from completion
extracted = _extract_answer(completions)
# Compare with ground truth
if answer is not None and extracted == str(answer):
return 1.0
return 0.0
except Exception:
logger.warning("Exception in reward computation", exc_info=True)
return 0.0
def _extract_answer(completion: str) -> str:
"""Extract the answer from a completion string.
Implement your extraction logic here.
"""
# Example: Extract content from \boxed{}
import re
match = re.search(r"\\boxed\{([^}]+)\}", completion)
if match:
return match.group(1).strip()
return completion.strip()
```
### Step 2: Register in __init__.py
Update `areal/reward/__init__.py`:
```python
# Add to VALID_REWARD_FN
VALID_REWARD_FN = [
# ... existing reward functions
"<name>",
]
# Add to get_reward_fn function
def get_reward_fn(name: str, **kwargs):
# ... existing code
elif name == "<name>":
from areal.reward.<name> import <name>_reward_fn
return <name>_reward_fn
```
### Step 3: Handle Blocking Operations
If your reward function uses blocking operations (e.g., API calls, model inference), the
workflow will wrap it with `AsyncRewardWrapper`:
```python
# In your workflow
from areal.reward import AsyncRewardWrapper
self.reward_fn = AsyncRewardWrapper(reward_fn)
# Then call it asynchronously
rewards = await self.reward_fn(prompt, completions, **data)
```
### Step 4: Add Tests
Create `areal/tests/test_<name>_reward.py`:
```python
import pytest
from areal.reward.<name> import <name>_reward_fn
def test_reward_correct_answer():
reward = <name>_reward_fn(
prompt="What is 2+2?",
completions="The answer is \\boxed{4}",
prompt_ids=None,
completion_ids=None,
answer="4",
)
assert reward == 1.0
def test_reward_wrong_answer():
reward = <name>_reward_fn(
prompt="What is 2+2?",
completions="The answer is \\boxed{5}",
prompt_ids=None,
completion_ids=None,
answer="4",
)
assert reward == 0.0
```
## Reference Implementations
| Reward | File | Description |
| ---------- | --------------------------------- | ---------------------------- |
| GSM8K | `areal/reward/gsm8k.py` | Math answer verification |
| Geometry3K | `areal/reward/geometry3k.py` | Geometry answer verification |
| CLEVR | `areal/reward/clevr_count_70k.py` | Counting verification |
| MathVerify | `areal/reward/math_verify.py` | General math verification |
## Function Signature
All reward functions must follow this signature:
```python
def reward_fn(
prompt: str, # Input prompt string
completions: str, # Model completion string
prompt_ids, # Tokenized prompt
completion_ids, # Tokenized completion
**kwargs: Any, # Additional data from dataset (e.g., answer)
) -> float: # Reward value (typically 0.0 or 1.0)
```
**Note**: The reward function is called once per sample. Batching is handled by
`AsyncRewardWrapper` in the workflow.
## Key Requirements
1. **Deterministic**: Same inputs should produce same outputs
1. **Return float**: Output is a single float value per sample
1. **No blocking in async context**: Use `AsyncRewardWrapper` if needed
1. **Logging**: Use `areal.utils.logging`, not `print`
1. **Handle exceptions**: Return 0.0 on error, don't raise
## Common Mistakes
- ❌ Returning a tensor instead of a float
- ❌ Expecting batched inputs (reward is called per sample)
- ❌ Non-deterministic behavior
- ❌ Blocking operations without `AsyncRewardWrapper`
- ❌ Raising exceptions instead of returning 0.0
______________________________________________________________________
<!--
================================================================================
MAINTAINER GUIDE
================================================================================
Location: .claude/skills/add-reward/SKILL.md
Invocation: /add-reward <name>
## Purpose
Step-by-step guide for adding new reward functions.
## How to Update
### When Reward API Changes
1. Update the function signature section
2. Update the code template
3. Update key requirements
### When New Reward Patterns Emerge
1. Add to "Reference Implementations" table
2. Add examples for new patterns
================================================================================
-->Related Skills
vly-money
Generate crypto payment links for supported tokens and networks, manage access to X402 payment-protected content, and provide direct access to the vly.money wallet interface.
grail-miner
This skill assists in setting up, managing, and optimizing Grail miners on Bittensor Subnet 81, handling tasks like environment configuration, R2 storage, model checkpoint management, and performance tuning.
chrome-debug
This skill empowers AI agents to debug web applications and inspect browser behavior using the Chrome DevTools Protocol (CDP), offering both collaborative (headful) and automated (headless) modes.
ontopo
An AI agent skill to search for Israeli restaurants, check table availability, view menus, and retrieve booking links via the Ontopo platform, acting as an unofficial interface to its data.
lets-go-rss
A lightweight, full-platform RSS subscription manager that aggregates content from YouTube, Vimeo, Behance, Twitter/X, and Chinese platforms like Bilibili, Weibo, and Douyin, featuring deduplication and AI smart classification.
whisper-transcribe
Transcribes audio and video files to text using OpenAI's Whisper CLI, enhanced with contextual grounding from local markdown files for improved accuracy.
astro
This skill provides essential Astro framework patterns, focusing on server-side rendering (SSR), static site generation (SSG), middleware, and TypeScript best practices. It helps AI agents implement secure authentication, manage API routes, and debug rendering behaviors within Astro projects.
tech-blog
Generates comprehensive technical blog posts, offering detailed explanations of system internals, architecture, and implementation, either through source code analysis or document-driven research.
thor-skills
An entry point and router for AI agents to manage various THOR-related cybersecurity tasks, including running scans, analyzing logs, troubleshooting, and maintenance.
modal-deployment
Run Python code in the cloud with serverless containers, GPUs, and autoscaling using Modal. This skill enables agents to generate code for deploying ML models, running batch jobs, serving APIs, and scaling compute-intensive workloads.
ux
This AI agent skill provides comprehensive guidance for creating professional and insightful User Experience (UX) designs, covering user research, information architecture, interaction design, visual guidance, and usability evaluation. It aims to produce actionable, user-centered solutions that avoid generic AI aesthetics.
advanced-skill-creator
Meta-skill that generates domain-specific skills using advanced reasoning techniques. PROACTIVELY activate for: (1) Create/build/make skills, (2) Generate expert panels for any domain, (3) Design evaluation frameworks, (4) Create research workflows, (5) Structure complex multi-step processes, (6) Instantiate templates with parameters. Triggers: "create a skill for", "build evaluation for", "design workflow for", "generate expert panel for", "how should I approach [complex task]", "create skill", "new skill for", "skill template", "generate skill"