Coding Environment

A Python code execution environment that runs arbitrary Python code and returns results. Perfect for testing code execution infrastructure and demonstrating environment usage patterns.

Try it on the openenv/coding_env Space, or connect a client to https://openenv-coding-env.hf.space.

Quick Start

The simplest way to use the Coding environment is through the CodingEnv class. The client is async by default:

import asyncio
from coding_env import CodeAction, CodingEnv

async def main():
    # Create environment from Docker image
    client = await CodingEnv.from_docker_image("coding-env:latest")

    async with client:
        # Reset
        result = await client.reset()
        print(f"Reset complete: exit_code={result.observation.exit_code}")

        # Execute Python code
        code_samples = [
            "print('Hello, World!')",
            "x = 5 + 3\nprint(f'Result: {x}')",
            "import math\nprint(math.pi)"
        ]

        for code in code_samples:
            result = await client.step(CodeAction(code=code))
            print(f"Code: {code}")
            print(f"  → stdout: {result.observation.stdout.strip()}")
            print(f"  → exit_code: {result.observation.exit_code}")

asyncio.run(main())

For synchronous usage, use the .sync() wrapper:

from coding_env import CodeAction, CodingEnv

with CodingEnv(base_url="http://localhost:8000").sync() as client:
    result = client.reset()
    result = client.step(CodeAction(code="print('Hello!')"))
    print(result.observation.stdout)

The CodingEnv.from_docker_image() method handles:

  • Starting the Docker container
  • Waiting for the server to be ready
  • Connecting to the environment
  • Container cleanup when the context manager exits

Building the Docker Image

Before using the environment, you need to build the Docker image:

# From project root
docker build -t coding-env:latest -f envs/coding_env/server/Dockerfile .

Environment Details

Action

CodeAction: Contains a single field

  • code (str) - The Python code to execute

Observation

CodeObservation: Contains the execution results

  • stdout (str) - Standard output from code execution
  • stderr (str) - Standard error from code execution
  • exit_code (int) - Exit code (0 for success, non-zero for errors)

State

CodeState: Tracks execution state

  • episode_id (str) - Unique identifier for the episode
  • step_count (int) - Number of steps taken
  • last_exit_code (int) - Exit code from the last execution

Sessions and isolation

Each session runs its code in its own Python worker process, and reset() starts a new one, so nothing an episode defines or changes in the interpreter reaches the next episode or another session.

Workers are forked from a template process (a zygote) that the server starts on the first reset(). The zygote starts with a minimal environment, so neither it nor the workers see the server’s environment variables, and it imports smolagents and the authorized modules once, which takes a few seconds. After that a new worker is ready in milliseconds and shares most of its memory with the zygote (about 10 MB per worker on Linux). Each worker gets its own home, working and temporary directory (HOME, TMPDIR), removed when the session ends. A step that runs past the timeout kills only its own worker, and if the zygote dies the server starts a new one.

When the server runs as root, each worker switches to the unprivileged nobody user right after the fork, before it runs any model code, so it can’t signal the server, the zygote or processes of other users. On Linux the zygote and the workers are non-dumpable, and so is the server started from server/app.py, so other processes of the same user can’t read their memory or environment through /proc.

On Linux (x86_64 and aarch64) each worker also installs a seccomp filter before it runs any model code: it can’t create sockets of any family, so even with modules like requests or pandas authorized, model code has no network. The filter needs no capability, so it also applies where network namespaces are not available (no CAP_SYS_ADMIN). Elsewhere the server logs a warning.

  • CODING_ENV_EXEC_TIMEOUT_S: hard limit per step (default 30). A step that runs longer is stopped, its worker is killed, and the next step starts with a fresh interpreter.
  • MAX_CONCURRENT_ENVS: max concurrent sessions (default 8). Each session holds one worker process.

Limits:

  • All workers run as the same user, and when the server isn’t root they run as the server’s user. The import allowlist, which leaves out os by default, is what keeps one session’s code from signaling other sessions’ workers (or, without root, the server).
  • Each session has its own temporary directory, but /tmp itself is still shared if file access (os, open) is authorized.
  • There is no memory limit per worker. The container’s limit is the guard, and a worker that gets killed only restarts its own session.
  • Workers share the server’s stderr, so if os is authorized, model code can write lines into the server log.

Advanced Usage

Connecting to an Existing Server

If you already have a Coding environment server running, you can connect directly:

from coding_env import CodeAction, CodingEnv

# Async usage
async with CodingEnv(base_url="http://localhost:8000") as client:
    result = await client.reset()
    result = await client.step(CodeAction(code="print('Hello!')"))

# Sync usage
with CodingEnv(base_url="http://localhost:8000").sync() as client:
    result = client.reset()
    result = client.step(CodeAction(code="print('Hello!')"))

Note: When connecting to an existing server, closing the client will NOT stop the server.

Development & Testing

Running Tests

Install the coding_env package with dev dependencies and run the tests from the repo root:

# Install coding_env with dev dependencies (includes smolagents and pytest)
uv pip install -e "envs/coding_env[dev]"

# Run unit tests (no Docker required)
uv run pytest tests/envs/test_python_codeact_reset.py tests/envs/test_python_codeact_rewards.py -v

# Run integration tests (requires Docker image to be built)
docker build -t coding-env:latest -f envs/coding_env/server/Dockerfile .
SKIP_DOCKER_TESTS=0 uv run pytest tests/envs/test_coding_env_integration.py -v

Running the Full Example

Run the complete example that demonstrates the full workflow:

python3 envs/coding_env/client/example_usage.py

This example shows:

  • Creating an environment from a Docker image
  • Resetting and executing code through the environment
  • Automatic cleanup with close()

Project Structure

coding_env/
├── README.md              # This file
├── models.py              # Action, Observation, and State models
├── client/
│   ├── coding_env_client.py  # CodingEnv client implementation
│   └── example_usage.py      # Usage examples
└── server/
    ├── python_codeact_env.py  # Core environment logic
    ├── app.py                 # FastAPI application
    ├── transforms.py          # Observation transforms
    ├── Dockerfile             # Container image definition
    └── README.md              # Server-specific documentation
Update on GitHub