Skip to content
SurogateSurogateDocs
↑↓ to move↵ to openesc to close

RL Environments

An environment gives the model its tasks and scores what it does, which makes it the reward side of RL training. This guide shows you how to build one with the verifiers library, from simple single-turn tasks to multi-turn agents with tools.

An environment built with Verifiers is a self-contained Python module. To start from a fresh template, run:

shell
surogate vf-init <env_name>

This creates a new, empty environment in ./environments/<env_name>.

The simplest single-turn environment needs only a dataset of tasks and a reward function that scores responses:

python
import verifiers as vf
from datasets import Dataset
def load_environment():
# Your task data
dataset = Dataset.from_list([
{"prompt": [{"role": "user", "content": "What is 2+2?"}], "answer": "4"},
{"prompt": [{"role": "user", "content": "What is 3*5?"}], "answer": "15"},
])
# Your reward function
async def correct_answer(completion, answer) -> float:
response = completion[-1]["content"]
return 1.0 if answer in response else 0.0
rubric = vf.Rubric(funcs=[correct_answer])
return vf.SingleTurnEnv(dataset=dataset, rubric=rubric)

When you run this environment, each row in the dataset becomes a rollout:

  1. The prompt is sent to the model.
  2. The model generates a response, which becomes the completion.
  3. The reward function scores the result.

SingleTurnEnv is the simplest environment type: each rollout gets one model response. Other environment types add tool use or your own interaction protocols.

Environments load and manipulate data with the Hugging Face datasets library. Each row usually has a prompt column holding the list of initial messages to send to the model. Two optional columns help with scoring:

  • answer: a plain string to compare against as ground truth
  • info: structured metadata (a dict or a JSON string)

Depending on what your environment needs, you can include answer, info, both, or neither.

If rows may have different schemas for info (different fields or nested structures, for example), use JSON strings:

python
dataset = Dataset.from_list([
{"prompt": [...], "info": '{"type": "math", "difficulty": 3}'},
{"prompt": [...], "info": '{"type": "code", "language": "python"}'},
])

The environment parses them into a dict when it runs rollouts.

The examples above use prompt directly, as a list of messages ready to send to the model. You can instead provide a question column holding a string, and the environment wraps it in a user message:

python
dataset = Dataset.from_list([
{"question": "What is 2+2?", "answer": "4"},
])

You can also pass a system_prompt to the environment, which prepends a system message:

python
return vf.SingleTurnEnv(
dataset=dataset,
system_prompt="You are a helpful math tutor.",
rubric=rubric,
)

Together, these build the full prompt:

python
[
{"role": "system", "content": "You are a helpful math tutor."},
{"role": "user", "content": "What is 2+2?"}
]

If your dataset already has a prompt column, question is ignored. A system_prompt, if you give one, is still prepended to any prompt that doesn’t already start with a system message.

You can give an environment a separate eval_dataset for evaluation, apart from the training dataset:

python
return vf.SingleTurnEnv(
dataset=train_dataset,
eval_dataset=eval_dataset,
rubric=rubric,
)

surogate vf-eval uses the evaluation dataset by default (see Evaluating a RULER-trained model for a full command). Without an eval_dataset, evaluation falls back to the training dataset.

For large datasets, or when you run several environment replicas, you can defer loading with a DatasetBuilder, a callable that returns a Dataset when called:

python
def get_dataset_builder(split: str = "train", seed: int = 42) -> vf.DatasetBuilder:
"""Returns a builder that lazily loads the dataset."""
def build() -> Dataset:
ds = load_dataset("my-dataset", split=split)
ds = ds.shuffle(seed=seed)
return ds
return build
def load_environment():
dataset_builder = get_dataset_builder(split="train")
eval_builder = get_dataset_builder(split="test")
return vf.SingleTurnEnv(
dataset=dataset_builder, # built on first access
eval_dataset=eval_builder, # built on first access
rubric=rubric,
)

A builder helps when:

  • loading the dataset is expensive (downloading from Hugging Face, for example)
  • not every environment replica needs its own copy of the dataset
  • you want to parameterize dataset creation without loading it right away

A plain Dataset passed directly (the default pattern) is loaded eagerly when the environment initializes, for backwards compatibility.

