How to wrap a tool-use task as a Gymnasium environment for an LLM agent
At a glance
Subclass gymnasium.Env, declare Text spaces for actions and observations, build the task from self.np_random in reset, parse each action as a tool call in step, and compute the reward from the final state. Register it with a versioned id and max_episode_steps, then run the environment checker.
- Compiled by
- AgenticRLEnvironments editors
- First recorded
- Last revised
- Reading time
- 3 min
To turn a tool-use task into a Gymnasium environment, put the task's state in a class that subclasses gymnasium.Env, let reset create a new task from a seed, let step run one tool call and return what the tool said, and give a reward only when a program checks the final state. The example below is complete and was run as published.
What does the finished environment do?
The environment below asks an agent to cancel a customer's one pending order out of three, without touching the others. The agent acts by sending one JSON tool call per step: get_order, cancel_order or finish. The reward is 1 when the pending order is cancelled and the shipped ones are unchanged, and 0 otherwise.
Table: The example environment's interface
| Element | In this example |
|---|---|
| Action | A JSON string such as {"tool": "cancel_order", "id": "A715"} |
| Observation | The task text after reset, then each tool's text output |
| State | A dictionary of three orders and which one is the target |
| Reward | 1.0 or 0.0, computed when the agent calls finish |
| Terminated | When the agent calls finish |
| Truncated | After 10 steps, set by max_episode_steps at registration |
Step 1: How do I install a pinned Gymnasium?
Install Gymnasium at a fixed version in a fresh virtual environment, so the example behaves the same later.
python3 -m venv .venv
.venv/bin/pip install gymnasium==1.4.0
Gymnasium 1.4.0 was released on 5 October 2026 and needs Python 3.10 or later (gymnasium on PyPI, read 2026-11-26). We ran the code on this page with it under Python 3.14.
Step 2: How do I declare text actions and observations?
Declare both spaces as gymnasium.spaces.Text with an explicit character set. The constructor is Text(max_length, *, min_length=1, charset=..., seed=None), and its default character set is "the lower and upper english alphabet plus latin digits" (Gymnasium fundamental spaces, read 2026-11-26). JSON needs braces, quotes and spaces, so the example uses Python's string.printable.
Step 3: How do I write reset, step and the grader?
Write reset to build a task from the environment's own random generator, step to run one tool call, and a private _grade method that inspects the state. Gymnasium's guide says that in reset "you must call super().reset(seed=seed) to properly initialize the random number generator" (Gymnasium custom environment guide, read 2026-11-26).
Save this as orders_env.py:
import json
import string
import gymnasium as gym
from gymnasium import spaces
TEXT = string.printable
class OrdersEnv(gym.Env):
"""A tool-use task: cancel the customer's pending order, leave the others alone."""
metadata = {"render_modes": []}
def __init__(self):
self.observation_space = spaces.Text(max_length=4096, charset=TEXT)
self.action_space = spaces.Text(max_length=512, charset=TEXT)
self.orders = {}
self.target = None
def reset(self, *, seed=None, options=None):
super().reset(seed=seed)
ids = [f"A{n}" for n in self.np_random.choice(900, size=3, replace=False) + 100]
self.orders = {i: "shipped" for i in ids}
self.target = ids[int(self.np_random.integers(3))]
self.orders[self.target] = "pending"
task = (
"Task: the customer wants their pending order cancelled. "
f"Their orders are {', '.join(ids)}. "
'Reply with one JSON tool call: {"tool": "get_order", "id": ...}, '
'{"tool": "cancel_order", "id": ...} or {"tool": "finish"}.'
)
return task, {"target": self.target}
def step(self, action):
try:
call = json.loads(action)
tool = call["tool"]
except (ValueError, KeyError, TypeError):
return "Error: not a JSON tool call.", 0.0, False, False, {}
if tool == "get_order" and call.get("id") in self.orders:
obs = f"Order {call['id']}: {self.orders[call['id']]}"
return obs, 0.0, False, False, {}
if tool == "cancel_order" and call.get("id") in self.orders:
self.orders[call["id"]] = "cancelled"
return f"Order {call['id']} cancelled.", 0.0, False, False, {}
if tool == "finish":
reward = self._grade()
return "Episode finished.", reward, True, False, {"orders": dict(self.orders)}
return f"Error: unknown tool or order: {action}", 0.0, False, False, {}
def _grade(self):
# Outcome check on the final state: the pending order is cancelled
# and no other order was touched.
others_ok = all(s == "shipped" for i, s in self.orders.items() if i != self.target)
return 1.0 if self.orders[self.target] == "cancelled" and others_ok else 0.0
gym.register(id="toolenv/Orders-v0", entry_point=OrdersEnv, max_episode_steps=10)
Three design choices in this code matter for any agent environment:
- The target goes in
info, not in the observation. The trainer can log it; the agent cannot read it. - A bad action costs a step, not the episode. The agent sees an error and can try again.
- The grader reads state, not the transcript. An agent that says "done" without cancelling gets 0.
Step 4: How do I register it with a version and a step limit?
Register the class with gymnasium.register, an id of the form namespace/Name-vN, and max_episode_steps. Gymnasium's registry documents the id syntax as [namespace/](env_name)[-v(version)] (Gymnasium registry API, read 2026-11-26). The custom environment guide recommends the full form with namespace and version for clarity, and uses max_episode_steps to "Prevent infinite episodes" (Gymnasium custom environment guide, read 2026-11-26). The last line of orders_env.py does this.
Step 5: How do I check that it works?
Run Gymnasium's environment checker, play one episode with a scripted policy, and confirm that the step limit and the seed behave. Save this as run.py next to orders_env.py:
import json
import gymnasium as gym
from gymnasium.utils.env_checker import check_env
import orders_env # registers toolenv/Orders-v0
env = gym.make("toolenv/Orders-v0")
check_env(env.unwrapped)
obs, info = env.reset(seed=7)
ids = obs.split("orders are ")[1].split(".")[0].split(", ")
pending = None
for i in ids:
obs, r, term, trunc, info = env.step(json.dumps({"tool": "get_order", "id": i}))
if obs.endswith("pending"):
pending = i
env.step(json.dumps({"tool": "cancel_order", "id": pending}))
obs, r, term, trunc, info = env.step(json.dumps({"tool": "finish"}))
print("reward", r, "terminated", term, "truncated", trunc)
obs, info = env.reset(seed=7)
for t in range(20):
obs, r, term, trunc, info = env.step('{"tool": "get_order", "id": "nope"}')
if term or trunc:
print("stopped after", t + 1, "steps; truncated =", trunc)
break
a, _ = env.reset(seed=123)
b, _ = env.reset(seed=123)
print("same task for same seed:", a == b)
env.close()
Run it with warnings turned into errors, so a checker warning cannot pass unnoticed:
.venv/bin/python -W error::UserWarning run.py
Our run printed:
reward 1.0 terminated True truncated False
stopped after 10 steps; truncated = True
same task for same seed: True
How do I connect a language model to it?
Connect a model by turning each observation into a message and each model reply into the next action. A minimal loop:
- Call
env.reset(seed=...)and send the observation as the first user message. - Ask the model for one tool call, and pass its text to
env.step. - Append the observation to the conversation and repeat until
terminatedortruncated. - Store the whole trajectory with the seed, the environment id and the reward.
For training, the reward from step 4 is what the RL algorithm optimises. The same environment, with a frozen list of seeds, is an evaluation set. To run many copies at once, see scaling environment instances.
What we read for this article
- Gymnasium custom environment guide, read 2026-11-26
- Gymnasium fundamental spaces (Text, Discrete), read 2026-11-26
- Gymnasium registry API, read 2026-11-26
- Gymnasium Env API, read 2026-11-26
- gymnasium on PyPI, read 2026-11-26
Field questions
Can Gymnasium spaces hold text?
Yes. gymnasium.spaces.Text holds strings between a minimum and maximum length over a character set. The default character set is only English letters and digits, so set charset to string.printable or your own set if actions and observations contain spaces, quotes or punctuation.
Where should the randomness of a task come from?
From self.np_random, after calling super().reset(seed=seed) on the first line of reset. Then the same seed always produces the same task, which you need for debugging and for fair comparisons between agents.
What should happen when the agent sends an action that does not parse?
Return an error message as the observation with zero reward and let the episode go on. The step limit set with max_episode_steps will truncate an agent that never recovers. Ending the episode on the first malformed call makes learning harder for little benefit.
Do I need a Gymnasium environment to train an LLM agent?
No. Many RL libraries for language models use their own interfaces. Writing the environment against reset and step still pays off, because the task, the tools and the grader live in one testable class that any training loop can call.