Guide · RL Environment Design

SkyRL explained: SkyRL-Gym environments, the init, step and close lifecycle, and rewards

SkyRL is a full-stack RL library for LLMs from Berkeley's Sky Computing Lab, and SkyRL-Gym is the part you write environments in. This guide covers what its environment interface promises, how the trainer drives it, and where API-backed environments lose their reset.

Last reviewed against the sources listed at the end of this guide.

At a glance

What it is
A modular, full-stack reinforcement learning library for LLMs
Made by
Berkeley Sky Computing Lab, in collaboration with Anyscale
Parts
skyrl (training, with skyrl-train and skyrl-tx), skyrl-agent (long-horizon agents) and skyrl-gym (environments)
Environment API
init(), step() and close() on a Gymnasium-style Env; text in, text out
Install
pip install skyrl-gym for the environments (Python 3.10 or newer)
License
Apache-2.0 for the repository; check the license of each package you install on PyPI

What SkyRL is

SkyRL describes itself as a modular full-stack RL library for LLMs. It is built at the Berkeley Sky Computing Lab in collaboration with Anyscale, and its code lives at skyrl-project/SkyRL on GitHub (the older NovaSky-AI/SkyRL address redirects there), with documentation at docs.skyrl.ai.

The repository holds three things you will meet under separate names:

PackageWhat it does
skyrlThe training stack for RL on your own hardware. It combines skyrl-train, the modular training framework, and skyrl-tx, a backend that implements the Tinker API so Tinker training scripts run on local GPUs.
skyrl-agentAn agent layer for multi-turn, long-horizon agent training and evaluation, such as SWE-Bench-style tasks.
skyrl-gymA library of RL environments for LLMs written to a Gymnasium-style API, with ready-made math, code, search and text-to-SQL environments and a reusable tool interface.

If your question is how to write an environment for SkyRL, SkyRL-Gym is the part to read, and it is what the rest of this guide is about. If your environment already exists in another format, SkyRL ships integration examples for OpenEnv, Harbor, Prime Intellect Verifiers and OpenReward under examples/train_integrations in the repository.

The environment interface: init(), step() and close()

Every SkyRL-Gym environment subclasses Env from skyrl_gym/core.py. For LLM tasks you subclass BaseTextEnv instead, which fixes the types: the action is the model's response as a string, and the observation is a list of chat messages in the OpenAI format.

MethodWhat it does
init(prompt)Takes the prompt from the dataset row and returns the first prompt the model sees plus a metadata dict. The default returns the prompt unchanged.
step(action)Parses and runs the model's response and returns observations, reward, done and metadata (and optionally a postprocessed_action).
close()Cleans up. The docstring names database and HTTP connections as the reason it exists.
get_metrics()Optional per-episode metrics, averaged across episodes by aggregate_metrics() unless you override it.

Two things differ from Gymnasium and catch people porting code. There is no reset(): an episode begins with init() on a fresh instance. And step() returns a typed dict, not a tuple, with the new messages to append to the conversation rather than a whole new observation.

class MultiplyEnv(BaseTextEnv):
    def step(self, action: str) -> BaseTextEnvStepOutput:
        self.turns += 1
        answer = self._parse_action(action)
        is_correct = answer is not None and answer.strip() == str(self.ground_truth).strip()
        done = self.turns >= self.max_turns or is_correct

        if done:
            reward = 1.0 if is_correct else (0.5 if answer is not None else 0.0)
            return BaseTextEnvStepOutput(observations=[], reward=reward, done=True, metadata={})

        return BaseTextEnvStepOutput(
            observations=[{"role": "user", "content": "Incorrect. Please try again."}],
            reward=0.0,
            done=False,
            metadata={"parsed_answer": answer},
        )
The multi-turn step from SkyRL's multiplication tutorial, shortened

One instance per trajectory: where SkyRL's reset happens

SkyRL's generator builds a new environment for every trajectory. For each sample it calls skyrl_gym.make(env_class, env_config=..., extras=...), where extras is the dataset row's own fields (its reward_spec, any task data, and max_turns), then init(), then step() on each model turn until done, then get_metrics() and close(). The constructor is the reset.

That makes the in-process state easy: whatever you keep on self starts empty for every episode. It does not reset anything the instance talks to. If step() writes to a database file, a sandbox account or a third-party API, the next trajectory's fresh instance sees what the last one left, and so do the trajectories running beside it. That is the episodic reset contract moved into __init__ and close().

  • Put everything that defines the starting world in the dataset row and read it from extras. There is no seed argument on init(), so the row is what makes two runs of the same task start the same way.
  • Build or restore the backend in __init__ (or init()), and tear it down in close(). The built-in text-to-SQL environment finds its SQLite database from a db_id in the row and builds its SQL tool group in the constructor; it is a useful pattern to copy.
  • Several trajectories run at once: GRPO groups sample the same prompt many times (generator.n_samples_per_prompt). Two copies of one task must not share mutable state, which is a worker isolation decision, not a SkyRL setting.
  • Return what you need to reproduce a trajectory in metadata, since it is the only per-step channel back to the trainer besides the reward.

Turn rewards, outcome rewards and what the trainer sees

Every step() returns a reward. Return 0.0 on every turn but the last and you have an outcome reward; return non-zero values on earlier turns and you have turn-level rewards. Either way SkyRL turns them into per-token rewards by placing each turn's reward on the last token of that turn's response.

