OpenEnv documentation

OpenEnv: Production RL Made Simple

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.6.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

OpenEnv: Production RL Made Simple

From โ€œHello Worldโ€ to RL Training in 5 Minutes โœจ

What if RL environments were as easy to use as REST APIs?

Thatโ€™s OpenEnv. Type-safe. Isolated. Production-ready. ๐ŸŽฏ

Open In Colab GitHub License PyTorch

Author: Sanyam Bhutani

Why OpenEnv?

Letโ€™s take a trip down memory lane:

Itโ€™s 2016, RL is popular. You read some papers, it looks promising.

But in real world: Cartpole is the best you can run on a gaming GPU.

What do you do beyond Cartpole?

Fast-forward to 2025, GRPO is awesome and this time itโ€™s not JUST in theory, it works well in practise and is really here!

The problem still remains, how do you take these RL algorithms and take them beyond Cartpole?

A huge part of RL is giving your algorithms environment access to learn.

We are excited to introduce an Environment Spec for adding Open Environments for RL Training. This will allow you to focus on your experiments and allow everyone to bring their environments.

Focus on experiments, use OpenEnvironments, and build agents that go beyond Cartpole on a single spec.


๐Ÿ“‹ What Youโ€™ll Learn

๐ŸŽฏ Part 1-2: The Fundamentals

  • โšก RL in 60 seconds
  • ๐Ÿค” Why existing solutions fall short
  • ๐Ÿ’ก The OpenEnv solution

๐Ÿ—๏ธ Part 3-5: The Architecture

  • ๐Ÿ”ง How OpenEnv works
  • ๐Ÿ” Exploring real code
  • ๐ŸŽฎ OpenSpiel integration example

๐ŸŽฎ Part 6-8: Hands-On Demo

  • ๐Ÿ”Œ Use existing OpenSpiel environment
  • ๐Ÿค– Test 4 different policies
  • ๐Ÿ‘€ Watch learning happen live

๐Ÿ”ง Part 9-10: Going Further

  • ๐ŸŽฎ Switch to other OpenSpiel games
  • โœจ Build your own integration
  • ๐ŸŒ Deploy to production

This notebook is designed to run top-to-bottom in Google Colab with zero setup!

โฑ๏ธ Time: ~5 minutes | ๐Ÿ“Š Difficulty: Beginner-friendly | ๐ŸŽฏ Outcome: Production-ready RL knowledge


๐Ÿ“‘ Table of Contents

Foundation

Architecture

Hands-On Demo

Advanced

Wrap Up


Part 1: RL in 60 Seconds โฑ๏ธ

Reinforcement Learning is simpler than you think.

Itโ€™s just a loop:

while not done:
    observation = environment.observe()
    action = policy.choose(observation)
    reward = environment.step(action)
    policy.learn(reward)

Thatโ€™s it. Thatโ€™s RL.

Letโ€™s see it in action:

import random

print("๐ŸŽฒ " + "="*58 + " ๐ŸŽฒ")
print("   Number Guessing Game - The Simplest RL Example")
print("๐ŸŽฒ " + "="*58 + " ๐ŸŽฒ")

# Environment setup
target = random.randint(1, 10)
guesses_left = 3

print(f"\n๐ŸŽฏ I'm thinking of a number between 1 and 10...")
print(f"๐Ÿ’ญ You have {guesses_left} guesses. Let's see how random guessing works!\n")

# The RL Loop - Pure random policy (no learning!)
while guesses_left > 0:
    # Policy: Random guessing (no learning yet!)
    guess = random.randint(1, 10)
    guesses_left -= 1

    print(f"๐Ÿ’ญ Guess #{3-guesses_left}: {guess}", end=" โ†’ ")

    # Reward signal (but we're not using it!)
    if guess == target:
        print("๐ŸŽ‰ Correct! +10 points")
        break
    elif abs(guess - target) <= 2:
        print("๐Ÿ”ฅ Warm! (close)")
    else:
        print("โ„๏ธ  Cold! (far)")
else:
    print(f"\n๐Ÿ’” Out of guesses. The number was {target}.")

print("\n" + "="*62)
print("๐Ÿ’ก This is RL: Observe โ†’ Act โ†’ Reward โ†’ Repeat")
print("   But this policy is terrible! It doesn't learn from rewards.")
print("="*62 + "\n")

Output:

๐ŸŽฒ ========================================================== ๐ŸŽฒ
   Number Guessing Game - The Simplest RL Example
๐ŸŽฒ ========================================================== ๐ŸŽฒ

๐ŸŽฏ I'm thinking of a number between 1 and 10...
๐Ÿ’ญ You have 3 guesses. Let's see how random guessing works!

๐Ÿ’ญ Guess #1: 2 โ†’ โ„๏ธ  Cold! (far)
๐Ÿ’ญ Guess #2: 10 โ†’ ๐ŸŽ‰ Correct! +10 points

==============================================================
๐Ÿ’ก This is RL: Observe โ†’ Act โ†’ Reward โ†’ Repeat
   But this policy is terrible! It doesn't learn from rewards.
==============================================================

