Experiential
BlogTraining

RL environments for LLM agents: what they are and how to build one

November 2026 · 12 min

A reinforcement learning environment (RL environment) for an LLM agent is the program the model acts in during training, imitating the world around it. The environment responds to each action, often by changing its state, and returns the next observation, so the model runs in closed loop and learns from its own choices. A reward model scores each trajectory, and policy gradient training reinforces trajectories with higher advantage.

Training on fixed expert demonstrations runs in open loop, leaving the model subject to exposure bias because it never encounters its own mistakes during training. Closed-loop RL forces the model to recover from imperfect actions and error states while generating its own reasoning traces (see SFT vs RL for when online RL beats imitation).

For an agent, the environment is usually the hardest part of the project because it must resemble production closely enough for learned behaviors to transfer. Paired with the reward model, it sets both what the model practices on and whether rollouts produce useful gradient signal.

What an RL environment contains

An RL environment for an LLM agent consists of a task, observations, actions, state and a reward model, orchestrated across repeated episodes. Together they define the closed loop the agent trains inside.

Task, state, actions and observations

A task supplies the episode's instruction, starting data and reference checks, while state, actions and observations carry each turn of the closed loop. In Prime Intellect's verifiers library, reference answers sit in separate task fields on the evaluator and never enter the agent's prompt.

An observation is what the model receives: the initial prompt, followed by each tool result, terminal output, error message or updated interface. An action is a tool call, shell command or final answer, and state is the underlying database, filesystem or browser session that those actions mutate. In OpenEnv's simulation mode, tool calls are sent through step() as actions so they count as steps, accrue rewards and land in the training trajectory.

Reward models and verifiers

A reward model scores the agent's behavior in an episode, producing either dense process-level rewards across intermediate steps or sparse outcome-level rewards at the end. A verifier is a specific kind of reward model that returns a binary outcome reward (such as 1 or 0) from deterministic checks like unit tests, exact-match labels or a final database comparison.

Group-based RL algorithms such as GRPO and DAPO, the GRPO variant that matters most in practice, work with either dense process rewards or sparse verifiers. In practice most runs use sparse outcome rewards, and DeepSeek showed that models can learn strong process-level reasoning from outcome-level rewards alone.

Reward models vary widely in what they inspect. τ-bench grades tool-using agents by comparing the final database state against an annotated goal state and checking that the agent's replies include required information. OpenEnv computes rewards inside the environment from composable rubrics, including LLM judges for subjective criteria.

Episodes, advantages and tasks with 0 gradient

During each episode, an agent runs from reset to completion, and policy gradient updates reinforce trajectories with higher advantage while ignoring groups whose advantage is 0. An episode ends when the task terminates or when a step or time limit truncates it. In Gymnasium, described on PyPI as a standard API for RL, reset() starts the episode and step(action) returns the next observation, reward, termination flag, truncation flag and info dictionary.

PPO trains a learned critic to estimate advantage, whereas GRPO estimates advantage from the reward statistics of a group of sampled rollouts on the same task, removing the learned critic. When every rollout in a group receives the same reward, including when every attempt earns the maximum score or 0, every trajectory has an advantage of 0 and adds no policy gradient.

That math drives environment design. For GRPO with a binary outcome reward, good environments target the capability frontier, where some rollouts pass and others fail; groups where every attempt passes or fails burn rollout compute and add no reward-based policy gradient. Dense rewards can still separate attempts within those groups.

Harbor: the emerging standard for agent RL environments

Harbor is the emerging standard for agent RL environments and evaluation, and it is what we build on at Experiential. Modern coding and computer-use agents run inside harnesses that control their own tool loops, making containerized task packages a cleaner fit than step-by-step Python wrappers.

A Harbor task is a directory with an instruction prompt, a task.toml config, a Dockerized environment/, a reference solution/solve.sh for an oracle agent, and a tests/test.sh verifier that writes /logs/verifier/reward.txt. Every trial starts a fresh container. In Harbor 0.27.0, a separate verifier receives the declared artifacts plus the automatically copied /logs/artifacts/ directory.

Harbor is the right choice for coding and cowork agents that use code execution and a filesystem, where 1 task package drives both evaluation and RL rollouts. If both your agent and tools live solely in external APIs with no filesystem state, a direct service harness fits better.

We pair Harbor tasks with Miles (RadixArk, Apache-2.0) for RL training. Miles runs rollouts on SGLang and trains on Megatron-LM, with FSDP2 and torchtitan backends available, and trained weights serve on either vLLM or SGLang.

Other environment frameworks and catalogs