Each environment has a Rubric that handles scoring. The rubric holds the reward functions, combines their outputs into a final reward, and tracks metrics so you can see what is happening.

A reward function evaluates a rollout and returns a float, usually between 0.0 and 1.0. It asks for rollout data by naming it as an argument:

python
async def correct_answer(completion, answer) -> float:
response = completion[-1]["content"]
return 1.0 if answer in response else 0.0

The basic arguments, when present, are:

  • completion: the model’s output (a list of messages)
  • prompt: the input messages
  • answer: from the dataset
  • info: from the dataset
  • state: the full rollout state (used in more complex environments)

The same naming pattern works for the extra objects a rubric provides in more advanced setups.

A rubric can combine several reward functions, each with its own weight:

python
async def check_keywords(completion, info) -> float:
response = completion[-1]["content"]
keywords = info["required_keywords"]
found = sum(1 for kw in keywords if kw.lower() in response.lower())
return found / len(keywords)
async def length_reward(completion) -> float:
response = completion[-1]["content"]
return 1.0 if len(response) < 500 else 0.5
rubric = vf.Rubric(
funcs=[check_keywords, length_reward],
weights=[1.0, 0.1]
)

The final reward for a rollout is the weighted sum of all reward function scores.

You can also add reward functions to a rubric after creating it:

python
rubric = vf.Rubric()
rubric.add_reward_func(check_keywords, weight=1.0)
rubric.add_reward_func(length_reward, weight=0.1)

A reward function with weight=0 doesn’t affect the score, which makes it a way to track a metric:

python
async def response_length(completion) -> float:
return float(len(completion[-1]["content"]))
rubric.add_metric(response_length) # shorthand for weight=0

All reward functions (weighted or not) appear in the rollout metrics.

Reward functions run in the order you add them to the rubric. Since state is mutable and shared by all of them, an earlier function can store a value for a later one to use:

python
async def similarity_score(completion, answer, state) -> float:
response = completion[-1]["content"]
score = compute_similarity(response, answer) # continuous 0-1
state["similarity"] = score
return score
async def similarity_threshold(state) -> float:
return 1.0 if state["similarity"] > 0.8 else 0.0
rubric = vf.Rubric(
funcs=[similarity_score, similarity_threshold],
weights=[0.0, 1.0] # log similarity, but only reward threshold
)

This saves recomputing a value that several reward functions need.

During evaluation and RL training, rollouts from the same input example form a group. In evaluation, groups give you per-example aggregate statistics such as pass@k. In RL training, each rollout’s advantage is computed relative to the other rollouts in its group. A dataset with 100 example rows and 4 rollouts per example gives 100 groups of 4 rollouts each.

Sometimes a reward function should work on the whole group, for example to measure diversity or rank responses against each other. To write a group reward function, use plural argument names (completions, prompts, answers, infos) and return a list of scores:

python
async def diversity_bonus(completions) -> list[float]:
"""Reward unique responses within a group."""
responses = [c[-1]["content"] for c in completions]
unique = set(responses)
# Higher reward if this response is unique
return [0.2 if responses.count(r) == 1 else 0.0 for r in responses]
rubric = vf.Rubric(funcs=[correct_answer, diversity_bonus])

Reward functions can also ask for static objects that live in the rubric. These are stored in the rubric’s class_objects dictionary, and you can add more after creating it with add_class_object():

python
rubric = vf.Rubric(funcs=[my_reward_func])
rubric.add_class_object("my_helper", some_helper_object)
async def my_reward_func(completion, my_helper) -> float:
# my_helper is now available by name
return await my_helper.score(completion)

Two common kinds of shared object are parsers and judges.

A parser holds the logic for pulling structured content out of model responses. Pass one to a rubric and its reward functions can use it:

python
parser = vf.XMLParser(["reasoning", "answer"])
rubric = vf.Rubric(funcs=[my_reward_func], parser=parser)
async def my_reward_func(completion, parser) -> float:
parsed = parser.parse_answer(completion)
# parsed.reasoning, parsed.answer available
...

You can pass a parser to the environment too, which often uses it during rollouts to validate or extract content. That way the environment’s interaction loop and the rubric’s reward functions share the same parsing logic.

A judge is an LLM that scores responses, for tasks where a deterministic check is impractical. The built-in JudgeRubric class stores an LLM client in the rubric and gives reward functions a judge callable for scoring:

