theykk commited on
Commit
d4cd8ce
·
verified ·
1 Parent(s): 06e44a0

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ task_categories: [question-answering]
4
+ pretty_name: Ledger Check
5
+ ---
6
+ # Ledger Check (OpenEnv)
7
+ Single-step ledger reconciliation tasks: given a short CSV ledger (id,account,amount), compute a closing balance, an account total, net flow, or identify a duplicate / largest-expense / unknown-account entry.
8
+
9
+ - 12 deterministic tasks (6 kinds x 2 sizes); `reset(task_id=...)` regenerates the ledger from a seeded RNG.
10
+ - Action: `{"answer": "<number or entry id>"}`. Numbers are accepted within 0.005; ids are case-insensitive.
11
+ - Reward: 1.0 for the exact correct answer, otherwise 0.0; the episode ends after one step.
12
+ - `tasks.jsonl` lists the task ids. Source of truth is the image.
source/README.md ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Ledger Check Environment Server
3
+ emoji: 🔊
4
+ colorFrom: gray
5
+ colorTo: pink
6
+ sdk: docker
7
+ pinned: false
8
+ app_port: 8000
9
+ base_path: /web
10
+ tags:
11
+ - openenv
12
+ ---
13
+
14
+ # Ledger Check 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 Ledger Check environment is through the `LedgerCheckEnv` class:
21
+
22
+ ```python
23
+ from ledger_check import LedgerCheckAction, LedgerCheckEnv
24
+
25
+ try:
26
+ # Create environment from Docker image (.sync() for synchronous use)
27
+ ledger_checkenv = LedgerCheckEnv.from_docker_image(
28
+ "ledger_check-env:latest"
29
+ ).sync()
30
+
31
+ # Reset
32
+ result = ledger_checkenv.reset()
33
+ print(f"Reset: {result.observation.echoed_message}")
34
+
35
+ # Send multiple messages
36
+ messages = ["Hello, World!", "Testing echo", "Final message"]
37
+
38
+ for msg in messages:
39
+ result = ledger_checkenv.step(LedgerCheckAction(message=msg))
40
+ print(f"Sent: '{msg}'")
41
+ print(f" → Echoed: '{result.observation.echoed_message}'")
42
+ print(f" → Length: {result.observation.message_length}")
43
+ print(f" → Reward: {result.reward}")
44
+
45
+ finally:
46
+ # Always clean up
47
+ ledger_checkenv.close()
48
+ ```
49
+
50
+ That's it! The `LedgerCheckEnv.from_docker_image()` method handles:
51
+ - Starting the Docker container
52
+ - Waiting for the server to be ready
53
+ - Connecting to the environment
54
+ - Container cleanup when you call `close()`
55
+
56
+ ## Building the Docker Image
57
+
58
+ Before using the environment, you need to build the Docker image:
59
+
60
+ ```bash
61
+ # From project root
62
+ docker build -t ledger_check-env:latest -f server/Dockerfile .
63
+ ```
64
+
65
+ ## Deploying to Hugging Face Spaces
66
+
67
+ You can easily deploy your OpenEnv environment to Hugging Face Spaces using the `openenv push` command:
68
+
69
+ ```bash
70
+ # From the environment directory (where openenv.yaml is located)
71
+ openenv push
72
+
73
+ # Or specify options
74
+ openenv push --namespace my-org --private
75
+ ```
76
+
77
+ The `openenv push` command will:
78
+ 1. Validate that the directory is an OpenEnv environment (checks for `openenv.yaml`)
79
+ 2. Prepare a custom build for Hugging Face Docker space (enables web interface)
80
+ 3. Upload to Hugging Face (ensuring you're logged in)
81
+
82
+ ### Prerequisites
83
+
84
+ - Authenticate with Hugging Face: The command will prompt for login if not already authenticated
85
+
86
+ ### Options
87
+
88
+ - `--directory`, `-d`: Directory containing the OpenEnv environment (defaults to current directory)
89
+ - `--repo-id`, `-r`: Repository ID in format 'username/repo-name' (defaults to 'username/env-name' from openenv.yaml)
90
+ - `--base-image`, `-b`: Base Docker image to use (overrides Dockerfile FROM)
91
+ - `--private`: Deploy the space as private (default: public)
92
+
93
+ ### Examples
94
+
95
+ ```bash
96
+ # Push to your personal namespace (defaults to username/env-name from openenv.yaml)
97
+ openenv push
98
+
99
+ # Push to a specific repository
100
+ openenv push --repo-id my-org/my-env
101
+
102
+ # Push with a custom base image
103
+ openenv push --base-image ghcr.io/huggingface/openenv-base:latest
104
+
105
+ # Push as a private space
106
+ openenv push --private
107
+
108
+ # Combine options
109
+ openenv push --repo-id my-org/my-env --base-image custom-base:latest --private
110
+ ```
111
+
112
+ After deployment, your space will be available at:
113
+ `https://huggingface.co/spaces/<repo-id>`
114
+
115
+ The deployed space includes:
116
+ - **Web Interface** at `/web` - Interactive UI for exploring the environment
117
+ - **API Documentation** at `/docs` - Full OpenAPI/Swagger interface
118
+ - **Health Check** at `/health` - Container health monitoring
119
+ - **WebSocket** at `/ws` - Persistent session endpoint for low-latency interactions
120
+
121
+ ## Environment Details
122
+
123
+ ### Action
124
+ **LedgerCheckAction**: Contains a single field
125
+ - `message` (str) - The message to echo back
126
+
127
+ ### Observation
128
+ **LedgerCheckObservation**: Contains the echo response and metadata
129
+ - `echoed_message` (str) - The message echoed back
130
+ - `message_length` (int) - Length of the message
131
+ - `reward` (float) - Reward based on message length (length × 0.1)
132
+ - `done` (bool) - Always False for echo environment
133
+ - `metadata` (dict) - Additional info like step count
134
+
135
+ ### Reward
136
+ The reward is calculated as: `message_length × 0.1`
137
+ - "Hi" → reward: 0.2
138
+ - "Hello, World!" → reward: 1.3
139
+ - Empty message → reward: 0.0
140
+
141
+ ## Advanced Usage
142
+
143
+ ### Connecting to an Existing Server
144
+
145
+ If you already have a Ledger Check environment server running, you can connect directly:
146
+
147
+ ```python
148
+ from ledger_check import LedgerCheckEnv
149
+
150
+ # Connect to existing server
151
+ ledger_checkenv = LedgerCheckEnv(base_url="<ENV_HTTP_URL_HERE>")
152
+
153
+ # Use as normal
154
+ result = ledger_checkenv.reset()
155
+ result = ledger_checkenv.step(LedgerCheckAction(message="Hello!"))
156
+ ```
157
+
158
+ Note: When connecting to an existing server, `ledger_checkenv.close()` will NOT stop the server.
159
+
160
+ ### Using the Context Manager
161
+
162
+ The client supports context manager usage for automatic connection management:
163
+
164
+ ```python
165
+ from ledger_check import LedgerCheckAction, LedgerCheckEnv
166
+
167
+ # Connect with context manager (auto-connects and closes)
168
+ with LedgerCheckEnv(base_url="http://localhost:8000") as env:
169
+ result = env.reset()
170
+ print(f"Reset: {result.observation.echoed_message}")
171
+ # Multiple steps with low latency
172
+ for msg in ["Hello", "World", "!"]:
173
+ result = env.step(LedgerCheckAction(message=msg))
174
+ print(f"Echoed: {result.observation.echoed_message}")
175
+ ```
176
+
177
+ The client uses WebSocket connections for:
178
+ - **Lower latency**: No HTTP connection overhead per request
179
+ - **Persistent session**: Server maintains your environment state
180
+ - **Efficient for episodes**: Better for many sequential steps
181
+
182
+ ### Concurrent WebSocket Sessions
183
+
184
+ The server supports multiple concurrent WebSocket connections. To enable this,
185
+ modify `server/app.py` to use factory mode:
186
+
187
+ ```python
188
+ # In server/app.py - use factory mode for concurrent sessions
189
+ app = create_app(
190
+ LedgerCheckEnvironment, # Pass class, not instance
191
+ LedgerCheckAction,
192
+ LedgerCheckObservation,
193
+ max_concurrent_envs=4, # Allow 4 concurrent sessions
194
+ )
195
+ ```
196
+
197
+ Then multiple clients can connect simultaneously:
198
+
199
+ ```python
200
+ from ledger_check import LedgerCheckAction, LedgerCheckEnv
201
+ from concurrent.futures import ThreadPoolExecutor
202
+
203
+
204
+ def run_episode(client_id: int):
205
+ with LedgerCheckEnv(base_url="http://localhost:8000") as env:
206
+ result = env.reset()
207
+ for i in range(10):
208
+ result = env.step(
209
+ LedgerCheckAction(message=f"Client {client_id}, step {i}")
210
+ )
211
+ return client_id, result.observation.message_length
212
+
213
+
214
+ # Run 4 episodes concurrently
215
+ with ThreadPoolExecutor(max_workers=4) as executor:
216
+ results = list(executor.map(run_episode, range(4)))
217
+ ```
218
+
219
+ ## Development & Testing
220
+
221
+ ### Direct Environment Testing
222
+
223
+ Test the environment logic directly without starting the HTTP server:
224
+
225
+ ```bash
226
+ # From the server directory
227
+ python3 server/ledger_check_environment.py
228
+ ```
229
+
230
+ This verifies that:
231
+ - Environment resets correctly
232
+ - Step executes actions properly
233
+ - State tracking works
234
+ - Rewards are calculated correctly
235
+
236
+ ### Running Locally
237
+
238
+ Run the server locally for development:
239
+
240
+ ```bash
241
+ uvicorn server.app:app --reload
242
+ ```
243
+
244
+ ## Project Structure
245
+
246
+ ```
247
+ ledger_check/
248
+ ├── .dockerignore # Docker build exclusions
249
+ ├── __init__.py # Module exports
250
+ ├── README.md # This file
251
+ ├── openenv.yaml # OpenEnv manifest
252
+ ├── pyproject.toml # Project metadata and dependencies
253
+ ├── uv.lock # Locked dependencies (generated)
254
+ ├── client.py # LedgerCheckEnv client
255
+ ├── models.py # Action and Observation models
256
+ └── server/
257
+ ├── __init__.py # Server module exports
258
+ ├── ledger_check_environment.py # Core environment logic
259
+ ├── app.py # FastAPI application (HTTP + WebSocket endpoints)
260
+ └── Dockerfile # Container image definition
261
+ ```
source/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+
3
+ """Ledger Check Environment."""
4
+
5
+ from .client import LedgerCheckEnv
6
+ from .models import LedgerCheckAction, LedgerCheckObservation
7
+
8
+ __all__ = [
9
+ "LedgerCheckAction",
10
+ "LedgerCheckObservation",
11
+ "LedgerCheckEnv",
12
+ ]
source/client.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+
3
+ """Ledger Check Environment Client."""
4
+
5
+ from typing import Dict
6
+
7
+ from openenv.core import EnvClient
8
+ from openenv.core.client_types import StepResult
9
+ from openenv.core.env_server.types import State
10
+
11
+ from .models import LedgerCheckAction, LedgerCheckObservation
12
+
13
+
14
+ class LedgerCheckEnv(
15
+ EnvClient[LedgerCheckAction, LedgerCheckObservation, State]
16
+ ):
17
+ """
18
+ Client for the Ledger Check Environment.
19
+
20
+ This client maintains a persistent WebSocket connection to the environment server,
21
+ enabling efficient multi-step interactions with lower latency.
22
+ Each client instance has its own dedicated environment session on the server.
23
+
24
+ Example:
25
+ >>> # Connect to a running server
26
+ >>> with LedgerCheckEnv(base_url="http://localhost:8000") as client:
27
+ ... result = client.reset()
28
+ ... print(result.observation.echoed_message)
29
+ ...
30
+ ... result = client.step(LedgerCheckAction(message="Hello!"))
31
+ ... print(result.observation.echoed_message)
32
+
33
+ Example with Docker:
34
+ >>> # Automatically start container and connect (.sync() for sync use)
35
+ >>> client = LedgerCheckEnv.from_docker_image("ledger_check-env:latest").sync()
36
+ >>> try:
37
+ ... result = client.reset()
38
+ ... result = client.step(LedgerCheckAction(message="Test"))
39
+ ... finally:
40
+ ... client.close()
41
+ """
42
+
43
+ def _step_payload(self, action: LedgerCheckAction) -> Dict:
44
+ """
45
+ Convert LedgerCheckAction to JSON payload for step message.
46
+
47
+ Args:
48
+ action: LedgerCheckAction instance
49
+
50
+ Returns:
51
+ Dictionary representation suitable for JSON encoding
52
+ """
53
+ return {
54
+ "answer": action.answer,
55
+ }
56
+
57
+ def _parse_result(self, payload: Dict) -> StepResult[LedgerCheckObservation]:
58
+ """
59
+ Parse server response into StepResult[LedgerCheckObservation].
60
+
61
+ Args:
62
+ payload: JSON response data from server
63
+
64
+ Returns:
65
+ StepResult with LedgerCheckObservation
66
+ """
67
+ obs_data = payload.get("observation", {})
68
+ observation = LedgerCheckObservation(
69
+ task_id=obs_data.get("task_id", ""),
70
+ question=obs_data.get("question", ""),
71
+ ledger=obs_data.get("ledger", ""),
72
+ feedback=obs_data.get("feedback", ""),
73
+ done=payload.get("done", False),
74
+ reward=payload.get("reward"),
75
+ metadata=payload.get("metadata", obs_data.get("metadata", {})),
76
+ )
77
+
78
+ return StepResult(
79
+ observation=observation,
80
+ reward=payload.get("reward"),
81
+ done=payload.get("done", False),
82
+ metadata=payload.get("metadata"),
83
+ )
84
+
85
+ def _parse_state(self, payload: Dict) -> State:
86
+ """
87
+ Parse server response into State object.
88
+
89
+ Args:
90
+ payload: JSON response from state request
91
+
92
+ Returns:
93
+ State object with episode_id and step_count
94
+ """
95
+ return State(
96
+ episode_id=payload.get("episode_id"),
97
+ step_count=payload.get("step_count", 0),
98
+ )
source/models.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openenv.core.env_server.types import Action, Observation
2
+ from pydantic import Field
3
+
4
+
5
+ class LedgerCheckAction(Action):
6
+ answer: str = Field(..., description="Final answer: a number (e.g. 1234.50) or an entry id (e.g. T07)")
7
+
8
+
9
+ class LedgerCheckObservation(Observation):
10
+ task_id: str = Field(default="")
11
+ question: str = Field(default="")
12
+ ledger: str = Field(default="", description="CSV: id,account,amount")
13
+ feedback: str = Field(default="")
source/openenv.yaml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ spec_version: 1
2
+ name: ledger_check
3
+ version: 0.1.0
4
+ type: space
5
+ runtime: fastapi
6
+ app: server.app:app
7
+ port: 8000
8
+ validation:
9
+ reward:
10
+ range: [0.0, 1.0]
11
+ oracle_tolerance: 0.0
12
+ floor_margin: 0.1
13
+ resources:
14
+ cpu: 1.0
15
+ memory_mb: 1024
16
+ disk_mb: 512
17
+ episode_timeout_s: 60.0
18
+ capabilities:
19
+ verifier:
20
+ kind: reward_channel
21
+ types:
22
+ tags: [demo]
23
+
source/pyproject.toml ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+
3
+ [build-system]
4
+ requires = ["setuptools>=45", "wheel"]
5
+ build-backend = "setuptools.build_meta"
6
+
7
+ [project]
8
+ name = "openenv-ledger_check"
9
+ version = "0.1.0"
10
+ description = "Ledger Check environment for OpenEnv"
11
+ requires-python = ">=3.10"
12
+ dependencies = [
13
+ # Core OpenEnv runtime (provides FastAPI server + HTTP client types)
14
+ # install from github
15
+ # "openenv @ git+https://github.com/huggingface/OpenEnv.git",
16
+ "openenv @ git+https://github.com/meta-pytorch/OpenEnv.git@86a180ede21e044f7929b9a7783ad83aa67d83a3",
17
+ # Environment-specific dependencies
18
+ # Add all dependencies needed for your environment here
19
+ # Examples:
20
+ # "numpy>=1.19.0",
21
+ # "torch>=2.0.0",
22
+ # "gymnasium>=0.29.0",
23
+ # "openspiel>=1.0.0",
24
+ # "smolagents>=1.22.0,<2",
25
+ ]
26
+
27
+ [project.optional-dependencies]
28
+ dev = [
29
+ "pytest>=8.0.0",
30
+ "pytest-cov>=4.0.0",
31
+ ]
32
+
33
+ [project.scripts]
34
+ # Server entry point - enables running via: uv run --project . server
35
+ # or: python -m ledger_check.server.app
36
+ server = "ledger_check.server.app:main"
37
+
38
+ [tool.setuptools]
39
+ include-package-data = true
40
+ packages = ["ledger_check", "ledger_check.server"]
41
+ package-dir = { "ledger_check" = ".", "ledger_check.server" = "server" }
source/server/Dockerfile ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+
3
+ # Multi-stage build using openenv-base
4
+ # This Dockerfile is flexible and works for both:
5
+ # - In-repo environments (with local OpenEnv sources)
6
+ # - Standalone environments (with openenv from PyPI/Git)
7
+ # The build script (openenv build) handles context detection and sets appropriate build args.
8
+
9
+ ARG BASE_IMAGE=ghcr.io/huggingface/openenv-base:latest
10
+ FROM ${BASE_IMAGE} AS builder
11
+
12
+ WORKDIR /app
13
+
14
+ # Ensure git is available (required for installing dependencies from VCS)
15
+ RUN apt-get update && \
16
+ apt-get install -y --no-install-recommends git && \
17
+ rm -rf /var/lib/apt/lists/*
18
+
19
+ # Build argument to control whether we're building standalone or in-repo
20
+ ARG BUILD_MODE=in-repo
21
+ ARG ENV_NAME=ledger_check
22
+
23
+ # Copy environment code (always at root of build context)
24
+ COPY . /app/env
25
+
26
+ # For in-repo builds, openenv is already vendored in the build context
27
+ # For standalone builds, openenv will be installed via pyproject.toml
28
+ WORKDIR /app/env
29
+
30
+ # Ensure uv is available (for local builds where base image lacks it)
31
+ RUN if ! command -v uv >/dev/null 2>&1; then \
32
+ curl -LsSf https://astral.sh/uv/install.sh | sh && \
33
+ mv /root/.local/bin/uv /usr/local/bin/uv && \
34
+ mv /root/.local/bin/uvx /usr/local/bin/uvx; \
35
+ fi
36
+
37
+ # Install dependencies using uv sync
38
+ # If uv.lock exists, use it; otherwise resolve on the fly
39
+ RUN \
40
+ if [ -f uv.lock ]; then \
41
+ uv sync --frozen --no-install-project --no-editable; \
42
+ else \
43
+ uv sync --no-install-project --no-editable; \
44
+ fi
45
+
46
+ RUN \
47
+ if [ -f uv.lock ]; then \
48
+ uv sync --frozen --no-editable; \
49
+ else \
50
+ uv sync --no-editable; \
51
+ fi
52
+
53
+ # Move the venv out of /app/env so it isn't nested inside the directory we
54
+ # copy wholesale below. Copying /app/env/.venv separately AND /app/env would
55
+ # otherwise ship the venv twice (once at /app/.venv, once at
56
+ # /app/env/.venv), roughly doubling the image size.
57
+ RUN mv /app/env/.venv /app/.venv
58
+
59
+ # Final runtime stage
60
+ FROM ${BASE_IMAGE}
61
+
62
+ WORKDIR /app
63
+
64
+ # Copy the virtual environment from builder
65
+ COPY --from=builder /app/.venv /app/.venv
66
+
67
+ # Copy the environment code (no longer contains .venv, see builder stage)
68
+ COPY --from=builder /app/env /app/env
69
+
70
+ # Recreate a .venv symlink inside the env directory for tools (e.g. `uv run`,
71
+ # editors) that expect the virtual environment alongside the project, without
72
+ # storing a second physical copy of it.
73
+ RUN ln -s /app/.venv /app/env/.venv
74
+
75
+ # Set PATH to use the virtual environment
76
+ ENV PATH="/app/.venv/bin:$PATH"
77
+
78
+ # Set PYTHONPATH so imports work correctly
79
+ ENV PYTHONPATH="/app/env:$PYTHONPATH"
80
+
81
+ # Health check
82
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
83
+ CMD curl -f http://localhost:8000/health || exit 1
84
+
85
+ # Run the FastAPI server
86
+ # The module path is constructed to work with the /app/env structure
87
+ CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
source/server/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+
3
+ """Ledger Check environment server components."""
4
+
5
+ from .ledger_check_environment import LedgerCheckEnvironment
6
+
7
+ __all__ = ["LedgerCheckEnvironment"]
source/server/app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+
3
+ """
4
+ FastAPI application for the Ledger Check Environment.
5
+
6
+ This module creates an HTTP server that exposes the LedgerCheckEnvironment
7
+ over HTTP and WebSocket endpoints, compatible with EnvClient.
8
+
9
+ Endpoints:
10
+ - POST /reset: Reset the environment
11
+ - POST /step: Execute an action
12
+ - GET /state: Get current environment state
13
+ - GET /schema: Get action/observation schemas
14
+ - WS /ws: WebSocket endpoint for persistent sessions
15
+
16
+ Usage:
17
+ # Development (with auto-reload):
18
+ uvicorn server.app:app --reload --host 0.0.0.0 --port 8000
19
+
20
+ # Production:
21
+ uvicorn server.app:app --host 0.0.0.0 --port 8000 --workers 4
22
+
23
+ # Or run directly:
24
+ python -m server.app
25
+ """
26
+
27
+ try:
28
+ from openenv.core.env_server.http_server import create_app
29
+ except Exception as e: # pragma: no cover
30
+ raise ImportError(
31
+ "openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
32
+ ) from e
33
+
34
+ try:
35
+ from ..models import LedgerCheckAction, LedgerCheckObservation
36
+ from .ledger_check_environment import LedgerCheckEnvironment
37
+ except ImportError:
38
+ from models import LedgerCheckAction, LedgerCheckObservation
39
+ from server.ledger_check_environment import LedgerCheckEnvironment
40
+
41
+
42
+ # Create the app with web interface and README integration
43
+ app = create_app(
44
+ LedgerCheckEnvironment,
45
+ LedgerCheckAction,
46
+ LedgerCheckObservation,
47
+ env_name="ledger_check",
48
+ max_concurrent_envs=8, # increase this number to allow more concurrent WebSocket sessions
49
+ )
50
+
51
+
52
+ def main(host: str = "0.0.0.0", port: int = 8000):
53
+ """
54
+ Entry point for direct execution via uv run or python -m.
55
+
56
+ This function enables running the server without Docker:
57
+ uv run --project . server
58
+ uv run --project . server --port 8001
59
+ python -m ledger_check.server.app
60
+
61
+ Args:
62
+ host: Host address to bind to (default: "0.0.0.0")
63
+ port: Port number to listen on (default: 8000)
64
+
65
+ For production deployments, consider using uvicorn directly with
66
+ multiple workers:
67
+ uvicorn ledger_check.server.app:app --workers 4
68
+ """
69
+ import uvicorn
70
+
71
+ uvicorn.run(app, host=host, port=port)
72
+
73
+
74
+ if __name__ == "__main__":
75
+ import argparse
76
+
77
+ parser = argparse.ArgumentParser()
78
+ parser.add_argument("--port", type=int, default=8000)
79
+ args = parser.parse_args()
80
+ main(port=args.port)
source/server/ledger_check_environment.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from uuid import uuid4
2
+
3
+ from openenv.core.env_server.interfaces import Environment
4
+ from openenv.core.env_server.types import State
5
+
6
+ try:
7
+ from ..models import LedgerCheckAction, LedgerCheckObservation
8
+ from .tasks import TASK_IDS, build, score
9
+ except ImportError:
10
+ from models import LedgerCheckAction, LedgerCheckObservation
11
+ from server.tasks import TASK_IDS, build, score
12
+
13
+
14
+ class LedgerCheckEnvironment(Environment):
15
+ """Single-step ledger reconciliation. Reward 1.0 for the exact answer, else 0.0."""
16
+
17
+ SUPPORTS_CONCURRENT_SESSIONS: bool = True
18
+
19
+ def __init__(self):
20
+ self._state = State(episode_id=str(uuid4()), step_count=0)
21
+ self._task_id = TASK_IDS[0]
22
+ self._expected = None
23
+ self._done = False
24
+
25
+ def reset(self, seed=None, episode_id=None, task_id=None, **kwargs) -> LedgerCheckObservation:
26
+ self._task_id = task_id or TASK_IDS[0]
27
+ csv, q, self._expected = build(self._task_id)
28
+ self._done = False
29
+ self._state = State(episode_id=episode_id or str(uuid4()), step_count=0)
30
+ return LedgerCheckObservation(task_id=self._task_id, question=q, ledger=csv, done=False, reward=0.0)
31
+
32
+ def step(self, action: LedgerCheckAction, timeout_s=None, **kwargs) -> LedgerCheckObservation: # type: ignore[override]
33
+ self._state.step_count += 1
34
+ if self._done or self._expected is None:
35
+ return LedgerCheckObservation(task_id=self._task_id, done=True, reward=0.0, feedback="episode over")
36
+ self._done = True
37
+ r = score(self._expected, action.answer)
38
+ return LedgerCheckObservation(task_id=self._task_id, done=True, reward=r,
39
+ feedback="correct" if r == 1.0 else "incorrect")
40
+
41
+ @property
42
+ def state(self) -> State:
43
+ return self._state
source/server/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ openenv>=0.2.0
2
+ fastapi>=0.116.0
3
+ uvicorn>=0.24.0
4
+
5
+
6
+
source/server/tasks.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic ledger tasks. Each task_id -> (ledger csv, question, expected answer)."""
2
+ import random
3
+
4
+ KINDS = ["balance", "category_total", "duplicate", "largest_expense", "net_flow", "unmatched"]
5
+ TASK_IDS = [f"{k}-{i}" for k in KINDS for i in (1, 2)]
6
+ ACCOUNTS = ["rent", "salary", "food", "travel", "tools", "tax"]
7
+
8
+
9
+ def build(task_id: str):
10
+ kind, idx = task_id.rsplit("-", 1)
11
+ if kind not in KINDS:
12
+ raise KeyError(task_id)
13
+ rng = random.Random(f"ledger-{task_id}")
14
+ n = 8 + 2 * int(idx)
15
+ rows = []
16
+ for i in range(1, n + 1):
17
+ acct = rng.choice(ACCOUNTS)
18
+ amt = round(rng.uniform(5, 900), 2)
19
+ if acct == "salary":
20
+ amt = round(rng.uniform(1000, 3000), 2)
21
+ else:
22
+ amt = -amt
23
+ rows.append([f"T{i:02d}", acct, amt])
24
+ if kind == "balance":
25
+ opening = round(rng.uniform(500, 5000), 2)
26
+ q = f"Opening balance is {opening:.2f}. What is the closing balance after all entries? Answer with a number, 2 decimals."
27
+ ans = f"{opening + sum(r[2] for r in rows):.2f}"
28
+ elif kind == "category_total":
29
+ acct = rng.choice([r[1] for r in rows])
30
+ q = f"What is the total (signed sum) of all entries in account '{acct}'? Answer with a number, 2 decimals."
31
+ ans = f"{sum(r[2] for r in rows if r[1] == acct):.2f}"
32
+ elif kind == "duplicate":
33
+ j = rng.randrange(2, n)
34
+ dup = list(rows[rng.randrange(0, j)])
35
+ dup[0] = f"T{j+1:02d}x"
36
+ rows.insert(j, dup)
37
+ q = "Exactly one entry duplicates an earlier entry (same account and amount) with a later id. Which entry id is the duplicate?"
38
+ ans = dup[0]
39
+ elif kind == "largest_expense":
40
+ q = "Which entry id is the largest expense (most negative amount)?"
41
+ ans = min(rows, key=lambda r: r[2])[0]
42
+ elif kind == "net_flow":
43
+ q = "What is the sum of all positive entries minus the absolute sum of all negative entries (i.e. net flow)? Answer with a number, 2 decimals."
44
+ ans = f"{sum(r[2] for r in rows):.2f}"
45
+ else: # unmatched
46
+ k = rng.randrange(0, n)
47
+ rows[k][1] = "unknown"
48
+ q = "Exactly one entry has account 'unknown'. Which entry id is it?"
49
+ ans = rows[k][0]
50
+ csv = "id,account,amount\n" + "\n".join(f"{r[0]},{r[1]},{r[2]:.2f}" for r in rows)
51
+ return csv, q, ans
52
+
53
+
54
+ def score(expected: str, given: str) -> float:
55
+ g = given.strip().strip("'\"").replace(",", "")
56
+ try:
57
+ return 1.0 if abs(float(g) - float(expected)) < 0.005 else 0.0
58
+ except ValueError:
59
+ return 1.0 if g.lower() == expected.lower() else 0.0
tasks.jsonl ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"task_id": "balance-1", "kind": "balance"}
2
+ {"task_id": "balance-2", "kind": "balance"}
3
+ {"task_id": "category_total-1", "kind": "category_total"}
4
+ {"task_id": "category_total-2", "kind": "category_total"}
5
+ {"task_id": "duplicate-1", "kind": "duplicate"}
6
+ {"task_id": "duplicate-2", "kind": "duplicate"}
7
+ {"task_id": "largest_expense-1", "kind": "largest_expense"}
8
+ {"task_id": "largest_expense-2", "kind": "largest_expense"}
9
+ {"task_id": "net_flow-1", "kind": "net_flow"}
10
+ {"task_id": "net_flow-2", "kind": "net_flow"}
11
+ {"task_id": "unmatched-1", "kind": "unmatched"}
12
+ {"task_id": "unmatched-2", "kind": "unmatched"}