Part 2: The Problem with Traditional RL ๐Ÿ˜ค

๐Ÿค” Why Canโ€™t We Just Use OpenAI Gym?

Good question! Gym is great for research, but production needs moreโ€ฆ

ChallengeTraditional ApproachOpenEnv Solution
Type SafetyโŒ obs[0][3] - what is this?โœ… obs.info_state - IDE knows!
IsolationโŒ Same process (can crash your training)โœ… Docker containers (fully isolated)
DeploymentโŒ โ€œWorks on my machineโ€ ๐Ÿคทโœ… Same container everywhere ๐Ÿณ
ScalingโŒ Hard to distributeโœ… Deploy to Kubernetes โ˜ธ๏ธ
LanguageโŒ Python onlyโœ… Any language (HTTP API) ๐ŸŒ
DebuggingโŒ Cryptic numpy errorsโœ… Clear type errors ๐Ÿ›

๐Ÿ’ก The OpenEnv Philosophy

โ€œRL environments should be like microservicesโ€

Think of it like this: You donโ€™t run your database in the same process as your web server, right? Same principle!

  • ๐Ÿ”’ Isolated: Run in containers (security + stability)
  • ๐ŸŒ Standard: HTTP API, works everywhere
  • ๐Ÿ“ฆ Versioned: Docker images (reproducibility!)
  • ๐Ÿš€ Scalable: Deploy to cloud with one command
  • ๐Ÿ›ก๏ธ Type-safe: Catch bugs before they happen
  • ๐Ÿ”„ Portable: Works on Mac, Linux, Windows, Cloud

The Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  YOUR TRAINING CODE                                        โ”‚
โ”‚                                                            โ”‚
โ”‚  env = OpenSpielEnv(...).sync() โ† Synchronous client      โ”‚
โ”‚  result = env.reset()           โ† Type-safe!             โ”‚
โ”‚  result = env.step(action)      โ† Type-safe!             โ”‚
โ”‚                                                            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                  โ”‚
                  โ”‚  WebSocket/JSON (Language-Agnostic)
                  โ”‚  reset, step, state messages on /ws
                  โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  DOCKER CONTAINER                                          โ”‚
โ”‚                                                            โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”         โ”‚
โ”‚  โ”‚  FastAPI Server                              โ”‚         โ”‚
โ”‚  โ”‚  โ””โ”€ Environment (reset, step, state)         โ”‚         โ”‚
โ”‚  โ”‚     โ””โ”€ Your Game/Simulation Logic            โ”‚         โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜         โ”‚
โ”‚                                                            โ”‚
โ”‚  Isolated โ€ข Reproducible โ€ข Secure                          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

You never see WebSocket details - just clean Python methods!

env.reset()    # Under the hood: reset message over /ws
env.step(...)  # Under the hood: step message over /ws
env.state()    # Under the hood: state message over /ws

The magic? OpenEnv handles all the plumbing. You focus on RL! โœจ


Part 3: Setup ๐Ÿ› ๏ธ

Running in Colab? This cell will clone OpenEnv and install dependencies automatically.

Running locally? From the OpenEnv directory, install the dependencies into your active environment before running the cells:

uv pip install -e . open_spiel
import os
import subprocess
import sys
from pathlib import Path

try:
    import google.colab
    IN_COLAB = True
except ImportError:
    IN_COLAB = False

if IN_COLAB and Path.cwd().name != "OpenEnv":
    if not Path("OpenEnv").exists():
        subprocess.check_call(["git", "clone", "https://github.com/huggingface/OpenEnv.git"])
    os.chdir("OpenEnv")

# Run from the repository root, or its examples/ directory.
work_dir = Path.cwd()
if not (work_dir / "pyproject.toml").exists():
    work_dir = work_dir.parent
if not (work_dir / "envs" / "openspiel_env").is_dir():
    raise RuntimeError("Run this tutorial from the OpenEnv repository root.")

if IN_COLAB:
    subprocess.check_call([
        sys.executable, "-m", "pip", "install", "-q", "-e", str(work_dir), "open_spiel"
    ])
for directory in (work_dir / "src", work_dir / "envs"):
    sys.path.insert(0, str(directory))

print("โœ… OpenEnv and OpenSpiel are ready")

Output:

โœ… OpenEnv and OpenSpiel are ready

Part 4: The OpenEnv Pattern ๐Ÿ—๏ธ

Every OpenEnv Environment Has 3 Components:

envs/your_env/
โ”œโ”€โ”€ ๐Ÿ“ models.py          โ† Type-safe contracts
โ”‚                           (Action, Observation, State)
โ”‚
โ”œโ”€โ”€ ๐Ÿ“ฑ client.py          โ† What YOU import
โ”‚                           (EnvClient implementation)
โ”‚
โ””โ”€โ”€ ๐Ÿ–ฅ๏ธ  server/
    โ”œโ”€โ”€ environment.py    โ† Game/simulation logic
    โ”œโ”€โ”€ app.py            โ† FastAPI server
    โ””โ”€โ”€ Dockerfile        โ† Container definition

Letโ€™s explore the actual OpenEnv code to see how this works:

# Import OpenEnv's core abstractions
from openenv.core.env_server import Environment, Action, Observation, State
from openenv.core.env_client import EnvClient

print("="*70)
print("   ๐Ÿงฉ OPENENV CORE ABSTRACTIONS")
print("="*70)

print("""
๐Ÿ–ฅ๏ธ  SERVER SIDE (runs in Docker):

    class Environment(ABC):
        '''Base class for all environment implementations'''

        @abstractmethod
        def reset(self) -> Observation:
            '''Start new episode'''

        @abstractmethod
        def step(self, action: Action) -> Observation:
            '''Execute action, return observation'''

        @property
        def state(self) -> State:
            '''Get episode metadata'''

๐Ÿ“ฑ CLIENT SIDE (your training code):

    class EnvClient(ABC):
        '''Base class for environment clients'''

        def reset(self) -> StepResult:
            # WebSocket reset message

        def step(self, action) -> StepResult:
            # WebSocket step message

        def state(self) -> State:
            # WebSocket state message
""")

print("="*70)
print("\nโœจ Same interface on both sides - communication via WebSocket!")
print("๐ŸŽฏ You focus on RL, OpenEnv handles the infrastructure.\n")

Output:

======================================================================
   ๐Ÿงฉ OPENENV CORE ABSTRACTIONS
======================================================================

๐Ÿ–ฅ๏ธ  SERVER SIDE (runs in Docker):

    class Environment(ABC):
        '''Base class for all environment implementations'''

        @abstractmethod
        def reset(self) -> Observation:
            '''Start new episode'''

        @abstractmethod
        def step(self, action: Action) -> Observation:
            '''Execute action, return observation'''

        @property
        def state(self) -> State:
            '''Get episode metadata'''

๐Ÿ“ฑ CLIENT SIDE (your training code):

    class EnvClient(ABC):
        '''Base class for environment clients'''

        def reset(self) -> StepResult:
            # WebSocket reset message

        def step(self, action) -> StepResult:
            # WebSocket step message

        def state(self) -> State:
            # WebSocket state message

======================================================================

โœจ Same interface on both sides - communication via WebSocket!
๐ŸŽฏ You focus on RL, OpenEnv handles the infrastructure.

Part 5: Example Integration - OpenSpiel ๐ŸŽฎ

What is OpenSpiel?

OpenSpiel is a library from DeepMind with 70+ game environments for RL research.

OpenEnvโ€™s Integration

Weโ€™ve wrapped 6 OpenSpiel games following the OpenEnv pattern:

๐ŸŽฏ Single-Player๐Ÿ‘ฅ Multi-Player
1. Catch - Catch falling ball5. Tic-Tac-Toe - Classic 3ร—3
2. Cliff Walking - Navigate grid6. Kuhn Poker - Imperfect info poker
3. 2048 - Tile puzzle
4. Blackjack - Card game

This shows how OpenEnv can wrap any existing RL library!

from openspiel_env.client import OpenSpielEnv

print("="*70)
print("   ๐Ÿ”Œ HOW OPENENV WRAPS OPENSPIEL")
print("="*70)

print("""
class OpenSpielEnv(EnvClient[OpenSpielAction, OpenSpielObservation, OpenSpielState]):

    def _step_payload(self, action: OpenSpielAction) -> dict:
        '''Convert typed action to JSON for WebSocket'''
        return {
            "action_id": action.action_id,
            "game_name": action.game_name,
        }

    def _parse_result(self, payload: dict) -> StepResult:
        '''Parse JSON response into typed observation'''
        return StepResult(
            observation=OpenSpielObservation(...),
            reward=payload['reward'],
            done=payload['done']
        )

""")

print("โ”€" * 70)
print("\nโœจ Usage (works for ALL OpenEnv environments):")
print("""
  env = OpenSpielEnv(base_url="http://localhost:8000").sync()

  result = env.reset()
  # Returns StepResult[OpenSpielObservation] - Type safe!

  result = env.step(OpenSpielAction(action_id=2, game_name="catch"))
  # Type checker knows this is valid!

  state = env.state()
  # Returns OpenSpielState
""")

print("โ”€" * 70)
print("\n๐ŸŽฏ This pattern works for ANY environment you want to wrap!\n")

Output:

======================================================================
   ๐Ÿ”Œ HOW OPENENV WRAPS OPENSPIEL
======================================================================

class OpenSpielEnv(EnvClient[OpenSpielAction, OpenSpielObservation, OpenSpielState]):

    def _step_payload(self, action: OpenSpielAction) -> dict:
        '''Convert typed action to JSON for WebSocket'''
        return {
            "action_id": action.action_id,
            "game_name": action.game_name,
        }

    def _parse_result(self, payload: dict) -> StepResult:
        '''Parse JSON response into typed observation'''
        return StepResult(
            observation=OpenSpielObservation(...),
            reward=payload['reward'],
            done=payload['done']
        )


โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