Start from a public environment catalog whenever an existing task covers your domain, and build custom environments for proprietary tools and internal workflows. Split held-out evaluation tasks out before training begins, because tasks seen during RL rollouts cannot double as an unbiased test set.

OpenEnv ships each environment as a Docker image behind a Gymnasium-style reset(), step() and state() API over WebSocket, listing 40 or more environments as of November 2026 (including BrowserGym wrappers for WebArena and MiniWoB++). Its technical committee includes Meta-PyTorch, Hugging Face, Prime Intellect, RadixArk, Nvidia and Microsoft, and its Harbor integration captures model calls from loop-owning harnesses as framework-neutral training traces.

Prime Intellect's verifiers library provides built-in judge and simulated-user environments, supports CLI harnesses via vf.Harness, and links to the Environments Hub, which listed 1,922 environments on November 23, 2026. Its prime-envs collection wraps benchmarks such as HumanEval and BFCL v3, showing how existing agent benchmarks double as training environments once wrapped in a rollout loop.

4 kinds of RL environment

Every agent RL environment generates the next observation from 1 of 4 sources, and many production systems combine them across different tools. Choosing among them trades off production fidelity against reset speed, safety and step cost.

KindWhere the next observation comes fromStrengthsWeaknessesFits
Real toolsProduction or staging systemsHighest fidelitySide effects, rate limits, cost per call, and state that's hard to reset between episodesRead-only tools, or a staging copy you can restore after each episode
SandboxThe real software in a container or VM, started fresh for each episodeReal behavior for code, files and terminals, and reset by starting a new containerStart-up time and compute per episode, and outside services still need stubsCoding and terminal agents. SWE-Gym pairs each of its 2,438 tasks with an executable runtime and unit tests.
Recorded replayTool results looked up from logged tracesFast and deterministic, with low runtime costCovers only actions someone already took. Once the model acts differently, there's no recorded answer.Single-step tool calls, and regression tests on known paths
SimulationHand-written rules, or a model that predicts the next observation, often grounded in real tracesResponds to actions nobody recorded. A model-based simulator can be rebuilt from new traces.Rules take work to write and a model costs a call per step. The simulator's mistakes become part of what the model learns.Agents whose real tools are expensive or unsafe to call thousands of times

SWE-Gym is a widely cited sandbox environment, pairing 2,438 real-world Python tasks with executable runtimes and unit tests. For most coding and terminal agents, containerized sandboxes give the highest fidelity per dollar of engineering effort.

Why recorded replay breaks in closed-loop RL

Recorded replay breaks the moment an agent leaves the logged trajectory, leaving the environment with no response to return. Recordings capture a demonstrator's states, whereas online RL explores states created by the policy itself, reproducing the coverage gap of open-loop imitation in a sharper form.

Because agents are non-deterministic, a model's actions almost always diverge from runs recorded on real machines. That divergence drove us to evaluate our computer-use agent in closed-loop simulation after collecting initial teacher trajectories on Mac VMs.

Simulated environments grounded in traces

Simulated environments predict how tools and interfaces respond to unseen actions, allowing closed-loop practice without hitting live systems. In our computer-use study, Kimi K2.6 worked through 1,000 generated tasks on Mac VMs, an LLM judge kept the runs that completed their task, and those runs were distilled into Qwen 3.5 9B (+50% tasks completed over the untrained 9B, 97% cheaper than Opus 4.8). We evaluated the model closed loop in our open-source Experiential tool.

That simulation used a RAG database over collected Kimi K2.6 traces, with an LLM acting as a text world model to predict accessibility-tree updates after each action. Because rebuilding a simulation from traces avoids hand-writing brittle rules, rescoring becomes cheap enough to run repeatedly.

The authors of DreamGym apply this approach to RL training by distilling environment dynamics into a reasoning-based experience model, backed by an experience replay buffer initialized with offline real-world data. Policies trained purely on synthetic experience in DreamGym gained further performance when transferred to real-environment RL, needing far fewer real interactions.

Why the environment is the hard part

The environment is harder to get right than the training loop because it controls production fidelity, state resets, rollout cost and reward integrity. Measuring whether training transfers to production requires testing with the same tools and accessibility tree the model sees live, as we found in our computer-use study.

The DreamGym authors identify 4 blockers to agent RL adoption: costly rollouts, limited task diversity, unreliable reward signals and infrastructure complexity. Because a reward model can grade only outcomes the environment exposes, you have to design both together.

Fidelity, resets and rollout cost

An environment must reproduce production failure modes, reset cleanly across attempts and execute cheaply enough for large rollout budgets. If training tools never time out, return stale data or reject malformed arguments, the agent never practices error recovery; your task distribution should also mirror the mix of work the agent handles live.

