File size: 5,988 Bytes
344db23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# OpenEnv API Reference (v0.2.3) β€” Quick Reference for Building

---

## Base Classes (from `openenv.core.env_server`)

### Action
```python
from openenv.core.env_server import Action

class Action(BaseModel):
    model_config = ConfigDict(extra="forbid")
    metadata: Dict[str, Any] = Field(default_factory=dict)
```

### Observation
```python
from openenv.core.env_server import Observation

class Observation(BaseModel):
    model_config = ConfigDict(extra="forbid")
    done: bool = Field(default=False)
    reward: bool | int | float | None = Field(default=None)
    metadata: Dict[str, Any] = Field(default_factory=dict)
```

### State
```python
from openenv.core.env_server import State

class State(BaseModel):
    model_config = ConfigDict(extra="allow")  # NOTE: allows extra fields
    episode_id: Optional[str] = Field(default=None)
    step_count: int = Field(default=0, ge=0)
```

---

## Environment Base Class

```python
from openenv.core.env_server.interfaces import Environment

class Environment(ABC, Generic[ActT, ObsT, StateT]):
    SUPPORTS_CONCURRENT_SESSIONS: bool = False
    rubric: Optional[Rubric] = None

    def __init__(self, transform=None, rubric=None): ...

    # --- YOU MUST IMPLEMENT THESE ---
    @abstractmethod
    def reset(self, seed=None, episode_id=None, **kwargs) -> ObsT: ...

    @abstractmethod
    def step(self, action: ActT, timeout_s=None, **kwargs) -> ObsT: ...

    @property
    @abstractmethod
    def state(self) -> StateT: ...

    # --- OPTIONAL OVERRIDES ---
    def get_metadata(self) -> EnvironmentMetadata: ...
    def close(self): ...

    # --- BUILT-IN HELPERS ---
    def _apply_transform(self, observation): ...
    def _apply_rubric(self, action, observation) -> float: ...
    def _reset_rubric(self): ...
```

---

## EnvClient Base Class

```python
from openenv.core.env_client import EnvClient

class EnvClient(ABC, Generic[ActT, ObsT, StateT]):
    def __init__(self, base_url, connect_timeout_s=10.0,
                 message_timeout_s=60.0, max_message_size_mb=100.0,
                 provider=None, mode=None): ...

    # --- YOU MUST IMPLEMENT THESE ---
    @abstractmethod
    def _step_payload(self, action: ActT) -> Dict[str, Any]: ...

    @abstractmethod
    def _parse_result(self, payload: Dict[str, Any]) -> StepResult[ObsT]: ...

    @abstractmethod
    def _parse_state(self, payload: Dict[str, Any]) -> StateT: ...

    # --- PROVIDED (don't override) ---
    async def reset(**kwargs) -> StepResult[ObsT]: ...
    async def step(action, **kwargs) -> StepResult[ObsT]: ...
    async def state() -> StateT: ...
    def sync() -> SyncEnvClient: ...  # synchronous wrapper

    # --- FACTORY METHODS ---
    @classmethod
    async def from_docker_image(cls, image, provider=None, **kwargs): ...
    @classmethod
    async def from_env(cls, repo_id, use_docker=True, ...): ...
```

---

## StepResult

```python
from openenv.core.client_types import StepResult

@dataclass
class StepResult(Generic[ObsT]):
    observation: ObsT
    reward: Optional[float] = None
    done: bool = False
```

---

## Server Factory

```python
from openenv.core.env_server import create_app

app = create_app(
    env=MyEnvironment,              # Environment CLASS (not instance)
    action_cls=MyAction,            # Action subclass
    observation_cls=MyObservation,  # Observation subclass
    env_name="my_env",             # optional
    max_concurrent_envs=1,         # optional
)
```

**Auto-generated endpoints:**
| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/reset` | POST | Initialize new episode |
| `/step` | POST | Execute action |
| `/state` | GET | Get current state |
| `/health` | GET | Health check |
| `/metadata` | GET | Environment info |
| `/schema` | GET | JSON schemas |
| `/ws` | WS | WebSocket sessions |
| `/mcp` | POST | MCP JSON-RPC |
| `/docs` | GET | Swagger UI |

---

## Rubric Base Class

```python
from openenv.core.rubrics.base import Rubric

class Rubric(ABC):
    last_score: float

    @abstractmethod
    def forward(self, action, observation) -> float: ...

    def reset(self): ...
    def state_dict(self) -> dict: ...
    def load_state_dict(self, state_dict): ...
```

---

## openenv.yaml Format

```yaml
spec_version: 1
name: my_env
type: space
runtime: fastapi
app: server.app:app
port: 8000
```

---

## CLI Commands

```bash
openenv init my_env                              # scaffold project
openenv validate                                  # validate locally
openenv validate --url https://space.hf.space    # validate remote
openenv push --repo-id user/my-env               # deploy to HF Spaces
```

---

## Project Structure (from openenv init)

```
my_env/
β”œβ”€β”€ __init__.py          # exports
β”œβ”€β”€ models.py            # Action, Observation, State
β”œβ”€β”€ client.py            # EnvClient subclass
β”œβ”€β”€ openenv.yaml         # manifest
β”œβ”€β”€ pyproject.toml       # deps
β”œβ”€β”€ inference.py         # baseline (hackathon requirement)
β”œβ”€β”€ README.md
└── server/
    β”œβ”€β”€ __init__.py
    β”œβ”€β”€ environment.py   # Environment subclass
    β”œβ”€β”€ app.py           # create_app()
    β”œβ”€β”€ requirements.txt
    └── Dockerfile
```

---

## Dependencies (openenv-core 0.2.3)

```
# Core
fastapi>=0.104.0
pydantic>=2.0.0
uvicorn>=0.24.0
requests>=2.25.0
websockets>=15.0.1
httpx>=0.28.1

# CLI
typer>=0.9.0
rich>=13.0.0
pyyaml>=6.0
huggingface_hub>=0.20.0
openai>=2.7.2
tomli>=2.3.0
tomli-w>=1.2.0

# MCP + UI
fastmcp>=3.0.0
gradio>=4.0.0
```

Python >= 3.10 required.

---

## Sync Usage Pattern (for inference.py)

```python
from my_env import MyEnv, MyAction

with MyEnv(base_url="https://your-space.hf.space").sync() as env:
    result = env.reset()
    observation = result.observation

    result = env.step(MyAction(field="value"))
    print(result.observation)
    print(result.reward)
    print(result.done)

    state = env.state()
    print(state.episode_id, state.step_count)
```