โœจ Usage (works for ALL OpenEnv environments):

  env = OpenSpielEnv(base_url="http://localhost:8000").sync()

  result = env.reset()
  # Returns StepResult[OpenSpielObservation] - Type safe!

  result = env.step(OpenSpielAction(action_id=2, game_name="catch"))
  # Type checker knows this is valid!

  state = env.state()
  # Returns OpenSpielState

โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

๐ŸŽฏ This pattern works for ANY environment you want to wrap!

Type-Safe Models

# Import OpenSpiel integration models
from openspiel_env.models import (
    OpenSpielAction,
    OpenSpielObservation,
    OpenSpielState
)

print("="*70)
print("   ๐ŸŽฎ OPENSPIEL INTEGRATION - TYPE-SAFE MODELS")
print("="*70)

print("\n๐Ÿ“ค OpenSpielAction (what you send):")
print("   " + "โ”€" * 64)
for name, field in OpenSpielAction.model_fields.items():
    print(f"   โ€ข {name:20s} : {field.annotation}")

print("\n๐Ÿ“ฅ OpenSpielObservation (what you receive):")
print("   " + "โ”€" * 64)
for name, field in OpenSpielObservation.model_fields.items():
    print(f"   โ€ข {name:20s} : {field.annotation}")

print("\n๐Ÿ“Š OpenSpielState (episode metadata):")
print("   " + "โ”€" * 64)
for name, field in OpenSpielState.model_fields.items():
    print(f"   โ€ข {name:20s} : {field.annotation}")

print("\n" + "="*70)
print("\n๐Ÿ’ก Type safety means:")
print("   โœ… Your IDE autocompletes these fields")
print("   โœ… Typos are caught before running")
print("   โœ… Refactoring is safe")
print("   โœ… Self-documenting code\n")

Output:

======================================================================
   ๐ŸŽฎ OPENSPIEL INTEGRATION - TYPE-SAFE MODELS
======================================================================

๐Ÿ“ค OpenSpielAction (what you send):
   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
   โ€ข metadata             : typing.Dict[str, typing.Any]
   โ€ข action_id            : <class 'int'>
   โ€ข game_name            : <class 'str'>
   โ€ข game_params          : typing.Dict[str, typing.Any]

๐Ÿ“ฅ OpenSpielObservation (what you receive):
   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
   โ€ข done                 : <class 'bool'>
   โ€ข reward               : bool | int | float | None
   โ€ข metadata             : typing.Dict[str, typing.Any]
   โ€ข info_state           : typing.List[float]
   โ€ข legal_actions        : typing.List[int]
   โ€ข game_phase           : <class 'str'>
   โ€ข current_player_id    : <class 'int'>
   โ€ข opponent_last_action : typing.Optional[int]

๐Ÿ“Š OpenSpielState (episode metadata):
   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
   โ€ข episode_id           : typing.Optional[str]
   โ€ข step_count           : <class 'int'>
   โ€ข game_name            : <class 'str'>
   โ€ข agent_player         : <class 'int'>
   โ€ข opponent_policy      : <class 'str'>
   โ€ข game_params          : typing.Dict[str, typing.Any]
   โ€ข num_players          : <class 'int'>

======================================================================

๐Ÿ’ก Type safety means:
   โœ… Your IDE autocompletes these fields
   โœ… Typos are caught before running
   โœ… Refactoring is safe
   โœ… Self-documenting code

How the Client Works

The client inherits from EnvClient and implements 3 methods:

  1. _step_payload() - Convert action โ†’ JSON
  2. _parse_result() - Parse JSON โ†’ typed observation
  3. _parse_state() - Parse JSON โ†’ state

Thatโ€™s it! The base class handles the WebSocket session.


Part 6: Using Real OpenSpiel ๐ŸŽฎ

Now letโ€™s USE a production environment!

Weโ€™ll play Catch using OpenEnvโ€™s OpenSpiel integration ๐ŸŽฏ

This is a REAL environment running in production at companies!

Get ready for:

  • ๐Ÿ”Œ Using existing environments (not building)
  • ๐Ÿค– Testing policies against real games
  • ๐Ÿ“Š Live gameplay visualization
  • ๐ŸŽฏ Production-ready patterns

The Game: Catch ๐Ÿ”ด๐Ÿ“

โฌœ โฌœ ๐Ÿ”ด โฌœ โฌœ
โฌœ โฌœ โฌœ โฌœ โฌœ
โฌœ โฌœ โฌœ โฌœ โฌœ   Ball
โฌœ โฌœ โฌœ โฌœ โฌœ
โฌœ โฌœ โฌœ โฌœ โฌœ   falls
โฌœ โฌœ โฌœ โฌœ โฌœ
โฌœ โฌœ โฌœ โฌœ โฌœ   down
โฌœ โฌœ โฌœ โฌœ โฌœ
โฌœ โฌœ โฌœ โฌœ โฌœ
โฌœ โฌœ ๐Ÿ“ โฌœ โฌœ
     Paddle

Rules:

  • 10ร—5 grid
  • Ball falls from random column
  • Move paddle left/right to catch it

Actions:

  • 0 = Move LEFT โฌ…๏ธ
  • 1 = STAY ๐Ÿ›‘
  • 2 = Move RIGHT โžก๏ธ