python
judge_rubric = vf.JudgeRubric(
judge_model="gpt-4.1-mini",
)
async def judge_correctness(prompt, completion, answer, judge) -> float:
verdict = await judge(prompt, completion, answer)
return 1.0 if "yes" in verdict.lower() else 0.0
judge_rubric.add_reward_func(judge_correctness)

The judge callable builds a prompt that compares the model’s response with the ground truth, and returns the judge model’s verdict.

For more control, JudgeRubric accepts a custom judge_prompt template and exposes its internals (judge_client, judge_model, judge_prompt, judge_sampling_args) as class objects:

python
judge_rubric = vf.JudgeRubric(
judge_model="gpt-4.1-mini",
judge_prompt="""Rate the writing quality of this response from 0-10.
Response: {response}
Score:"""
)
async def quality_score(completion, judge_client, judge_model, judge_prompt, parser) -> float:
response = parser.parse_answer(completion)
filled_prompt = judge_prompt.format(response=response)
result = await judge_client.chat.completions.create(
model=judge_model,
messages=[{"role": "user", "content": filled_prompt}],
)
# parse numeric score from result
...
return score

To use several rubrics in one environment, combine them into a RubricGroup. The group behaves as a single rubric and collects the rewards and metrics of all its members, which is handy for mixing rubrics of different types.

For example, the built-in MathRubric checks mathematical correctness with symbolic verification:

python
math_rubric = vf.MathRubric()

MathRubric includes a correct_answer reward function that parses \boxed{} answers and checks symbolic equivalence with the math-verify library. To add an LLM judge alongside it:

python
math_rubric = vf.MathRubric()
judge_rubric = vf.JudgeRubric(judge_model="gpt-4.1-mini")
judge_rubric.add_reward_func(judge_correctness, weight=0.5)
rubric = vf.RubricGroup([math_rubric, judge_rubric])

All rubrics in a group run in parallel. The final reward is the sum of their rewards, and their metrics are collected together.

In simple cases you add metrics straight to a rubric with add_metric(), as shown above. A monitor rubric goes one step further: it packages metrics into a separate rubric that you combine with add_rubric(). This lets each environment type in a class hierarchy add its own metrics automatically.

Many environment types come with a monitor rubric that tracks metrics for their level of the class hierarchy:

EnvironmentTracked Metrics
MultiTurnEnv#num_turns
ToolEnv#total_tool_calls, per-tool counts
SandboxEnv#sandbox_ready_wait_time, sandbox_command_execution_time
PythonEnv#python_ready_wait_time

These metrics show up in rollout results automatically, next to your own reward functions.

To add your own metrics to an environment, define a monitor rubric class and add it with add_rubric():

python
class MyMonitorRubric(vf.Rubric):
def __init__(self):
super().__init__()
self.add_metric(self.custom_metric)
async def custom_metric(self, state: vf.State) -> float:
return len(state["trajectory"])
env = vf.ToolEnv(dataset=dataset, tools=tools, rubric=rubric)
env.add_rubric(MyMonitorRubric())

The environment wraps rubrics in a RubricGroup when needed, so monitor rubrics stack up the class hierarchy. PythonEnv, for example, inherits metrics from both SandboxEnv and ToolEnv.

Every environment type Verifiers currently supports is built on MultiTurnEnv, which implements the core single-agent rollout loop. Even SingleTurnEnv is a MultiTurnEnv with max_turns=1 and a placeholder env_response method. ToolEnv adds tool calling on top.

You define tools as Python functions. Verifiers reads the tool schemas from function signatures and docstrings, for OpenAI-compatible tool calling:

python
async def calculate(expression: str) -> str:
"""Evaluate a mathematical expression.
Args:
expression: A mathematical expression to evaluate (e.g. "2 + 2 * 3")
Returns:
The result of the evaluation.
"""
try:
result = eval(expression)
return str(result)
except Exception as e:
return f"Error: {e}"
async def lookup(term: str) -> str:
"""Look up a term in the knowledge base.
Args:
term: The term to search for.
Returns:
Information about the term.
"""
# your lookup logic here
...

The function name becomes the tool name, the type hints set the parameter types, and the docstring supplies the tool description and, through its Args section, each parameter’s description. Tools can be sync or async. We recommend async, because a sync tool blocks the main thread.

