jeevank0 commited on
Commit
cef0e76
·
1 Parent(s): 2624f74

first push

Browse files
.DS_Store ADDED
Binary file (10.2 kB). View file
 
.dockerignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ .git
2
+ .venv
3
+ __pycache__
4
+ *.pyc
5
+ .DS_Store
Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY . .
6
+
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+
9
+ CMD ["uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1 +1,118 @@
1
- # Scaler-Hackathon
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FarmRL OpenEnv Environment
2
+
3
+ ## Overview
4
+
5
+ FarmRL simulates real-world crop operations where an agent chooses daily irrigation, fertilizer, and pesticide actions to improve productivity while preserving sustainability. This is a practical farm-operations decision problem, not a game task.
6
+
7
+ The environment is OpenEnv-compatible and exposes typed state/action/reward models with API endpoints for reset, step, and state retrieval.
8
+
9
+ ## Motivation
10
+
11
+ Farm operations require balancing short-term yield goals with long-term soil and resource health. This environment provides a deterministic, reproducible benchmark for evaluating whether an LLM can make adaptive control decisions under changing weather and soil conditions.
12
+
13
+ ## Observation Space
14
+
15
+ Observation is represented by `FarmState`:
16
+
17
+ - `soil_moisture` (0-100)
18
+ - `soil_ph` (4-9)
19
+ - `temperature` (float)
20
+ - `rainfall` (>=0)
21
+ - `crop_stage` (int, >=0)
22
+ - `day` (int, >=0)
23
+
24
+ ## Action Space
25
+
26
+ Action is represented by `FarmAction`:
27
+
28
+ - `water` in [0, 50]
29
+ - `fertilizer` in [0, 20]
30
+ - `pesticide` in [0, 10]
31
+
32
+ ## Reward Design
33
+
34
+ Reward is provided at every step and includes:
35
+
36
+ - Positive yield progress (`yield_score`)
37
+ - Sustainability encouragement (`sustainability_bonus`)
38
+ - Resource overuse penalty (`resource_penalty`)
39
+ - Explicit penalties for excessive chemical usage (`overuse_penalty`)
40
+ - Explicit loop/stall penalty (`loop_penalty`)
41
+
42
+ This gives dense trajectory feedback and discourages destructive/repetitive behavior.
43
+
44
+ ## Tasks and Difficulty
45
+
46
+ Three deterministic grader tasks are provided:
47
+
48
+ 1. `task_easy_yield` (easy): maximize normalized total reward.
49
+ 2. `task_medium_chemical_efficiency` (medium): minimize aggregate fertilizer + pesticide usage.
50
+ 3. `task_hard_sustainability_balance` (hard): optimize yield-to-chemical-use ratio.
51
+
52
+ Each grader returns a score in [0.0, 1.0].
53
+
54
+ ## OpenEnv Interface
55
+
56
+ API endpoints:
57
+
58
+ - `POST /reset`
59
+ - `POST /step`
60
+ - `GET /state`
61
+
62
+ `step(action)` returns `observation`, `reward`, `done`, `info`.
63
+
64
+ OpenEnv metadata is declared in `openenv.yaml`.
65
+
66
+ ## Setup
67
+
68
+ 1. Create and activate a virtual environment.
69
+ 2. Install dependencies:
70
+
71
+ ```bash
72
+ pip install -r requirements.txt
73
+ ```
74
+
75
+ 3. Configure `.env`:
76
+
77
+ - `API_BASE_URL=https://api.openai.com/v1`
78
+ - `MODEL_NAME=gpt-4o-mini`
79
+ - `OPENAI_API_KEY=<your_key>`
80
+
81
+ ## Usage
82
+
83
+ Run baseline inference:
84
+
85
+ ```bash
86
+ python inference.py
87
+ ```
88
+
89
+ Run API server:
90
+
91
+ ```bash
92
+ uvicorn api.main:app --host 0.0.0.0 --port 7860
93
+ ```
94
+
95
+ ## Baseline Scores
96
+
97
+ Typical baseline output includes an `[END]` line with score and rewards. Example from a recent run:
98
+
99
+ - `overall score`: 0.564
100
+ - `steps`: 60
101
+
102
+ Task-level baseline scores are reported by `tasks/graders.py` and constrained to [0.0, 1.0].
103
+
104
+ ## Container and Deployment
105
+
106
+ Build container:
107
+
108
+ ```bash
109
+ docker build -t farmrl-space-check:latest .
110
+ ```
111
+
112
+ Run container:
113
+
114
+ ```bash
115
+ docker run --rm -p 7860:7860 farmrl-space-check:latest
116
+ ```
117
+
118
+ This image is suitable for Hugging Face Space deployment.
__pycache__/inference.cpython-313.pyc ADDED
Binary file (10.8 kB). View file
 
api/__pycache__/main.cpython-313.pyc ADDED
Binary file (2.28 kB). View file
 
api/main.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ from fastapi import FastAPI, HTTPException
4
+ from pydantic import BaseModel
5
+
6
+ from env.farm_env import FarmAction, FarmEnv, FarmState, FarmStepResult
7
+
8
+ app = FastAPI(title="FarmRL OpenEnv API", version="0.1.0")
9
+ DATASET_PATH = Path(__file__).resolve(
10
+ ).parents[1] / "farmer_advisor_dataset.csv"
11
+ env = FarmEnv(dataset_path=DATASET_PATH)
12
+
13
+
14
+ class ResetRequest(BaseModel):
15
+ seed: int | None = None
16
+
17
+
18
+ @app.post("/reset", response_model=FarmState)
19
+ def reset(payload: ResetRequest | None = None) -> FarmState:
20
+ seed = payload.seed if payload is not None else None
21
+ return env.reset(seed=seed)
22
+
23
+
24
+ @app.post("/step", response_model=FarmStepResult)
25
+ def step(action: FarmAction) -> FarmStepResult:
26
+ try:
27
+ return env.step(action)
28
+ except RuntimeError as exc:
29
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
30
+
31
+
32
+ @app.get("/state", response_model=FarmState)
33
+ def state() -> FarmState:
34
+ try:
35
+ return env.state()
36
+ except RuntimeError as exc:
37
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
env/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .farm_env import FarmAction, FarmEnv, FarmState, FarmStepResult
2
+
3
+ __all__ = ["FarmAction", "FarmEnv", "FarmState", "FarmStepResult"]
env/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (282 Bytes). View file
 
env/__pycache__/farm_env.cpython-313.pyc ADDED
Binary file (9.78 kB). View file
 
env/farm_env.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ from pydantic import BaseModel, Field
9
+
10
+
11
+ class FarmState(BaseModel):
12
+ soil_moisture: float = Field(ge=0.0, le=100.0)
13
+ soil_ph: float = Field(ge=4.0, le=9.0)
14
+ temperature: float
15
+ rainfall: float = Field(ge=0.0)
16
+ crop_stage: int = Field(ge=0)
17
+ day: int = Field(ge=0)
18
+
19
+
20
+ class FarmAction(BaseModel):
21
+ water: float = Field(ge=0.0, le=50.0)
22
+ fertilizer: float = Field(ge=0.0, le=20.0)
23
+ pesticide: float = Field(ge=0.0, le=10.0)
24
+
25
+
26
+ class FarmStepResult(BaseModel):
27
+ observation: FarmState
28
+ reward: float
29
+ done: bool
30
+ info: dict[str, Any]
31
+
32
+
33
+ class FarmEnv:
34
+ """Minimal deterministic OpenEnv-style farm environment for Phase-1."""
35
+
36
+ REQUIRED_COLUMNS = {
37
+ "Soil_pH",
38
+ "Soil_Moisture",
39
+ "Temperature_C",
40
+ "Rainfall_mm",
41
+ }
42
+
43
+ def __init__(
44
+ self,
45
+ dataset_path: str | Path = "farmer_advisor_dataset.csv",
46
+ seed: int = 42,
47
+ max_days: int = 30,
48
+ ) -> None:
49
+ self.dataset_path = Path(dataset_path)
50
+ self.max_days = max_days
51
+ self._rng = np.random.default_rng(seed)
52
+ self._dataset = self._load_dataset(self.dataset_path)
53
+ self._row_index = 0
54
+ self._state: FarmState | None = None
55
+
56
+ def _load_dataset(self, dataset_path: Path) -> pd.DataFrame:
57
+ if not dataset_path.exists():
58
+ raise FileNotFoundError(f"Dataset not found: {dataset_path}")
59
+
60
+ df = pd.read_csv(dataset_path)
61
+ missing = self.REQUIRED_COLUMNS - set(df.columns)
62
+ if missing:
63
+ raise ValueError(
64
+ f"Dataset is missing required columns: {sorted(missing)}")
65
+ return df.reset_index(drop=True)
66
+
67
+ def _next_weather_row(self) -> pd.Series:
68
+ self._row_index = (self._row_index + 1) % len(self._dataset)
69
+ return self._dataset.iloc[self._row_index]
70
+
71
+ def reset(self, seed: int | None = None) -> FarmState:
72
+ if seed is not None:
73
+ self._rng = np.random.default_rng(seed)
74
+
75
+ self._row_index = int(self._rng.integers(0, len(self._dataset)))
76
+ row = self._dataset.iloc[self._row_index]
77
+
78
+ self._state = FarmState(
79
+ soil_moisture=float(np.clip(row["Soil_Moisture"], 0.0, 100.0)),
80
+ soil_ph=float(np.clip(row["Soil_pH"], 4.5, 8.5)),
81
+ temperature=float(row["Temperature_C"]),
82
+ rainfall=float(np.clip(row["Rainfall_mm"], 0.0, 200.0)),
83
+ crop_stage=0,
84
+ day=0,
85
+ )
86
+ return self._state
87
+
88
+ def state(self) -> FarmState:
89
+ if self._state is None:
90
+ raise RuntimeError(
91
+ "Environment is not initialized. Call reset() first.")
92
+ return self._state
93
+
94
+ @staticmethod
95
+ def _clip(value: float, low: float, high: float) -> float:
96
+ return float(np.clip(value, low, high))
97
+
98
+ @staticmethod
99
+ def _compute_reward(state: FarmState, action: FarmAction, day: int) -> tuple[float, dict[str, float]]:
100
+ moisture_score = np.clip(state.soil_moisture / 100.0, 0.0, 1.0)
101
+ temperature_factor = np.clip(
102
+ 1.0 - abs(state.temperature - 26.0) / 16.0, 0.0, 1.0)
103
+ rainfall_factor = np.clip(
104
+ 1.0 - abs(state.rainfall - 60.0) / 60.0, 0.0, 1.0)
105
+
106
+ yield_score = (
107
+ 0.4 * float(moisture_score)
108
+ + 0.3 * float(temperature_factor)
109
+ + 0.3 * float(rainfall_factor)
110
+ )
111
+
112
+ resource_penalty = 0.03 * \
113
+ (action.fertilizer**1.2) + 0.04 * (action.pesticide**1.3)
114
+ sustainability_bonus = 0.2 * np.exp(-action.fertilizer / 20.0) + 0.2 * np.exp(
115
+ -action.pesticide / 10.0
116
+ )
117
+
118
+ overuse_penalty = 0.0
119
+ if action.fertilizer > 12.0:
120
+ overuse_penalty += 0.02 * (action.fertilizer - 12.0)
121
+ if action.pesticide > 6.0:
122
+ overuse_penalty += 0.03 * (action.pesticide - 6.0)
123
+
124
+ loop_penalty = 0.0
125
+ if day > 20 and action.water == 0.0 and action.fertilizer == 0.0 and action.pesticide == 0.0:
126
+ loop_penalty = 0.1
127
+
128
+ reward = float(yield_score + sustainability_bonus -
129
+ resource_penalty - overuse_penalty - loop_penalty)
130
+ info = {
131
+ "yield_score": float(yield_score),
132
+ "resource_penalty": float(resource_penalty),
133
+ "sustainability_bonus": float(sustainability_bonus),
134
+ "overuse_penalty": float(overuse_penalty),
135
+ "loop_penalty": float(loop_penalty),
136
+ }
137
+ return reward, info
138
+
139
+ def step(self, action: FarmAction | dict[str, float]) -> FarmStepResult:
140
+ if self._state is None:
141
+ raise RuntimeError(
142
+ "Environment is not initialized. Call reset() first.")
143
+
144
+ action_model = action if isinstance(
145
+ action, FarmAction) else FarmAction(**action)
146
+ previous_state = self._state
147
+ weather = self._next_weather_row()
148
+
149
+ day = previous_state.day + 1
150
+ crop_stage = min(5, day // 6)
151
+
152
+ temperature = 0.7 * previous_state.temperature + \
153
+ 0.3 * float(weather["Temperature_C"])
154
+ rainfall = 0.5 * previous_state.rainfall + \
155
+ 0.5 * float(weather["Rainfall_mm"])
156
+ rainfall = self._clip(rainfall, 0.0, 200.0)
157
+
158
+ evaporation = max(temperature - 20.0, 0.0) * 0.35
159
+ moisture_gain = 0.12 * rainfall + 0.65 * action_model.water
160
+ moisture_loss = evaporation + 0.5 * crop_stage
161
+ soil_moisture = self._clip(
162
+ previous_state.soil_moisture + moisture_gain - moisture_loss,
163
+ 0.0,
164
+ 100.0,
165
+ )
166
+
167
+ soil_ph = self._clip(
168
+ previous_state.soil_ph - 0.012 *
169
+ action_model.fertilizer + 0.002 * action_model.water,
170
+ 4.5,
171
+ 8.5,
172
+ )
173
+
174
+ self._state = FarmState(
175
+ soil_moisture=soil_moisture,
176
+ soil_ph=soil_ph,
177
+ temperature=float(temperature),
178
+ rainfall=rainfall,
179
+ crop_stage=crop_stage,
180
+ day=day,
181
+ )
182
+
183
+ reward, reward_info = self._compute_reward(
184
+ self._state, action_model, day=day)
185
+ done = day >= self.max_days
186
+ return FarmStepResult(
187
+ observation=self._state,
188
+ reward=reward,
189
+ done=done,
190
+ info=reward_info,
191
+ )
farmer_advisor_dataset.csv ADDED
The diff for this file is too large to render. See raw diff
 
final-requirements.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Functional Requirements:
2
+
3
+ 1. Real-World Task Simulation
4
+ The environment must represent tasks that humans actually perform in real settings—no games
5
+ or toy problems.
6
+ Examples include email triage, code review, data cleaning, scheduling, customer support, and
7
+ content moderation.
8
+
9
+ 2. OpenEnv Specification Compliance
10
+ The environment must fully implement the OpenEnv interface, including:
11
+ Typed Observation, Action, and Reward models using Pydantic
12
+ step(action) → returns (observation, reward, done, info)
13
+ reset() → returns the initial observation
14
+ state() → returns the current state
15
+ An openenv.yaml file containing metadata
16
+ The implementation must successfully pass validation via openenv validate.
17
+
18
+ 3. Minimum of Three Tasks with Agent Graders
19
+ Provide at least three tasks, each with a clearly defined objective
20
+ Tasks should span increasing difficulty: easy → medium → hard
21
+ Each task must include a programmatic grader that assigns a score between 0.0 and
22
+ 1.0
23
+ Grading criteria must be clear, deterministic, and reproducible
24
+
25
+ 4. Meaningful Reward Function
26
+ The reward function must provide feedback throughout the task trajectory, not just at
27
+ completion
28
+ It should reward incremental progress toward the objective
29
+ It must penalize undesirable behaviors such as infinite loops or destructive actions
30
+
31
+ 5. Baseline Inference Script
32
+ Include an inference script that uses the OpenAI API client to evaluate a model within
33
+ the environment
34
+ API credentials must be read from environment variables (HF_TOKEN)
35
+ The script should produce a reproducible baseline score across all tasks
36
+
37
+
38
+ Non-Functional Requirements:
39
+ 1. Deployment on Hugging Face Spaces
40
+ The environment must be deployable as a containerized Hugging Face Space
41
+ It should be tagged with openenv
42
+
43
+ 2. Containerized Execution
44
+ Provide a working Dockerfile
45
+ The environment must build and run successfully using:
46
+ docker build
47
+ docker run
48
+
49
+ 3. Documentation
50
+ The README must include:
51
+ Environment overview and motivation
52
+ Definitions of action and observation spaces
53
+ Task descriptions with expected difficulty levels
54
+ Setup and usage instructions
55
+ Baseline performance scores
inference.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Any, Dict, Optional
8
+
9
+ from dotenv import load_dotenv
10
+ from openai import OpenAI
11
+
12
+ from env.farm_env import FarmAction, FarmEnv, FarmState
13
+ from tasks.graders import grade_all
14
+
15
+ PROJECT_ROOT = Path(__file__).resolve().parent
16
+ ENV_FILE = PROJECT_ROOT / ".env"
17
+ load_dotenv(ENV_FILE)
18
+
19
+
20
+ def require_env(name: str) -> str:
21
+ value = os.getenv(name, "").strip()
22
+ if not value:
23
+ raise RuntimeError(
24
+ f"Missing required environment variable '{name}'. "
25
+ f"Set it in shell or in {ENV_FILE}."
26
+ )
27
+ return value
28
+
29
+
30
+ API_BASE_URL = require_env("API_BASE_URL")
31
+ MODEL_NAME = require_env("MODEL_NAME")
32
+ TASK_NAME = require_env("TASK_NAME")
33
+ BENCHMARK = require_env("BENCHMARK")
34
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "").strip()
35
+
36
+ PLACEHOLDER_TOKENS = {
37
+ "your_openai_api_key_here",
38
+ "replace_with_openai_api_key",
39
+ "replace-me",
40
+ "replace_me",
41
+ }
42
+
43
+ EPISODES = 3
44
+ STEPS_PER_EPISODE = 20
45
+ SUCCESS_SCORE_THRESHOLD = 0.10
46
+
47
+
48
+ def clamp(value: float, low: float, high: float) -> float:
49
+ return max(low, min(high, value))
50
+
51
+
52
+ def compute_yield_proxy(state: FarmState) -> float:
53
+ moisture_score = clamp(state.soil_moisture / 100.0, 0.0, 1.0)
54
+ temperature_factor = clamp(
55
+ 1.0 - abs(state.temperature - 26.0) / 16.0, 0.0, 1.0)
56
+ rainfall_factor = clamp(1.0 - abs(state.rainfall - 60.0) / 60.0, 0.0, 1.0)
57
+ return 0.4 * moisture_score + 0.3 * temperature_factor + 0.3 * rainfall_factor
58
+
59
+
60
+ def build_prompt(state: FarmState, step: int, recent_actions: list[dict[str, float]]) -> str:
61
+ recent_actions_text = "none"
62
+ if recent_actions:
63
+ recent_actions_text = json.dumps(recent_actions[-3:])
64
+ previous_action_text = "none"
65
+ if recent_actions:
66
+ previous_action_text = json.dumps(recent_actions[-1])
67
+
68
+ return (
69
+ "Farm state:\n"
70
+ f"step: {step}\n"
71
+ f"soil moisture: {state.soil_moisture:.2f}\n"
72
+ f"temperature: {state.temperature:.2f}\n"
73
+ f"rainfall: {state.rainfall:.2f}\n"
74
+ f"crop stage: {state.crop_stage}\n"
75
+ f"day: {state.day}\n"
76
+ f"previous action: {previous_action_text}\n"
77
+ f"recent actions: {recent_actions_text}\n\n"
78
+ "Choose action values in bounds:\n"
79
+ "water: 0 to 50\n"
80
+ "fertilizer: 0 to 20\n"
81
+ "pesticide: 0 to 10\n\n"
82
+ "Output must be a single valid JSON object with exactly these numeric keys: "
83
+ "water, fertilizer, pesticide.\n"
84
+ "If the previous action is identical, change at least one field by >= 2 unless safety constraints require otherwise."
85
+ )
86
+
87
+
88
+ def build_client() -> Optional[OpenAI]:
89
+ base_lower = API_BASE_URL.lower()
90
+ if "huggingface.co" in base_lower:
91
+ raise RuntimeError(
92
+ "Hugging Face router is disabled for LLM calls. "
93
+ "Set API_BASE_URL to https://api.openai.com/v1"
94
+ )
95
+
96
+ api_key = OPENAI_API_KEY
97
+ missing_msg = "Missing API key: set OPENAI_API_KEY."
98
+
99
+ if not api_key:
100
+ raise RuntimeError(missing_msg)
101
+
102
+ if api_key.lower() in PLACEHOLDER_TOKENS:
103
+ raise RuntimeError(
104
+ "OPENAI_API_KEY is a placeholder; set a real key before running inference.")
105
+ return OpenAI(base_url=API_BASE_URL, api_key=api_key)
106
+
107
+
108
+ def extract_json_object(text: str) -> Optional[Dict[str, Any]]:
109
+ text = text.strip()
110
+ if not text:
111
+ return None
112
+
113
+ try:
114
+ parsed = json.loads(text)
115
+ if isinstance(parsed, dict):
116
+ return parsed
117
+ except json.JSONDecodeError:
118
+ pass
119
+
120
+ match = re.search(r"\{.*\}", text, flags=re.DOTALL)
121
+ if not match:
122
+ return None
123
+
124
+ try:
125
+ parsed = json.loads(match.group(0))
126
+ if isinstance(parsed, dict):
127
+ return parsed
128
+ except json.JSONDecodeError:
129
+ return None
130
+ return None
131
+
132
+
133
+ def coerce_action(payload: Dict[str, Any]) -> FarmAction:
134
+ if "water" not in payload or "fertilizer" not in payload or "pesticide" not in payload:
135
+ raise ValueError(
136
+ "Model response must include water, fertilizer, and pesticide.")
137
+
138
+ water = float(payload["water"])
139
+ fertilizer = float(payload["fertilizer"])
140
+ pesticide = float(payload["pesticide"])
141
+
142
+ normalized = {
143
+ "water": clamp(water, 0.0, 50.0),
144
+ "fertilizer": clamp(fertilizer, 0.0, 20.0),
145
+ "pesticide": clamp(pesticide, 0.0, 10.0),
146
+ }
147
+ return FarmAction(**normalized)
148
+
149
+
150
+ def choose_action(
151
+ client: OpenAI,
152
+ state: FarmState,
153
+ step: int,
154
+ recent_actions: list[dict[str, float]],
155
+ ) -> FarmAction:
156
+ prompt = build_prompt(state, step=step, recent_actions=recent_actions)
157
+ completion = client.chat.completions.create(
158
+ model=MODEL_NAME,
159
+ messages=[
160
+ {
161
+ "role": "system",
162
+ "content": (
163
+ "You are a farm operations optimizer. "
164
+ "Produce state-dependent control decisions and avoid repetitive action loops. "
165
+ "Return strict JSON with numeric keys: water, fertilizer, pesticide. "
166
+ "No markdown, no prose, no extra keys. "
167
+ "Do not output the same action repeatedly across steps unless explicitly necessary."
168
+ ),
169
+ },
170
+ {"role": "user", "content": prompt},
171
+ ],
172
+ temperature=0.35,
173
+ top_p=0.9,
174
+ frequency_penalty=0.6,
175
+ response_format={"type": "json_object"},
176
+ seed=42 + step,
177
+ max_tokens=160,
178
+ )
179
+
180
+ content = (completion.choices[0].message.content or "").strip()
181
+ payload = extract_json_object(content)
182
+ if payload is None:
183
+ raise ValueError("Model did not return valid JSON action payload.")
184
+ return coerce_action(payload)
185
+
186
+
187
+ def to_action_string(action: FarmAction) -> str:
188
+ return json.dumps(action.model_dump(), separators=(",", ":"), sort_keys=True)
189
+
190
+
191
+ def log_start() -> None:
192
+ print(
193
+ f"[START] task={TASK_NAME} env={BENCHMARK} model={MODEL_NAME}", flush=True)
194
+
195
+
196
+ def log_step(step: int, action: FarmAction, reward: float, done: bool, error: Optional[str]) -> None:
197
+ error_value = error if error else "null"
198
+ done_value = str(done).lower()
199
+ action_str = to_action_string(action)
200
+ print(
201
+ f"[STEP] step={step} action={action_str} reward={reward:.2f} "
202
+ f"done={done_value} error={error_value}",
203
+ flush=True,
204
+ )
205
+
206
+
207
+ def log_end(success: bool, steps: int, score: float, rewards: list[float]) -> None:
208
+ rewards_str = ",".join(f"{value:.2f}" for value in rewards)
209
+ print(
210
+ f"[END] success={str(success).lower()} steps={steps} "
211
+ f"score={score:.3f} rewards={rewards_str}",
212
+ flush=True,
213
+ )
214
+
215
+
216
+ def run_inference() -> None:
217
+ dataset_path = Path(__file__).resolve().parent / \
218
+ "farmer_advisor_dataset.csv"
219
+ env = FarmEnv(dataset_path=dataset_path, seed=42, max_days=30)
220
+ client = build_client()
221
+
222
+ total_reward = 0.0
223
+ total_yield = 0.0
224
+ total_fertilizer = 0.0
225
+ total_pesticide = 0.0
226
+ total_steps = 0
227
+ rewards: list[float] = []
228
+ recent_actions: list[dict[str, float]] = []
229
+
230
+ log_start()
231
+
232
+ for episode in range(EPISODES):
233
+ state = env.reset(seed=42 + episode)
234
+
235
+ for _ in range(STEPS_PER_EPISODE):
236
+ action = choose_action(
237
+ client=client,
238
+ state=state,
239
+ step=total_steps + 1,
240
+ recent_actions=recent_actions,
241
+ )
242
+ step_result = env.step(action)
243
+
244
+ total_steps += 1
245
+ total_reward += step_result.reward
246
+ total_yield += compute_yield_proxy(step_result.observation)
247
+ total_fertilizer += action.fertilizer
248
+ total_pesticide += action.pesticide
249
+ rewards.append(step_result.reward)
250
+ recent_actions.append(action.model_dump())
251
+
252
+ log_step(
253
+ step=total_steps,
254
+ action=action,
255
+ reward=step_result.reward,
256
+ done=step_result.done,
257
+ error=None,
258
+ )
259
+ state = step_result.observation
260
+
261
+ if step_result.done:
262
+ break
263
+
264
+ task_scores = grade_all(
265
+ total_reward=total_reward,
266
+ total_yield=total_yield,
267
+ total_fertilizer=total_fertilizer,
268
+ total_pesticide=total_pesticide,
269
+ total_steps=total_steps,
270
+ )
271
+ overall_score = sum(item["score"]
272
+ for item in task_scores) / len(task_scores)
273
+ overall_score = clamp(overall_score, 0.0, 1.0)
274
+ success = overall_score >= SUCCESS_SCORE_THRESHOLD
275
+ log_end(success=success, steps=total_steps,
276
+ score=overall_score, rewards=rewards)
277
+
278
+
279
+ if __name__ == "__main__":
280
+ run_inference()
openenv.yaml ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ environment:
2
+ name: farmrl-phase1
3
+ version: 0.1.0
4
+ description: Minimal FarmRL OpenEnv implementation for Round-1 Phase-1.
5
+ api:
6
+ reset: POST /reset
7
+ step: POST /step
8
+ state: GET /state
9
+
10
+ observation_schema:
11
+ type: object
12
+ required:
13
+ - soil_moisture
14
+ - soil_ph
15
+ - temperature
16
+ - rainfall
17
+ - crop_stage
18
+ - day
19
+ properties:
20
+ soil_moisture:
21
+ type: number
22
+ minimum: 0
23
+ maximum: 100
24
+ soil_ph:
25
+ type: number
26
+ minimum: 4
27
+ maximum: 9
28
+ temperature:
29
+ type: number
30
+ rainfall:
31
+ type: number
32
+ minimum: 0
33
+ crop_stage:
34
+ type: integer
35
+ minimum: 0
36
+ day:
37
+ type: integer
38
+ minimum: 0
39
+
40
+ action_schema:
41
+ type: object
42
+ required:
43
+ - water
44
+ - fertilizer
45
+ - pesticide
46
+ properties:
47
+ water:
48
+ type: number
49
+ minimum: 0
50
+ maximum: 50
51
+ fertilizer:
52
+ type: number
53
+ minimum: 0
54
+ maximum: 20
55
+ pesticide:
56
+ type: number
57
+ minimum: 0
58
+ maximum: 10
59
+
60
+ reward_schema:
61
+ type: number
62
+ description: yield_score + sustainability_bonus - resource_penalty
63
+
64
+ tasks:
65
+ - id: task_easy_yield
66
+ difficulty: easy
67
+ description: Maximize agronomic yield performance using normalized total reward.
68
+ - id: task_medium_chemical_efficiency
69
+ difficulty: medium
70
+ description: Minimize total fertilizer and pesticide while maintaining productivity.
71
+ - id: task_hard_sustainability_balance
72
+ difficulty: hard
73
+ description: Optimize the long-term yield-to-chemical-use balance ratio.
pyproject.toml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "farmrl-openenv-submission"
7
+ version = "0.1.0"
8
+ description = "FarmRL OpenEnv submission package"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = [
12
+ "numpy",
13
+ "pandas",
14
+ "pydantic",
15
+ "pyyaml",
16
+ "openai",
17
+ "python-dotenv",
18
+ "fastapi",
19
+ "uvicorn",
20
+ "openenv-core>=0.2.0",
21
+ ]
22
+
23
+ [project.scripts]
24
+ server = "server.app:main"
reference-material/.DS_Store ADDED
Binary file (6.15 kB). View file
 
reference-material/add_water_variable.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ add_water_variable.py
3
+
4
+ Adds a Water_mm column to the farm dataset.
5
+ Water is drawn uniformly from [WATER_MIN, Rainfall_mm].
6
+ Rainfall_mm is reduced by the water drawn to prevent bias.
7
+ """
8
+
9
+ import pandas as pd
10
+ import numpy as np
11
+ import sys
12
+
13
+ WATER_MIN = 20 # minimum meaningful irrigation (mm)
14
+ WATER_MAX = 200 # hard ceiling - avoids flooding; also capped at rainfall
15
+
16
+ def add_water(df: pd.DataFrame, seed: int = 42) -> pd.DataFrame:
17
+ rng = np.random.default_rng(seed)
18
+ df = df.copy()
19
+
20
+ # Upper bound: rainfall itself, capped at WATER_MAX
21
+ upper = df["Rainfall_mm"].clip(upper=WATER_MAX)
22
+
23
+ # Where rainfall < WATER_MIN we can't irrigate meaningfully — set 0
24
+ can_irrigate = upper >= WATER_MIN
25
+ water = np.where(
26
+ can_irrigate,
27
+ rng.uniform(WATER_MIN, upper.where(can_irrigate, WATER_MIN)),
28
+ 0.0
29
+ )
30
+
31
+ df["Water_mm"] = np.round(water, 2)
32
+ df["Rainfall_mm"] = np.round(df["Rainfall_mm"] - df["Water_mm"], 2)
33
+ return df
34
+
35
+
36
+ def main():
37
+ path = sys.argv[1] if len(sys.argv) > 1 else "farm_data.csv"
38
+ out = sys.argv[2] if len(sys.argv) > 2 else path.replace(".csv", "_watered.csv")
39
+
40
+ df = pd.read_csv(path)
41
+ required = {"Rainfall_mm"}
42
+ missing = required - set(df.columns)
43
+ if missing:
44
+ raise ValueError(f"Missing columns: {missing}")
45
+
46
+ df_out = add_water(df)
47
+
48
+ print(f"Water_mm — min: {df_out['Water_mm'].min():.1f} "
49
+ f"max: {df_out['Water_mm'].max():.1f} "
50
+ f"mean: {df_out['Water_mm'].mean():.1f}")
51
+ print(f"Rainfall_mm after subtraction — min: {df_out['Rainfall_mm'].min():.1f} "
52
+ f"mean: {df_out['Rainfall_mm'].mean():.1f}")
53
+
54
+ df_out.to_csv(out, index=False)
55
+ print(f"Saved → {out}")
56
+
57
+
58
+ if __name__ == "__main__":
59
+ main()
reference-material/prevalidation-script.sh ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ #
3
+ # validate-submission.sh — OpenEnv Submission Validator
4
+ #
5
+ # Checks that your HF Space is live, Docker image builds, and openenv validate passes.
6
+ #
7
+ # Prerequisites:
8
+ # - Docker: https://docs.docker.com/get-docker/
9
+ # - openenv-core: pip install openenv-core
10
+ # - curl (usually pre-installed)
11
+ #
12
+ # Run:
13
+ # curl -fsSL https://raw.githubusercontent.com/<owner>/<repo>/main/scripts/validate-submission.sh | bash -s -- <ping_url> [repo_dir]
14
+ #
15
+ # Or download and run locally:
16
+ # chmod +x validate-submission.sh
17
+ # ./validate-submission.sh <ping_url> [repo_dir]
18
+ #
19
+ # Arguments:
20
+ # ping_url Your HuggingFace Space URL (e.g. https://your-space.hf.space)
21
+ # repo_dir Path to your repo (default: current directory)
22
+ #
23
+ # Examples:
24
+ # ./validate-submission.sh https://my-team.hf.space
25
+ # ./validate-submission.sh https://my-team.hf.space ./my-repo
26
+ #
27
+
28
+ set -uo pipefail
29
+
30
+ DOCKER_BUILD_TIMEOUT=600
31
+ if [ -t 1 ]; then
32
+ RED='\033[0;31m'
33
+ GREEN='\033[0;32m'
34
+ YELLOW='\033[1;33m'
35
+ BOLD='\033[1m'
36
+ NC='\033[0m'
37
+ else
38
+ RED='' GREEN='' YELLOW='' BOLD='' NC=''
39
+ fi
40
+
41
+ run_with_timeout() {
42
+ local secs="$1"; shift
43
+ if command -v timeout &>/dev/null; then
44
+ timeout "$secs" "$@"
45
+ elif command -v gtimeout &>/dev/null; then
46
+ gtimeout "$secs" "$@"
47
+ else
48
+ "$@" &
49
+ local pid=$!
50
+ ( sleep "$secs" && kill "$pid" 2>/dev/null ) &
51
+ local watcher=$!
52
+ wait "$pid" 2>/dev/null
53
+ local rc=$?
54
+ kill "$watcher" 2>/dev/null
55
+ wait "$watcher" 2>/dev/null
56
+ return $rc
57
+ fi
58
+ }
59
+
60
+ portable_mktemp() {
61
+ local prefix="${1:-validate}"
62
+ mktemp "${TMPDIR:-/tmp}/${prefix}-XXXXXX" 2>/dev/null || mktemp
63
+ }
64
+
65
+ CLEANUP_FILES=()
66
+ cleanup() { rm -f "${CLEANUP_FILES[@]+"${CLEANUP_FILES[@]}"}"; }
67
+ trap cleanup EXIT
68
+
69
+ PING_URL="${1:-}"
70
+ REPO_DIR="${2:-.}"
71
+
72
+ if [ -z "$PING_URL" ]; then
73
+ printf "Usage: %s <ping_url> [repo_dir]\n" "$0"
74
+ printf "\n"
75
+ printf " ping_url Your HuggingFace Space URL (e.g. https://your-space.hf.space)\n"
76
+ printf " repo_dir Path to your repo (default: current directory)\n"
77
+ exit 1
78
+ fi
79
+
80
+ if ! REPO_DIR="$(cd "$REPO_DIR" 2>/dev/null && pwd)"; then
81
+ printf "Error: directory '%s' not found\n" "${2:-.}"
82
+ exit 1
83
+ fi
84
+ PING_URL="${PING_URL%/}"
85
+ export PING_URL
86
+ PASS=0
87
+
88
+ log() { printf "[%s] %b\n" "$(date -u +%H:%M:%S)" "$*"; }
89
+ pass() { log "${GREEN}PASSED${NC} -- $1"; PASS=$((PASS + 1)); }
90
+ fail() { log "${RED}FAILED${NC} -- $1"; }
91
+ hint() { printf " ${YELLOW}Hint:${NC} %b\n" "$1"; }
92
+ stop_at() {
93
+ printf "\n"
94
+ printf "${RED}${BOLD}Validation stopped at %s.${NC} Fix the above before continuing.\n" "$1"
95
+ exit 1
96
+ }
97
+
98
+ printf "\n"
99
+ printf "${BOLD}========================================${NC}\n"
100
+ printf "${BOLD} OpenEnv Submission Validator${NC}\n"
101
+ printf "${BOLD}========================================${NC}\n"
102
+ log "Repo: $REPO_DIR"
103
+ log "Ping URL: $PING_URL"
104
+ printf "\n"
105
+
106
+ log "${BOLD}Step 1/3: Pinging HF Space${NC} ($PING_URL/reset) ..."
107
+
108
+ CURL_OUTPUT=$(portable_mktemp "validate-curl")
109
+ CLEANUP_FILES+=("$CURL_OUTPUT")
110
+ HTTP_CODE=$(curl -s -o "$CURL_OUTPUT" -w "%{http_code}" -X POST \
111
+ -H "Content-Type: application/json" -d '{}' \
112
+ "$PING_URL/reset" --max-time 30 2>"$CURL_OUTPUT" || printf "000")
113
+
114
+ if [ "$HTTP_CODE" = "200" ]; then
115
+ pass "HF Space is live and responds to /reset"
116
+ elif [ "$HTTP_CODE" = "000" ]; then
117
+ fail "HF Space not reachable (connection failed or timed out)"
118
+ hint "Check your network connection and that the Space is running."
119
+ hint "Try: curl -s -o /dev/null -w '%%{http_code}' -X POST $PING_URL/reset"
120
+ stop_at "Step 1"
121
+ else
122
+ fail "HF Space /reset returned HTTP $HTTP_CODE (expected 200)"
123
+ hint "Make sure your Space is running and the URL is correct."
124
+ hint "Try opening $PING_URL in your browser first."
125
+ stop_at "Step 1"
126
+ fi
127
+
128
+ log "${BOLD}Step 2/3: Running docker build${NC} ..."
129
+
130
+ if ! command -v docker &>/dev/null; then
131
+ fail "docker command not found"
132
+ hint "Install Docker: https://docs.docker.com/get-docker/"
133
+ stop_at "Step 2"
134
+ fi
135
+
136
+ if [ -f "$REPO_DIR/Dockerfile" ]; then
137
+ DOCKER_CONTEXT="$REPO_DIR"
138
+ elif [ -f "$REPO_DIR/server/Dockerfile" ]; then
139
+ DOCKER_CONTEXT="$REPO_DIR/server"
140
+ else
141
+ fail "No Dockerfile found in repo root or server/ directory"
142
+ stop_at "Step 2"
143
+ fi
144
+
145
+ log " Found Dockerfile in $DOCKER_CONTEXT"
146
+
147
+ BUILD_LOG=$(portable_mktemp "validate-build")
148
+ CLEANUP_FILES+=("$BUILD_LOG")
149
+
150
+ if run_with_timeout "$DOCKER_BUILD_TIMEOUT" docker build --progress=plain "$DOCKER_CONTEXT" 2>&1 | tee "$BUILD_LOG"; then
151
+ pass "Docker build succeeded"
152
+ else
153
+ fail "Docker build failed (timeout=${DOCKER_BUILD_TIMEOUT}s)"
154
+ tail -20 "$BUILD_LOG"
155
+ stop_at "Step 2"
156
+ fi
157
+
158
+ log "${BOLD}Step 3/3: Running openenv validate${NC} ..."
159
+
160
+ OPENENV_CMD=""
161
+ if command -v openenv &>/dev/null; then
162
+ OPENENV_CMD="$(command -v openenv)"
163
+ elif [ -x "/Library/Frameworks/Python.framework/Versions/3.13/bin/openenv" ]; then
164
+ OPENENV_CMD="/Library/Frameworks/Python.framework/Versions/3.13/bin/openenv"
165
+ fi
166
+
167
+ if [ -z "$OPENENV_CMD" ]; then
168
+ fail "openenv command not found"
169
+ hint "Install it: pip install openenv-core"
170
+ hint "Or ensure /Library/Frameworks/Python.framework/Versions/3.13/bin is in PATH"
171
+ stop_at "Step 3"
172
+ fi
173
+
174
+ VALIDATE_LOG=$(portable_mktemp "validate-openenv")
175
+ CLEANUP_FILES+=("$VALIDATE_LOG")
176
+
177
+ if (cd "$REPO_DIR" && "$OPENENV_CMD" validate 2>&1 | tee "$VALIDATE_LOG"); then
178
+ pass "openenv validate passed"
179
+ else
180
+ fail "openenv validate failed"
181
+ tail -50 "$VALIDATE_LOG"
182
+ stop_at "Step 3"
183
+ fi
184
+
185
+ printf "\n"
186
+ printf "${BOLD}========================================${NC}\n"
187
+ printf "${GREEN}${BOLD} All 3/3 checks passed!${NC}\n"
188
+ printf "${GREEN}${BOLD} Your submission is ready to submit.${NC}\n"
189
+ printf "${BOLD}========================================${NC}\n"
190
+ printf "\n"
191
+
192
+ exit 0
reference-material/roadmap.md ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FarmRL Round-1 Fast Development Roadmap
2
+
3
+ ## Reference Materials
4
+
5
+ ### Introduction
6
+
7
+ FarmRL is a reinforcement learning project that trains an agent to manage crop farming decisions. Given observable farm conditions such as soil properties, weather, and crop type, the agent learns to control irrigation, fertilizer application, and pesticide use in order to maximise crop yield while maintaining a healthy sustainability score.
8
+
9
+ The project is grounded in a tabular agricultural dataset and draws conceptual inspiration from the FarmGym simulation framework. Two training paradigms are supported: a classic RL agent via a custom OpenEnv environment, and an optional text-framing path using TRL for language-model-based decision making.
10
+
11
+ The raw CSV dataset is preprocessed once. The preprocessing adds the Water\_mm column (drawn uniformly from [20, min(Rainfall\_mm, 200)]) and subtracts that value from Rainfall\_mm to preserve water-balance invariance. A lightweight regression model (XGBoost) is then trained on the processed data to serve as the environment's transition model.
12
+
13
+ ---
14
+
15
+ ## Dataset preprocessing requirement
16
+
17
+ Add a preprocessing script that creates a new variable Water\_mm such that:
18
+
19
+ Rainfall\_original = Rainfall\_new + Water\_mm
20
+
21
+ This prevents bias by conserving total water availability.
22
+
23
+ Script file:
24
+
25
+ scripts/add\_water\_variable.py
26
+
27
+ ```
28
+ """
29
+ add_water_variable.py
30
+
31
+ Adds a Water_mm column to the farm dataset.
32
+ Water is drawn uniformly from [WATER_MIN, Rainfall_mm].
33
+ Rainfall_mm is reduced by the water drawn to prevent bias.
34
+ """
35
+
36
+ import pandas as pd
37
+ import numpy as np
38
+ import sys
39
+
40
+ WATER_MIN = 20 # minimum meaningful irrigation (mm)
41
+ WATER_MAX = 200 # hard ceiling - avoids flooding; also capped at rainfall
42
+
43
+ def add_water(df: pd.DataFrame, seed: int = 42) -> pd.DataFrame:
44
+ rng = np.random.default_rng(seed)
45
+ df = df.copy()
46
+
47
+ # Upper bound: rainfall itself, capped at WATER_MAX
48
+ upper = df["Rainfall_mm"].clip(upper=WATER_MAX)
49
+
50
+ # Where rainfall < WATER_MIN we can't irrigate meaningfully — set 0
51
+ can_irrigate = upper >= WATER_MIN
52
+ water = np.where(
53
+ can_irrigate,
54
+ rng.uniform(WATER_MIN, upper.where(can_irrigate, WATER_MIN)),
55
+ 0.0
56
+ )
57
+
58
+ df["Water_mm"] = np.round(water, 2)
59
+ df["Rainfall_mm"] = np.round(df["Rainfall_mm"] - df["Water_mm"], 2)
60
+ return df
61
+
62
+
63
+ def main():
64
+ path = sys.argv[1] if len(sys.argv) > 1 else "farm_data.csv"
65
+ out = sys.argv[2] if len(sys.argv) > 2 else path.replace(".csv", "_watered.csv")
66
+
67
+ df = pd.read_csv(path)
68
+ required = {"Rainfall_mm"}
69
+ missing = required - set(df.columns)
70
+ if missing:
71
+ raise ValueError(f"Missing columns: {missing}")
72
+
73
+ df_out = add_water(df)
74
+
75
+ print(f"Water_mm — min: {df_out['Water_mm'].min():.1f} "
76
+ f"max: {df_out['Water_mm'].max():.1f} "
77
+ f"mean: {df_out['Water_mm'].mean():.1f}")
78
+ print(f"Rainfall_mm after subtraction — min: {df_out['Rainfall_mm'].min():.1f} "
79
+ f"mean: {df_out['Rainfall_mm'].mean():.1f}")
80
+
81
+ df_out.to_csv(out, index=False)
82
+ print(f"Saved → {out}")
83
+
84
+
85
+ if __name__ == "__main__":
86
+ main()
87
+
88
+ ```
89
+
90
+ Purpose:
91
+
92
+ • introduces irrigation variable • prevents data leakage • preserves statistical consistency • improves realism of agent decisions
93
+
94
+ ---
95
+
96
+ # 3-Phase Fast Development Plan (3–4 hours)
97
+
98
+ Goal: produce validator-compliant submission with improved reward design.
99
+
100
+ Scope limitations:
101
+
102
+ • simple environment dynamics • minimal dataset preprocessing • basic transition model • improved reward shaping only
103
+
104
+ ---
105
+
106
+ # Phase 1 — OpenEnv Environment (Core functionality)
107
+
108
+ **Goal:** produce a valid OpenEnv-compliant environment that passes schema and endpoint checks.
109
+
110
+ Estimated time: **1.5 hours**
111
+
112
+ ---
113
+
114
+ ## Tasks
115
+
116
+ ### 1. Define typed state model (Pydantic)
117
+
118
+ Keep small but realistic.
119
+
120
+ Example variables:
121
+
122
+ ```
123
+ soil_moisture : float
124
+ soil_ph : float
125
+ temperature : float
126
+ rainfall : float
127
+ crop_stage : int
128
+ day : int
129
+
130
+ ```
131
+
132
+ Requirements satisfied:
133
+
134
+ - typed models required by OpenEnv spec
135
+ - deterministic state structure
136
+
137
+ ---
138
+
139
+ ### 2. Define typed action model
140
+
141
+ Discrete actions simplify LLM reliability:
142
+
143
+ ```
144
+ water : float (0–50)
145
+ fertilizer : float (0–20)
146
+ pesticide : float (0–10)
147
+
148
+ ```
149
+
150
+ Keep ranges bounded to stabilize scoring.
151
+
152
+ ---
153
+
154
+ ### 3. Implement environment class
155
+
156
+ File:
157
+
158
+ ```
159
+ env/farm_env.py
160
+
161
+ ```
162
+
163
+ Must implement:
164
+
165
+ ```
166
+ reset()
167
+ step(action)
168
+ state()
169
+
170
+ ```
171
+
172
+ ---
173
+
174
+ ### 4. Implement improved reward design (only sophistication added)
175
+
176
+ Reward must reflect:
177
+
178
+ - yield improvement
179
+ - sustainability balance
180
+ - penalty for overuse of chemicals
181
+
182
+ Example reward:
183
+
184
+ ```
185
+ yield_score =
186
+ 0.4 * soil_moisture
187
+ + 0.3 * temperature_factor
188
+ + 0.3 * rainfall_factor
189
+
190
+ resource_penalty =
191
+ 0.03 * fertilizer^1.2
192
+ + 0.04 * pesticide^1.3
193
+
194
+ sustainability_bonus =
195
+ 0.2 * exp(-fertilizer/20)
196
+ + 0.2 * exp(-pesticide/10)
197
+
198
+ reward =
199
+ yield_score
200
+ + sustainability_bonus
201
+ - resource_penalty
202
+
203
+ ```
204
+
205
+ Characteristics:
206
+
207
+ - diminishing returns on fertilizer
208
+ - discourages excessive pesticide
209
+ - stable numeric range
210
+ - smooth gradients
211
+
212
+ ---
213
+
214
+ ### 5. Episode termination rule
215
+
216
+ ```
217
+ max_days = 30
218
+
219
+ ```
220
+
221
+ Short episodes ensure runtime < 20 min.
222
+
223
+ ---
224
+
225
+ ### 6. Create openenv.yaml
226
+
227
+ Define:
228
+
229
+ ```
230
+ environment metadata
231
+ observation schema
232
+ action schema
233
+ reward schema
234
+ task definitions
235
+
236
+ ```
237
+
238
+ Ensure field names exactly match Pydantic models.
239
+
240
+ ---
241
+
242
+ ### 7. Implement API wrapper (if required by spec)
243
+
244
+ Expose:
245
+
246
+ ```
247
+ POST /reset
248
+ POST /step
249
+ GET /state
250
+
251
+ ```
252
+
253
+ Ensure reset returns valid initial state.
254
+
255
+ Requirement satisfied:
256
+
257
+ HF Space ping must return 200.
258
+
259
+ ---
260
+
261
+ # Phase 2 — inference pipeline + tasks + graders
262
+
263
+ **Goal:** produce valid evaluation run with structured logs and normalized scores.
264
+
265
+ Estimated time: **1.5 hours**
266
+
267
+ ---
268
+
269
+ ## Tasks
270
+
271
+ ### 1. Create inference.py in root directory
272
+
273
+ File location:
274
+
275
+ ```
276
+ /inference.py
277
+
278
+ ```
279
+
280
+ Must:
281
+
282
+ - load environment
283
+ - call LLM via OpenAI client
284
+ - run episodes
285
+ - log structured output
286
+ - compute task scores
287
+
288
+ ---
289
+
290
+ ### 2. Implement OpenAI client usage
291
+
292
+ Must use env variables:
293
+
294
+ ```
295
+ API_BASE_URL
296
+ MODEL_NAME
297
+ HF_TOKEN
298
+
299
+ ```
300
+
301
+ LLM prompt format:
302
+
303
+ ```
304
+ Farm state:
305
+ soil moisture: 34
306
+ temperature: 26
307
+ rainfall: 3
308
+ crop stage: 2
309
+
310
+ Choose action values:
311
+ water
312
+ fertilizer
313
+ pesticide
314
+
315
+ ```
316
+
317
+ LLM output expected as JSON:
318
+
319
+ ```
320
+ {
321
+ "water": 20,
322
+ "fertilizer": 5,
323
+ "pesticide": 1
324
+ }
325
+
326
+ ```
327
+
328
+ Add fallback defaults if parsing fails.
329
+
330
+ ---
331
+
332
+ ### 3. Define 3 tasks
333
+
334
+ Tasks must produce score ∈ [0,1].
335
+
336
+ ---
337
+
338
+ #### Task 1 — yield performance
339
+
340
+ Measures productivity.
341
+
342
+ ```
343
+ score =
344
+ normalized(total_reward)
345
+
346
+ ```
347
+
348
+ ---
349
+
350
+ #### Task 2 — chemical efficiency
351
+
352
+ Penalizes excessive fertilizer/pesticide.
353
+
354
+ ```
355
+ score =
356
+ 1 - normalized(total_chemical_use)
357
+
358
+ ```
359
+
360
+ ---
361
+
362
+ #### Task 3 — sustainability balance
363
+
364
+ Encourages moderate actions.
365
+
366
+ ```
367
+ score =
368
+ yield / (fertilizer + pesticide + 1)
369
+ normalized to 0–1
370
+
371
+ ```
372
+
373
+ ---
374
+
375
+ ### 4. Implement graders
376
+
377
+ Each grader returns:
378
+
379
+ ```
380
+ {
381
+ "task_id": "...",
382
+ "score": float
383
+ }
384
+
385
+ ```
386
+
387
+ Ensure:
388
+
389
+ ```
390
+ 0 ≤ score ≤ 1
391
+
392
+ ```
393
+
394
+ Validator requirement.
395
+
396
+ ---
397
+
398
+ ### 5. Implement structured logs
399
+
400
+ Strict format:
401
+
402
+ ```
403
+ [START]
404
+ model: MODEL_NAME
405
+
406
+ [STEP]
407
+ step: 1
408
+ action: {...}
409
+ reward: ...
410
+
411
+ [STEP]
412
+ step: 2
413
+ ...
414
+
415
+ [END]
416
+ task_scores:
417
+ task1: 0.63
418
+ task2: 0.71
419
+ task3: 0.59
420
+
421
+ ```
422
+
423
+ Formatting must match specification exactly.
424
+
425
+ ---
426
+
427
+ ### 6. Runtime optimization
428
+
429
+ Keep small:
430
+
431
+ ```
432
+ episodes = 3
433
+ steps per episode = 20–30
434
+
435
+ ```
436
+
437
+ Ensures runtime well below 20 minutes.
438
+
439
+ ---
440
+
441
+ # Phase 3 — packaging, docker, validation
442
+
443
+ **Goal:** ensure infrastructure compatibility and reproducibility.
444
+
445
+ Estimated time: **1 hour**
446
+
447
+ ---
448
+
449
+ ## Tasks
450
+
451
+ ### 1. requirements.txt
452
+
453
+ Minimal dependencies:
454
+
455
+ ```
456
+ pydantic
457
+ numpy
458
+ pyyaml
459
+ openai
460
+ fastapi (optional)
461
+ uvicorn (optional)
462
+
463
+ ```
464
+
465
+ Avoid heavy ML libraries.
466
+
467
+ ---
468
+
469
+ ### 2. Dockerfile
470
+
471
+ Must build automatically.
472
+
473
+ Example flow:
474
+
475
+ ```
476
+ FROM python:3.11-slim
477
+
478
+ WORKDIR /app
479
+
480
+ COPY . .
481
+
482
+ RUN pip install -r requirements.txt
483
+
484
+ CMD ["python", "inference.py"]
485
+
486
+ ```
487
+
488
+ Validator requirement satisfied.
489
+
490
+ ---
491
+
492
+ ### 3. environment variables support
493
+
494
+ Ensure inference.py reads:
495
+
496
+ ```
497
+ API_BASE_URL
498
+ MODEL_NAME
499
+ HF_TOKEN
500
+
501
+ ```
502
+
503
+ No hardcoding.
504
+
505
+ ---
506
+
507
+ ### 4. basic local tests
508
+
509
+ Run:
510
+
511
+ ```
512
+ python inference.py
513
+
514
+ ```
515
+
516
+ Verify:
517
+
518
+ - no crashes
519
+ - scores generated
520
+ - logs formatted correctly
521
+
522
+ ---
523
+
524
+ ### 5. validation checklist
525
+
526
+ Confirm:
527
+
528
+ HF Space can call:
529
+
530
+ ```
531
+ reset()
532
+ step()
533
+ state()
534
+
535
+ ```
536
+
537
+ Ensure:
538
+
539
+ - numeric reward returned
540
+ - valid JSON outputs
541
+ - docker build successful
542
+
543
+ ---
544
+
545
+ # Final deliverable structure
546
+
547
+ ```
548
+ project/
549
+
550
+ ├── openenv.yaml
551
+ ├── inference.py
552
+ ├── Dockerfile
553
+ ├── requirements.txt
554
+
555
+ ├── env/
556
+ │ └── farm_env.py
557
+
558
+ └── tasks/
559
+ └── graders.py
560
+
561
+ ```
562
+
563
+ ---
564
+
565
+ # Expected outcome
566
+
567
+ Submission will pass:
568
+
569
+ - OpenEnv compliance
570
+ - structured logging requirement
571
+ - 3 task requirement
572
+ - reproducibility requirement
573
+ - runtime constraint
574
+ - docker build requirement
575
+ - HF space endpoint validation
576
+
577
+ ---
reference-material/sample-inference-script.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference Script Example
3
+ ===================================
4
+ MANDATORY
5
+ - Before submitting, ensure the following variables are defined in your environment configuration:
6
+ API_BASE_URL The API endpoint for the LLM.
7
+ MODEL_NAME The model identifier to use for inference.
8
+ HF_TOKEN Your Hugging Face / API key.
9
+ LOCAL_IMAGE_NAME The name of the local image to use for the environment if you are using from_docker_image()
10
+ method
11
+
12
+ - Defaults are set only for API_BASE_URL and MODEL_NAME
13
+ (and should reflect your active inference setup):
14
+ API_BASE_URL = os.getenv("API_BASE_URL", "<your-active-endpoint>")
15
+ MODEL_NAME = os.getenv("MODEL_NAME", "<your-active-model>")
16
+
17
+ - The inference script must be named `inference.py` and placed in the root directory of the project
18
+ - Participants must use OpenAI Client for all LLM calls using above variables
19
+
20
+ STDOUT FORMAT
21
+ - The script must emit exactly three line types to stdout, in this order:
22
+
23
+ [START] task=<task_name> env=<benchmark> model=<model_name>
24
+ [STEP] step=<n> action=<action_str> reward=<0.00> done=<true|false> error=<msg|null>
25
+ [END] success=<true|false> steps=<n> score=<score> rewards=<r1,r2,...,rn>
26
+
27
+ Rules:
28
+ - One [START] line at episode begin.
29
+ - One [STEP] line per step, immediately after env.step() returns.
30
+ - One [END] line after env.close(), always emitted (even on exception).
31
+ - reward and rewards are formatted to 2 decimal places.
32
+ - done and success are lowercase booleans: true or false.
33
+ - error is the raw last_action_error string, or null if none.
34
+ - All fields on a single line with no newlines within a line.
35
+ - Each tasks should return score in [0, 1]
36
+
37
+ Example:
38
+ [START] task=click-test env=miniwob model=Qwen3-VL-30B
39
+ [STEP] step=1 action=click('123') reward=0.00 done=false error=null
40
+ [STEP] step=2 action=fill('456','text') reward=0.00 done=false error=null
41
+ [STEP] step=3 action=click('789') reward=1.00 done=true error=null
42
+ [END] success=true steps=3 score=1.00 rewards=0.00,0.00,1.00
43
+ """
44
+
45
+ import asyncio
46
+ import os
47
+ import textwrap
48
+ from typing import List, Optional
49
+
50
+ from openai import OpenAI
51
+
52
+ from my_env_v4 import MyEnvV4Action, MyEnvV4Env
53
+ IMAGE_NAME = os.getenv("IMAGE_NAME") # If you are using docker image
54
+ API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
55
+
56
+ API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"
57
+ MODEL_NAME = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"
58
+ TASK_NAME = os.getenv("MY_ENV_V4_TASK", "echo")
59
+ BENCHMARK = os.getenv("MY_ENV_V4_BENCHMARK", "my_env_v4")
60
+ MAX_STEPS = 8
61
+ TEMPERATURE = 0.7
62
+ MAX_TOKENS = 150
63
+ SUCCESS_SCORE_THRESHOLD = 0.1 # normalized score in [0, 1]
64
+
65
+ # Max possible reward: each token contributes 0.1, across all steps
66
+ _MAX_REWARD_PER_STEP = MAX_TOKENS * 0.1
67
+ MAX_TOTAL_REWARD = MAX_STEPS * _MAX_REWARD_PER_STEP
68
+
69
+ SYSTEM_PROMPT = textwrap.dedent(
70
+ """
71
+ You are interacting with a simple echo environment.
72
+ Each turn you must send a message. The environment will echo it back.
73
+ Reward is proportional to message length: reward = len(message) * 0.1
74
+ Your goal is to maximize total reward by sending meaningful, substantive messages.
75
+ Reply with exactly one message string — no quotes, no prefixes, just the message text.
76
+ """
77
+ ).strip()
78
+
79
+
80
+ def log_start(task: str, env: str, model: str) -> None:
81
+ print(f"[START] task={task} env={env} model={model}", flush=True)
82
+
83
+
84
+ def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:
85
+ error_val = error if error else "null"
86
+ done_val = str(done).lower()
87
+ print(
88
+ f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}",
89
+ flush=True,
90
+ )
91
+
92
+
93
+ def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
94
+ rewards_str = ",".join(f"{r:.2f}" for r in rewards)
95
+ print(f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={rewards_str}", flush=True)
96
+
97
+
98
+ def build_user_prompt(step: int, last_echoed: str, last_reward: float, history: List[str]) -> str:
99
+ history_block = "\n".join(history[-4:]) if history else "None"
100
+ return textwrap.dedent(
101
+ f"""
102
+ Step: {step}
103
+ Last echoed message: {last_echoed!r}
104
+ Last reward: {last_reward:.2f}
105
+ Previous steps:
106
+ {history_block}
107
+ Send your next message.
108
+ """
109
+ ).strip()
110
+
111
+
112
+ def get_model_message(client: OpenAI, step: int, last_echoed: str, last_reward: float, history: List[str]) -> str:
113
+ user_prompt = build_user_prompt(step, last_echoed, last_reward, history)
114
+ try:
115
+ completion = client.chat.completions.create(
116
+ model=MODEL_NAME,
117
+ messages=[
118
+ {"role": "system", "content": SYSTEM_PROMPT},
119
+ {"role": "user", "content": user_prompt},
120
+ ],
121
+ temperature=TEMPERATURE,
122
+ max_tokens=MAX_TOKENS,
123
+ stream=False,
124
+ )
125
+ text = (completion.choices[0].message.content or "").strip()
126
+ return text if text else "hello"
127
+ except Exception as exc:
128
+ print(f"[DEBUG] Model request failed: {exc}", flush=True)
129
+ return "hello"
130
+
131
+
132
+ async def main() -> None:
133
+ client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
134
+
135
+ env = await MyEnvV4Env.from_docker_image(IMAGE_NAME)
136
+
137
+ history: List[str] = []
138
+ rewards: List[float] = []
139
+ steps_taken = 0
140
+ score = 0.0
141
+ success = False
142
+
143
+ log_start(task=TASK_NAME, env=BENCHMARK, model=MODEL_NAME)
144
+
145
+ try:
146
+ result = await env.reset() # OpenENV.reset()
147
+ last_echoed = result.observation.echoed_message
148
+ last_reward = 0.0
149
+
150
+ for step in range(1, MAX_STEPS + 1):
151
+ if result.done:
152
+ break
153
+
154
+ message = get_model_message(client, step, last_echoed, last_reward, history)
155
+
156
+ result = await env.step(MyEnvV4Action(message=message))
157
+ obs = result.observation
158
+
159
+ reward = result.reward or 0.0
160
+ done = result.done
161
+ error = None
162
+
163
+ rewards.append(reward)
164
+ steps_taken = step
165
+ last_echoed = obs.echoed_message
166
+ last_reward = reward
167
+
168
+ log_step(step=step, action=message, reward=reward, done=done, error=error)
169
+
170
+ history.append(f"Step {step}: {message!r} -> reward {reward:+.2f}")
171
+
172
+ if done:
173
+ break
174
+
175
+ score = sum(rewards) / MAX_TOTAL_REWARD if MAX_TOTAL_REWARD > 0 else 0.0
176
+ score = min(max(score, 0.0), 1.0) # clamp to [0, 1]
177
+ success = score >= SUCCESS_SCORE_THRESHOLD
178
+
179
+ finally:
180
+ try:
181
+ await env.close()
182
+ except Exception as e:
183
+ print(f"[DEBUG] env.close() error (container cleanup): {e}", flush=True)
184
+ log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
185
+
186
+
187
+ if __name__ == "__main__":
188
+ asyncio.run(main())
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ numpy
2
+ pandas
3
+ pydantic
4
+ pyyaml
5
+ openai
6
+ python-dotenv
7
+ fastapi
8
+ uvicorn
9
+ openenv-core>=0.2.0
scripts/__pycache__/openai_responses_demo.cpython-313.pyc ADDED
Binary file (4.84 kB). View file
 
scripts/add_water_variable.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ add_water_variable.py
3
+
4
+ Adds a Water_mm column to the farm dataset.
5
+ Water is drawn uniformly from [WATER_MIN, Rainfall_mm].
6
+ Rainfall_mm is reduced by the water drawn to prevent bias.
7
+ """
8
+
9
+ import sys
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ WATER_MIN = 20
15
+ WATER_MAX = 200
16
+
17
+
18
+ def add_water(df: pd.DataFrame, seed: int = 42) -> pd.DataFrame:
19
+ rng = np.random.default_rng(seed)
20
+ df = df.copy()
21
+
22
+ upper = df["Rainfall_mm"].clip(upper=WATER_MAX)
23
+ can_irrigate = upper >= WATER_MIN
24
+ water = np.where(
25
+ can_irrigate,
26
+ rng.uniform(WATER_MIN, upper.where(can_irrigate, WATER_MIN)),
27
+ 0.0,
28
+ )
29
+
30
+ df["Water_mm"] = np.round(water, 2)
31
+ df["Rainfall_mm"] = np.round(df["Rainfall_mm"] - df["Water_mm"], 2)
32
+ return df
33
+
34
+
35
+ def main() -> None:
36
+ path = sys.argv[1] if len(sys.argv) > 1 else "farm_data.csv"
37
+ out = sys.argv[2] if len(sys.argv) > 2 else path.replace(
38
+ ".csv", "_watered.csv")
39
+
40
+ df = pd.read_csv(path)
41
+ required = {"Rainfall_mm"}
42
+ missing = required - set(df.columns)
43
+ if missing:
44
+ raise ValueError(f"Missing columns: {missing}")
45
+
46
+ df_out = add_water(df)
47
+
48
+ print(
49
+ f"Water_mm - min: {df_out['Water_mm'].min():.1f} "
50
+ f"max: {df_out['Water_mm'].max():.1f} "
51
+ f"mean: {df_out['Water_mm'].mean():.1f}"
52
+ )
53
+ print(
54
+ "Rainfall_mm after subtraction - "
55
+ f"min: {df_out['Rainfall_mm'].min():.1f} "
56
+ f"mean: {df_out['Rainfall_mm'].mean():.1f}"
57
+ )
58
+
59
+ df_out.to_csv(out, index=False)
60
+ print(f"Saved -> {out}")
61
+
62
+
63
+ if __name__ == "__main__":
64
+ main()
scripts/openai_responses_demo.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from dotenv import load_dotenv
8
+ from openai import OpenAI
9
+
10
+
11
+ ROOT_DIR = Path(__file__).resolve().parents[1]
12
+ ENV_FILE = ROOT_DIR / ".env"
13
+ load_dotenv(ENV_FILE)
14
+
15
+
16
+ def require_env(name: str) -> str:
17
+ value = os.getenv(name, "").strip()
18
+ if not value:
19
+ raise RuntimeError(
20
+ f"Missing required environment variable '{name}'. "
21
+ f"Set it in {ENV_FILE}."
22
+ )
23
+ return value
24
+
25
+
26
+ def extract_output_text(response: object) -> str:
27
+ text = (getattr(response, "output_text", "") or "").strip()
28
+ if text:
29
+ return text
30
+
31
+ parts: list[str] = []
32
+ output_items = getattr(response, "output", None)
33
+ if output_items is None and hasattr(response, "model_dump"):
34
+ payload = response.model_dump()
35
+ output_items = payload.get("output", [])
36
+
37
+ for item in output_items or []:
38
+ if isinstance(item, dict):
39
+ content_items = item.get("content", [])
40
+ else:
41
+ content_items = getattr(item, "content", []) or []
42
+
43
+ for content in content_items:
44
+ if isinstance(content, dict):
45
+ chunk = content.get("text")
46
+ else:
47
+ chunk = getattr(content, "text", None)
48
+ if chunk:
49
+ parts.append(str(chunk))
50
+ return "\n".join(parts).strip()
51
+
52
+
53
+ def get_response_error_message(response: object) -> str | None:
54
+ error_obj = getattr(response, "error", None)
55
+ if not error_obj:
56
+ return None
57
+
58
+ if isinstance(error_obj, dict):
59
+ code = error_obj.get("code")
60
+ message = error_obj.get("message")
61
+ else:
62
+ code = getattr(error_obj, "code", None)
63
+ message = getattr(error_obj, "message", None)
64
+
65
+ if code and message:
66
+ return f"{code}: {message}"
67
+ if message:
68
+ return str(message)
69
+ return str(error_obj)
70
+
71
+
72
+ def select_client_config() -> tuple[str, str]:
73
+ base_url = os.getenv("API_BASE_URL", "https://api.openai.com/v1").strip()
74
+ openai_api_key = os.getenv("OPENAI_API_KEY", "").strip()
75
+
76
+ if "huggingface.co" in base_url.lower():
77
+ raise RuntimeError(
78
+ "Hugging Face router is disabled for LLM calls in this script. "
79
+ "Set API_BASE_URL to https://api.openai.com/v1"
80
+ )
81
+
82
+ if not openai_api_key:
83
+ raise RuntimeError(
84
+ "Missing OPENAI_API_KEY for the configured API_BASE_URL."
85
+ )
86
+ return base_url, openai_api_key
87
+
88
+
89
+ def main() -> None:
90
+ base_url, api_key = select_client_config()
91
+ model = os.getenv("MODEL_NAME", "gpt-5-nano").strip()
92
+ prompt = " ".join(sys.argv[1:]).strip() or "write a haiku about ai"
93
+
94
+ client = OpenAI(api_key=api_key, base_url=base_url)
95
+
96
+ response = client.responses.create(
97
+ model=model,
98
+ input=prompt,
99
+ store=True,
100
+ )
101
+
102
+ error_message = get_response_error_message(response)
103
+ if error_message:
104
+ raise RuntimeError(f"Responses API failed: {error_message}")
105
+
106
+ output_text = extract_output_text(response)
107
+ if not output_text:
108
+ raise RuntimeError("OpenAI response did not contain output text.")
109
+
110
+ print(output_text)
111
+
112
+
113
+ if __name__ == "__main__":
114
+ main()
server/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Server package marker for OpenEnv entrypoint discovery.
server/app.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from api.main import app
4
+
5
+
6
+ def main() -> None:
7
+ import uvicorn
8
+
9
+ port = int(os.getenv("PORT", "7860"))
10
+ uvicorn.run("server.app:app", host="0.0.0.0", port=port)
11
+
12
+
13
+ if __name__ == "__main__":
14
+ main()
tasks/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .graders import grade_all
2
+
3
+ __all__ = ["grade_all"]
tasks/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (221 Bytes). View file
 
tasks/__pycache__/graders.cpython-313.pyc ADDED
Binary file (2.63 kB). View file
 
tasks/graders.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, List
4
+
5
+ MIN_REWARD_PER_STEP = -1.75
6
+ MAX_REWARD_PER_STEP = 1.40
7
+ MAX_CHEMICAL_PER_STEP = 30.0
8
+
9
+
10
+ def clamp_01(value: float) -> float:
11
+ return max(0.0, min(1.0, float(value)))
12
+
13
+
14
+ def normalize(value: float, low: float, high: float) -> float:
15
+ if high <= low:
16
+ return 0.0
17
+ return clamp_01((value - low) / (high - low))
18
+
19
+
20
+ def grade_yield_performance(total_reward: float, total_steps: int) -> Dict[str, float]:
21
+ min_total = MIN_REWARD_PER_STEP * total_steps
22
+ max_total = MAX_REWARD_PER_STEP * total_steps
23
+ score = normalize(total_reward, min_total, max_total)
24
+ return {"task_id": "task_easy_yield", "score": score}
25
+
26
+
27
+ def grade_chemical_efficiency(
28
+ total_fertilizer: float,
29
+ total_pesticide: float,
30
+ total_steps: int,
31
+ ) -> Dict[str, float]:
32
+ total_chemical_use = total_fertilizer + total_pesticide
33
+ max_chemical_use = MAX_CHEMICAL_PER_STEP * total_steps
34
+ score = 1.0 - normalize(total_chemical_use, 0.0, max_chemical_use)
35
+ return {"task_id": "task_medium_chemical_efficiency", "score": clamp_01(score)}
36
+
37
+
38
+ def grade_sustainability_balance(
39
+ total_yield: float,
40
+ total_fertilizer: float,
41
+ total_pesticide: float,
42
+ ) -> Dict[str, float]:
43
+ ratio = total_yield / (total_fertilizer + total_pesticide + 1.0)
44
+ score = ratio / (ratio + 1.0)
45
+ return {"task_id": "task_hard_sustainability_balance", "score": clamp_01(score)}
46
+
47
+
48
+ def grade_all(
49
+ total_reward: float,
50
+ total_yield: float,
51
+ total_fertilizer: float,
52
+ total_pesticide: float,
53
+ total_steps: int,
54
+ ) -> List[Dict[str, float]]:
55
+ return [
56
+ grade_yield_performance(
57
+ total_reward=total_reward, total_steps=total_steps),
58
+ grade_chemical_efficiency(
59
+ total_fertilizer=total_fertilizer,
60
+ total_pesticide=total_pesticide,
61
+ total_steps=total_steps,
62
+ ),
63
+ grade_sustainability_balance(
64
+ total_yield=total_yield,
65
+ total_fertilizer=total_fertilizer,
66
+ total_pesticide=total_pesticide,
67
+ ),
68
+ ]
uv.lock ADDED
The diff for this file is too large to render. See raw diff