It also logs two metrics without being asked: pass_at_n, which counts a sample as passed if any of its trajectories ends with a positive last-turn reward, and mean_raw_reward, the sum of turn rewards per trajectory averaged across trajectories. Because pass_at_n reads only the last turn, an environment that pays out early and returns 0.0 at the end will look like it never passes.

Where the reward comes from is up to you. The tutorial checks an answer against reward_spec.ground_truth from the dataset row; an API-backed environment should read the backend's state after the action rather than the tool's response text, or it will reward whatever the backend claims happened. Sparse vs. dense rewards in agentic API tasks covers which of the two to start with.

Tools and ToolGroups

SkyRL-Gym separates tools from environments so a tool written once can be reused. A ToolGroup is a class whose methods marked with the @tool decorator are registered by name; an environment passes its groups to init_tool_groups() and runs one with _execute_tool(group_name, tool_name, args). The library ships Python, search and SQL tool groups, and an environment can hold several groups at once.

Parsing the call is the environment's job. The built-in environments look for tags such as <sql>...</sql> in the model's response with a regular expression, so the tool-call format is whatever your prompt and parser agree on. That is the place to enforce tool-call constraints, and the observation you append afterwards is where you decide how much of an API response the agent reads.

Building and registering your own environment

You do not fork SkyRL to add an environment. Write the class anywhere, register it under a name, and put that name in your data.

  1. Subclass BaseTextEnv and read your task fields from extras in __init__.
  2. Implement step(), and init() and close() if the environment holds anything to set up or tear down.
  3. Register it with register(id="my_env", entry_point="my_package.env:MyEnv") inside the Ray entrypoint task, as SkyRL's examples do, so the workers can build it with skyrl_gym.make("my_env").
  4. Write a dataset whose rows carry prompt, env_class (the registered name) and reward_spec, plus any fields your environment reads. Setting env_class per row is what lets one run train on several environments.
{
    "data_source": "synthetic_multiply",
    "prompt": [system_prompt, {"role": "user", "content": question}],
    "env_class": "multiply",
    "reward_spec": {"method": "rule", "ground_truth": answer},
    "extra_info": {"num_digits": num_digits, "split": split_name},
}
A dataset row, from SkyRL's multiplication tutorial

The full walkthrough, with the training script and GPU settings, is the Creating a New Environment or Task tutorial in SkyRL's docs.

Wrapping a third-party API as a SkyRL-Gym environment

Text-to-SQL fits SkyRL-Gym neatly: the task row names the database, and each instance builds its own SQL tool group pointed at it. Most agentic API tasks (open a GitHub issue, refund a Stripe charge, post to Slack) need the same thing: a backend each trajectory can own, start from a known state and throw away in close().

Backend behind the toolsFresh per trajectory?What goes wrong
The live API or a vendor sandboxNo: every instance shares one accountRate limits across a GRPO group, credentials on every worker, trajectories that see each other's writes
A stateless mockTrivially, because it never changesReads ignore writes, so the agent learns the wrong causal model
A stateful simulator per instanceYes: start it seeded from the row in __init__, stop it in close()Only as good as its fidelity to the real API; check how the vendor verifies it

The third row fits SkyRL's lifecycle. Rystic, for example, builds stateful simulators of APIs such as Slack, GitHub and Stripe that run locally or in CI; evaluate an option like that alongside writing your own. Scaffolding a simulated API backend as a Gym environment walks through the shape of that environment, and if a step waits on a real network call, structuring the training loop clock covers what that does to throughput.

Frequently asked questions

Is SkyRL-Gym compatible with Gymnasium?

It follows Gymnasium's style but is not a drop-in replacement: episodes start with init() on a new instance instead of reset(), and step() returns a dict of chat messages, reward, done and metadata rather than a tuple. A Gymnasium environment needs a thin BaseTextEnv wrapper to be trained with SkyRL.

Does SkyRL reset an environment between episodes?

It creates a new instance for every trajectory and calls close() when the trajectory ends. State kept on the instance starts fresh; anything outside it, such as a database, a sandbox account or an API, is only reset if your constructor or close() does it.

Can I train SkyRL on an OpenEnv environment?

Yes. The repository has an OpenEnv integration example under examples/train_integrations/openenv that wraps OpenEnv environments, run as Docker images, in a SkyRL-Gym environment. See the OpenEnv guide for that side of the contract.

Who maintains SkyRL?

It is developed at the Berkeley Sky Computing Lab in collaboration with Anyscale, and released as open source on GitHub. The README lists the compute sponsors and the projects built on it.

Does SkyRL cost anything?

The code is open source. Training costs whatever your GPUs cost: check your cloud provider's pricing, or Anyscale's if you run it there.

Which models can I train with SkyRL?

SkyRL keeps a Supported Models page in its docs; check it for the current list and the recipes for each model rather than relying on a list copied elsewhere.

Sources

  1. SkyRL on GitHub (README)
  2. SkyRL documentation
  3. SkyRL: Creating a New Environment or Task
  4. SkyRL-Gym README
  5. SkyRL-Gym core environment API (core.py)
  6. SkyRL generator (skyrl_gym_generator.py)
  7. SkyRL OpenEnv integration example

Related reading