Reward:

  • +1 if caught ๐ŸŽ‰
  • -1 if missed ๐Ÿ˜ข
  • Simple rules (easy to understand)
  • Fast episodes (~9 steps)
  • Clear success/failure
  • Part of OpenSpielโ€™s 70+ games!

๐Ÿ’ก The Big Idea: Instead of building this from scratch, weโ€™ll USE OpenEnvโ€™s existing OpenSpiel integration. Same interface, but production-ready!

from openspiel_env import OpenSpielEnv
from openspiel_env.models import (
    OpenSpielAction,
    OpenSpielObservation,
    OpenSpielState
)

print("๐ŸŽฎ " + "="*64 + " ๐ŸŽฎ")
print("   โœ… Importing Real OpenSpiel Environment!")
print("๐ŸŽฎ " + "="*64 + " ๐ŸŽฎ\n")

print("๐Ÿ“ฆ What we just imported:")
print("   โ€ข OpenSpielEnv - WebSocket client for OpenSpiel games")
print("   โ€ข OpenSpielAction - Type-safe actions")
print("   โ€ข OpenSpielObservation - Type-safe observations")
print("   โ€ข OpenSpielState - Episode metadata\n")

print("๐Ÿ“‹ OpenSpielObservation fields:")
print("   " + "โ”€" * 60)
for name, field in OpenSpielObservation.model_fields.items():
    print(f"   โ€ข {name:25s} : {field.annotation}")

print("\n" + "="*70)
print("\n๐Ÿ’ก This is REAL OpenEnv code - used in production!")
print("   โ€ข Wraps 6 OpenSpiel games (Catch, Tic-Tac-Toe, Poker, etc.)")
print("   โ€ข Type-safe actions and observations")
print("   โ€ข Works via WebSocket (we'll see that next!)\n")

Output:

๐ŸŽฎ ================================================================ ๐ŸŽฎ
   โœ… Importing Real OpenSpiel Environment!
๐ŸŽฎ ================================================================ ๐ŸŽฎ

๐Ÿ“ฆ What we just imported:
   โ€ข OpenSpielEnv - WebSocket client for OpenSpiel games
   โ€ข OpenSpielAction - Type-safe actions
   โ€ข OpenSpielObservation - Type-safe observations
   โ€ข OpenSpielState - Episode metadata

๐Ÿ“‹ OpenSpielObservation fields:
   โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
   โ€ข done                      : <class 'bool'>
   โ€ข reward                    : bool | int | float | None
   โ€ข metadata                  : typing.Dict[str, typing.Any]
   โ€ข info_state                : typing.List[float]
   โ€ข legal_actions             : typing.List[int]
   โ€ข game_phase                : <class 'str'>
   โ€ข current_player_id         : <class 'int'>
   โ€ข opponent_last_action      : typing.Optional[int]

======================================================================

