Skip to main content

Environment

Base abstract class for creating RL environments to train and evaluate LLMs.

Overview

The Environment class provides the core infrastructure for:
  • Managing datasets (training and evaluation)
  • Running rollouts with LLM clients
  • Scoring rollouts with rubrics
  • Handling state lifecycle and cleanup
  • Token usage tracking
All custom environments must inherit from this class and implement the rollout() method.

Inheritance Hierarchy

Constructor

Parameters

Dataset | DatasetBuilder | None
Training dataset or a callable that returns a dataset. Either dataset or eval_dataset must be provided.
Dataset | DatasetBuilder | None
Evaluation dataset or a callable that returns a dataset.
str | None
System prompt to prepend to all conversations.
Messages | None
Few-shot examples to include in prompts.
Parser | None
Parser for extracting structured data from completions. Defaults to Parser().
Rubric | None
Rubric for scoring rollouts. Defaults to Rubric().
SamplingArgs | None
Default sampling arguments for generation (temperature, top_p, etc.).
list[Tool] | None
Provider-agnostic tool definitions in vf.Tool format.
int
default:"512"
Maximum number of worker threads for synchronous execution.
str | None
Unique identifier for this environment.
dict | None
Additional environment-specific arguments.
dict
default:"{}"
Keyword arguments to pass to HuggingFace dataset .map() operations.
int | None
Maximum sequence length for tokenization and truncation.
bool
default:"True"
Whether to score rollouts using the rubric.
float
default:"0.5"
Reward threshold for considering a rollout as “passed”.

Core Methods

rollout

Run a single rollout for a given input. Must be implemented by subclasses.
RolloutInput
Input data from the dataset containing prompt, answer, etc.
Client
LLM client for making API calls.
str
Model identifier (e.g., “gpt-4”, “claude-3-5-sonnet”).
SamplingArgs | None
Optional sampling arguments to override defaults.
Returns: State - Final state after rollout completion.

get_model_response

Get model response for a given prompt (chat or completion).
State
Current rollout state.
Messages | str
Prompt as messages or string.
Client | None
Client to use (defaults to state["client"]).
str | None
Model to use (defaults to state["model"]).
list[Tool] | None
Tools available for this request (defaults to state["tool_defs"]).
SamplingArgs | None
Sampling arguments (defaults to state["sampling_args"]).
Returns: Response - Model response with message, usage, etc.

init_state

Create initial state from dataset input. Called automatically at the start of each rollout.
RolloutInput
Input data from the dataset.
Client | ClientConfig
Client or client configuration.
str
Model identifier.
SamplingArgs | None
Sampling arguments.
Returns: State - Initialized state with input fields, client, model, etc.

Dataset Methods

build_dataset

Build and cache the training dataset from source if needed. Returns: Dataset | None - Built dataset or None if no source.

build_eval_dataset

Build and cache the evaluation dataset from source if needed. Returns: Dataset | None - Built dataset or None if no source.

get_dataset

Get the training dataset, optionally shuffled and limited.
int
default:"-1"
Maximum number of examples to return. -1 returns all.
int | None
Random seed for shuffling.
Returns: Dataset - Training dataset.

get_eval_dataset

Get the evaluation dataset, optionally shuffled and limited. Falls back to training dataset if no eval dataset exists.
int
default:"-1"
Maximum number of examples to return. -1 returns all.
int | None
Random seed for shuffling.
Returns: Dataset - Evaluation dataset.

Generation & Evaluation

generate

Generate rollouts for a set of inputs.
Dataset | List[RolloutInput]
Input examples to generate rollouts for.
Client | ClientConfig
LLM client or client configuration.
str
Model identifier.
SamplingArgs | None
Sampling arguments to override defaults.
int
default:"-1"
Maximum concurrent rollouts. -1 for unlimited.
Path | None
Path to save/resume results.
list[str] | None
Additional state fields to include in outputs.
bool
default:"False"
Whether to save results to disk.
bool
default:"False"
Whether to push results to HuggingFace Hub.
str | None
Dataset name for HuggingFace Hub.
bool
default:"False"
Score rollouts independently vs. in groups.
int
default:"0"
Maximum retries for failed rollouts.
StartCallback | None
Callback when generation starts.
ProgressCallback | list[ProgressCallback] | None
Progress callback(s). None uses default tqdm progress bar.
LogCallback | None
Logging callback.
Returns: GenerateOutputs - Dictionary with outputs and metadata keys.

generate_sync

Synchronous wrapper for generate(). Handles event loop creation.

evaluate

Evaluate model on the environment’s evaluation dataset.
Client | ClientConfig
LLM client or client configuration.
str
Model identifier.
int
default:"-1"
Number of examples to evaluate. -1 for all.
int
default:"1"
Number of rollouts to generate per example.
Other parameters are the same as generate(). Returns: GenerateOutputs - Dictionary with outputs and metadata keys.

evaluate_sync

Synchronous wrapper for evaluate().

Token Usage Tracking

get_state_usage

Get token usage statistics for a state.
State
Rollout state.
Returns: TokenUsage | None - Dictionary with input_tokens and output_tokens keys, or None.

increment_state_usage

Manually increment token usage for a state.

increment_state_usage_from_response

Extract and increment token usage from a response object.

State Lifecycle

is_completed

Check all stop conditions. Sets state["is_completed"] = True if any condition is met.
State
Current rollout state.
Returns: bool - True if any stop condition is met.

Configuration

set_kwargs

Set environment attributes using setter methods when available.

add_rubric

Add a rubric to the environment. Creates a RubricGroup if a rubric already exists.

set_max_seq_len

Set the maximum sequence length.

set_score_rollouts

Set whether to score rollouts.

Server Methods

start_server

This method is subject to change. External users should avoid depending on it directly.
Start a ZMQ server process for distributed rollout execution.

stop_server

This method is subject to change. External users should avoid depending on it directly.
Stop the ZMQ server process.

Static Methods

make_dataset

Utility for creating HuggingFace datasets. See verifiers.utils.save_utils.make_dataset for details.

Example Usage

See Also