To create a tool environment, pass the tools to ToolEnv:

python
vf_env = vf.ToolEnv(
dataset=dataset,
tools=[calculate, lookup],
rubric=rubric,
max_turns=10,
)

During a rollout, the model can call tools, get the results and keep reasoning until it gives a response with no tool calls (or hits max_turns). Each turn is a model response followed by the environment running the tools. Monitor rubrics count tool calls automatically (see above).

If your tools are MCP (Model Context Protocol) servers, use MCPEnv. It extends ToolEnv, connects to the MCP servers and exposes their tools to the model:

python
mcp_servers = [
{
"name": "fetch",
"command": "uvx",
"args": ["mcp-server-fetch"],
},
]
vf_env = vf.MCPEnv(
mcp_servers=mcp_servers,
dataset=dataset,
rubric=rubric,
)

ToolEnv and MCPEnv are meant for stateless, read-only tools, where no session state has to survive between calls in a rollout. For tools that need per-rollout state (a sandbox container, a database connection or a session ID, for example), use StatefulToolEnv.

Every environment that extends MultiTurnEnv calls setup_state at the start of each rollout, but by default it does nothing (in ToolEnv too).

StatefulToolEnv overrides it to set up per-rollout resources, and adds two concepts:

  1. Hidden arguments: a tool function can have parameters that the environment injects but that are left out of the model’s tool schema (with args_to_skip).
  2. update_tool_args: an abstract method you implement to inject state into tool calls at runtime.
python
class MySandboxEnv(vf.StatefulToolEnv):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_tool(self.run_code, args_to_skip=["session_id"])
async def setup_state(self, state, **kwargs):
state["session_id"] = await create_session()
return await super().setup_state(state, **kwargs)
def update_tool_args(self, tool_name, tool_args, messages, state, **kwargs):
if tool_name == "run_code":
tool_args["session_id"] = state["session_id"]
return tool_args
async def run_code(self, code: str, session_id: str) -> str:
"""Execute code in the sandbox."""
return await execute_in_session(session_id, code)

The model sees run_code(code: str) in its tool schema, but the environment injects session_id from rollout state before each call.

Verifiers has built-in stateful environment classes: SandboxEnv gives the model a containerized bash shell, and PythonEnv extends it with a persistent Python REPL. Both manage the sandbox lifecycle for you.

Both SandboxEnv and CliAgentEnv accept a labels parameter for tagging sandboxes:

python
env = vf.SandboxEnv(
dataset=dataset,
rubric=rubric
)

Stateful environments often manage resources with methods decorated with @vf.cleanup (called after each rollout) or @vf.teardown (called once when the environment shuts down). Together with @vf.stop for custom stop conditions (boolean functions checked after each turn), these decorators give you control over the rollout lifecycle in custom MultiTurnEnv subclasses.

For interactions other than tool calling, such as games, simulations or your own protocols, subclass MultiTurnEnv directly. That gives you full control over the rollout loop.

Each rollout follows this structure:

  1. Initialize state: setup_state(state) prepares per-rollout resources.
  2. Loop until done:
    • Get the prompt messages (the initial prompt, or the conversation so far plus the environment’s response).
    • Get the model’s response.
    • Check stop conditions. If any @vf.stop method returns True, exit the loop.
  3. Render the completion: the final conversation is assembled into state["completion"].
  4. Clean up: all @vf.cleanup methods are called.

Every MultiTurnEnv subclass must override the abstract env_response method, which defines how the environment responds after each model turn:

python
class MyGameEnv(vf.MultiTurnEnv):
async def env_response(self, messages: vf.Messages, state: vf.State) -> vf.Messages:
"""Generate the environment's response after each model turn."""
parsed = self.parser.parse(messages)
action = parsed.action
feedback = process_action(action)
return [{"role": "user", "content": feedback}]
async def correct_action(parser, completion, answer) -> float:
parsed = parser.parse(completion)
return 1.0 if parsed.action == answer else 0.0
def load_environment():
parser = vf.XMLParser(fields=["action"])
rubric = vf.Rubric(funcs=[correct_action], parser=parser)
return MyGameEnv(dataset=dataset, rubric=rubric, parser=parser)

