Team Ai
Apppublic

openenv/coding_env

sourceHugging Faceupdated 3mo agoView on Hugging Face
21likes
README.md256 linesDownload Raw Back to openenv_env
1---2title: __ENV_TITLE_NAME__ Environment Server3emoji: __HF_EMOJI__4colorFrom: __HF_COLOR_FROM__5colorTo: __HF_COLOR_TO__6sdk: docker7pinned: false8app_port: 80009base_path: /web10tags:11  - openenv12---13 14# __ENV_TITLE_NAME__ Environment15 16A simple test environment that echoes back messages. Perfect for testing the env APIs as well as demonstrating environment usage patterns.17 18## Quick Start19 20The simplest way to use the __ENV_TITLE_NAME__ environment is through the `__ENV_CLASS_NAME__Env` class:21 22```python23from __ENV_NAME__ import __ENV_CLASS_NAME__Action, __ENV_CLASS_NAME__Env24 25try:26    # Create environment from Docker image27    __ENV_NAME__env = __ENV_CLASS_NAME__Env.from_docker_image("__ENV_NAME__-env:latest")28 29    # Reset30    result = __ENV_NAME__env.reset()31    print(f"Reset: {result.observation.echoed_message}")32 33    # Send multiple messages34    messages = ["Hello, World!", "Testing echo", "Final message"]35 36    for msg in messages:37        result = __ENV_NAME__env.step(__ENV_CLASS_NAME__Action(message=msg))38        print(f"Sent: '{msg}'")39        print(f"  → Echoed: '{result.observation.echoed_message}'")40        print(f"  → Length: {result.observation.message_length}")41        print(f"  → Reward: {result.reward}")42 43finally:44    # Always clean up45    __ENV_NAME__env.close()46```47 48That's it! The `__ENV_CLASS_NAME__Env.from_docker_image()` method handles:49- Starting the Docker container50- Waiting for the server to be ready51- Connecting to the environment52- Container cleanup when you call `close()`53 54## Building the Docker Image55 56Before using the environment, you need to build the Docker image:57 58```bash59# From project root60docker build -t __ENV_NAME__-env:latest -f server/Dockerfile .61```62 63## Deploying to Hugging Face Spaces64 65You can easily deploy your OpenEnv environment to Hugging Face Spaces using the `openenv push` command:66 67```bash68# From the environment directory (where openenv.yaml is located)69openenv push70 71# Or specify options72openenv push --namespace my-org --private73```74 75The `openenv push` command will:761. Validate that the directory is an OpenEnv environment (checks for `openenv.yaml`)772. Prepare a custom build for Hugging Face Docker space (enables web interface)783. Upload to Hugging Face (ensuring you're logged in)79 80### Prerequisites81 82- Authenticate with Hugging Face: The command will prompt for login if not already authenticated83 84### Options85 86- `--directory`, `-d`: Directory containing the OpenEnv environment (defaults to current directory)87- `--repo-id`, `-r`: Repository ID in format 'username/repo-name' (defaults to 'username/env-name' from openenv.yaml)88- `--base-image`, `-b`: Base Docker image to use (overrides Dockerfile FROM)89- `--private`: Deploy the space as private (default: public)90 91### Examples92 93```bash94# Push to your personal namespace (defaults to username/env-name from openenv.yaml)95openenv push96 97# Push to a specific repository98openenv push --repo-id my-org/my-env99 100# Push with a custom base image101openenv push --base-image ghcr.io/meta-pytorch/openenv-base:latest102 103# Push as a private space104openenv push --private105 106# Combine options107openenv push --repo-id my-org/my-env --base-image custom-base:latest --private108```109 110After deployment, your space will be available at:111`https://huggingface.co/spaces/<repo-id>`112 113The deployed space includes:114- **Web Interface** at `/web` - Interactive UI for exploring the environment115- **API Documentation** at `/docs` - Full OpenAPI/Swagger interface116- **Health Check** at `/health` - Container health monitoring117- **WebSocket** at `/ws` - Persistent session endpoint for low-latency interactions118 119## Environment Details120 121### Action122**__ENV_CLASS_NAME__Action**: Contains a single field123- `message` (str) - The message to echo back124 125### Observation126**__ENV_CLASS_NAME__Observation**: Contains the echo response and metadata127- `echoed_message` (str) - The message echoed back128- `message_length` (int) - Length of the message129- `reward` (float) - Reward based on message length (length × 0.1)130- `done` (bool) - Always False for echo environment131- `metadata` (dict) - Additional info like step count132 133### Reward134The reward is calculated as: `message_length × 0.1`135- "Hi" → reward: 0.2136- "Hello, World!" → reward: 1.3137- Empty message → reward: 0.0138 139## Advanced Usage140 141### Connecting to an Existing Server142 143If you already have a __ENV_TITLE_NAME__ environment server running, you can connect directly:144 145```python146from __ENV_NAME__ import __ENV_CLASS_NAME__Env147 148# Connect to existing server149__ENV_NAME__env = __ENV_CLASS_NAME__Env(base_url="<ENV_HTTP_URL_HERE>")150 151# Use as normal152result = __ENV_NAME__env.reset()153result = __ENV_NAME__env.step(__ENV_CLASS_NAME__Action(message="Hello!"))154```155 156Note: When connecting to an existing server, `__ENV_NAME__env.close()` will NOT stop the server.157 158### Using the Context Manager159 160The client supports context manager usage for automatic connection management:161 162```python163from __ENV_NAME__ import __ENV_CLASS_NAME__Action, __ENV_CLASS_NAME__Env164 165# Connect with context manager (auto-connects and closes)166with __ENV_CLASS_NAME__Env(base_url="http://localhost:8000") as env:167    result = env.reset()168    print(f"Reset: {result.observation.echoed_message}")169    # Multiple steps with low latency170    for msg in ["Hello", "World", "!"]:171        result = env.step(__ENV_CLASS_NAME__Action(message=msg))172        print(f"Echoed: {result.observation.echoed_message}")173```174 175The client uses WebSocket connections for:176- **Lower latency**: No HTTP connection overhead per request177- **Persistent session**: Server maintains your environment state178- **Efficient for episodes**: Better for many sequential steps179 180### Concurrent WebSocket Sessions181 182The server supports multiple concurrent WebSocket connections. To enable this,183modify `server/app.py` to use factory mode:184 185```python186# In server/app.py - use factory mode for concurrent sessions187app = create_app(188    __ENV_CLASS_NAME__Environment,  # Pass class, not instance189    __ENV_CLASS_NAME__Action,190    __ENV_CLASS_NAME__Observation,191    max_concurrent_envs=4,  # Allow 4 concurrent sessions192)193```194 195Then multiple clients can connect simultaneously:196 197```python198from __ENV_NAME__ import __ENV_CLASS_NAME__Action, __ENV_CLASS_NAME__Env199from concurrent.futures import ThreadPoolExecutor200 201def run_episode(client_id: int):202    with __ENV_CLASS_NAME__Env(base_url="http://localhost:8000") as env:203        result = env.reset()204        for i in range(10):205            result = env.step(__ENV_CLASS_NAME__Action(message=f"Client {client_id}, step {i}"))206        return client_id, result.observation.message_length207 208# Run 4 episodes concurrently209with ThreadPoolExecutor(max_workers=4) as executor:210    results = list(executor.map(run_episode, range(4)))211```212 213## Development & Testing214 215### Direct Environment Testing216 217Test the environment logic directly without starting the HTTP server:218 219```bash220# From the server directory221python3 server/__ENV_NAME___environment.py222```223 224This verifies that:225- Environment resets correctly226- Step executes actions properly227- State tracking works228- Rewards are calculated correctly229 230### Running Locally231 232Run the server locally for development:233 234```bash235uvicorn server.app:app --reload236```237 238## Project Structure239 240```241__ENV_NAME__/242├── .dockerignore         # Docker build exclusions243├── __init__.py            # Module exports244├── README.md              # This file245├── openenv.yaml           # OpenEnv manifest246├── pyproject.toml         # Project metadata and dependencies247├── uv.lock                # Locked dependencies (generated)248├── client.py              # __ENV_CLASS_NAME__Env client249├── models.py              # Action and Observation models250└── server/251    ├── __init__.py        # Server module exports252    ├── __ENV_NAME___environment.py  # Core environment logic253    ├── app.py             # FastAPI application (HTTP + WebSocket endpoints)254    └── Dockerfile         # Container image definition255```256