RL environments Python guide: build a small agent task with a checker
For agent builders4 min read
This RL environments Python guide builds a small environment for an LLM agent. It has a reset, a step function with three tools, and a checker that scores the final state. The code uses only the standard library and returns the same five values as Gymnasium's step, so you can move it into a Gymnasium class later.
The task
The agent gets a folder that holds one file, report_draft.txt, whose content is a random code. It must rename the file to report_final.txt without changing the content. It has three tools plus a way to say it is finished: ls lists files, cat reads one, mv moves one, done ends the episode.
The environment holds the files in a dictionary, so nothing touches the real disk. That makes reset instant and attempts independent.
RL environments Python code: the environment class
import random class RenameFileEnv: """Task: rename report_draft.txt to report_final.txt, keep contents.""" max_steps = 6 def reset(self, seed=None): rng = random.Random(seed) self.secret = f"code={rng.randint(1000, 9999)}" self.files = {"report_draft.txt": self.secret} self.steps = 0 return self._obs("ready"), {} def _obs(self, text): return {"text": text, "files": sorted(self.files)} def step(self, action): self.steps += 1 tool, args = action["tool"], action.get("args", {}) if tool == "ls": msg = ", ".join(sorted(self.files)) elif tool == "cat": msg = self.files.get(args.get("name"), "error: no such file") elif tool == "mv": src, dst = args.get("src"), args.get("dst") if src in self.files and dst not in self.files: self.files[dst] = self.files.pop(src) msg = "ok" else: msg = "error: cannot move" elif tool == "done": return self._obs("finished"), self.check(), True, False, {} else: msg = "error: unknown tool" truncated = self.steps >= self.max_steps return self._obs(msg), 0.0, False, truncated, {} def check(self): ok = ( self.files.get("report_final.txt") == self.secret and "report_draft.txt" not in self.files and len(self.files) == 1 ) return 1.0 if ok else 0.0Read step the way the Gymnasium docs describe it: an observation, a reward, terminated, truncated and info. Reward is zero until the agent calls done. Calling done ends the episode as terminated. Hitting the step limit ends it as truncated, with no reward.
Source: Gymnasium: basic usage(opens in a new tab)
Prove that the task can be solved
Before any model sees this, run a scripted solution. If you cannot pass your own task with a hand-written policy, the task is broken.
env = RenameFileEnv()obs, info = env.reset(seed=7) plan = [ {"tool": "ls"}, {"tool": "mv", "args": {"src": "report_draft.txt", "dst": "report_final.txt"}}, {"tool": "done"},]for action in plan: obs, reward, terminated, truncated, info = env.step(action) print(action["tool"], "->", obs["text"], reward) assert reward == 1.0Prove that the checker can fail
Then run policies that should score zero. Finishing without doing anything, moving the file but changing nothing else, and running out of steps are three useful ones.
env = RenameFileEnv()env.reset(seed=1)_, reward, *_ = env.step({"tool": "done"})assert reward == 0.0 # did nothing env.reset(seed=1)for _ in range(6): _, reward, terminated, truncated, _ = env.step({"tool": "ls"})assert truncated and reward == 0.0 # wandered until the step limitTwo details are worth copying. The seed makes the secret code different for every episode, so a model cannot memorize an answer. And the checker looks at the final state: the new file exists with the right content, the old one is gone, and nothing else was added.
Hooking up a model
A model needs two translations. Your prompt describes the task and the tools, and your loop parses each tool call the model returns into the action dictionary. Most chat APIs have a tool or function calling feature that returns the name and JSON arguments of a call, which maps straight onto the action format used here.
Cap the loop at max_steps yourself, pass each observation back as the tool result, and save every episode as a record you can read later. Reading the records is how you find the checker's blind spots.
Where to take it next
- Add a write tool and make the task harder. Then ask what a lazy agent could do to pass the checker without doing the work.
- Randomize file names as well as contents so a memorized plan fails.
- Wrap the class in gymnasium.Env, declare the action and observation spaces, and register it with gym.register so tools that expect that interface can load it.
- Add a second check on the path: for example, flag runs that read files they had no reason to read.
Source: Gymnasium: create a custom environment(opens in a new tab)
Keep each environment small. Twenty tiny environments with exact checkers teach you more than one large environment whose score nobody trusts.