Spaces:
Sleeping
Sleeping
databoysu commited on
Commit ·
fdc5ba1
0
Parent(s):
initial
Browse filesFiles changed (13)
- .gitignoreAdded+3
- my_env/README.mdAdded+255
- my_env/__init__.pyAdded+16
- my_env/client.pyAdded+99
- my_env/models.pyAdded+27
- my_env/openenv.yamlAdded+7
- my_env/pyproject.tomlAdded+45
- my_env/server/DockerfileAdded+80
- my_env/server/__init__.pyAdded+11
- my_env/server/app.pyAdded+84
- my_env/server/my_env_environment.pyAdded+104
- my_env/server/requirements.txtAdded+6
- my_env/uv.lockAdded
123.venv.agents.env123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255---title: My Env Environment Serveremoji: 🖥️colorFrom: indigocolorTo: indigosdk: dockerpinned: falseapp_port: 8000base_path: /webtags: - openenv---
# My Env Environment
A simple test environment that echoes back messages. Perfect for testing the env APIs as well as demonstrating environment usage patterns.
## Quick Start
The simplest way to use the My Env environment is through the `MyEnv` class:
```pythonfrom my_env import MyAction, MyEnv
try: # Create environment from Docker image my_envenv = MyEnv.from_docker_image("my_env-env:latest")
# Reset result = my_envenv.reset() print(f"Reset: {result.observation.echoed_message}")
# Send multiple messages messages = ["Hello, World!", "Testing echo", "Final message"]
for msg in messages: result = my_envenv.step(MyAction(message=msg)) print(f"Sent: '{msg}'") print(f" → Echoed: '{result.observation.echoed_message}'") print(f" → Length: {result.observation.message_length}") print(f" → Reward: {result.reward}")
finally: # Always clean up my_envenv.close()```
That's it! The `MyEnv.from_docker_image()` method handles:- Starting the Docker container- Waiting for the server to be ready- Connecting to the environment- Container cleanup when you call `close()`
## Building the Docker Image
Before using the environment, you need to build the Docker image:
```bash# From project rootdocker build -t my_env-env:latest -f server/Dockerfile .```
## Deploying to Hugging Face Spaces
You can easily deploy your OpenEnv environment to Hugging Face Spaces using the `openenv push` command:
```bash# From the environment directory (where openenv.yaml is located)openenv push
# Or specify optionsopenenv push --namespace my-org --private```
The `openenv push` command will:1. Validate that the directory is an OpenEnv environment (checks for `openenv.yaml`)2. Prepare a custom build for Hugging Face Docker space (enables web interface)3. Upload to Hugging Face (ensuring you're logged in)
### Prerequisites
- Authenticate with Hugging Face: The command will prompt for login if not already authenticated
### Options
- `--directory`, `-d`: Directory containing the OpenEnv environment (defaults to current directory)- `--repo-id`, `-r`: Repository ID in format 'username/repo-name' (defaults to 'username/env-name' from openenv.yaml)- `--base-image`, `-b`: Base Docker image to use (overrides Dockerfile FROM)- `--private`: Deploy the space as private (default: public)
### Examples
```bash# Push to your personal namespace (defaults to username/env-name from openenv.yaml)openenv push
# Push to a specific repositoryopenenv push --repo-id my-org/my-env
# Push with a custom base imageopenenv push --base-image ghcr.io/meta-pytorch/openenv-base:latest
# Push as a private spaceopenenv push --private
# Combine optionsopenenv push --repo-id my-org/my-env --base-image custom-base:latest --private```
After deployment, your space will be available at:`https://huggingface.co/spaces/<repo-id>`
The deployed space includes:- **Web Interface** at `/web` - Interactive UI for exploring the environment- **API Documentation** at `/docs` - Full OpenAPI/Swagger interface- **Health Check** at `/health` - Container health monitoring- **WebSocket** at `/ws` - Persistent session endpoint for low-latency interactions
## Environment Details
### Action**MyAction**: Contains a single field- `message` (str) - The message to echo back
### Observation**MyObservation**: Contains the echo response and metadata- `echoed_message` (str) - The message echoed back- `message_length` (int) - Length of the message- `reward` (float) - Reward based on message length (length × 0.1)- `done` (bool) - Always False for echo environment- `metadata` (dict) - Additional info like step count
### RewardThe reward is calculated as: `message_length × 0.1`- "Hi" → reward: 0.2- "Hello, World!" → reward: 1.3- Empty message → reward: 0.0
## Advanced Usage
### Connecting to an Existing Server
If you already have a My Env environment server running, you can connect directly:
```pythonfrom my_env import MyEnv
# Connect to existing servermy_envenv = MyEnv(base_url="<ENV_HTTP_URL_HERE>")
# Use as normalresult = my_envenv.reset()result = my_envenv.step(MyAction(message="Hello!"))```
Note: When connecting to an existing server, `my_envenv.close()` will NOT stop the server.
### Using the Context Manager
The client supports context manager usage for automatic connection management:
```pythonfrom my_env import MyAction, MyEnv
# Connect with context manager (auto-connects and closes)with MyEnv(base_url="http://localhost:8000") as env: result = env.reset() print(f"Reset: {result.observation.echoed_message}") # Multiple steps with low latency for msg in ["Hello", "World", "!"]: result = env.step(MyAction(message=msg)) print(f"Echoed: {result.observation.echoed_message}")```
The client uses WebSocket connections for:- **Lower latency**: No HTTP connection overhead per request- **Persistent session**: Server maintains your environment state- **Efficient for episodes**: Better for many sequential steps
### Concurrent WebSocket Sessions
The server supports multiple concurrent WebSocket connections. To enable this,modify `server/app.py` to use factory mode:
```python# In server/app.py - use factory mode for concurrent sessionsapp = create_app( MyEnvironment, # Pass class, not instance MyAction, MyObservation, max_concurrent_envs=4, # Allow 4 concurrent sessions)```
Then multiple clients can connect simultaneously:
```pythonfrom my_env import MyAction, MyEnvfrom concurrent.futures import ThreadPoolExecutor
def run_episode(client_id: int): with MyEnv(base_url="http://localhost:8000") as env: result = env.reset() for i in range(10): result = env.step(MyAction(message=f"Client {client_id}, step {i}")) return client_id, result.observation.message_length
# Run 4 episodes concurrentlywith ThreadPoolExecutor(max_workers=4) as executor: results = list(executor.map(run_episode, range(4)))```
## Development & Testing
### Direct Environment Testing
Test the environment logic directly without starting the HTTP server:
```bash# From the server directorypython3 server/my_env_environment.py```
This verifies that:- Environment resets correctly- Step executes actions properly- State tracking works- Rewards are calculated correctly
### Running Locally
Run the server locally for development:
```bashuvicorn server.app:app --reload```
## Project Structure
```my_env/├── .dockerignore # Docker build exclusions├── __init__.py # Module exports├── README.md # This file├── openenv.yaml # OpenEnv manifest├── pyproject.toml # Project metadata and dependencies├── uv.lock # Locked dependencies (generated)├── client.py # MyEnv client├── models.py # Action and Observation models└── server/ ├── __init__.py # Server module exports ├── my_env_environment.py # Core environment logic ├── app.py # FastAPI application (HTTP + WebSocket endpoints) └── Dockerfile # Container image definition```12345678910111213141516# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""My Env Environment."""
from .client import MyEnvfrom .models import MyAction, MyObservation
__all__ = [ "MyAction", "MyObservation", "MyEnv",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""My Env Environment Client."""
from typing import Dict
from openenv.core import EnvClientfrom openenv.core.client_types import StepResultfrom openenv.core.env_server.types import State
from .models import MyAction, MyObservation
class MyEnv( EnvClient[MyAction, MyObservation, State]): """ Client for the My Env Environment.
This client maintains a persistent WebSocket connection to the environment server, enabling efficient multi-step interactions with lower latency. Each client instance has its own dedicated environment session on the server.
Example: >>> # Connect to a running server >>> with MyEnv(base_url="http://localhost:8000") as client: ... result = client.reset() ... print(result.observation.echoed_message) ... ... result = client.step(MyAction(message="Hello!")) ... print(result.observation.echoed_message)
Example with Docker: >>> # Automatically start container and connect >>> client = MyEnv.from_docker_image("my_env-env:latest") >>> try: ... result = client.reset() ... result = client.step(MyAction(message="Test")) ... finally: ... client.close() """
def _step_payload(self, action: MyAction) -> Dict: """ Convert MyAction to JSON payload for step message.
Args: action: MyAction instance
Returns: Dictionary representation suitable for JSON encoding """ return { "message": action.message, }
def _parse_result(self, payload: Dict) -> StepResult[MyObservation]: """ Parse server response into StepResult[MyObservation].
Args: payload: JSON response data from server
Returns: StepResult with MyObservation """ obs_data = payload.get("observation", {}) observation = MyObservation( echoed_message=obs_data.get("echoed_message", ""), message_length=obs_data.get("message_length", 0), done=payload.get("done", False), reward=payload.get("reward"), metadata=obs_data.get("metadata", {}), )
return StepResult( observation=observation, reward=payload.get("reward"), done=payload.get("done", False), )
def _parse_state(self, payload: Dict) -> State: """ Parse server response into State object.
Args: payload: JSON response from state request
Returns: State object with episode_id and step_count """ return State( episode_id=payload.get("episode_id"), step_count=payload.get("step_count", 0), )123456789101112131415161718192021222324252627# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""Data models for the My Env Environment.
The my_env environment is a simple test environment that echoes back messages."""
from openenv.core.env_server.types import Action, Observationfrom pydantic import Field
class MyAction(Action): """Action for the My Env environment - just a message to echo."""
message: str = Field(..., description="Message to echo back")
class MyObservation(Observation): """Observation from the My Env environment - the echoed message."""
echoed_message: str = Field(default="", description="The echoed message") message_length: int = Field(default=0, description="Length of the echoed message")1234567spec_version: 1name: my_envtype: spaceruntime: fastapiapp: server.app:appport: 8000
123456789101112131415161718192021222324252627282930313233343536373839404142434445# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
[build-system]requires = ["setuptools>=45", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "openenv-my_env"version = "0.1.0"description = "My Env environment for OpenEnv"requires-python = ">=3.10"dependencies = [ # Core OpenEnv runtime (provides FastAPI server + HTTP client types) # install from github # "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git", "openenv-core[core]>=0.2.2", # Environment-specific dependencies # Add all dependencies needed for your environment here # Examples: # "numpy>=1.19.0", # "torch>=2.0.0", # "gymnasium>=0.29.0", # "openspiel>=1.0.0", # "smolagents>=1.22.0,<2",]
[project.optional-dependencies]dev = [ "pytest>=8.0.0", "pytest-cov>=4.0.0",]
[project.scripts]# Server entry point - enables running via: uv run --project . server# or: python -m my_env.server.appserver = "my_env.server.app:main"
[tool.setuptools]include-package-data = truepackages = ["my_env", "my_env.server"]package-dir = { "my_env" = ".", "my_env.server" = "server" }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
# Multi-stage build using openenv-base# This Dockerfile is flexible and works for both:# - In-repo environments (with local OpenEnv sources)# - Standalone environments (with openenv from PyPI/Git)# The build script (openenv build) handles context detection and sets appropriate build args.
ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latestFROM ${BASE_IMAGE} AS builder
WORKDIR /app
# Ensure git is available (required for installing dependencies from VCS)RUN apt-get update && \ apt-get install -y --no-install-recommends git && \ rm -rf /var/lib/apt/lists/*
# Build argument to control whether we're building standalone or in-repoARG BUILD_MODE=in-repoARG ENV_NAME=my_env
# Copy environment code (always at root of build context)COPY . /app/env
# For in-repo builds, openenv is already vendored in the build context# For standalone builds, openenv will be installed via pyproject.tomlWORKDIR /app/env
# Ensure uv is available (for local builds where base image lacks it)RUN if ! command -v uv >/dev/null 2>&1; then \ curl -LsSf https://astral.sh/uv/install.sh | sh && \ mv /root/.local/bin/uv /usr/local/bin/uv && \ mv /root/.local/bin/uvx /usr/local/bin/uvx; \ fi # Install dependencies using uv sync# If uv.lock exists, use it; otherwise resolve on the flyRUN --mount=type=cache,target=/root/.cache/uv \ if [ -f uv.lock ]; then \ uv sync --frozen --no-install-project --no-editable; \ else \ uv sync --no-install-project --no-editable; \ fi
RUN --mount=type=cache,target=/root/.cache/uv \ if [ -f uv.lock ]; then \ uv sync --frozen --no-editable; \ else \ uv sync --no-editable; \ fi
# Final runtime stageFROM ${BASE_IMAGE}
WORKDIR /app
# Copy the virtual environment from builderCOPY --from=builder /app/env/.venv /app/.venv
# Copy the environment codeCOPY --from=builder /app/env /app/env
# Set PATH to use the virtual environmentENV PATH="/app/.venv/bin:$PATH"
# Set PYTHONPATH so imports work correctlyENV PYTHONPATH="/app/env:$PYTHONPATH"
# Health checkHEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:8000/health || exit 1
# Run the FastAPI server# The module path is constructed to work with the /app/env structureCMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]1234567891011# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""My Env environment server components."""
from .my_env_environment import MyEnvironment
__all__ = ["MyEnvironment"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""FastAPI application for the My Env Environment.
This module creates an HTTP server that exposes the MyEnvironmentover HTTP and WebSocket endpoints, compatible with EnvClient.
Endpoints: - POST /reset: Reset the environment - POST /step: Execute an action - GET /state: Get current environment state - GET /schema: Get action/observation schemas - WS /ws: WebSocket endpoint for persistent sessions
Usage: # Development (with auto-reload): uvicorn server.app:app --reload --host 0.0.0.0 --port 8000
# Production: uvicorn server.app:app --host 0.0.0.0 --port 8000 --workers 4
# Or run directly: python -m server.app"""
try: from openenv.core.env_server.http_server import create_appexcept Exception as e: # pragma: no cover raise ImportError( "openenv is required for the web interface. Install dependencies with '\n uv sync\n'" ) from e
try: from ..models import MyAction, MyObservation from .my_env_environment import MyEnvironmentexcept ModuleNotFoundError: from models import MyAction, MyObservation from server.my_env_environment import MyEnvironment
# Create the app with web interface and README integrationapp = create_app( MyEnvironment, MyAction, MyObservation, env_name="my_env", max_concurrent_envs=1, # increase this number to allow more concurrent WebSocket sessions)
def main(host: str = "0.0.0.0", port: int = 8000): """ Entry point for direct execution via uv run or python -m.
This function enables running the server without Docker: uv run --project . server uv run --project . server --port 8001 python -m my_env.server.app
Args: host: Host address to bind to (default: "0.0.0.0") port: Port number to listen on (default: 8000)
For production deployments, consider using uvicorn directly with multiple workers: uvicorn my_env.server.app:app --workers 4 """ import uvicorn
uvicorn.run(app, host=host, port=port)
if __name__ == "__main__": import argparse
parser = argparse.ArgumentParser() parser.add_argument("--port", type=int, default=8000) args = parser.parse_args() main(port=args.port)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree.
"""My Env Environment Implementation.
A simple test environment that echoes back messages sent to it.Perfect for testing HTTP server infrastructure."""
from uuid import uuid4
from openenv.core.env_server.interfaces import Environmentfrom openenv.core.env_server.types import State
try: from ..models import MyAction, MyObservationexcept ImportError: from models import MyAction, MyObservation
class MyEnvironment(Environment): """ A simple echo environment that echoes back messages.
This environment is designed for testing the HTTP server infrastructure. It maintains minimal state and simply echoes back whatever message it receives.
Example: >>> env = MyEnvironment() >>> obs = env.reset() >>> print(obs.echoed_message) # "My Env environment ready!" >>> >>> obs = env.step(MyAction(message="Hello")) >>> print(obs.echoed_message) # "Hello" >>> print(obs.message_length) # 5 """
# Enable concurrent WebSocket sessions. # Set to True if your environment isolates state between instances. # When True, multiple WebSocket clients can connect simultaneously, each # getting their own environment instance (when using factory mode in app.py). SUPPORTS_CONCURRENT_SESSIONS: bool = True
def __init__(self): """Initialize the my_env environment.""" self._state = State(episode_id=str(uuid4()), step_count=0) self._reset_count = 0
def reset(self) -> MyObservation: """ Reset the environment.
Returns: MyObservation with a ready message """ self._state = State(episode_id=str(uuid4()), step_count=0) self._reset_count += 1
return MyObservation( echoed_message="My Env environment ready!", message_length=0, done=False, reward=0.0, )
def step(self, action: MyAction) -> MyObservation: # type: ignore[override] """ Execute a step in the environment by echoing the message.
Args: action: MyAction containing the message to echo
Returns: MyObservation with the echoed message and its length """ self._state.step_count += 1
message = action.message length = len(message)
# Simple reward: longer messages get higher rewards reward = length * 0.1
return MyObservation( echoed_message=message, message_length=length, done=False, reward=reward, metadata={"original_message": message, "step": self._state.step_count}, )
@property def state(self) -> State: """ Get the current environment state.
Returns: Current State with episode_id and step_count """ return self._state123456openenv[core]>=0.2.0fastapi>=0.115.0uvicorn>=0.24.0
.gitignoreAdded+3
my_env/README.mdAdded+255
my_env/__init__.pyAdded+16
my_env/client.pyAdded+99
my_env/models.pyAdded+27
my_env/openenv.yamlAdded+7
my_env/pyproject.tomlAdded+45
my_env/server/DockerfileAdded+80
my_env/server/__init__.pyAdded+11
my_env/server/app.pyAdded+84
my_env/server/my_env_environment.pyAdded+104
my_env/server/requirements.txtAdded+6
my_env/uv.lockAdded