Environments (OpenEnv)¶
Every LLM-training environment in AgileRL is reached the same way: text in, text
out, through the OpenEnv API
(installed with the [llm] extra). A RolloutHarness drives the env in the
training process, or over a URL.
Two types¶
env_type is required. It is not inferred from the algorithm.
|
What it means |
|---|---|
|
The model generates and the environment scores it. A single-turn scored
task is |
|
Supervised, no generation. Requires |
The text interface¶
An environment is any object with two methods:
def reset(self, seed: int | None = None) -> tuple[str, dict]:
# returns (prompt_text, info)
...
def step(self, action: str) -> tuple[str, float, bool, bool, dict]:
# returns (observation_text, reward, terminated, truncated, info)
...
reset returns the first prompt; step receives the model’s decoded text and
returns the next observation, a reward, and whether the episode has ended. Optional
extras: a tools attribute, and a dataset_size property with extra reset
kwargs (covered below).
Each concurrent rollout gets its own env instance, created once and reused for the whole run. Over a URL, one server fronts the whole batch: each rollout opens its own WebSocket session and the server builds a fresh env for that session.
Writing one in Python¶
Pass the env to RolloutHarness.local.
It runs in the training process, with no HTTP:
from agilerl.llm_envs import RolloutHarness
class GuessEnv:
"""Guess-the-number: the model proposes a number; the env scores it."""
def __init__(self, target: int = 7, max_turns: int = 3) -> None:
self.target, self.max_turns, self._turn = target, max_turns, 0
def reset(self, seed: int | None = None) -> tuple[str, dict]:
self._turn = 0
return "Guess a number between 1 and 10.", {}
def step(self, action: str) -> tuple[str, float, bool, bool, dict]:
self._turn += 1
guess = int("".join(c for c in action if c.isdigit()) or 0)
correct = guess == self.target
done = correct or self._turn >= self.max_turns
feedback = "Correct!" if correct else ("Too high." if guess > self.target else "Too low.")
return feedback, float(correct), done, False, {}
env = RolloutHarness.local(GuessEnv(), tokenizer, max_turns=3)
max_turns bounds the episode; the env can still finish earlier by returning
terminated=True. max_turns=None puts no cap on turns: the episode runs
until the env ends it or the next prompt no longer fits max_model_len, which
must then be set. For a batch, wrap the same call so each slot gets its own
instance:
env_factory = lambda: RolloutHarness.local(GuessEnv(), tokenizer, max_turns=3)
Naming one from a manifest¶
A rollout names exactly one source. That is what decides where it runs.
The manifest names |
The environment runs |
Started by |
|---|---|---|
|
in the training process |
the job |
|
in the training process |
the job |
|
wherever it already is |
someone else, beforehand |
Dataset rows plus a reward file¶
The model answers each labelled row once; a Python file scores it. This is still
env_type: rollout (the model generates). Full example:
configs/training/llm_finetuning/grpo.yaml.
environment:
env_type: rollout
dataset: Jiayi-Pan/Countdown-Tasks-3to4
columns:
nums: question
target: answer
rubric_file_path: reward.py
rubric_name: RUBRIC
prompt_template:
system_0: You are a helpful assistant.
user_1: Using each number in {question}, make an equation that equals {answer}.
max_reward: 2.0
train_test_split: 0.8
dataset is a HuggingFace id or a Parquet path. rubric_file_path also
accepts the alias reward_file_path. The reward file sits next to the
manifest (see docs/_static/examples/gsm8k-grpo/reward.py).
A Python entrypoint¶
entrypoint is the env to build (a registry id, or module:Class). Optional
factory is the module:attr callable that receives that id as its first
argument. env_config is leftover kwargs only — not a place for env_id:
environment:
env_type: rollout
factory: gem:make
entrypoint: game:GuessTheNumber-v0-easy
max_turns: 50
max_reward: 1.0
The same GuessEnv from above, as a file next to the run:
environment:
env_type: rollout
entrypoint: guess_env.py:GuessEnv
env_config:
target: 7
max_turns: 3
That env runs in the training process. Leaving max_turns out is allowed
here: it is probed off one throwaway env and cached. A remote env cannot be
probed, which is why env_url requires it.
Put a system prompt in env_config; RolloutHarness renders it as a leading
system message. It is set on the built env, not forwarded to gem.make:
env_config:
system_prompt: You are playing a guessing game. Reply with one number.
An already-running server¶
If the environment is already an OpenEnv server, point at its URL. Nothing is
started locally. max_turns is required. To stand the server up from an
entrypoint, use resolve_env() (same
entrypoint / env_config as a local run):
from agilerl.llm_envs.openenv_server import resolve_env
url, server = resolve_env(
"code:Taco8k",
factory="gem:make",
env_config={"sandbox_type": "bwrap"},
port=8000,
max_concurrent_envs=16,
)
environment:
env_type: rollout
env_url: http://127.0.0.1:8000
max_turns: 1
request_timeout_s: 600
Each rollout opens its own /ws session. The server’s max_concurrent_envs
must cover batch_size * group_size sessions plus one for the evaluation
env, which is built lazily at the first evaluation. request_timeout_s bounds
each message at 300 seconds by default (0 disables the bound).
Walkthrough: Serving Environments Remotely (WebSocket Sessions) — host a coding env on one machine and train on a GPU box.
Scoring any env with a rubric¶
rubric_file_path works with every source above, not only dataset rows. The
rubric scores every turn and its score replaces the env’s reward for that turn.
Without one, the env’s own reward is used.
A rubric is an OpenEnv Rubric called with a
TurnAction (message the env got after
action_processor, completion with reasoning, parsed tool_calls) and a
TurnObservation (env_reward,
env_ran, done, prompt, question / answer when the env sends
them). EnvReward brings the env’s reward in as
the env component; combine it with OpenEnv’s WeightedSum, Gate or
Sequential:
from openenv.core.rubrics.base import Rubric
from openenv.core.rubrics.containers import WeightedSum
from agilerl.llm_envs.rubrics import EnvReward
class Concise(Rubric):
component_name = "concise"
def forward(self, action, observation) -> float:
return 1.0 if len(action.message) < 200 else 0.0
class RUBRIC(WeightedSum):
def __init__(self) -> None:
super().__init__([EnvReward(), Concise()], weights=[0.8, 0.2])
environment:
env_type: rollout
entrypoint: guess_env.py:GuessEnv
rubric_file_path: reward.py
rubric_name: RUBRIC
max_turns: 3
A turn rejected for a malformed tool call reaches the rubric with
env_ran=False and env_reward set to min_reward. Each leaf is logged as
reward_<name>.
An LLM judge¶
LLMJudgeRubric scores an episode against
criteria you write. Set judge next to rubric_file_path; a Rubric class
whose __init__ takes judge is built with the run’s shared client:
from openenv.core.rubrics.containers import WeightedSum
from agilerl.llm_envs.rubrics import EnvReward, LLMJudgeRubric
class RUBRIC(WeightedSum):
def __init__(self, judge) -> None:
super().__init__(
[EnvReward(), LLMJudgeRubric(judge, "The reply is correct and polite.")],
weights=[0.7, 0.3],
)
environment:
env_type: rollout
entrypoint: guess_env.py:GuessEnv
rubric_file_path: reward.py
rubric_name: RUBRIC
judge:
provider: openai # or anthropic (needs the anthropic package)
model: gpt-4.1-mini
api_key_env: OPENAI_API_KEY # the variable's name, never the key
max_concurrency: 16
base_urlpoints the judge at any OpenAI-compatible endpoint withprovider: openai: a router or cheaper host (OpenRouter, Together, Groq) or self-hosted vLLM. A URL with a path is used as given (https://openrouter.ai/api/v1); a bare host (http://judge:8000) gets/v1. Leaveapi_key_envunset when the endpoint needs no key.On Arena,
api_key_envnames an organization secret: store the key witharena secrets set OPENAI_API_KEY(see Organization Secrets).provider: bedrockcalls Amazon Bedrock’s Converse API with the machine’s AWS credentials. Setmodelto a Bedrock model id andregion; it takes nobase_urlorapi_key_env.The judge reads the prompt, each turn’s text after its reasoning, and the env’s replies.
LLMJudgeRubric(..., include_reasoning=True)also shows it the reasoning. Scoring reasoning trains the model to write reasoning the judge likes, so leave it off unless that is the goal.It scores the episode’s last turn, earlier turns 0;
every_turn=Truejudges each turn.The provider SDK retries rate limits, server errors and timed-out attempts;
timeout_sbounds each attempt. A call that still fails stops the run. A verdict without a readable{"score": ...}scores 0.On dataset rows, the judge reads the row’s question and is shown its answer as
REFERENCE ANSWER, so criteria can compare against it.Anthropic judges take no
temperature: setting one is rejected.max_tokens(default 4096) also covers a thinking judge’s thinking, such asclaude-haiku-5-5’s: set it too low and the verdict is cut off.Two judges in one rubric need distinct names,
LLMJudgeRubric(..., name=...): each leaf reports onereward_<name>metric, and a repeated name is an error.reward_<name>counts an episode aSequentialorGatekept from that leaf as 0.Training logs
judge_calls,judge_parse_failure_rateandjudge_mean_latency_s.
For an end-to-end walkthrough on Arena, from storing the key to reading the judge’s notes, see Training GRPO with an LLM Judge in Arena.
Scoring a group together (RULER)¶
A GroupRubric scores a group’s completions
together, once every member has finished. Each score is added to that episode’s
final-turn reward before the buffer, so tied-group filtering, adaptive task
sampling and advantages all see it. Write your own score_group(episodes), or
use LLMGroupJudgeRubric (RULER), which shows a
judge the whole group in one call:
from agilerl.llm_envs.rubrics import LLMGroupJudgeRubric
class RULER(LLMGroupJudgeRubric):
def __init__(self, judge) -> None:
super().__init__(judge, "The reply is correct and concise.")
environment:
env_type: rollout
entrypoint: guess_env.py:GuessEnv
rubric_file_path: reward.py
group_rubric_name: RULER
judge:
provider: openai
model: gpt-4.1-mini
api_key_env: OPENAI_API_KEY
group_rubric_namenames a symbol inrubric_file_path. Leaverubric_nameunset to keep the env’s own turn reward; on dataset rows the turn reward is 0, so the group score is the whole reward. Set it to add a per-turn rubric as well.With
judgeset, the group rubric must be a class takingjudge; the turn rubric takes the judge only if its__init__asks for it.The judge sees no reasoning unless
include_reasoning=True. It replies with{"scores": [...]}, each clamped to [0, 1]. A reply it cannot read, or with the wrong number of scores, scores the whole group 0 and counts as a parse failure.Each call shows the episodes in a new random order and maps the scores back, so a judge that favours a position adds noise rather than bias.
seed=makes the order repeatable.One instance serves the whole collector and groups overlap, so keep no per-group state on
self.Training logs the score as
reward_<component_name>(groupby default,group_judgeforLLMGroupJudgeRubric).Group replay is off with a group rubric: a score relative to one group cannot be compared with a return stored from another.
max_rewardsuccess counts include the group score, because it is part of the reward. Held-out evaluation episodes get no group score.On async rollouts, a judge call that still fails after the SDK’s retries fails that group’s episode tasks, which drops the group; repeated failures stop the run.
Training GRPO with an LLM Judge in Arena ends with a RULER variant of its GSM8K run.
Supervised (SFT / DPO)¶
No generation. objective picks the columns and the loss:
environment:
env_type: dataset
objective: sft
dataset: HumanLLMs/Human-Like-DPO-Dataset
response_column: chosen
train_test_split: 0.9
For DPO, objective: preference.
Declaring what the environment needs¶
If the entrypoint’s package is not installed, add env_packages:
environment:
env_type: rollout
factory: gem:make
entrypoint: game:GuessTheNumber-v0-easy
env_packages:
uv: [gem-llm==1.0.0]
max_turns: 50
Warning
env_packages installs into the interpreter training is running in.
The install runs only when the entrypoint cannot already be imported. There
is no prompt and no dry-run. Install the package yourself and leave the
field out if you would rather manage it.
Both uv: and pip: are installed with uv, so uv has to be on
PATH. Package names only; anything starting with - is rejected.
If the packages cannot resolve alongside the trainer’s own dependencies, the
install fails rather than half-upgrading the environment. Host it with
resolve_env() and point env_url
at the URL it returns.
Manifest fields¶
These are the names this package reads:
Field |
Default |
Meaning |
|---|---|---|
|
required |
|
|
|
HuggingFace id or Parquet path. |
|
|
Catalog / dataset label only. Not the env id. |
|
|
Rename source columns (e.g. |
|
|
Reward / rubric file scoring every turn. Required for a dataset-backed
rollout; on an env it replaces the env’s reward. Alias:
|
|
|
Symbol in that file. Alias: |
|
|
|
|
|
LLM judge handed to the rubric: |
|
|
Chat-template pieces rendered into the prompt on reset. |
|
|
Extra kwargs for |
|
|
Fraction of the dataset used for training. |
|
|
Maximum achievable reward, used for accuracy reporting. |
|
|
Send each turn’s reasoning, with the model’s markers ( |
|
|
The env to build: a registry id, or |
|
|
Optional |
|
|
Keyword arguments after the env id. Not a place for |
|
|
|
|
probed |
Turn budget ( |
|
|
URL of an already-running OpenEnv server. |
|
|
Name of the env’s answer tool for prose turns; only applies with |
|
|
Field the env puts the model’s text in ( |
|
|
Field the observation’s text lives in. |
|
|
|
|
|
Per-message bound on a |
|
|
|
|
|
SFT completion column. |
Evaluation and grouped rollouts¶
A dataset-backed env exposes dataset_size and accepts two extra kwargs on
reset:
def reset(self, seed=None, *, row_index: int | None = None,
evaluation: bool | None = None) -> tuple[str, dict]:
# row_index selects a row; evaluation=True serves the held-out split
...
The collector draws one row per batch item and reuses it across that item’s
GRPO group, so grouped-advantage compares like with like. At evaluation it
passes evaluation=True and opens one extra session (the + 1 in
max_concurrent_envs). The env must be reproducible from
(seed, row_index).
Advantage granularity¶
On GRPO (and CISPO / GSPO), algorithm.advantage_granularity is
auto | trajectory | turn, default auto. trajectory is one
group-relative scalar per completion; turn normalises each turn’s reward
within the group; auto picks turn when the batch has per-turn rewards
and more than one turn. token is not a GRPO value.
LLMPPO and LLMREINFORCE take advantage_granularity over
{turn, token, auto}.
Observations that are not plain text¶
Third-party OpenEnv environments do not agree on where their observation’s text
lives — a coding env returns {"stdout": "...", "stderr": "", "exit_code": 0},
BrowserGym {"text": "..."}, OpenSpiel a numeric {"info_state": [...]}.
The harness renders the payload via an observation processor:
observation_fieldnames the field, when a lookup is enough.observation_processoris amodule:fn/path/to/file.py:fnthat turns the payload into prompt text.
environment:
env_type: rollout
env_url: https://my-openspiel-env.example.com
max_turns: 12
observation_processor: render_board.py:render
# render_board.py
def render(payload: dict) -> str:
return "Board state: " + ", ".join(str(v) for v in payload["info_state"])
Keep the processor a pure function of the payload; it runs on the collector’s I/O threads.
Note
observation_field and observation_processor are read by local
agilerl training. On Arena, have the
environment server render text itself.
Tools¶
A plain-text env advertises tool schemas with a tools attribute (a list of
JSON schemas). AgileRL renders them into the chat template. There is no
separate tools config.
An MCP-backed env (an MCPEnvironment subclass hosting tools) is driven by
tool calls instead of text. The harness detects this from the env itself, so
manifests need no extra flag. The env never parses the model’s output. Each
model family has its own tool-call format: the special
tokens around a call and the body between them. The harness reads every call
from each generation’s token IDs with that family’s chat format, and steps the env
once per call, in order, within the turn. The turn’s reward is the sum of those
steps. Tool schemas are discovered over list_tools and rendered into
prompts through the chat template.
Chat formats cover the Qwen, Hermes, Granite, Nemotron, Gemma 4, GPT-OSS, GLM,
and DeepSeek-V4 model families. The same format also says where the model’s
reasoning ends, so the env acts only on the answer. Name one with
chat_format on RolloutHarness; unset, the harness picks the format whose
tokens are in the tokenizer vocab. An MCP env with a tokenizer no format matches fails at the
first reset.
A turn with no tool call is a prose answer. answer_tool="<tool_name>" on
RolloutHarness or in the manifest names one of the env’s real tools (e.g.
guess, submit_answer) to receive that prose as its action_field
argument, so the env scores it. Without answer_tool the model gets a tool
error to retry. A malformed call runs nothing: the model gets a tool error,
and the turn scores min_reward (0 unless the manifest sets it). Rules
about which tools may run, in what order, and how an answer scores belong to
the env, behind its tools.
An env whose tools change per episode returns them from reset in the info
under episode_tools (OpenAI function schemas); the harness renders and
parses that episode against them, and [] gives the episode no tools. A
reset without the key uses the env’s listed tools. Each call the harness steps
carries its whole turn on CallToolAction.metadata (turn_tool_calls and
turn_tool_call_index), so an env that must see a turn’s calls together
gets them on the turn’s first step.
Prime Intellect Hub (verifiers) envs¶
agilerl.llm_envs.verifiers_env:make serves a verifiers v1 env (pip install
agilerl[verifiers]). The entrypoint is the taskset id; env_config is the
verifiers env config, plus num_tasks to serve only the first tasks
(required for an infinite taskset). verifiers tasksets have no held-out split,
so an evaluation reset serves the same tasks as training. A taskset whose
tasks bring tools is served as an MCP env with episode_tools; give it
answer_tool: verifiers_reply so a turn without a call reaches verifiers as
the model’s reply. verifiers_reply reads its one argument whatever its
name, so action_field is optional:
environment:
env_type: rollout
factory: agilerl.llm_envs.verifiers_env:make
entrypoint: bfcl-v3
env_packages:
uv: [verifiers==0.4.2.dev6, "bfcl-v3 @ git+https://..."]
env_config:
taskset:
test_categories: [simple_python, parallel, multi_turn_base]
agent:
harness: {id: "null"}
answer_tool: verifiers_reply
max_turns: 6
Tasks that deny network access or run in a container need a sandbox runtime
under agent.runtime: verifiers’ docker or prime runtime, or your own
backend as type: custom with its import_path.
Lifecycle¶
The environment is built once per rollout and reused for the whole run.
close()(if the env has one) is called exactly once, on teardown — not per step.Closing a
RolloutHarnessends its WebSocket session or closes the in-process env.
Lower-level pieces¶
InProcessEnvClient— drives a local env’sreset/stepdirectly. WhatRolloutHarness.local()uses.RemoteEnvClient— one/wssession against a server, which backs each session with its own env.resolve_env— start a server from the sameentrypoint/env_configa local manifest would use. Returns(url, server).max_concurrent_envsgives each session its own env instance.
from agilerl.llm_envs.openenv import RemoteEnvClient
from agilerl.llm_envs.openenv_server import resolve_env
url, server = resolve_env(
"guess_env.py:GuessEnv",
env_config={"target": 7},
max_concurrent_envs=8,
)
client = RemoteEnvClient(url)
payload, _ = client.reset()
payload, reward, terminated, truncated, info = client.step("5")
client.close()
server.stop()
RolloutHarness.from_spec
picks the trainer-side transport: a URL → WebSocket client; a
package.module:EnvClass entrypoint → in-process. Use resolve_env when
you want that entrypoint hosted as a URL instead.
Training on Arena¶
This package’s manifest names a dataset, an entrypoint, or an env_url.
On Arena, a container or an external URL is an
environment version you pick in the UI, not a field this spec validates.
Unknown extra keys on environment are ignored.
Migrating from the pre-OpenEnv API¶
Retired keys are rejected rather than coerced, so a stale manifest fails at parse instead of quietly training something else.
Manifest keys:
Was |
Is now |
|---|---|
|
|
|
|
|
|
|
|
|
|
Python API:
Was |
Is now |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
There is no compatibility shim; the old names are gone.
Rollout data: the trajectory tensor on the wire is token_ids, not
completion_ids. A custom environment no longer subclasses anything —
reset and step, in text, are the whole interface.
See the API reference for the full signatures.