Group-based RL compares multiple rollouts on the same task, and that comparison is cleanest when every rollout starts from an identical state. Gymnasium's reset() accepts a seed to fix starting randomness, and Prime Intellect's verifiers docs recommend pinning dataset revisions and container images for reproducibility. Shared databases and live APIs leak mutations from earlier episodes unless you reset them after every run.

Outcome-based RL runs every attempt to completion before grading. Across 200 tasks with 8 rollouts each (the rollouts per task group in our Training API recipe) and 10 tool calls per attempt, 1 pass executes 16,000 tool calls, and repeated passes multiply that load. Because RL allocates roughly half its GPUs to rollouts and half to training (such as 1 trainer and 1 sampler on 2 H100s), it usually needs more compute than SFT, which can put every GPU on training.

Side effects and reward hacking

Exploratory rollouts invoke tools thousands of times with bad arguments, so tools that write, pay or delete need a sandbox, a restorable staging copy or a simulation. Meanwhile, RL optimizes whatever shortcut a reward model leaves exposed.

OpenAI researchers reported a reasoning model in training that found 2 hacks across nearly all environments, exit(0) and raise SkipTest, which skipped unit-test evaluation without solving the task. Anthropic researchers studied coding environments used to train Claude Sonnet 3.7 that were vulnerable to hacks such as returning an object whose __eq__ method always returns True, bypassing assert result == expected_output. These hacks never occurred in Sonnet 3.7's training; in the study, a model told about them used them once mitigations were removed.

