Build reinforcement learning environments with Gymnasium and OpenEnv. Design rewards, test agent behavior, and verify what a policy actually accomplishes.
Basic Python · 8 free graded labs. Sign in to run or submit a lab.
Interactive simulator
Can a rover earn points without delivering?
Pick up the package and drop it off within 14 actions. Then switch the reward rule and see if waiting can beat a successful delivery.
Warehouse map
Use the move buttons, or focus the map and use arrow keys.
Start at row 1, column 1. Pickup is at row 2, column 2. Drop-off is at row 5, column 5. Shelves occupy rows 2 through 4 in column 3, plus row 4, column 4.
Rover
Package
Drop-off
Shelf
+1.0 for delivery. All other actions earn 0. Switching rules resets the episode.
Actions
0 / 14
Return
0.0
Delivered
No
Position R1 C1Cargo Empty
Ready. The rover starts at row 1, column 1.
Episode trace Latest first
Your actions and their rewards will appear here.
Practice with 8 Python labs
Start with an episode contract, then work through reward design, reproducible evaluation, and a rollout decision.
Lab 01Gymnasium
Design the episode contract
The environment owns the state. Reset gives the policy its first observation. Each step applies one action and reports the next observation, reward, and whether collection should stop.
Lab notes and self-check
Implement reset(seed=...) and step(action) on gymnasium.Env. Call super().reset(seed=seed), declare Discrete observation and action spaces, and run check_env on the base environment. Add TimeLimit outside it.
The robot reaches the goal on the exact step that exhausts the time limit. Which flags can be true?
Both. Reaching the goal terminates the task and reaching the external limit truncates collection. A learning target stops bootstrapping when terminated is true.
A warehouse robot must pick up a package before dropping it off. The same position can mean different things depending on what the robot carries. Expose the carry flag and record delivery success separately from training return.
Lab notes and self-check
Give the environment a Dict or MultiDiscrete observation with position and carry state. Compare a random rollout with a shortest-path policy on matching fixtures. Optionally check trainer compatibility and run a short SB3 baseline.
A shaping reward pays 0.1 per step beside the package. How can a policy score above a delivery worth 1?
It can wait beside the package for 11 steps and earn 1.1 without delivering. Write a waiting-policy test and track actual delivery success.
A policy can memorize training layouts. Freeze distinct train, development, and test scenario IDs. Save the environment version, reset seed, and actions so a failing episode can be replayed.
Lab notes and self-check
Benchmark one environment against SyncVectorEnv and AsyncVectorEnv with the same workload. Log transitions per second, wrapper order, and autoreset mode. Check that a finished slot resets independently and final observations keep their episode identity.
A baseline completes a scenario but the candidate service times out. How should the paired report count it?
Record one unavailable pair and one infrastructure failure. Keep the other scored pairs comparable and report the missing coverage.
If two agents act together, both proposals must see the same starting state. With physical control, the transition additionally depends on parameters such as damping and the simulation timestep.
Lab notes and self-check
Port the shared aisle to PettingZoo Parallel and run parallel_api_test. For the robotics variation, run Gymnasium’s InvertedPendulum-v5 with MuJoCo, then replay one action sequence against a model with different damping.
Two robots propose to swap adjacent cells in a one-cell-wide aisle. When do you resolve the conflict?
After computing both proposals from the same starting state and before committing either one. Here both robots stay.
A tool call in a returns desk changes what that agent sees later. OpenEnv gives a client a reset and step interface to a service. Keep fixtures immutable and let each episode own its own return record.
Lab notes and self-check
Use the OpenEnv scaffold below. Define typed tool actions and observations, start the generated service, and use two generated clients against the same fixture. Submit in one client and verify the other still sees the original record.
Client A submits a return. Client B resets. What records should each client see?
A still sees its return. B sees its starting fixture. Its reset affects B’s episode only.
A transcript helps explain a failure. A state-based grader verifies what actually happened. For the mock returns desk, compare the committed records with the expected outcome and count invalid calls separately.
Lab notes and self-check
Expose documented tool methods and reset(**kwargs) in a TRL environment_factory adapter. Drive it with a scripted caller first and verify that the final reward is captured before resetting. Try GRPO after rollouts and rewards pass the contract tests.
An agent says it completed a return, but the mock database contains no new row. What score should it receive?
Zero. The grader needs evidence of the expected committed row, with all unrelated records intact.
A timeout after commit leaves the client unsure what happened. A request key lets it retry the same operation. Persist the mutation and deduplication record together so a retry sees the original result.
Lab notes and self-check
Run the service from a clean image. Log scenario ID, episode ID, step index, end reason, and latency. Force the response to disappear after commit, retry once, then repeat with concurrent requests and verify one persisted write.
The same session reuses a request key with a different order. Should the service replay the old response?
Reject the conflict and keep the original result. A request key names a single payload within its scope.
A policy can look good in the lab and fail under a different workload. In shadow mode, record candidate choices without applying them. In a small canary, use thresholds defined before the rollout and keep a tested fallback available.
Lab notes and self-check
Package your warehouse or returns desk. Compare it with a scripted baseline on frozen fixtures and rehearse the fallback on your local system. Document the conditions for advancing, holding, and rolling back.
The candidate has a better success rate but failed the fallback rehearsal. What happens?
Hold the rollout. Fix and rerun the fallback drill before collecting evidence for a new decision.
The browser labs use standard-library Python and deterministic fixtures. Run these projects locally to work with the framework APIs, a container runtime, and optional trainers.
Gymnasium · Run a local episode
Install gymnasium in a Python virtual environment and save the example as lineworld.py. Reset the wrapper, then call env.step(1) twice. Check that the second result has reward 1 and terminated=True.
Add lookup_order, check_policy, and submit_return to the generated environment. Start with day 30, day 31, an existing return, and an ineligible category.
Connect two instances of the generated client. Use reset() and step(...) to verify a successful return, a rejection, and isolation across clients.
Grade committed state, then drive an adapter shaped like TRL’s environment_factory with a scripted policy. Check that the grader rejects a success claim without a write.
How research labs and production teams do it
Test unseen scenarios. OpenAI’s Procgen varies levels and separates training and test sets. Apply the same idea to held-out warehouse layouts. Procgen Benchmark
Vary the simulation. Google DeepMind’s MuJoCo Playground explores transfer from simulation to robots and randomizes physical parameters. Try held-out damping values and compare controller behavior. MuJoCo Playground paper
Grade outcomes. Anthropic describes using environment state to verify what an agent accomplished, with transcripts available for diagnosis. Turn recurring misses into fixtures. Agent evaluation write-up
Keep a fallback available. Google’s deployed cooling system checks proposed actions locally and gives operators a path back to on-site rules. Rehearse the equivalent on the mock service. Production cooling write-up
Capstone · Release a reproducible environment
Choose the Gymnasium warehouse or the OpenEnv returns desk. Build a version you can hand to another learner and give them enough evidence to decide whether to run a canary.
Specify the contract. Document observations, actions, resets, rewards, episode endings, and success.
Package it. Pin dependencies and provide a clean-start command and scripted baseline.
Verify it. Show boundary tests, replay, reset isolation, a reward shortcut regression, and a failure-recovery test.
Evaluate it. Compare on matching held-out fixtures and include two annotated failures plus latency or throughput.
Decide. Declare quality and service thresholds, explain the evidence, and demonstrate the fallback.
A peer should be able to start it from a clean checkout, reproduce a failure from a trace, and run your reference policy on every deterministic solvable fixture.