env_response receives the conversation so far (and state) and returns a list of new messages to append. A parser passed to the environment is available as self.parser, and passing the same parser to the rubric lets reward functions ask for it by name. In a tool environment, env_response usually runs the tool calls and returns the results. In a game or another custom protocol, it might parse structured output (as above) and return state updates or feedback.

For more control in complex environments, you can also override these methods:

  • setup_state(state): add environment-specific state fields when a rollout starts
  • get_prompt_messages(state): change how messages are assembled (for non-linear conversations, for example)
  • render_completion(state): change how the final completion is assembled
  • add_trajectory_step(state, step): set intermediate rewards, advantages or extra metadata per turn

A rollout continues until a stop condition is met. Stop conditions are checked after each model response, and you define your own with the @vf.stop decorator:

python
class MyGameEnv(vf.MultiTurnEnv):
@vf.stop
async def game_won(self, state: vf.State) -> bool:
return state.get("won", False)
@vf.stop
async def game_lost(self, state: vf.State) -> bool:
return state.get("lives", 1) <= 0

By default, MultiTurnEnv has built-in stop conditions for errors, prompt length limits and max_turns.

priority sets the order in which conditions run (higher runs first), so you can check cheap conditions before expensive ones:

python
@vf.stop(priority=10) # cheap keyword check runs first
async def answer_submitted(self, state: vf.State) -> bool:
completion = state.get("completion", [])
if not completion:
return False
return "FINAL ANSWER:" in completion[-1].get("content", "")
@vf.stop(priority=-10) # expensive validation runs last
async def answer_detected(self, state: vf.State) -> bool:
# only runs if cheap checks didn't already stop
return await self.validator_client.check_for_answer(state)

Verifiers defines a hierarchy of error types under vf.Error:

  • vf.ModelError: errors from model interactions (for example vf.EmptyModelResponseError)
  • vf.OverlongPromptError: the prompt is longer than the model’s context
  • vf.ToolError: tool errors (vf.ToolParseError, vf.ToolCallError)
  • vf.InfraError: infrastructure errors (for example vf.SandboxError)

A vf.Error raised during a rollout is caught and stored in state["error"], and the built-in has_error stop condition ends the rollout at the next check. The rollout stops cleanly instead of crashing.

In a tool environment, stop_errors sets which errors end the rollout immediately:

python
vf_env = vf.ToolEnv(
tools=[my_tool],
stop_errors=[vf.ToolParseError], # stop on parse errors, but continue on other tool errors
...
)

Errors not listed in stop_errors are caught and returned as tool response messages, which gives the model a chance to recover.

Override setup_state to initialize per-rollout state:

python
class MyGameEnv(vf.MultiTurnEnv):
async def setup_state(self, state: vf.State) -> vf.State:
state["board"] = initialize_board()
state["score"] = 0
return await super().setup_state(state)

For resource management, use @vf.cleanup (per-rollout) and @vf.teardown (at environment shutdown):

python
class MyGameEnv(vf.MultiTurnEnv):
@vf.cleanup
async def save_game_log(self, state: vf.State):
await log_game_result(state["game_id"], state["score"])
@vf.teardown
async def close_connections(self):
await self.db_connection.close()

Important: Cleanup methods should be idempotent (safe to call more than once) and should handle their own errors. Then they behave correctly when a rollout is cancelled or interrupted, and cleanup still finishes when resources are in an unexpected state.

To end a rollout from inside env_response (when the game ends, for example), set state["final_env_response"]:

python
async def env_response(self, messages: vf.Messages, state: vf.State) -> vf.Messages:
if check_game_over(state):
final_message = [{"role": "user", "content": "Game over! Final score: " + str(state["score"])}]
state["final_env_response"] = final_message
return final_message
# ... normal response logic

This skips the normal model response loop and ends the rollout at once. Use it when the environment’s response itself marks the end (a game is won, an answer is submitted) or is needed to compute the reward (final feedback or tool results).

Environments are packaged as installable Python projects. surogate vf-init creates a new environment project:

bash
surogate vf-init my-env

This creates the following structure:

environments/my_env/
├── my_env.py # environment implementation
├── pyproject.toml # package metadata and dependencies
└── README.md # documentation template

The environment file must export a load_environment() function that returns a vf.Environment. Declare every argument your environment accepts explicitly:

python
import verifiers as vf
def load_environment(difficulty: str = "easy", num_examples: int = -1) -> vf.Environment:
# build dataset, rubric, etc.
return vf.SingleTurnEnv(dataset=dataset, rubric=rubric)

pyproject.toml holds the package metadata, dependencies and evaluation defaults:

toml
[project]
name = "my-env"
description = "My custom environment"
tags = ["single-turn", "math", "train", "eval"]
version = "0.1.0"
requires-python = ">=3.10"
dependencies = [
"verifiers>=0.3.0",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build]
include = ["my_env.py", "pyproject.toml"]
[tool.verifiers.eval]
num_examples = 20
rollouts_per_example = 5

The main pyproject.toml sections:

  • [project]: package name (used by surogate vf-eval), description, version and dependencies.
  • [build-system]: Hatchling is the build backend for the Environments Hub.
  • [tool.hatch.build]: the files to include in the package. Always list pyproject.toml next to your environment file, so the environment metadata is available once it is installed. Add any other source files here.
  • [tool.verifiers.eval]: default parameters for surogate vf-eval when you don’t pass flags.

Declare every package your environment needs in the dependencies array, always including verifiers with a minimum version. Libraries listed here are installed automatically along with the environment:

toml
dependencies = [
"verifiers>=0.3.0",
"chromadb",
"nltk>=3.9.2",
]

If your environment needs external API keys (for a judge model or another service, for example), check them early in load_environment() with vf.ensure_keys():

python
import verifiers as vf
def load_environment(api_key_var: str = "OPENAI_API_KEY") -> vf.Environment:
vf.ensure_keys([api_key_var])
# now safe to use os.environ[api_key_var]
...

If keys are missing, it raises MissingKeyError with a message that lists them and explains how to set them:

  • Environments Hub CI: add secrets on the environment’s Settings page.
  • Hosted Training: set env_file in your config (for example env_file = ["secrets.env"]).
  • Local: export them in your shell (for example export OPENAI_API_KEY=...).

List the required variables in your README, under a “Required Environment Variables” section.

EnvGroup combines several environments into one, so you can evaluate and train on different tasks from a single entry point. Each sub-environment keeps its own dataset, rubric and rollout logic, and the group handles routing and collects the metrics:

python
math_env = load_math_environment()
code_env = load_code_environment()
reasoning_env = load_reasoning_environment()
combined = vf.EnvGroup(
envs=[math_env, code_env, reasoning_env],
env_names=["math", "code", "reasoning"],
)

The group concatenates the sub-environment datasets and sets each row’s info["env_id"] to the name of its sub-environment. That tag sends each rollout to the right environment for generation and scoring, and it is carried through to the info of each RolloutOutput. Metrics from all environments are tracked together.

Integrations and Experimental Environments

Section titled “Integrations and Experimental Environments”

Besides the core environment types, Verifiers integrates with several third-party environment libraries, and has a few newer, experimental environment classes (less stable and more likely to change).

Third-party integrations:

  • TextArenaEnv wraps TextArena text-based game environments.
  • ReasoningGymEnv wraps reasoning-gym procedural datasets.
  • BrowserEnv drives a browser through Browserbase, in DOM or CUA mode.

These need extra dependencies, installed as extras (for example uv add 'verifiers[ta]' for TextArena, uv add 'verifiers[browser]' for BrowserEnv, uv add 'verifiers[openenv]' for OpenEnvEnv).

Experimental environment classes:

  • GymEnv runs any Gym-compatible environment (OpenAI Gym / Gymnasium API).
  • CliAgentEnv runs your own agent code inside sandboxes and intercepts its API requests. It takes sandbox settings including docker_image, cpu_cores, memory_gb, disk_size_gb, gpu_count, timeout_minutes, environment_vars, and labels for grouping sandboxes. Through SandboxMixin it also takes retry settings (like max_retries) and connection pooling settings (like sandbox_client_max_workers).
  • HarborEnv loads Harbor-format agent benchmark tasks.
  • RLMEnv implements Recursive Language Models, which handle unbounded context by decomposing it in a REPL and making recursive sub-LLM calls.

Next: RL Training (GRPO) shows how to train a model on your environment, and the GRPO kits are complete environments with configs you can copy.