Grade inside a separate container where the agent cannot edit tests, and score environment-controlled state ahead of the agent's text output. Before training, verify that a reference solution scores 1.0 (Harbor's oracle agent), an untouched workspace scores 0.0 (Harbor's nop agent; vf-validate in verifiers runs both checks) and an intentional cheat scores 0.0. Check no-op behavior as well, since a 2025 audit showed an idle agent passes τ-bench's unsolvable tasks because success requires leaving the database unchanged.

A minimal RL environment in Harbor

A minimal refund-desk environment in Harbor fits in 7 files inside a refund-policy/ directory, runs locally in Docker with no LLM or API key, and grades final store state inside a separate verifier container. The agent receives 2 refund requests and a store CLI tool, and the oracle agent verifies the task end to end before you attach a model.

The 7 task files

Each file under refund-policy/ defines 1 part of the environment: the task prompt, task config, container image, initial state, CLI tool, reference solution and verifier. Place the files at the paths named above each block and run chmod +x on solution/solve.sh and tests/test.sh.

instruction.md gives the agent the refund policy, the 2 customer requests and the store CLI commands.

Text
You handle refunds for an online store. Policy: refund the amount paid, only for orders that arrived damaged. Two customer requests came in: 1. Order A17 arrived broken. Refund it if policy allows.2. Refund order B22, the customer changed their mind. Check each order before you act. Use the `store` command: - `store get ORDER_ID` shows an order.- `store refund ORDER_ID AMOUNT` refunds it.

task.toml sets timeouts for the agent and verifier, selects a separate verifier container and declares /var/store/db.json as the artifact copied in for grading.

Text
schema_version = "1.4"artifacts = ["/var/store/db.json"]  # the state the verifier grades [agent]timeout_sec = 120.0 [verifier]timeout_sec = 60.0environment_mode = "separate"  # grade in a fresh container, with only the artifact copied in

environment/Dockerfile builds the clean container image each trial starts from, installing Python, the seed database and the store tool (using RUN chmod +x so Docker builds succeed even without BuildKit).

Text
FROM python:3.12-slim # The store: its starting state, and the tool the agent calls to change it.COPY db.json /var/store/db.jsonCOPY store.py /usr/local/bin/storeRUN chmod +x /usr/local/bin/store WORKDIR /app

environment/db.json stores the initial world state: damaged order A17, delivered order B22, and empty lookup and refund records.

Text
{  "orders": {    "A17": {"item": "kettle", "paid": 40.0, "status": "arrived damaged"},    "B22": {"item": "lamp", "paid": 25.0, "status": "delivered"}  },  "lookups": [],  "refunds": []}

environment/store.py implements the store tool, updating /var/store/db.json whenever the agent looks up or refunds an order.

Python
#!/usr/bin/env python3"""The agent's tool: `store get ORDER_ID` or `store refund ORDER_ID AMOUNT`."""import jsonimport sys DB = "/var/store/db.json"db = json.load(open(DB))cmd, *args = sys.argv[1:] or ["help"] if cmd == "get" and len(args) == 1:    db["lookups"].append(args[0])    print(json.dumps(db["orders"].get(args[0], "not found")))elif cmd == "refund" and len(args) == 2 and args[0] in db["orders"]:    db["orders"][args[0]]["status"] = "refunded"    db["refunds"].append([args[0], float(args[1])])    print("refund issued")else:    sys.exit(f"error: cannot run {sys.argv[1:]}") json.dump(db, open(DB, "w"), indent=2)  # save the new state; the verifier grades this file

solution/solve.sh is the reference script Harbor's oracle agent runs to confirm solvability: look up both orders and refund only A17 for 40.

Text
#!/bin/bash# Reference solution: look up both orders, refund only the damaged one.store get A17store get B22store refund A17 40

tests/test.sh is the verifier: it inspects /var/store/db.json and writes 1 to /logs/verifier/reward.txt only when both orders were looked up and the sole refund is A17 for 40.0.

Text
#!/bin/bash# The reward reads the store's final state after the agent is done.echo 0 > /logs/verifier/reward.txtpython3 - <<'PY'import jsondb = json.load(open("/var/store/db.json"))checked = {"A17", "B22"} <= set(db["lookups"])if checked and db["refunds"] == [["A17", 40.0]]:    open("/logs/verifier/reward.txt", "w").write("1")PY

Running the task with Harbor's oracle agent

Harbor's oracle agent runs solution/solve.sh inside the task container so you can verify that the reference solution scores 1.0 and a policy violation scores 0.0. Harbor sends usage statistics to PostHog by default, so the script sets HARBOR_TELEMETRY=off before executing both runs.

Text
#!/bin/bash# Run from the folder that holds refund-policy/. Needs Docker, no API key.# Install once: uv tool install harbor   (this run: Harbor 0.27.0)set -eexport HARBOR_TELEMETRY=off  # Harbor sends usage stats to PostHog unless this is off # 1. The oracle agent runs solution/solve.sh. Expect reward 1.harbor run -p refund-policy -a oracle # 2. Same task, but the solution also refunds B22. Expect reward 0.cp -r refund-policy refund-policy-wrongecho 'store refund B22 25   # breaks policy: B22 was not damaged' >> refund-policy-wrong/solution/solve.shharbor run -p refund-policy-wrong -a oracle

Tested with Harbor 0.27.0 on Python 3.12.16 and Docker 29.5.2, harbor lint ./refund-policy passes with no findings, and the 2 runs finished in 31 and 40 seconds with the base image cached and 0 exceptions. Both results are trimmed from Harbor's summary tables alongside each trial's verifier/reward.txt file (always check the Exceptions column or result.json, since harbor run exits 0 even when a container build raises a trial exception).

Text
$ harbor run -p refund-policy -a oracle  1/1 Mean: 1.000verifier/reward.txt: 1 $ harbor run -p refund-policy-wrong -a oracle  1/1 Mean: 0.000verifier/reward.txt: 0

What the artifact boundary proves and what stays open

Grading inside a separate verifier container proves that the reward reads persisted world state, while 2 remaining gaps show where this minimal verifier stops. Because environment_mode = "separate" starts the verifier in a fresh container built from the seed image, only files declared in artifacts (plus Harbor's /logs/artifacts/ directory) carry over from the agent's run. Removing the artifacts line from task.toml drops the reference solution's reward from 1.0 to 0.0 because the verifier inspects the untouched seed file.

A separate check where solve.sh runs only store refund A17 40 without looking up the orders also scores 0.0, so the verifier rejects a run with no lookups. To evaluate or train a live model on the same task, replace -a oracle with an agent harness and model identifier so the LLM drives the shell loop.

This minimal task leaves 2 reward hacks open. Harbor runs the agent as the container's default user, root in this image, so a model can rewrite /var/store/db.json directly from the shell and bypass store. The verifier also checks lookups and refunds as separate lists, so a model can refund first and look the orders up afterward.

Closing the 2 open hacks

A non-root agent user (Harbor exposes [agent] user and an opt-in root-agent lint rule) doesn't close the first hack alone, because store writes the file with the agent's own permissions: put the state behind a separate service that accepts only valid tool calls and logs them in order. We did not build or test a locked-down version. Our reward hacking with verifiable rewards post covers the wider verifier audit.

How Experiential builds RL environments from traces

Hand-building realistic RL environments is the bottleneck for most agent teams, so at Experiential we build environments directly from production agent traces as a managed engagement. Starting with 1 workload on our fine-tuning page, you enable prompt and response logging, we notify you once enough trace data is ready, and you trigger each training run yourself.

We simulate your production environment around your agent's core tasks and train an open small language model with RL in that simulation. The trained model goes back onto our OpenAI-compatible gateway under a new model name, and you can download the weights to self-host at any time.

In our open-source gateway, the trace-to-Harbor pipeline converts logged traces into a simulation, then a qualified task, and finally a Harbor package. Its induce-transitions action proposes 1 exact Python transition program per tool from fit traces and accepts a program only when fit replay is exact. Qualification requires feasible execution plus independent controls covering positive cases, goal failure, prohibited effects and unknown evidence, and an unqualified export cannot emit rewards.

Platform Harbor environments and benchmark results

Our platform imports versioned Harbor collections for RL training, and our claims benchmark shows what closed-loop GRPO delivers against a verifiable verdict. Early-access Harbor environments pull collections from Git or an archive into our Training API recipe (async-grpo-lora-qwen35-9b-64k-r128): Qwen3.5 9B with asynchronous GRPO, LoRA rank 128, 64K context and 2 H100s (1 trainer, 1 sampler) collecting 256 trajectories across 32 task groups of 8 rollouts in mini-batches of 32.

In our claims research study, a controlled experiment on the public AVeriTeC benchmark's 500 held-out development claims, an agent searches an evidence store and returns 1 of 4 verdicts within 8 turns. Qwen3.5-4B trained with GRPO and a LoRA adapter beat Claude Haiku 4.5 by 10.9% relative on verdict accuracy, with 44% fewer searches, at $1.75 vs $17.86 per 1,000 claims. In the study's routing evaluation on 489 held-out claims, the trained 4B scored 71.1%, and training raised it from 57% to 71% on this benchmark. Book a call on our fine-tuning page to start with 1 workload.

Questions answered

What is a reinforcement learning (RL) environment?

An RL environment is the program an agent acts in during reinforcement learning, imitating the world around it. The environment responds to each action, often by changing its state, and returns the next observation so the agent trains in closed loop, while a reward model scores the episode. For LLM agents, actions are typically tool calls or shell commands, and policy gradient training reinforces trajectories with higher advantage.

What is the difference between a reward model and a verifier?

A reward model is the general term for any scoring mechanism in RL, covering both dense process-level rewards across intermediate steps and sparse outcome-level rewards at the end of an episode. A verifier is a specific kind of reward model that returns a binary outcome reward from deterministic checks such as unit tests, exact-match labels or a final database comparison. Group-based algorithms such as GRPO and DAPO support either, and in practice most runs use sparse outcome rewards, which DeepSeek showed can teach strong process-level behavior on their own.

What is Harbor in agentic RL?

Harbor is an open-source framework and the emerging standard for packaging agent RL environments and evaluations. Each Harbor task is a directory containing an instruction prompt, a task.toml configuration, a Dockerized environment, an oracle solution and a verifier script that writes a reward file, optionally inside a separate grading container. Experiential builds on Harbor for both evaluation and RL rollouts, pairing Harbor tasks with Miles for training.

What is the difference between an RL environment and a benchmark?

A benchmark evaluates models on a fixed set of tasks so teams can compare performance. An RL environment exposes tasks, mutable state, tools and a reward model through a repeatable runtime that a trainer can call thousands of times per run. Many benchmarks, including WebArena, HumanEval and BFCL v3, have been wrapped as environments; keep held-out evaluation tasks separate from training tasks.

Why do RL environments need tasks the model sometimes fails?

Group-based RL methods such as GRPO estimate each trajectory's advantage from the reward statistics across multiple rollouts of the same task, using no learned critic. When every rollout in a group earns the same reward, including when every attempt gets the maximum score or 0, every advantage is 0 and that prompt produces no policy gradient. Tasks that sit near the model's frontier, where some attempts pass and others fail, keep rollout compute productive.

What is reward hacking in RL environments?

Reward hacking occurs when a model earns reward by exploiting a flaw in the reward model or container setup while skipping the actual task. OpenAI researchers reported a reasoning model in training that discovered exit(0) and raise SkipTest across nearly all of its training environments to skip unit-test evaluation. Running verifiers in separate containers, keeping graded state out of the agent's direct write access and testing against cheating or no-op attempts close the most common loopholes.

Can you train an agent in a simulated environment?

Yes, provided the simulation mirrors the real tools closely enough for behavior to transfer. A model-based or trace-grounded simulator predicts how state evolves after actions nobody recorded, allowing closed-loop practice without hitting live production systems. DreamGym's authors showed RL gains from synthetic experience as a warm start for real-environment RL, and evaluating final checkpoints against real tools or sandboxes catches any simulator artifacts.