burtenshaw HF Staff commited on
Commit
014828d
·
verified ·
1 Parent(s): 26a881d

Upload folder using huggingface_hub

Browse files
Files changed (10) hide show
  1. Dockerfile +81 -0
  2. README.md +194 -5
  3. __init__.py +13 -0
  4. client.py +100 -0
  5. models.py +31 -0
  6. openenv.yaml +7 -0
  7. pyproject.toml +51 -0
  8. server/__init__.py +12 -0
  9. server/app.py +72 -0
  10. server/test_123_environment.py +95 -0
Dockerfile ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # Multi-stage build using openenv-base
8
+ # This Dockerfile is flexible and works for both:
9
+ # - In-repo environments (with local src/core)
10
+ # - Standalone environments (with openenv-core from pip)
11
+ # The build script (openenv build) handles context detection and sets appropriate build args.
12
+
13
+ ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
14
+ FROM ${BASE_IMAGE} AS builder
15
+
16
+ WORKDIR /app
17
+
18
+ # Ensure git is available (required for installing dependencies from VCS)
19
+ RUN apt-get update && \
20
+ apt-get install -y --no-install-recommends git && \
21
+ rm -rf /var/lib/apt/lists/*
22
+
23
+ # Build argument to control whether we're building standalone or in-repo
24
+ ARG BUILD_MODE=in-repo
25
+ ARG ENV_NAME=test_123
26
+
27
+ # Copy environment code (always at root of build context)
28
+ COPY . /app/env
29
+
30
+ # For in-repo builds, openenv-core is already in the pyproject.toml dependencies
31
+ # For standalone builds, openenv-core will be installed from pip via pyproject.toml
32
+ WORKDIR /app/env
33
+
34
+ # Ensure uv is available (for local builds where base image lacks it)
35
+ RUN if ! command -v uv >/dev/null 2>&1; then \
36
+ curl -LsSf https://astral.sh/uv/install.sh | sh && \
37
+ mv /root/.local/bin/uv /usr/local/bin/uv && \
38
+ mv /root/.local/bin/uvx /usr/local/bin/uvx; \
39
+ fi
40
+
41
+ # Install dependencies using uv sync
42
+ # If uv.lock exists, use it; otherwise resolve on the fly
43
+ RUN --mount=type=cache,target=/root/.cache/uv \
44
+ if [ -f uv.lock ]; then \
45
+ uv sync --frozen --no-install-project --no-editable; \
46
+ else \
47
+ uv sync --no-install-project --no-editable; \
48
+ fi
49
+
50
+ RUN --mount=type=cache,target=/root/.cache/uv \
51
+ if [ -f uv.lock ]; then \
52
+ uv sync --frozen --no-editable; \
53
+ else \
54
+ uv sync --no-editable; \
55
+ fi
56
+
57
+ # Final runtime stage
58
+ FROM ${BASE_IMAGE}
59
+
60
+ WORKDIR /app
61
+
62
+ # Copy the virtual environment from builder
63
+ COPY --from=builder /app/env/.venv /app/.venv
64
+
65
+ # Copy the environment code
66
+ COPY --from=builder /app/env /app/env
67
+
68
+ # Set PATH to use the virtual environment
69
+ ENV PATH="/app/.venv/bin:$PATH"
70
+
71
+ # Set PYTHONPATH so imports work correctly
72
+ ENV PYTHONPATH="/app/env:$PYTHONPATH"
73
+
74
+ # Health check
75
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
76
+ CMD curl -f http://localhost:8000/health || exit 1
77
+
78
+ # Run the FastAPI server
79
+ # The module path is constructed to work with the /app/env structure
80
+ ENV ENABLE_WEB_INTERFACE=true
81
+ CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
README.md CHANGED
@@ -1,10 +1,199 @@
1
  ---
2
- title: Test Pr 123
3
- emoji: 🚀
4
- colorFrom: indigo
5
- colorTo: purple
6
  sdk: docker
7
  pinned: false
 
 
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Test 123 Environment Server
3
+ emoji: 🖱️
4
+ colorFrom: pink
5
+ colorTo: green
6
  sdk: docker
7
  pinned: false
8
+ app_port: 8000
9
+ base_path: /web
10
+ tags:
11
+ - openenv
12
  ---
13
 
14
+ # Test 123 Environment
15
+
16
+ A simple test environment that echoes back messages. Perfect for testing the env APIs as well as demonstrating environment usage patterns.
17
+
18
+ ## Quick Start
19
+
20
+ The simplest way to use the Test 123 environment is through the `Test123Env` class:
21
+
22
+ ```python
23
+ from test_123 import Test123Action, Test123Env
24
+
25
+ try:
26
+ # Create environment from Docker image
27
+ test_123env = Test123Env.from_docker_image("test_123-env:latest")
28
+
29
+ # Reset
30
+ result = test_123env.reset()
31
+ print(f"Reset: {result.observation.echoed_message}")
32
+
33
+ # Send multiple messages
34
+ messages = ["Hello, World!", "Testing echo", "Final message"]
35
+
36
+ for msg in messages:
37
+ result = test_123env.step(Test123Action(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
+
43
+ finally:
44
+ # Always clean up
45
+ test_123env.close()
46
+ ```
47
+
48
+ That's it! The `Test123Env.from_docker_image()` method handles:
49
+ - Starting the Docker container
50
+ - Waiting for the server to be ready
51
+ - Connecting to the environment
52
+ - Container cleanup when you call `close()`
53
+
54
+ ## Building the Docker Image
55
+
56
+ Before using the environment, you need to build the Docker image:
57
+
58
+ ```bash
59
+ # From project root
60
+ docker build -t test_123-env:latest -f server/Dockerfile .
61
+ ```
62
+
63
+ ## Deploying to Hugging Face Spaces
64
+
65
+ You can easily deploy your OpenEnv environment to Hugging Face Spaces using the `openenv push` command:
66
+
67
+ ```bash
68
+ # From the environment directory (where openenv.yaml is located)
69
+ openenv push
70
+
71
+ # Or specify options
72
+ openenv push --namespace my-org --private
73
+ ```
74
+
75
+ The `openenv push` command will:
76
+ 1. Validate that the directory is an OpenEnv environment (checks for `openenv.yaml`)
77
+ 2. Prepare a custom build for Hugging Face Docker space (enables web interface)
78
+ 3. Upload to Hugging Face (ensuring you're logged in)
79
+
80
+ ### Prerequisites
81
+
82
+ - Authenticate with Hugging Face: The command will prompt for login if not already authenticated
83
+
84
+ ### Options
85
+
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
+ ### Examples
92
+
93
+ ```bash
94
+ # Push to your personal namespace (defaults to username/env-name from openenv.yaml)
95
+ openenv push
96
+
97
+ # Push to a specific repository
98
+ openenv push --repo-id my-org/my-env
99
+
100
+ # Push with a custom base image
101
+ openenv push --base-image ghcr.io/meta-pytorch/openenv-base:latest
102
+
103
+ # Push as a private space
104
+ openenv push --private
105
+
106
+ # Combine options
107
+ openenv push --repo-id my-org/my-env --base-image custom-base:latest --private
108
+ ```
109
+
110
+ After deployment, your space will be available at:
111
+ `https://huggingface.co/spaces/<repo-id>`
112
+
113
+ The deployed space includes:
114
+ - **Web Interface** at `/web` - Interactive UI for exploring the environment
115
+ - **API Documentation** at `/docs` - Full OpenAPI/Swagger interface
116
+ - **Health Check** at `/health` - Container health monitoring
117
+
118
+ ## Environment Details
119
+
120
+ ### Action
121
+ **Test123Action**: Contains a single field
122
+ - `message` (str) - The message to echo back
123
+
124
+ ### Observation
125
+ **Test123Observation**: Contains the echo response and metadata
126
+ - `echoed_message` (str) - The message echoed back
127
+ - `message_length` (int) - Length of the message
128
+ - `reward` (float) - Reward based on message length (length × 0.1)
129
+ - `done` (bool) - Always False for echo environment
130
+ - `metadata` (dict) - Additional info like step count
131
+
132
+ ### Reward
133
+ The reward is calculated as: `message_length × 0.1`
134
+ - "Hi" → reward: 0.2
135
+ - "Hello, World!" → reward: 1.3
136
+ - Empty message → reward: 0.0
137
+
138
+ ## Advanced Usage
139
+
140
+ ### Connecting to an Existing Server
141
+
142
+ If you already have a Test 123 environment server running, you can connect directly:
143
+
144
+ ```python
145
+ from test_123 import Test123Env
146
+
147
+ # Connect to existing server
148
+ test_123env = Test123Env(base_url="<ENV_HTTP_URL_HERE>")
149
+
150
+ # Use as normal
151
+ result = test_123env.reset()
152
+ result = test_123env.step(Test123Action(message="Hello!"))
153
+ ```
154
+
155
+ Note: When connecting to an existing server, `test_123env.close()` will NOT stop the server.
156
+
157
+ ## Development & Testing
158
+
159
+ ### Direct Environment Testing
160
+
161
+ Test the environment logic directly without starting the HTTP server:
162
+
163
+ ```bash
164
+ # From the server directory
165
+ python3 server/test_123_environment.py
166
+ ```
167
+
168
+ This verifies that:
169
+ - Environment resets correctly
170
+ - Step executes actions properly
171
+ - State tracking works
172
+ - Rewards are calculated correctly
173
+
174
+ ### Running Locally
175
+
176
+ Run the server locally for development:
177
+
178
+ ```bash
179
+ uvicorn server.app:app --reload
180
+ ```
181
+
182
+ ## Project Structure
183
+
184
+ ```
185
+ test_123/
186
+ ├── .dockerignore # Docker build exclusions
187
+ ├── __init__.py # Module exports
188
+ ├── README.md # This file
189
+ ├── openenv.yaml # OpenEnv manifest
190
+ ├── pyproject.toml # Project metadata and dependencies
191
+ ├── uv.lock # Locked dependencies (generated)
192
+ ├── client.py # Test123Env client implementation
193
+ ├── models.py # Action and Observation models
194
+ └── server/
195
+ ├── __init__.py # Server module exports
196
+ ├── test_123_environment.py # Core environment logic
197
+ ├── app.py # FastAPI application
198
+ └── Dockerfile # Container image definition
199
+ ```
__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Test 123 Environment - A simple test environment for HTTP server."""
8
+
9
+ from .client import Test123Env
10
+ from .models import Test123Action, Test123Observation
11
+
12
+ __all__ = ["Test123Action", "Test123Observation", "Test123Env"]
13
+
client.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Test 123 Environment HTTP Client.
9
+
10
+ This module provides the client for connecting to a Test 123 Environment server
11
+ over HTTP.
12
+ """
13
+
14
+ from typing import Any, Dict
15
+
16
+ from openenv_core.client_types import StepResult
17
+ from openenv_core.env_server.types import State
18
+ from openenv_core.http_env_client import HTTPEnvClient
19
+
20
+ from .models import Test123Action, Test123Observation
21
+
22
+
23
+ class Test123Env(HTTPEnvClient[Test123Action, Test123Observation]):
24
+ """
25
+ HTTP client for the Test 123 Environment.
26
+
27
+ This client connects to a Test123Environment HTTP server and provides
28
+ methods to interact with it: reset(), step(), and state access.
29
+
30
+ Example:
31
+ >>> # Connect to a running server
32
+ >>> client = Test123Env(base_url="http://localhost:8000")
33
+ >>> result = client.reset()
34
+ >>> print(result.observation.echoed_message)
35
+ >>>
36
+ >>> # Send a message
37
+ >>> result = client.step(Test123Action(message="Hello!"))
38
+ >>> print(result.observation.echoed_message)
39
+ >>> print(result.reward)
40
+
41
+ Example with Docker:
42
+ >>> # Automatically start container and connect
43
+ >>> client = Test123Env.from_docker_image("test_123-env:latest")
44
+ >>> result = client.reset()
45
+ >>> result = client.step(Test123Action(message="Test"))
46
+ """
47
+
48
+ def _step_payload(self, action: Test123Action) -> Dict:
49
+ """
50
+ Convert Test123Action to JSON payload for step request.
51
+
52
+ Args:
53
+ action: Test123Action instance
54
+
55
+ Returns:
56
+ Dictionary representation suitable for JSON encoding
57
+ """
58
+ return {
59
+ "message": action.message,
60
+ }
61
+
62
+ def _parse_result(self, payload: Dict) -> StepResult[Test123Observation]:
63
+ """
64
+ Parse server response into StepResult[Test123Observation].
65
+
66
+ Args:
67
+ payload: JSON response from server
68
+
69
+ Returns:
70
+ StepResult with Test123Observation
71
+ """
72
+ obs_data = payload.get("observation", {})
73
+ observation = Test123Observation(
74
+ echoed_message=obs_data.get("echoed_message", ""),
75
+ message_length=obs_data.get("message_length", 0),
76
+ done=payload.get("done", False),
77
+ reward=payload.get("reward"),
78
+ metadata=obs_data.get("metadata", {}),
79
+ )
80
+
81
+ return StepResult(
82
+ observation=observation,
83
+ reward=payload.get("reward"),
84
+ done=payload.get("done", False),
85
+ )
86
+
87
+ def _parse_state(self, payload: Dict) -> State:
88
+ """
89
+ Parse server response into State object.
90
+
91
+ Args:
92
+ payload: JSON response from /state endpoint
93
+
94
+ Returns:
95
+ State object with episode_id and step_count
96
+ """
97
+ return State(
98
+ episode_id=payload.get("episode_id"),
99
+ step_count=payload.get("step_count", 0),
100
+ )
models.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Data models for the Test 123 Environment.
9
+
10
+ The test_123 environment is a simple test environment that echoes back messages.
11
+ """
12
+
13
+ from dataclasses import dataclass
14
+
15
+ from openenv_core.env_server.types import Action, Observation
16
+
17
+
18
+ @dataclass(kw_only=True)
19
+ class Test123Action(Action):
20
+ """Action for the Test 123 environment - just a message to echo."""
21
+
22
+ message: str
23
+
24
+
25
+ @dataclass(kw_only=True)
26
+ class Test123Observation(Observation):
27
+ """Observation from the Test 123 environment - the echoed message."""
28
+
29
+ echoed_message: str
30
+ message_length: int = 0
31
+
openenv.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ spec_version: 1
2
+ name: test_123
3
+ type: space
4
+ runtime: fastapi
5
+ app: server.app:app
6
+ port: 8000
7
+
pyproject.toml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ [build-system]
8
+ requires = ["setuptools>=45", "wheel"]
9
+ build-backend = "setuptools.build_meta"
10
+
11
+ [project]
12
+ name = "openenv-test_123"
13
+ version = "0.1.0"
14
+ description = "Test 123 environment for OpenEnv"
15
+ requires-python = ">=3.10"
16
+ dependencies = [
17
+ # Core OpenEnv dependencies (required for server functionality)
18
+ # "openenv-core @ git+https://github.com/meta-pytorch/OpenEnv.git@main#subdirectory=src/core",
19
+ "openenv-core>=0.1.0",
20
+ "fastapi>=0.115.0",
21
+ "pydantic>=2.0.0",
22
+ "uvicorn>=0.24.0",
23
+ "requests>=2.31.0",
24
+ # Environment-specific dependencies
25
+ # Add all dependencies needed for your environment here
26
+ # Examples:
27
+ # "numpy>=1.19.0",
28
+ # "torch>=2.0.0",
29
+ # "gymnasium>=0.29.0",
30
+ # "openspiel>=1.0.0",
31
+ # "smolagents>=1.22.0,<2",
32
+ ]
33
+
34
+ [project.optional-dependencies]
35
+ dev = [
36
+ "pytest>=8.0.0",
37
+ "pytest-cov>=4.0.0",
38
+ ]
39
+
40
+ [project.scripts]
41
+ # Server entry point - enables running via: uv run --project . server
42
+ # or: python -m test_123.server.app
43
+ server = "test_123.server.app:main"
44
+
45
+ [tool.setuptools]
46
+ include-package-data = true
47
+ packages = ["test_123", "test_123.server"]
48
+ package-dir = { "test_123" = ".", "test_123.server" = "server" }
49
+
50
+ [tool.setuptools.packages.find]
51
+ include = ["test_123*"]
server/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Test 123 environment server components."""
8
+
9
+ from .test_123_environment import Test123Environment
10
+
11
+ __all__ = ["Test123Environment"]
12
+
server/app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ FastAPI application for the Test 123 Environment.
9
+
10
+ This module creates an HTTP server that exposes the Test123Environment
11
+ over HTTP endpoints, making it compatible with HTTPEnvClient.
12
+
13
+ Usage:
14
+ # Development (with auto-reload):
15
+ uvicorn server.app:app --reload --host 0.0.0.0 --port 8000
16
+
17
+ # Production:
18
+ uvicorn server.app:app --host 0.0.0.0 --port 8000 --workers 4
19
+
20
+ # Or run directly:
21
+ python -m server.app
22
+ """
23
+
24
+ try:
25
+ from openenv_core.env_server.http_server import create_app
26
+ except Exception as e: # pragma: no cover
27
+ raise ImportError("openenv_core is required for the web interface. Install dependencies with '\n uv sync\n'") from e
28
+
29
+ from .test_123_environment import Test123Environment
30
+ from models import Test123Action, Test123Observation
31
+
32
+ # Create the environment instance
33
+ env = Test123Environment()
34
+
35
+ # Create the app with web interface and README integration
36
+ app = create_app(
37
+ env,
38
+ Test123Action,
39
+ Test123Observation,
40
+ env_name="test_123",
41
+ )
42
+
43
+
44
+ def main(host: str = "0.0.0.0", port: int = 8000):
45
+ """
46
+ Entry point for direct execution via uv run or python -m.
47
+
48
+ This function enables running the server without Docker:
49
+ uv run --project . server
50
+ uv run --project . server --port 8001
51
+ python -m test_123.server.app
52
+
53
+ Args:
54
+ host: Host address to bind to (default: "0.0.0.0")
55
+ port: Port number to listen on (default: 8000)
56
+
57
+ For production deployments, consider using uvicorn directly with
58
+ multiple workers:
59
+ uvicorn test_123.server.app:app --workers 4
60
+ """
61
+ import uvicorn
62
+
63
+ uvicorn.run(app, host=host, port=port)
64
+
65
+
66
+ if __name__ == "__main__":
67
+ import argparse
68
+
69
+ parser = argparse.ArgumentParser()
70
+ parser.add_argument("--port", type=int, default=8000)
71
+ args = parser.parse_args()
72
+ main(port=args.port)
server/test_123_environment.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Test 123 Environment Implementation.
9
+
10
+ A simple test environment that echoes back messages sent to it.
11
+ Perfect for testing HTTP server infrastructure.
12
+ """
13
+
14
+ from uuid import uuid4
15
+
16
+ from openenv_core.env_server.interfaces import Environment
17
+ from openenv_core.env_server.types import State
18
+
19
+ from models import Test123Action, Test123Observation
20
+
21
+
22
+ class Test123Environment(Environment):
23
+ """
24
+ A simple echo environment that echoes back messages.
25
+
26
+ This environment is designed for testing the HTTP server infrastructure.
27
+ It maintains minimal state and simply echoes back whatever message it receives.
28
+
29
+ Example:
30
+ >>> env = Test123Environment()
31
+ >>> obs = env.reset()
32
+ >>> print(obs.echoed_message) # "Test 123 environment ready!"
33
+ >>>
34
+ >>> obs = env.step(Test123Action(message="Hello"))
35
+ >>> print(obs.echoed_message) # "Hello"
36
+ >>> print(obs.message_length) # 5
37
+ """
38
+
39
+ def __init__(self):
40
+ """Initialize the test_123 environment."""
41
+ self._state = State(episode_id=str(uuid4()), step_count=0)
42
+ self._reset_count = 0
43
+
44
+ def reset(self) -> Test123Observation:
45
+ """
46
+ Reset the environment.
47
+
48
+ Returns:
49
+ Test123Observation with a ready message
50
+ """
51
+ self._state = State(episode_id=str(uuid4()), step_count=0)
52
+ self._reset_count += 1
53
+
54
+ return Test123Observation(
55
+ echoed_message="Test 123 environment ready!",
56
+ message_length=0,
57
+ done=False,
58
+ reward=0.0,
59
+ )
60
+
61
+ def step(self, action: Test123Action) -> Test123Observation: # type: ignore[override]
62
+ """
63
+ Execute a step in the environment by echoing the message.
64
+
65
+ Args:
66
+ action: Test123Action containing the message to echo
67
+
68
+ Returns:
69
+ Test123Observation with the echoed message and its length
70
+ """
71
+ self._state.step_count += 1
72
+
73
+ message = action.message
74
+ length = len(message)
75
+
76
+ # Simple reward: longer messages get higher rewards
77
+ reward = length * 0.1
78
+
79
+ return Test123Observation(
80
+ echoed_message=message,
81
+ message_length=length,
82
+ done=False,
83
+ reward=reward,
84
+ metadata={"original_message": message, "step": self._state.step_count},
85
+ )
86
+
87
+ @property
88
+ def state(self) -> State:
89
+ """
90
+ Get the current environment state.
91
+
92
+ Returns:
93
+ Current State with episode_id and step_count
94
+ """
95
+ return self._state