๐Ÿ’ก This is REAL OpenEnv code - used in production!
   โ€ข Wraps 6 OpenSpiel games (Catch, Tic-Tac-Toe, Poker, etc.)
   โ€ข Type-safe actions and observations
   โ€ข Works via WebSocket (we'll see that next!)

Start the local server

Run this cell before evaluating policies. It starts Catch and waits for the health endpoint. Set PORT to an unused local port (8000 by default). Server output is written to openspiel-server.log. The synchronous wrapper also works in notebooks with an active event loop.

import socket
import time
import requests

PORT = 8000
BASE_URL = f"http://127.0.0.1:{PORT}"

server_env = {
    **os.environ,
    "PYTHONPATH": os.pathsep.join(
        [str(work_dir / "src"), str(work_dir / "envs"), os.environ.get("PYTHONPATH", "")]
    ),
    "OPENSPIEL_GAME": "catch",
}

def start_server(game_name="catch"):
    # Fail clearly if another service already owns this port.
    with socket.socket() as probe:
        if probe.connect_ex(("127.0.0.1", PORT)) == 0:
            raise RuntimeError(f"Port {PORT} is already in use; choose another PORT.")
    with (work_dir / "openspiel-server.log").open("w") as log:
        process = subprocess.Popen(
            [sys.executable, "-m", "uvicorn", "openspiel_env.server.app:app",
             "--host", "127.0.0.1", "--port", str(PORT)],
            cwd=work_dir,
            env={**server_env, "OPENSPIEL_GAME": game_name},
            stdout=log,
            stderr=subprocess.STDOUT,
        )
    for _ in range(100):
        if process.poll() is not None:
            raise RuntimeError("Server exited; check openspiel-server.log")
        try:
            if requests.get(f"{BASE_URL}/health", timeout=1).ok:
                return process
        except requests.RequestException:
            pass
        time.sleep(0.1)
    process.terminate()
    process.wait(timeout=10)
    raise RuntimeError("Server did not become ready; check openspiel-server.log")

server_process = start_server()
client = OpenSpielEnv(base_url=BASE_URL).sync()
client.connect()
print(client.reset().observation)

Part 7: Four Policies ๐Ÿค–

Letโ€™s test 4 different AI strategies:

PolicyStrategyExpected Performance
๐ŸŽฒ RandomPick random action every step~20% (pure luck)
๐Ÿ›‘ Always StayNever move, hope ball lands in center~20% (terrible!)
๐Ÿง  SmartMove paddle toward ball100% (optimal!)
๐Ÿ“ˆ LearningStart random, learn smart strategy~85% (improves over time)

These policies use the OpenSpiel observation type. The movement heuristics below are specific to Catch.

LearningPolicy illustrates decaying exploration with a supplied heuristic; it does not learn from rewards.

import random

# ============================================================================
# POLICIES - Different AI strategies (adapted for OpenSpiel)
# ============================================================================

class RandomPolicy:
    """Baseline: Pure random guessing."""
    name = "๐ŸŽฒ Random Guesser"

    def select_action(self, obs: OpenSpielObservation) -> int:
        return random.choice(obs.legal_actions)


class AlwaysStayPolicy:
    """Bad strategy: Never moves."""
    name = "๐Ÿ›‘ Always Stay"

    def select_action(self, obs: OpenSpielObservation) -> int:
        return 1  # STAY


class SmartPolicy:
    """Optimal: Move paddle toward ball."""
    name = "๐Ÿง  Smart Heuristic"

    def select_action(self, obs: OpenSpielObservation) -> int:
        # Parse OpenSpiel observation
        # For Catch: info_state is a flattened 10x5 grid
        # Ball position and paddle position encoded in the vector
        info_state = obs.info_state

        # Find ball and paddle positions from info_state
        # Catch uses a 10x5 grid, so 50 values
        grid_size = 5

        # Find positions (ball = 1.0 in the flattened grid, paddle = 1.0 in the last row of the flattened grid)
        ball_col = None
        paddle_col = None

        for idx, val in enumerate(info_state):
            if abs(val - 1.0) < 0.01:  # Ball
                ball_col = idx % grid_size
                break

        last_row = info_state[-grid_size:]
        paddle_col = last_row.index(1.0) # Paddle

        if ball_col is not None and paddle_col is not None:
            if paddle_col < ball_col:
                return 2  # Move RIGHT
            elif paddle_col > ball_col:
                return 0  # Move LEFT

        return 1  # STAY (fallback)


class LearningPolicy:
    """Simulated RL: Epsilon-greedy exploration."""
    name = "๐Ÿ“ˆ Learning Agent"

    def __init__(self):
        self.steps = 0
        self.smart_policy = SmartPolicy()

    def select_action(self, obs: OpenSpielObservation) -> int:
        self.steps += 1

        # Decay exploration rate over time
        epsilon = max(0.1, 1.0 - (self.steps / 100))

        if random.random() < epsilon:
            # Explore: random action
            return random.choice(obs.legal_actions)
        else:
            # Exploit: use smart strategy
            return self.smart_policy.select_action(obs)


print("๐Ÿค– " + "="*64 + " ๐Ÿค–")
print("   โœ… 4 Policies Created (Adapted for OpenSpiel)!")
print("๐Ÿค– " + "="*64 + " ๐Ÿค–\n")

policies = [RandomPolicy(), AlwaysStayPolicy(), SmartPolicy(), LearningPolicy()]
for i, policy in enumerate(policies, 1):
    print(f"   {i}. {policy.name}")

print("\n๐Ÿ’ก These policies work with OpenSpielObservation!")
print("   โ€ข Read info_state (flattened grid)")
print("   โ€ข Use legal_actions")
print("   โ€ข Use Catch-specific movement and grid assumptions\n")

Output:

๐Ÿค– ================================================================ ๐Ÿค–
   โœ… 4 Policies Created (Adapted for OpenSpiel)!
๐Ÿค– ================================================================ ๐Ÿค–

   1. ๐ŸŽฒ Random Guesser
   2. ๐Ÿ›‘ Always Stay
   3. ๐Ÿง  Smart Heuristic
   4. ๐Ÿ“ˆ Learning Agent

๐Ÿ’ก These policies work with OpenSpielObservation!
   โ€ข Read info_state (flattened grid)
   โ€ข Use legal_actions
   โ€ข Use Catch-specific movement and grid assumptions

Part 8: Policy Competition! ๐Ÿ†

Letโ€™s run 50 episodes for each policy against REAL OpenSpiel and see who wins!

This is production code - every action is a WebSocket message to the OpenSpiel server!

def run_episode(env, policy, visualize=False):
    """Play one Catch episode and return whether the ball was caught."""
    result = env.reset()
    for _ in range(100):
        if result.done:
            return float(result.reward or 0) > 0
        action_id = policy.select_action(result.observation)
        result = env.step(OpenSpielAction(action_id=action_id, game_name="catch"))
        if visualize:
            print(result.observation.info_state)
    raise RuntimeError("Catch episode exceeded 100 steps")


def evaluate_policies(env, num_episodes=50):
    """Compare all policies over many episodes using real OpenSpiel."""
    policies = [
        RandomPolicy(),
        AlwaysStayPolicy(),
        SmartPolicy(),
        LearningPolicy(),
    ]

    print("\n๐Ÿ† " + "="*66 + " ๐Ÿ†")
    print(f"   POLICY SHOWDOWN - {num_episodes} Episodes Each")
    print(f"   Playing against REAL OpenSpiel Catch!")
    print("๐Ÿ† " + "="*66 + " ๐Ÿ†\n")

    results = []
    for policy in policies:
        print(f"โšก Testing {policy.name}...", end=" ")
        successes = sum(run_episode(env, policy, visualize=False)
                       for _ in range(num_episodes))
        success_rate = (successes / num_episodes) * 100
        results.append((policy.name, success_rate, successes))
        print(f"โœ“ Done!")

    print("\n" + "="*70)
    print("   ๐Ÿ“Š FINAL RESULTS")
    print("="*70 + "\n")

    # Sort by success rate (descending)
    results.sort(key=lambda x: x[1], reverse=True)

    # Award medals to top 3
    medals = ["๐Ÿฅ‡", "๐Ÿฅˆ", "๐Ÿฅ‰", "  "]

    for i, (name, rate, successes) in enumerate(results):
        medal = medals[i]
        bar = "โ–ˆ" * int(rate / 2)
        print(f"{medal} {name:25s} [{bar:<50}] {rate:5.1f}% ({successes}/{num_episodes})")

    print("\n" + "="*70)
    print("\nโœจ Key Insights:")
    print("   โ€ข Random (~20%):      Baseline - pure luck ๐ŸŽฒ")
    print("   โ€ข Always Stay (~20%): Bad strategy - stays center ๐Ÿ›‘")
    print("   โ€ข Smart (100%):       Optimal - perfect play! ๐Ÿง ")
    print("   โ€ข Learning (~85%):    Improves over time ๐Ÿ“ˆ")
    print("\n๐ŸŽ“ This is Reinforcement Learning + OpenEnv in action:")
    print("   1. We USED existing OpenSpiel environment (didn't build it)")
    print("   2. Type-safe communication over WebSocket")
    print("   3. Other games use the same client with game-specific policies")
    print("   4. Production-ready architecture\n")

# Run the epic competition!
print("๐ŸŽฎ Starting the showdown against REAL OpenSpiel...\n")
evaluate_policies(client, num_episodes=50)

Part 9: Switching to Other Games ๐ŸŽฎ

What We Just Used: Real OpenSpiel! ๐ŸŽ‰

In Parts 6-8, we USED the existing OpenSpiel Catch environment:

What We DidHow It Works
ImportedOpenSpielEnv client (pre-built)
StartedOpenSpiel server via uvicorn
ConnectedWebSocket client to server
PlayedReal OpenSpiel Catch game

๐ŸŽฏ This is production code! Every action was a WebSocket message to a real OpenSpiel environment.

๐ŸŽฎ 6 Games Available - Same Interface!

The beauty of OpenEnv? Same code, different games!

# We just used Catch
env = OpenSpielEnv(base_url=BASE_URL).sync()
# game_name="catch" was set via environment variable

# Want Tic-Tac-Toe instead? Just change the game!
# Start server with: OPENSPIEL_GAME=tic_tac_toe uvicorn ...
# Same client code works!

๐ŸŽฎ All 6 Games:

  1. โœ… catch - What we just used!
  2. tic_tac_toe - Classic 3ร—3
  3. kuhn_poker - Imperfect information poker
  4. cliff_walking - Grid navigation
  5. 2048 - Tile puzzle
  6. blackjack - Card game

All use the exact same OpenSpielEnv client!

Try Another Game (Optional):

client.close()
server_process.terminate()
server_process.wait(timeout=10)

server_process = start_server("tic_tac_toe")
client = OpenSpielEnv(base_url=BASE_URL).sync()
client.connect()
result = client.reset()
result = client.step(OpenSpielAction(
    action_id=result.observation.legal_actions[0], game_name="tic_tac_toe"
))

๐Ÿ’ก Key Insight: You donโ€™t rebuild anything - you just USE different games with the same client!

Clean up

After the competition (and the optional game switch), close the client and stop the local server:

client.close()
server_process.terminate()
server_process.wait(timeout=10)

Part 10: Create Your Own Integration ๐Ÿ› ๏ธ

The 5-Step Pattern

Want to wrap your own environment in OpenEnv? These skeletons show the structure; replace the ... placeholders with your environment logic. For a complete runnable example, follow Your First Environment.

Step 1: Define Types ( models.py )

from openenv.core.env_server import Action, Observation, State

class YourAction(Action):
    action_value: int
    # Add your action fields

class YourObservation(Observation):
    state_data: list[float]
    done: bool
    reward: float
    # Add your observation fields

class YourState(State):
    episode_id: str
    step_count: int
    # Add your state fields

Step 2: Implement Environment ( server/environment.py )

from openenv.core.env_server import Environment
from ..models import YourAction, YourObservation, YourState

class YourEnvironment(Environment[YourAction, YourObservation, YourState]):
    def reset(self) -> YourObservation:
        # Initialize your game/simulation
        return YourObservation(...)

    def step(self, action: YourAction) -> YourObservation:
        # Execute action, update state
        return YourObservation(...)

    @property
    def state(self) -> YourState:
        return self._state

Step 3: Create Client ( client.py )

from openenv.core.env_client import EnvClient
from openenv.core.client_types import StepResult
from .models import YourAction, YourObservation, YourState

class YourEnv(EnvClient[YourAction, YourObservation, YourState]):
    def _step_payload(self, action: YourAction) -> dict:
        """Convert action to JSON"""
        return {"action_value": action.action_value}

    def _parse_result(self, payload: dict) -> StepResult:
        """Parse JSON to observation"""
        return StepResult(
            observation=YourObservation(...),
            reward=payload['reward'],
            done=payload['done']
        )

    def _parse_state(self, payload: dict) -> YourState:
        return YourState(...)

Step 4: Create Server ( server/app.py )

from openenv.core.env_server import create_app
from ..models import YourAction, YourObservation, YourState
from .environment import YourEnvironment

app = create_app(
    YourEnvironment, YourAction, YourObservation, state_cls=YourState
)

# That's it! OpenEnv creates all endpoints for you.

Step 5: Dockerize ( server/Dockerfile )

Build from a project directory containing the your_env package and a requirements.txt that includes openenv plus your environment dependencies.

FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .
CMD ["uvicorn", "your_env.server.app:app", "--host", "0.0.0.0", "--port", "8000"]

๐ŸŽ“ Examples to Study

OpenEnv includes 3 complete examples:

  1. envs/echo_env/

    • Simplest possible environment
    • Great for testing and learning
  2. envs/openspiel_env/

    • Wraps external library (OpenSpiel)
    • Shows integration pattern
    • 6 games in one integration
  3. envs/coding_env/

    • Python code execution environment
    • Shows complex use case
    • Security considerations

๐Ÿ’ก Study these to understand the patterns!


(summary-your-journey)=

๐ŸŽ“ Summary: Your Journey

What You Learned

๐Ÿ“š Concepts

โœ… RL Fundamentals

  • The observe-act-reward loop
  • What makes good policies
  • Exploration vs exploitation

โœ… OpenEnv Architecture

  • Client-server separation
  • Type-safe contracts
  • WebSocket communication layer

โœ… Production Patterns

  • Docker isolation
  • API design
  • Reproducible deployments

๐Ÿ› ๏ธ Skills

โœ… Using Environments

  • Import OpenEnv clients
  • Call reset/step/state
  • Work with typed observations

โœ… Building Environments

  • Define type-safe models
  • Implement Environment class
  • Create EnvClient

โœ… Testing & Debugging

  • Compare policies
  • Visualize episodes
  • Measure performance

OpenEnv vs Traditional RL

FeatureTraditional (Gym)OpenEnvWinner
Type SafetyโŒ Arrays, dictsโœ… Pydantic models๐Ÿ† OpenEnv
IsolationโŒ Same processโœ… Docker๐Ÿ† OpenEnv
DeploymentโŒ Manual setupโœ… K8s-ready๐Ÿ† OpenEnv
LanguageโŒ Python onlyโœ… Any (HTTP)๐Ÿ† OpenEnv
ReproducibilityโŒ โ€œWorks on my machineโ€โœ… Same everywhere๐Ÿ† OpenEnv
Communityโœ… Large ecosystem๐ŸŸก Growing๐Ÿค Both!

OpenEnv brings production engineering to RL:

  • Same environments work locally and in production
  • Type safety catches bugs early
  • Docker isolation prevents conflicts
  • HTTP API works with any language

Itโ€™s RL for 2024 and beyond.


๐Ÿ“š Resources

๐Ÿ”— Essential Links

๐Ÿ“– Documentation Deep Dives

  • Environment Creation Guide: envs/README.md
  • OpenSpiel Integration: envs/openspiel_env/README.md
  • Example Scripts: examples/
  • RFC 001: Baseline API Specs

๐ŸŽ“ Community & Support

Openly governed by a technical committee including:

  • ๐Ÿ”ฅ Meta PyTorch
  • ๐ŸŒŸ Reflection
  • โšก Unsloth
  • โ˜๏ธ Modal
  • ๐Ÿง  Prime Intellect
  • ๐ŸŸข Nvidia
  • ๐Ÿ’ผ Mercor
  • ๐Ÿš€ Fleet AI
  • ๐ŸชŸ Microsoft
  • ๐Ÿค— Hugging Face

Supported by amazing organizations and contributors.

  • ๐Ÿš€ And many more!

Technical direction, RFCs, and release planning are coordinated in public through the OpenEnv repository.

License: BSD 3-Clause License

Contributions: Always welcome! Check out the issues tab.


๐ŸŒˆ Whatโ€™s Next?

  1. โญ Star the repo to show support and stay updated
  2. ๐Ÿ”„ Try modifying the Catch game (make it harder? bigger grid?)
  3. ๐ŸŽฎ Explore other OpenSpiel games
  4. ๐Ÿ› ๏ธ Build your own environment integration
  5. ๐Ÿ’ฌ Share what you build with the community!
Update on GitHub