jonyeazel commited on
Commit
72c45e7
·
verified ·
1 Parent(s): 8131e9e

Upload folder using huggingface_hub

Browse files
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 OpenEnv sources)
10
+ # - Standalone environments (with openenv from PyPI/Git)
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=sequence_env
26
+
27
+ # Copy environment code (always at root of build context)
28
+ COPY . /app/env
29
+
30
+ # For in-repo builds, openenv is already vendored in the build context
31
+ # For standalone builds, openenv will be installed 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,255 @@
1
  ---
2
- title: Cognitive Primitives Sequence
3
- emoji: 🦀
4
- colorFrom: gray
5
- colorTo: yellow
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: Sequence Env Environment Server
3
+ emoji: 🎾
4
+ colorFrom: yellow
5
+ colorTo: red
6
  sdk: docker
7
  pinned: false
8
+ app_port: 8000
9
+ base_path: /web
10
+ tags:
11
+ - openenv
12
  ---
13
 
14
+ # Sequence Env 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 Sequence Env environment is through the `SequenceEnv` class:
21
+
22
+ ```python
23
+ from sequence_env import SequenceAction, SequenceEnv
24
+
25
+ try:
26
+ # Create environment from Docker image
27
+ sequence_envenv = SequenceEnv.from_docker_image("sequence_env-env:latest")
28
+
29
+ # Reset
30
+ result = sequence_envenv.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 = sequence_envenv.step(SequenceAction(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
+ sequence_envenv.close()
46
+ ```
47
+
48
+ That's it! The `SequenceEnv.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 sequence_env-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
+ - **WebSocket** at `/ws` - Persistent session endpoint for low-latency interactions
118
+
119
+ ## Environment Details
120
+
121
+ ### Action
122
+ **SequenceAction**: Contains a single field
123
+ - `message` (str) - The message to echo back
124
+
125
+ ### Observation
126
+ **SequenceObservation**: Contains the echo response and metadata
127
+ - `echoed_message` (str) - The message echoed back
128
+ - `message_length` (int) - Length of the message
129
+ - `reward` (float) - Reward based on message length (length × 0.1)
130
+ - `done` (bool) - Always False for echo environment
131
+ - `metadata` (dict) - Additional info like step count
132
+
133
+ ### Reward
134
+ The reward is calculated as: `message_length × 0.1`
135
+ - "Hi" → reward: 0.2
136
+ - "Hello, World!" → reward: 1.3
137
+ - Empty message → reward: 0.0
138
+
139
+ ## Advanced Usage
140
+
141
+ ### Connecting to an Existing Server
142
+
143
+ If you already have a Sequence Env environment server running, you can connect directly:
144
+
145
+ ```python
146
+ from sequence_env import SequenceEnv
147
+
148
+ # Connect to existing server
149
+ sequence_envenv = SequenceEnv(base_url="<ENV_HTTP_URL_HERE>")
150
+
151
+ # Use as normal
152
+ result = sequence_envenv.reset()
153
+ result = sequence_envenv.step(SequenceAction(message="Hello!"))
154
+ ```
155
+
156
+ Note: When connecting to an existing server, `sequence_envenv.close()` will NOT stop the server.
157
+
158
+ ### Using the Context Manager
159
+
160
+ The client supports context manager usage for automatic connection management:
161
+
162
+ ```python
163
+ from sequence_env import SequenceAction, SequenceEnv
164
+
165
+ # Connect with context manager (auto-connects and closes)
166
+ with SequenceEnv(base_url="http://localhost:8000") as env:
167
+ result = env.reset()
168
+ print(f"Reset: {result.observation.echoed_message}")
169
+ # Multiple steps with low latency
170
+ for msg in ["Hello", "World", "!"]:
171
+ result = env.step(SequenceAction(message=msg))
172
+ print(f"Echoed: {result.observation.echoed_message}")
173
+ ```
174
+
175
+ The client uses WebSocket connections for:
176
+ - **Lower latency**: No HTTP connection overhead per request
177
+ - **Persistent session**: Server maintains your environment state
178
+ - **Efficient for episodes**: Better for many sequential steps
179
+
180
+ ### Concurrent WebSocket Sessions
181
+
182
+ The server supports multiple concurrent WebSocket connections. To enable this,
183
+ modify `server/app.py` to use factory mode:
184
+
185
+ ```python
186
+ # In server/app.py - use factory mode for concurrent sessions
187
+ app = create_app(
188
+ SequenceEnvironment, # Pass class, not instance
189
+ SequenceAction,
190
+ SequenceObservation,
191
+ max_concurrent_envs=4, # Allow 4 concurrent sessions
192
+ )
193
+ ```
194
+
195
+ Then multiple clients can connect simultaneously:
196
+
197
+ ```python
198
+ from sequence_env import SequenceAction, SequenceEnv
199
+ from concurrent.futures import ThreadPoolExecutor
200
+
201
+ def run_episode(client_id: int):
202
+ with SequenceEnv(base_url="http://localhost:8000") as env:
203
+ result = env.reset()
204
+ for i in range(10):
205
+ result = env.step(SequenceAction(message=f"Client {client_id}, step {i}"))
206
+ return client_id, result.observation.message_length
207
+
208
+ # Run 4 episodes concurrently
209
+ with ThreadPoolExecutor(max_workers=4) as executor:
210
+ results = list(executor.map(run_episode, range(4)))
211
+ ```
212
+
213
+ ## Development & Testing
214
+
215
+ ### Direct Environment Testing
216
+
217
+ Test the environment logic directly without starting the HTTP server:
218
+
219
+ ```bash
220
+ # From the server directory
221
+ python3 server/sequence_env_environment.py
222
+ ```
223
+
224
+ This verifies that:
225
+ - Environment resets correctly
226
+ - Step executes actions properly
227
+ - State tracking works
228
+ - Rewards are calculated correctly
229
+
230
+ ### Running Locally
231
+
232
+ Run the server locally for development:
233
+
234
+ ```bash
235
+ uvicorn server.app:app --reload
236
+ ```
237
+
238
+ ## Project Structure
239
+
240
+ ```
241
+ sequence_env/
242
+ ├── .dockerignore # Docker build exclusions
243
+ ├── __init__.py # Module exports
244
+ ├── README.md # This file
245
+ ├── openenv.yaml # OpenEnv manifest
246
+ ├── pyproject.toml # Project metadata and dependencies
247
+ ├── uv.lock # Locked dependencies (generated)
248
+ ├── client.py # SequenceEnv client
249
+ ├── models.py # Action and Observation models
250
+ └── server/
251
+ ├── __init__.py # Server module exports
252
+ ├── sequence_env_environment.py # Core environment logic
253
+ ├── app.py # FastAPI application (HTTP + WebSocket endpoints)
254
+ └── Dockerfile # Container image definition
255
+ ```
__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Sequence Env Environment."""
8
+
9
+ from .client import SequenceEnv
10
+ from .models import SequenceAction, SequenceObservation
11
+
12
+ __all__ = [
13
+ "SequenceAction",
14
+ "SequenceObservation",
15
+ "SequenceEnv",
16
+ ]
client.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Sequence Environment Client."""
8
+
9
+ from typing import Dict
10
+
11
+ from openenv.core import EnvClient
12
+ from openenv.core.client_types import StepResult
13
+ from openenv.core.env_server.types import State
14
+
15
+ from .models import SequenceAction, SequenceObservation
16
+
17
+
18
+ class SequenceEnv(EnvClient[SequenceAction, SequenceObservation]):
19
+ """
20
+ Client for the Sequence Environment.
21
+
22
+ Pattern recognition with 8 rounds of increasing difficulty.
23
+ """
24
+
25
+ def _step_payload(self, action: SequenceAction) -> Dict:
26
+ """Convert SequenceAction to JSON payload for step message."""
27
+ return {
28
+ "answer": action.answer,
29
+ }
30
+
31
+ def _parse_result(self, payload: Dict) -> StepResult[SequenceObservation]:
32
+ """Parse server response into StepResult[SequenceObservation]."""
33
+ obs_data = payload.get("observation", {})
34
+ observation = SequenceObservation(
35
+ sequence=obs_data.get("sequence", []),
36
+ round=obs_data.get("round", 0),
37
+ total_rounds=obs_data.get("total_rounds", 8),
38
+ correct=obs_data.get("correct"),
39
+ score=obs_data.get("score", 0),
40
+ choices=obs_data.get("choices", []),
41
+ done=payload.get("done", False),
42
+ reward=payload.get("reward"),
43
+ metadata=obs_data.get("metadata", {}),
44
+ )
45
+
46
+ return StepResult(
47
+ observation=observation,
48
+ reward=payload.get("reward"),
49
+ done=payload.get("done", False),
50
+ )
51
+
52
+ def _parse_state(self, payload: Dict) -> State:
53
+ """Parse server response into State object."""
54
+ return State(
55
+ episode_id=payload.get("episode_id"),
56
+ step_count=payload.get("step_count", 0),
57
+ )
models.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Sequence Environment.
9
+
10
+ Pattern recognition: show 5 numbers following a rule, agent predicts the 6th.
11
+ """
12
+
13
+ from typing import List, Optional
14
+
15
+ from openenv.core.env_server.types import Action, Observation
16
+ from pydantic import Field
17
+
18
+
19
+ class SequenceAction(Action):
20
+ """Action for the Sequence environment - predict the next number."""
21
+
22
+ answer: int = Field(..., description="The predicted next number in the sequence")
23
+
24
+
25
+ class SequenceObservation(Observation):
26
+ """Observation from the Sequence environment."""
27
+
28
+ sequence: List[int] = Field(default_factory=list, description="The 5 visible numbers")
29
+ round: int = Field(default=0, description="Current round number (1-8)")
30
+ total_rounds: int = Field(default=8, description="Total number of rounds")
31
+ correct: Optional[bool] = Field(default=None, description="Whether the last answer was correct")
32
+ score: int = Field(default=0, description="Number of correct answers so far")
33
+ choices: List[int] = Field(default_factory=list, description="4 possible answers including correct one")
openenv.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ spec_version: 1
2
+ name: sequence_env
3
+ type: space
4
+ runtime: fastapi
5
+ app: server.app:app
6
+ port: 8000
7
+
pyproject.toml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-sequence_env"
13
+ version = "0.1.0"
14
+ description = "Sequence Env environment for OpenEnv"
15
+ requires-python = ">=3.10"
16
+ dependencies = [
17
+ # Core OpenEnv runtime (provides FastAPI server + HTTP client types)
18
+ # install from github
19
+ # "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git",
20
+ "openenv-core[core]>=0.2.1",
21
+ # Environment-specific dependencies
22
+ # Add all dependencies needed for your environment here
23
+ # Examples:
24
+ # "numpy>=1.19.0",
25
+ # "torch>=2.0.0",
26
+ # "gymnasium>=0.29.0",
27
+ # "openspiel>=1.0.0",
28
+ # "smolagents>=1.22.0,<2",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ dev = [
33
+ "pytest>=8.0.0",
34
+ "pytest-cov>=4.0.0",
35
+ ]
36
+
37
+ [project.scripts]
38
+ # Server entry point - enables running via: uv run --project . server
39
+ # or: python -m sequence_env.server.app
40
+ server = "sequence_env.server.app:main"
41
+
42
+ [tool.setuptools]
43
+ include-package-data = true
44
+ packages = ["sequence_env", "sequence_env.server"]
45
+ package-dir = { "sequence_env" = ".", "sequence_env.server" = "server" }
server/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Sequence Env environment server components."""
8
+
9
+ from .sequence_env_environment import SequenceEnvironment
10
+
11
+ __all__ = ["SequenceEnvironment"]
server/app.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Sequence Env Environment.
9
+
10
+ This module creates an HTTP server that exposes the SequenceEnvironment
11
+ over HTTP and WebSocket endpoints, compatible with EnvClient.
12
+
13
+ Endpoints:
14
+ - POST /reset: Reset the environment
15
+ - POST /step: Execute an action
16
+ - GET /state: Get current environment state
17
+ - GET /schema: Get action/observation schemas
18
+ - WS /ws: WebSocket endpoint for persistent sessions
19
+
20
+ Usage:
21
+ # Development (with auto-reload):
22
+ uvicorn server.app:app --reload --host 0.0.0.0 --port 8000
23
+
24
+ # Production:
25
+ uvicorn server.app:app --host 0.0.0.0 --port 8000 --workers 4
26
+
27
+ # Or run directly:
28
+ python -m server.app
29
+ """
30
+
31
+ try:
32
+ from openenv.core.env_server.http_server import create_app
33
+ except Exception as e: # pragma: no cover
34
+ raise ImportError(
35
+ "openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
36
+ ) from e
37
+
38
+ # Import from local models.py (PYTHONPATH includes /app/env in Docker)
39
+ from models import SequenceAction, SequenceObservation
40
+
41
+ from .sequence_env_environment import SequenceEnvironment
42
+
43
+
44
+ # Create the app with web interface and README integration
45
+ app = create_app(
46
+ SequenceEnvironment,
47
+ SequenceAction,
48
+ SequenceObservation,
49
+ env_name="sequence_env",
50
+ max_concurrent_envs=1, # increase this number to allow more concurrent WebSocket sessions
51
+ )
52
+
53
+
54
+ def main(host: str = "0.0.0.0", port: int = 8000):
55
+ """
56
+ Entry point for direct execution via uv run or python -m.
57
+
58
+ This function enables running the server without Docker:
59
+ uv run --project . server
60
+ uv run --project . server --port 8001
61
+ python -m sequence_env.server.app
62
+
63
+ Args:
64
+ host: Host address to bind to (default: "0.0.0.0")
65
+ port: Port number to listen on (default: 8000)
66
+
67
+ For production deployments, consider using uvicorn directly with
68
+ multiple workers:
69
+ uvicorn sequence_env.server.app:app --workers 4
70
+ """
71
+ import uvicorn
72
+
73
+ uvicorn.run(app, host=host, port=port)
74
+
75
+
76
+ if __name__ == "__main__":
77
+ import argparse
78
+
79
+ parser = argparse.ArgumentParser()
80
+ parser.add_argument("--port", type=int, default=8000)
81
+ args = parser.parse_args()
82
+ main(port=args.port)
server/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ openenv[core]>=0.2.0
2
+ fastapi>=0.115.0
3
+ uvicorn>=0.24.0
4
+
5
+
6
+
server/sequence_env_environment.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Sequence Environment Implementation.
9
+
10
+ Pattern recognition with increasing difficulty. Agent sees 5 numbers and
11
+ must predict the 6th based on the underlying rule.
12
+ """
13
+
14
+ import random
15
+ from typing import List, Tuple, Callable
16
+ from uuid import uuid4
17
+
18
+ from models import SequenceAction, SequenceObservation
19
+ from openenv.core.env_server.interfaces import Environment
20
+ from openenv.core.env_server.types import State
21
+
22
+
23
+ class SequenceEnvironment(Environment):
24
+ """
25
+ Sequence prediction environment with 8 rounds of increasing difficulty.
26
+
27
+ Rules by round:
28
+ 1. Addition (constant difference)
29
+ 2. Multiplication (constant ratio)
30
+ 3. Alternating (two interleaved sequences)
31
+ 4. Squares (n^2)
32
+ 5. Fibonacci-like (sum of previous two)
33
+ 6. Triangular numbers
34
+ 7. Interleaved (two rules combined)
35
+ 8. Compound (rule changes at index)
36
+ """
37
+
38
+ SUPPORTS_CONCURRENT_SESSIONS: bool = True
39
+ TOTAL_ROUNDS = 8
40
+
41
+ def __init__(self):
42
+ """Initialize the sequence environment."""
43
+ self._state = State(episode_id=str(uuid4()), step_count=0)
44
+ self._sequences: List[Tuple[List[int], int]] = []
45
+ self._current_round: int = 0
46
+ self._score: int = 0
47
+ self._last_correct: bool | None = None
48
+
49
+ def _generate_addition_sequence(self) -> Tuple[List[int], int]:
50
+ """Round 1: Arithmetic sequence with constant difference."""
51
+ start = random.randint(1, 20)
52
+ diff = random.randint(2, 8)
53
+ seq = [start + i * diff for i in range(6)]
54
+ return seq[:5], seq[5]
55
+
56
+ def _generate_multiplication_sequence(self) -> Tuple[List[int], int]:
57
+ """Round 2: Geometric sequence with constant ratio."""
58
+ start = random.randint(1, 5)
59
+ ratio = random.randint(2, 3)
60
+ seq = [start * (ratio ** i) for i in range(6)]
61
+ return seq[:5], seq[5]
62
+
63
+ def _generate_alternating_sequence(self) -> Tuple[List[int], int]:
64
+ """Round 3: Two interleaved arithmetic sequences."""
65
+ start1 = random.randint(1, 10)
66
+ start2 = random.randint(11, 20)
67
+ diff1 = random.randint(2, 5)
68
+ diff2 = random.randint(2, 5)
69
+ seq = []
70
+ for i in range(6):
71
+ if i % 2 == 0:
72
+ seq.append(start1 + (i // 2) * diff1)
73
+ else:
74
+ seq.append(start2 + (i // 2) * diff2)
75
+ return seq[:5], seq[5]
76
+
77
+ def _generate_squares_sequence(self) -> Tuple[List[int], int]:
78
+ """Round 4: Perfect squares."""
79
+ start = random.randint(1, 5)
80
+ seq = [(start + i) ** 2 for i in range(6)]
81
+ return seq[:5], seq[5]
82
+
83
+ def _generate_fibonacci_sequence(self) -> Tuple[List[int], int]:
84
+ """Round 5: Fibonacci-like (sum of previous two)."""
85
+ a = random.randint(1, 5)
86
+ b = random.randint(2, 7)
87
+ seq = [a, b]
88
+ for _ in range(4):
89
+ seq.append(seq[-1] + seq[-2])
90
+ return seq[:5], seq[5]
91
+
92
+ def _generate_triangular_sequence(self) -> Tuple[List[int], int]:
93
+ """Round 6: Triangular numbers (n*(n+1)/2)."""
94
+ offset = random.randint(0, 3)
95
+ seq = [(n + offset) * (n + offset + 1) // 2 for n in range(1, 7)]
96
+ return seq[:5], seq[5]
97
+
98
+ def _generate_interleaved_sequence(self) -> Tuple[List[int], int]:
99
+ """Round 7: Evens are squares, odds are doubles."""
100
+ start_sq = random.randint(1, 4)
101
+ start_dbl = random.randint(2, 8)
102
+ seq = []
103
+ for i in range(6):
104
+ if i % 2 == 0:
105
+ seq.append((start_sq + i // 2) ** 2)
106
+ else:
107
+ seq.append(start_dbl * (2 ** (i // 2)))
108
+ return seq[:5], seq[5]
109
+
110
+ def _generate_compound_sequence(self) -> Tuple[List[int], int]:
111
+ """Round 8: First 3 add, last 3 multiply by 2."""
112
+ start = random.randint(2, 6)
113
+ diff = random.randint(2, 4)
114
+ seq = [start, start + diff, start + 2 * diff]
115
+ for i in range(3):
116
+ seq.append(seq[-1] * 2)
117
+ return seq[:5], seq[5]
118
+
119
+ def _generate_all_sequences(self):
120
+ """Generate all 8 sequences for the episode."""
121
+ generators = [
122
+ self._generate_addition_sequence,
123
+ self._generate_multiplication_sequence,
124
+ self._generate_alternating_sequence,
125
+ self._generate_squares_sequence,
126
+ self._generate_fibonacci_sequence,
127
+ self._generate_triangular_sequence,
128
+ self._generate_interleaved_sequence,
129
+ self._generate_compound_sequence,
130
+ ]
131
+ self._sequences = [gen() for gen in generators]
132
+
133
+ def _generate_choices(self, correct: int) -> List[int]:
134
+ """Generate 4 choices including the correct answer."""
135
+ choices = {correct}
136
+ while len(choices) < 4:
137
+ offset = random.choice([-3, -2, -1, 1, 2, 3])
138
+ wrong = correct + offset * random.randint(1, 5)
139
+ if wrong > 0:
140
+ choices.add(wrong)
141
+ result = list(choices)
142
+ random.shuffle(result)
143
+ return result
144
+
145
+ def reset(self) -> SequenceObservation:
146
+ """Reset the environment and generate new sequences."""
147
+ self._state = State(episode_id=str(uuid4()), step_count=0)
148
+ self._generate_all_sequences()
149
+ self._current_round = 0
150
+ self._score = 0
151
+ self._last_correct = None
152
+
153
+ seq, correct_answer = self._sequences[0]
154
+ choices = self._generate_choices(correct_answer)
155
+
156
+ return SequenceObservation(
157
+ sequence=seq,
158
+ round=1,
159
+ total_rounds=self.TOTAL_ROUNDS,
160
+ correct=None,
161
+ score=0,
162
+ choices=choices,
163
+ done=False,
164
+ reward=0.0,
165
+ )
166
+
167
+ def step(self, action: SequenceAction) -> SequenceObservation: # type: ignore[override]
168
+ """
169
+ Execute a step by checking the agent's answer.
170
+
171
+ Args:
172
+ action: SequenceAction with the predicted answer
173
+
174
+ Returns:
175
+ SequenceObservation with the next sequence or final results
176
+ """
177
+ self._state.step_count += 1
178
+
179
+ _, correct_answer = self._sequences[self._current_round]
180
+ is_correct = action.answer == correct_answer
181
+ reward = 1.0 if is_correct else 0.0
182
+
183
+ if is_correct:
184
+ self._score += 1
185
+ self._last_correct = is_correct
186
+ self._current_round += 1
187
+
188
+ done = self._current_round >= self.TOTAL_ROUNDS
189
+
190
+ if done:
191
+ return SequenceObservation(
192
+ sequence=[],
193
+ round=self._current_round,
194
+ total_rounds=self.TOTAL_ROUNDS,
195
+ correct=is_correct,
196
+ score=self._score,
197
+ choices=[],
198
+ done=True,
199
+ reward=reward,
200
+ )
201
+
202
+ next_seq, next_correct = self._sequences[self._current_round]
203
+ choices = self._generate_choices(next_correct)
204
+
205
+ return SequenceObservation(
206
+ sequence=next_seq,
207
+ round=self._current_round + 1,
208
+ total_rounds=self.TOTAL_ROUNDS,
209
+ correct=is_correct,
210
+ score=self._score,
211
+ choices=choices,
212
+ done=False,
213
+ reward=reward,
214
+ )
215
+
216
+ @property
217
+ def state(self) -> State:
218
+ """Get the current environment state."""
219
+ return self._state