Vidhiii1711 commited on
Commit
fb49915
Β·
1 Parent(s): 04437e7

Updated some files again

Browse files
Dockerfile CHANGED
@@ -10,76 +10,86 @@
10
  # - Standalone environments (with openenv from PyPI/Git)
11
  # The build script (openenv build) handles context detection and sets appropriate build args.
12
 
13
- ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
14
- FROM ${BASE_IMAGE} AS builder
15
 
16
- WORKDIR /app
17
 
18
- # Ensure git is available (required for installing dependencies from VCS)
19
- RUN apt-get update && \
20
- apt-get install -y --no-install-recommends git && \
21
- rm -rf /var/lib/apt/lists/*
22
 
23
- # Build argument to control whether we're building standalone or in-repo
24
- ARG BUILD_MODE=in-repo
25
- ARG ENV_NAME=my_env
26
 
27
- # Copy environment code (always at root of build context)
28
- COPY . /app/env
29
 
30
- # For in-repo builds, openenv is already vendored in the build context
31
- # For standalone builds, openenv will be installed via pyproject.toml
32
- WORKDIR /app/env
33
 
34
- # Ensure uv is available (for local builds where base image lacks it)
35
- RUN if ! command -v uv >/dev/null 2>&1; then \
36
- curl -LsSf https://astral.sh/uv/install.sh | sh && \
37
- mv /root/.local/bin/uv /usr/local/bin/uv && \
38
- mv /root/.local/bin/uvx /usr/local/bin/uvx; \
39
- fi
40
 
41
- # Install dependencies using uv sync
42
- # If uv.lock exists, use it; otherwise resolve on the fly
43
- RUN --mount=type=cache,target=/root/.cache/uv \
44
- if [ -f uv.lock ]; then \
45
- uv sync --frozen --no-install-project --no-editable; \
46
- else \
47
- uv sync --no-install-project --no-editable; \
48
- fi
49
-
50
- RUN --mount=type=cache,target=/root/.cache/uv \
51
- if [ -f uv.lock ]; then \
52
- uv sync --frozen --no-editable; \
53
- else \
54
- uv sync --no-editable; \
55
- fi
56
-
57
- # Final runtime stage
58
- FROM ${BASE_IMAGE}
59
 
60
- WORKDIR /app
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- # Copy the virtual environment from builder
63
- COPY --from=builder /app/env/.venv /app/.venv
64
 
65
- # Copy the environment code
66
- COPY --from=builder /app/env /app/env
67
 
68
- # Set PATH to use the virtual environment
69
- ENV PATH="/app/.venv/bin:$PATH"
70
 
71
- # Set PYTHONPATH so imports work correctly
72
- ENV PYTHONPATH="/app/env:$PYTHONPATH"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
- # Required LLM credentials for inference.py
75
- ENV API_BASE_URL="https://router.huggingface.co/v1"
76
- ENV MODEL_NAME="meta-llama/Llama-3.3-70B-Instruct"
77
- ENV HF_TOKEN=""
78
 
79
- # Health check
80
- HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
81
- CMD curl -f http://localhost:8000/health || exit 1
82
 
83
- # Run the FastAPI server
84
- # The module path is constructed to work with the /app/env structure
85
- CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
 
10
  # - Standalone environments (with openenv from PyPI/Git)
11
  # The build script (openenv build) handles context detection and sets appropriate build args.
12
 
13
+ # ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
14
+ # FROM ${BASE_IMAGE} AS builder
15
 
16
+ # WORKDIR /app
17
 
18
+ # # Ensure git is available (required for installing dependencies from VCS)
19
+ # RUN apt-get update && \
20
+ # apt-get install -y --no-install-recommends git && \
21
+ # rm -rf /var/lib/apt/lists/*
22
 
23
+ # # Build argument to control whether we're building standalone or in-repo
24
+ # ARG BUILD_MODE=in-repo
25
+ # ARG ENV_NAME=my_env
26
 
27
+ # # Copy environment code (always at root of build context)
28
+ # COPY . /app/env
29
 
30
+ # # For in-repo builds, openenv is already vendored in the build context
31
+ # # For standalone builds, openenv will be installed via pyproject.toml
32
+ # WORKDIR /app/env
33
 
34
+ # # Ensure uv is available (for local builds where base image lacks it)
35
+ # RUN if ! command -v uv >/dev/null 2>&1; then \
36
+ # curl -LsSf https://astral.sh/uv/install.sh | sh && \
37
+ # mv /root/.local/bin/uv /usr/local/bin/uv && \
38
+ # mv /root/.local/bin/uvx /usr/local/bin/uvx; \
39
+ # fi
40
 
41
+ # # Install dependencies using uv sync
42
+ # # If uv.lock exists, use it; otherwise resolve on the fly
43
+ # RUN --mount=type=cache,target=/root/.cache/uv \
44
+ # if [ -f uv.lock ]; then \
45
+ # uv sync --frozen --no-install-project --no-editable; \
46
+ # else \
47
+ # uv sync --no-install-project --no-editable; \
48
+ # fi
 
 
 
 
 
 
 
 
 
 
49
 
50
+ # RUN --mount=type=cache,target=/root/.cache/uv \
51
+ # if [ -f uv.lock ]; then \
52
+ # uv sync --frozen --no-editable; \
53
+ # else \
54
+ # uv sync --no-editable; \
55
+ # fi
56
+
57
+ # # Final runtime stage
58
+ # FROM ${BASE_IMAGE}
59
+
60
+ # WORKDIR /app
61
+
62
+ # # Copy the virtual environment from builder
63
+ # COPY --from=builder /app/env/.venv /app/.venv
64
 
65
+ # # Copy the environment code
66
+ # COPY --from=builder /app/env /app/env
67
 
68
+ # # Set PATH to use the virtual environment
69
+ # ENV PATH="/app/.venv/bin:$PATH"
70
 
71
+ # # Set PYTHONPATH so imports work correctly
72
+ # ENV PYTHONPATH="/app/env:$PYTHONPATH"
73
 
74
+ # # Required LLM credentials for inference.py
75
+ # ENV API_BASE_URL="https://router.huggingface.co/v1"
76
+ # ENV MODEL_NAME="meta-llama/Llama-3.3-70B-Instruct"
77
+ # ENV HF_TOKEN=""
78
+
79
+ # # Health check
80
+ # HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
81
+ # CMD curl -f http://localhost:8000/health || exit 1
82
+
83
+ # # Run the FastAPI server
84
+ # # The module path is constructed to work with the /app/env structure
85
+ # CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
86
+
87
+ FROM python:3.10
88
+
89
+ WORKDIR /app
90
 
91
+ COPY . .
 
 
 
92
 
93
+ RUN pip install --no-cache-dir -r server/requirements.txt
 
 
94
 
95
+ CMD ["uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "7860"]
 
 
inference.py CHANGED
@@ -7,7 +7,7 @@ each day based on real weather data, soil moisture, and crop health.
7
  Reads credentials from environment variables:
8
  API_BASE_URL β€” The API endpoint for the LLM
9
  MODEL_NAME β€” The model identifier to use for inference
10
- HF_TOKEN β€” Your Hugging Face / API key
11
 
12
  Emits structured stdout logs in [START] / [STEP] / [END] format
13
  as required by the hackathon evaluation system.
@@ -29,13 +29,11 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
29
  from openai import OpenAI
30
  import time
31
 
32
- # ─────────────────────────────────────────────────────────────
33
  # CREDENTIALS β€” read from environment variables (mandatory)
34
- # ─────────────────────────────────────────────────────────────
35
 
36
  API_BASE_URL = os.environ.get("API_BASE_URL", "https://router.huggingface.co/v1")
37
  MODEL_NAME = os.environ.get("MODEL_NAME", "meta-llama/Llama-3.3-70B-Instruct")
38
- HF_TOKEN = os.environ.get("HF_TOKEN", "")
39
 
40
  if not HF_TOKEN:
41
  print("[ERROR] HF_TOKEN environment variable is not set.", file=sys.stderr)
@@ -200,14 +198,7 @@ def run_task(env, task_id: int, city: str = "Indore") -> dict:
200
  task_name = config["name"]
201
 
202
  # ── [START] log β€” required by hackathon
203
- print(json.dumps({
204
- "event": "START",
205
- "task_id": task_id,
206
- "task_name": task_name,
207
- "city": city,
208
- "model": MODEL_NAME,
209
- "max_steps": max_steps,
210
- }))
211
 
212
  # Reset environment
213
  obs = env.reset(city=city)
@@ -222,6 +213,7 @@ def run_task(env, task_id: int, city: str = "Indore") -> dict:
222
  }
223
 
224
  episode_history = []
 
225
 
226
  action_map = {"none": 0, "low": 1, "medium": 2, "high": 3}
227
 
@@ -243,19 +235,9 @@ def run_task(env, task_id: int, city: str = "Indore") -> dict:
243
  "crop_stage": obs_dict["crop_stage"],
244
  }
245
  episode_history.append(record)
246
- time.sleep(1.5)
247
-
248
- # ── [STEP] log β€” required by hackathon ───────────────
249
- print(json.dumps({
250
- "event": "STEP",
251
- "task_id": task_id,
252
- "step": step + 1,
253
- "day": day,
254
- "observation": obs_dict,
255
- "action": action,
256
- "reason": reason,
257
- }))
258
 
 
259
  # Take action in environment
260
  try:
261
  from models import FarmAction, WaterAmount
@@ -265,7 +247,10 @@ def run_task(env, task_id: int, city: str = "Indore") -> dict:
265
 
266
  farm_action = FarmAction(water_amount=WaterAmount(action))
267
  result = env.step(farm_action)
268
-
 
 
 
269
  if result.done:
270
  break
271
 
@@ -278,24 +263,18 @@ def run_task(env, task_id: int, city: str = "Indore") -> dict:
278
  "day_number": result.day_number,
279
  "crop_stage": result.crop_stage.value,
280
  }
281
- time.sleep(1.5)
282
 
283
  # Grade the episode
284
  grade_task1, grade_task2, grade_task3 = _import_graders()
285
  graders = {1: grade_task1, 2: grade_task2, 3: grade_task3}
286
  score = graders[task_id](episode_history)
287
 
288
- # ── [END] log β€” required by hackathon ────────────────────
289
- print(json.dumps({
290
- "event": "END",
291
- "task_id": task_id,
292
- "task_name": task_name,
293
- "score": score,
294
- "steps_completed": len(episode_history),
295
- "city": city,
296
- "model": MODEL_NAME,
297
- }))
298
-
299
  return {
300
  "task_id": task_id,
301
  "task_name": task_name,
 
7
  Reads credentials from environment variables:
8
  API_BASE_URL β€” The API endpoint for the LLM
9
  MODEL_NAME β€” The model identifier to use for inference
10
+ +_TOKEN β€” Your Hugging Face / API key
11
 
12
  Emits structured stdout logs in [START] / [STEP] / [END] format
13
  as required by the hackathon evaluation system.
 
29
  from openai import OpenAI
30
  import time
31
 
 
32
  # CREDENTIALS β€” read from environment variables (mandatory)
 
33
 
34
  API_BASE_URL = os.environ.get("API_BASE_URL", "https://router.huggingface.co/v1")
35
  MODEL_NAME = os.environ.get("MODEL_NAME", "meta-llama/Llama-3.3-70B-Instruct")
36
+ HF_TOKEN = os.environ.get("HF_TOKEN")
37
 
38
  if not HF_TOKEN:
39
  print("[ERROR] HF_TOKEN environment variable is not set.", file=sys.stderr)
 
198
  task_name = config["name"]
199
 
200
  # ── [START] log β€” required by hackathon
201
+ print(f"[START] task={task_name} env=smart-farm-irrigation model={MODEL_NAME}", flush=True)
 
 
 
 
 
 
 
202
 
203
  # Reset environment
204
  obs = env.reset(city=city)
 
213
  }
214
 
215
  episode_history = []
216
+ rewards_list = []
217
 
218
  action_map = {"none": 0, "low": 1, "medium": 2, "high": 3}
219
 
 
235
  "crop_stage": obs_dict["crop_stage"],
236
  }
237
  episode_history.append(record)
238
+ time.sleep(0.5)
 
 
 
 
 
 
 
 
 
 
 
239
 
240
+ # ── [STEP] log β€” required by hackathon
241
  # Take action in environment
242
  try:
243
  from models import FarmAction, WaterAmount
 
247
 
248
  farm_action = FarmAction(water_amount=WaterAmount(action))
249
  result = env.step(farm_action)
250
+ rewards_list.append(result.reward if result.reward is not None else 0.0)
251
+ reward = result.reward if result.reward is not None else 0.0
252
+ done = result.done
253
+ print(f"[STEP] step={step+1} action={action} reward={reward:.2f} done={str(done).lower()} error=null", flush=True)
254
  if result.done:
255
  break
256
 
 
263
  "day_number": result.day_number,
264
  "crop_stage": result.crop_stage.value,
265
  }
266
+ time.sleep(0.5)
267
 
268
  # Grade the episode
269
  grade_task1, grade_task2, grade_task3 = _import_graders()
270
  graders = {1: grade_task1, 2: grade_task2, 3: grade_task3}
271
  score = graders[task_id](episode_history)
272
 
273
+ # ── [END] log β€” required by hackathon
274
+ rewards_str = ",".join(f"{r:.2f}" for r in rewards_list)
275
+ success = score >= 0.5
276
+ print(f"[END] success={str(success).lower()} steps={len(episode_history)} score={score:.3f} rewards={rewards_str}", flush=True)
277
+
 
 
 
 
 
 
278
  return {
279
  "task_id": task_id,
280
  "task_name": task_name,
server/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Smart Farm Irrigation environment server components."""
8
+
9
+ from .my_env_environment import FarmEnvironment
10
+
11
+ __all__ = ["FarmEnvironment"]
server/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (335 Bytes). View file
 
server/__pycache__/__init__.cpython-314.pyc ADDED
Binary file (327 Bytes). View file
 
server/__pycache__/app.cpython-313.pyc ADDED
Binary file (10.2 kB). View file
 
server/__pycache__/app.cpython-314.pyc ADDED
Binary file (8.53 kB). View file
 
server/__pycache__/my_env_environment.cpython-313.pyc ADDED
Binary file (8.59 kB). View file
 
server/__pycache__/my_env_environment.cpython-314.pyc ADDED
Binary file (8.89 kB). View file
 
server/app.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ FastAPI application for the Smart Farm Irrigation Environment.
9
+
10
+ Endpoints:
11
+ - POST /reset: Reset the environment
12
+ - POST /step: Execute an action
13
+ - GET /state: Get current environment state
14
+ - GET /schema: Get action/observation schemas
15
+ - WS /ws: WebSocket endpoint for persistent sessions
16
+
17
+ # Mandatory Hackathon Endpoints:
18
+ - GET /tasks: Returns list of all tasks + action schema
19
+ - POST /grader: Returns score after episode ends
20
+ - GET /baseline: Runs baseline agent, returns all 3 scores
21
+ """
22
+
23
+ try:
24
+ from openenv.core.env_server.http_server import create_app
25
+ except Exception as e: # pragma: no cover
26
+ raise ImportError(
27
+ "openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
28
+ ) from e
29
+
30
+ try:
31
+ from ..models import FarmAction, FarmObservation
32
+ from .my_env_environment import FarmEnvironment
33
+ except (ModuleNotFoundError, ImportError):
34
+ try:
35
+ from models import FarmAction, FarmObservation
36
+ from server.my_env_environment import FarmEnvironment
37
+ except ModuleNotFoundError:
38
+ import sys
39
+ import os
40
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
41
+ from models import FarmAction, FarmObservation
42
+ from server.my_env_environment import FarmEnvironment
43
+
44
+ from fastapi import Request
45
+ from fastapi.responses import JSONResponse,FileResponse
46
+ from fastapi.staticfiles import StaticFiles
47
+ import os
48
+
49
+ # Create the app with web interface and README integration
50
+ app = create_app(
51
+ FarmEnvironment,
52
+ FarmAction,
53
+ FarmObservation,
54
+ env_name="smart-farm-irrigation",
55
+ max_concurrent_envs=1,
56
+ )
57
+ from fastapi.middleware.cors import CORSMiddleware
58
+
59
+ # Serve the UI
60
+ @app.get("/ui")
61
+ async def serve_ui():
62
+ ui_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "smart-farm-ui.html")
63
+ return FileResponse(ui_path, media_type="text/html")
64
+ app.add_middleware(
65
+ CORSMiddleware,
66
+ allow_origins=["*"], # In production, replace * with your frontend URL
67
+ allow_methods=["*"],
68
+ allow_headers=["*"],
69
+ )
70
+
71
+ # MANDATORY ENDPOINT 1 β€” /tasks
72
+ # Returns list of tasks and action schema
73
+ @app.get("/tasks")
74
+ async def get_tasks():
75
+ """
76
+ Returns all 3 tasks and the action schema.
77
+ Mandatory endpoint for hackathon submission.
78
+ """
79
+ try:
80
+ from tasks import get_all_tasks
81
+ except ImportError:
82
+ try:
83
+ from my_env.tasks import get_all_tasks
84
+ except ImportError:
85
+ import sys, os
86
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
87
+ from tasks import get_all_tasks
88
+
89
+ return JSONResponse(content=get_all_tasks())
90
+
91
+ # MANDATORY ENDPOINT 2 β€” /grader
92
+ # Returns score after episode ends
93
+ @app.post("/grader")
94
+ async def grade_episode(request: Request):
95
+ """
96
+ Grades a completed episode and returns score.
97
+
98
+ Expected request body:
99
+ {
100
+ "task_id": 1,
101
+ "episode_history": [
102
+ {
103
+ "day": 1,
104
+ "soil_moisture": 55.0,
105
+ "crop_health": "good",
106
+ "water_action": 2,
107
+ "rainfall": 0.0
108
+ },
109
+ ...
110
+ ]
111
+ }
112
+
113
+ Returns score between 0.0 and 1.0
114
+ """
115
+ try:
116
+ from graders import grade_task1, grade_task2, grade_task3
117
+ except ImportError:
118
+ try:
119
+ from my_env.graders import grade_task1, grade_task2, grade_task3
120
+ except ImportError:
121
+ import sys, os
122
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
123
+ from graders import grade_task1, grade_task2, grade_task3
124
+
125
+ try:
126
+ body = await request.json()
127
+ task_id = body.get("task_id", 1)
128
+ episode_history = body.get("episode_history", [])
129
+
130
+ # Select correct grader
131
+ graders = {
132
+ 1: grade_task1,
133
+ 2: grade_task2,
134
+ 3: grade_task3,
135
+ }
136
+
137
+ if task_id not in graders:
138
+ return JSONResponse(
139
+ content={"error": f"Invalid task_id: {task_id}. Must be 1, 2, or 3"},
140
+ status_code=400
141
+ )
142
+
143
+ score = graders[task_id](episode_history)
144
+
145
+ return JSONResponse(content={
146
+ "task_id": task_id,
147
+ "score": score,
148
+ "min_score": 0.0,
149
+ "max_score": 1.0,
150
+ })
151
+
152
+ except Exception as e:
153
+ return JSONResponse(
154
+ content={"error": str(e)},
155
+ status_code=500
156
+ )
157
+
158
+ # MANDATORY ENDPOINT 3 β€” /baseline
159
+ # Runs baseline agent, returns all scores
160
+ @app.get("/baseline")
161
+ async def run_baseline(city: str = "Indore"):
162
+ """
163
+ Runs the baseline rule-based agent through all 3 tasks
164
+ and returns reproducible scores.
165
+
166
+ Query params:
167
+ city: City name for weather data (default: Indore)
168
+
169
+ Returns scores for all 3 tasks + average score
170
+ """
171
+ try:
172
+ from baseline import main as run_baseline_agent
173
+ except ImportError:
174
+ try:
175
+ from my_env.baseline import main as run_baseline_agent
176
+ except ImportError:
177
+ import sys, os
178
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
179
+ from baseline import main as run_baseline_agent
180
+
181
+ try:
182
+ results = run_baseline_agent(city=city)
183
+
184
+ # Format results for response
185
+ scores = {}
186
+ for result in results:
187
+ scores[f"task_{result['task_id']}"] = {
188
+ "name": result["task_name"],
189
+ "score": result["score"],
190
+ "steps_completed": result["steps_completed"],
191
+ }
192
+
193
+ avg = sum(r["score"] for r in results) / len(results)
194
+
195
+ return JSONResponse(content={
196
+ "city": city,
197
+ "agent": "Simple Rule-Based Agent",
198
+ "scores": scores,
199
+ "average_score": round(avg, 2),
200
+ "status": "success"
201
+ })
202
+
203
+ except Exception as e:
204
+ return JSONResponse(
205
+ content={"error": str(e)},
206
+ status_code=500
207
+ )
208
+
209
+ @app.post("/inference-step")
210
+ async def inference_step(request: Request):
211
+ """
212
+ Single step LLM decision for UI.
213
+ """
214
+ try:
215
+ from inference import llm_decide
216
+ except ImportError:
217
+ import sys, os
218
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
219
+ from inference import llm_decide
220
+
221
+ try:
222
+ body = await request.json()
223
+ observation = body.get("observation", {})
224
+ task_id = body.get("task_id", 1)
225
+ day = body.get("day", 1)
226
+ max_days = body.get("max_days", 7)
227
+
228
+ action, reason = llm_decide(observation, task_id, day, max_days)
229
+
230
+ return JSONResponse(content={
231
+ "action": action,
232
+ "reason": reason
233
+ })
234
+
235
+ except Exception as e:
236
+ return JSONResponse(
237
+ content={"error": str(e)},
238
+ status_code=500
239
+ )
240
+
241
+ def main(host: str = "0.0.0.0", port: int = 8000):
242
+ """
243
+ Entry point for direct execution via uv run or python -m.
244
+ """
245
+ import uvicorn
246
+ uvicorn.run(app, host=host, port=port)
247
+
248
+
249
+ if __name__ == "__main__":
250
+ import argparse
251
+
252
+ parser = argparse.ArgumentParser()
253
+ parser.add_argument("--port", type=int, default=8000)
254
+ args = parser.parse_args()
255
+ main(port=args.port)
server/my_env_environment.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """
8
+ Smart Farm Irrigation Environment Implementation.
9
+
10
+ A real-world environment where an AI agent manages crop irrigation
11
+ by deciding how much water to give crops each day based on:
12
+ - Weather conditions (temperature, rainfall) from real Weather API
13
+ - Soil moisture (from sensor or auto-calculated)
14
+ - Crop health (user input)
15
+ - Crop stage (auto-managed by code)
16
+ """
17
+
18
+ from uuid import uuid4
19
+
20
+ from openenv import Environment
21
+ from openenv.core.env_server.types import State
22
+
23
+ try:
24
+ from ..models import FarmAction, FarmObservation, CropStage, CropHealthStatus
25
+ from ..weather import WeatherService
26
+ except ImportError:
27
+ from models import FarmAction, FarmObservation, CropStage, CropHealthStatus
28
+ from weather import WeatherService
29
+
30
+
31
+ class FarmEnvironment(Environment):
32
+ """
33
+ Smart Farm Irrigation Environment.
34
+
35
+ The AI agent decides how much to water crops every day.
36
+ The environment simulates soil moisture, crop health,
37
+ weather conditions, and crop growth stages.
38
+ """
39
+
40
+ SUPPORTS_CONCURRENT_SESSIONS: bool = True
41
+
42
+ def __init__(self):
43
+ """Initialize the farm environment with default values."""
44
+ self._state = State(episode_id=str(uuid4()), step_count=0)
45
+
46
+ # --- Weather Service ---
47
+ self._weather_service = WeatherService()
48
+ self._city = "Indore"
49
+
50
+ # --- Farm State Variables ---
51
+ self._day = 1
52
+ self._soil_moisture = 30.0
53
+ self._crop_health = CropHealthStatus.FAIR
54
+ self._temperature = 30.0
55
+ self._rainfall = 0.0
56
+ self._crop_stage = CropStage.SEEDLING
57
+ self._sensor_moisture = None
58
+
59
+ def reset(
60
+ self,
61
+ city: str = "Indore",
62
+ sensor_moisture: float = None,
63
+ crop_health: str = "fair"
64
+ ) -> FarmObservation:
65
+ """
66
+ Reset the farm to Day 1 fresh state.
67
+ Fetches real weather data for the given city.
68
+
69
+ Args:
70
+ city: City name for weather data
71
+ sensor_moisture: Soil moisture from sensor (optional)
72
+ crop_health: User selected crop health status
73
+ """
74
+ self._state = State(episode_id=str(uuid4()), step_count=0)
75
+
76
+ # --- Fetch Real Weather Data ---
77
+ self._city = city
78
+ weather = self._weather_service.get_weather(city)
79
+ self._temperature = weather["temperature"]
80
+ self._rainfall = weather["rainfall"]
81
+
82
+ print(f"Weather for {city}: {self._temperature}C, {self._rainfall}mm rain")
83
+
84
+ # --- Soil Moisture ---
85
+ if sensor_moisture is not None:
86
+ # User has a sensor β€” use their reading
87
+ self._soil_moisture = sensor_moisture
88
+ print(f"Soil moisture from sensor: {self._soil_moisture}%")
89
+ else:
90
+ # No sensor β€” calculate from weather
91
+ self._soil_moisture = self._weather_service.calculate_soil_moisture(
92
+ current_moisture=50.0,
93
+ temperature=self._temperature,
94
+ rainfall=self._rainfall
95
+ )
96
+ print(f"Soil moisture calculated: {self._soil_moisture}%")
97
+
98
+ # --- Crop Health from User ---
99
+ try:
100
+ self._crop_health = CropHealthStatus(crop_health)
101
+ except ValueError:
102
+ self._crop_health = CropHealthStatus.FAIR
103
+
104
+ # --- Reset Other Values ---
105
+ self._day = 1
106
+ self._crop_stage = CropStage.SEEDLING
107
+
108
+ return FarmObservation(
109
+ temperature=self._temperature,
110
+ rainfall=self._rainfall,
111
+ soil_moisture=self._soil_moisture,
112
+ crop_health=self._crop_health,
113
+ day_number=self._day,
114
+ crop_stage=self._crop_stage,
115
+ done=False,
116
+ reward=0.0,
117
+ )
118
+
119
+ def step(self, action: FarmAction) -> FarmObservation:
120
+ """
121
+ Execute one day of farming.
122
+ AI provides water_amount, environment updates accordingly.
123
+ """
124
+ self._state.step_count += 1
125
+
126
+ # --- Water Amount Mapping ---
127
+ water_map = {
128
+ "none": 0,
129
+ "low": 10,
130
+ "medium": 25,
131
+ "high": 50,
132
+ }
133
+ water_added = water_map.get(action.water_amount.value, 0)
134
+
135
+ # --- Use real historical weather for each day ---
136
+ weather = self._weather_service.get_historical_weather(
137
+ self._city, self._day
138
+ )
139
+ self._temperature = weather["temperature"]
140
+ self._rainfall = weather["rainfall"]
141
+
142
+ # --- Update Soil Moisture ---
143
+ if self._sensor_moisture is not None:
144
+ # sensor user β€” just add water and subtract evaporation
145
+ evaporation = (self._temperature / 100) * 10
146
+ self._soil_moisture = self._soil_moisture + water_added - evaporation
147
+ else:
148
+ # no sensor β€” use weather calculator
149
+ self._soil_moisture = self._weather_service.calculate_soil_moisture(
150
+ current_moisture=self._soil_moisture + water_added,
151
+ temperature=self._temperature,
152
+ rainfall=self._rainfall
153
+ )
154
+
155
+ # Keep moisture in valid range 0-100
156
+ self._soil_moisture = max(0.0, min(100.0, self._soil_moisture))
157
+
158
+ # --- Update Crop Health based on moisture ---
159
+ health_order = ["poor", "fair", "good", "excellent"]
160
+ current_idx = health_order.index(self._crop_health.value)
161
+
162
+ if self._soil_moisture < 20 or self._soil_moisture > 90:
163
+ # Very wrong moisture β€” health degrades
164
+ new_idx = max(0, current_idx - 1)
165
+ self._crop_health = CropHealthStatus(health_order[new_idx])
166
+ elif 40 <= self._soil_moisture <= 75:
167
+ # Good moisture β€” health improves
168
+ new_idx = min(3, current_idx + 1)
169
+ self._crop_health = CropHealthStatus(health_order[new_idx])
170
+ # else: moisture okay but not ideal β€” health stays same
171
+
172
+ # --- Advance Day ---
173
+ self._day += 1
174
+
175
+ # --- Auto Update Crop Stage based on day ---
176
+ if self._day <= 10:
177
+ self._crop_stage = CropStage.SEEDLING
178
+ elif self._day <= 20:
179
+ self._crop_stage = CropStage.GROWING
180
+ else:
181
+ self._crop_stage = CropStage.MATURE
182
+
183
+ # --- Calculate Reward ---
184
+ reward = self._calculate_reward(water_added)
185
+
186
+ # --- Is episode done? ---
187
+ done = self._day > 30
188
+
189
+ return FarmObservation(
190
+ temperature=self._temperature,
191
+ rainfall=self._rainfall,
192
+ soil_moisture=self._soil_moisture,
193
+ crop_health=self._crop_health,
194
+ day_number=min(self._day, 30),
195
+ crop_stage=self._crop_stage,
196
+ done=done,
197
+ reward=reward,
198
+ )
199
+
200
+ def _calculate_reward(self, water_added: float) -> float:
201
+ """
202
+ Calculate reward based on soil moisture and water usage.
203
+ Returns value between -1.0 and 1.0
204
+ """
205
+ # Ideal moisture ranges per crop stage
206
+ ideal_ranges = {
207
+ CropStage.SEEDLING: (40, 70),
208
+ CropStage.GROWING: (45, 70),
209
+ CropStage.MATURE: (35, 60),
210
+ }
211
+
212
+ low, high = ideal_ranges[self._crop_stage]
213
+
214
+ # Perfect moisture range
215
+ if low <= self._soil_moisture <= high:
216
+ reward = 1.0
217
+
218
+ # Acceptable but not ideal
219
+ elif (low - 10) <= self._soil_moisture <= (high + 10):
220
+ reward = 0.5
221
+
222
+ # Too dry
223
+ elif self._soil_moisture < 20:
224
+ reward = -1.0
225
+
226
+ # Too wet
227
+ elif self._soil_moisture > 90:
228
+ reward = -0.5
229
+
230
+ else:
231
+ reward = 0.0
232
+
233
+ # Penalize watering on rainy days (water waste)
234
+ if self._rainfall > 15 and water_added > 0:
235
+ reward -= 0.3
236
+
237
+ return round(max(-1.0, min(1.0, reward)), 2)
238
+
239
+ @property
240
+ def state(self) -> State:
241
+ """Return current environment state."""
242
+ return self._state
server/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # openenv[core]>=0.2.0
2
+ openenv==0.1.13
3
+ fastapi>=0.115.0
4
+ uvicorn>=0.24.0
5
+ requests>=2.32.0
6
+
7
+