File size: 11,988 Bytes
9b12a80
 
 
 
 
 
 
 
 
fb49915
9b12a80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04437e7
 
9b12a80
04437e7
9b12a80
 
 
04437e7
9b12a80
fb49915
9b12a80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04437e7
 
 
 
 
 
9b12a80
 
 
 
 
 
 
 
 
 
04437e7
 
 
 
 
 
 
9b12a80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04437e7
fb49915
9b12a80
 
 
 
 
 
 
 
 
 
 
 
 
 
fb49915
9b12a80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb49915
9b12a80
fb49915
9b12a80
 
 
 
 
 
 
 
 
fb49915
 
 
 
9b12a80
 
 
 
 
 
 
 
 
 
 
 
fb49915
9b12a80
 
 
 
 
 
fb49915
 
 
 
 
9b12a80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
"""
inference.py β€” LLM-Powered Inference Script for Smart Farm Irrigation Environment.

Uses an LLM (via OpenAI-compatible client) to decide how much to water crops
each day based on real weather data, soil moisture, and crop health.

Reads credentials from environment variables:
    API_BASE_URL  β€” The API endpoint for the LLM
    MODEL_NAME    β€” The model identifier to use for inference
    +_TOKEN      β€” Your Hugging Face / API key

Emits structured stdout logs in [START] / [STEP] / [END] format
as required by the hackathon evaluation system.

Usage:
    export API_BASE_URL="https://api-inference.huggingface.co/v1"
    export MODEL_NAME="meta-llama/Llama-3.3-70B-Instruct"
    export HF_TOKEN="hf_xxxxxxxxxxxxxxxxxxxx"
    python inference.py
    python inference.py --city Mumbai --task 2
"""

import os
import sys
import json
import argparse
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "my_env"))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from openai import OpenAI
import time

# CREDENTIALS β€” read from environment variables (mandatory)

API_BASE_URL = os.environ.get("API_BASE_URL", "https://router.huggingface.co/v1")
MODEL_NAME   = os.environ.get("MODEL_NAME",   "meta-llama/Llama-3.3-70B-Instruct")
HF_TOKEN     = os.environ.get("HF_TOKEN")

if not HF_TOKEN:
    print("[ERROR] HF_TOKEN environment variable is not set.", file=sys.stderr)
    print("        export HF_TOKEN='your_hf_token'",      file=sys.stderr)
    sys.exit(1)

# OpenAI-compatible client pointed at HF Inference API

client = OpenAI(
    base_url=API_BASE_URL,
    api_key=HF_TOKEN,
)

# SYSTEM PROMPT β€” tells the LLM its role

SYSTEM_PROMPT = """You are an expert AI agricultural advisor helping farmers in India manage crop irrigation.

Every day you receive the current farm state and must decide how much water to give the crops.

You MUST respond with ONLY a valid JSON object β€” no explanation, no markdown, no extra text.
The JSON must have exactly these two fields:
{
  "action": "none" | "low" | "medium" | "high",
  "reason": "one short sentence explaining why"
}

Watering options:
- "none"   = 0mm   β€” use when soil is already wet or it is raining heavily
- "low"    = 10mm  β€” use when soil is slightly dry
- "medium" = 25mm  β€” use when soil is moderately dry
- "high"   = 50mm  β€” use when soil is very dry or temperature is extreme

Crop stage moisture targets:
- Seedling (Day 1-10):  keep soil moisture 50-75%
- Growing  (Day 11-20): keep soil moisture 45-70%
- Mature   (Day 21-30): keep soil moisture 35-60%

Rules:
1. NEVER water heavily (high) if rainfall > 15mm today β€” that wastes water
2. On very hot days (>= 38Β°C) with dry soil (< 40%), always use "high"
3. If soil moisture is already above 75%, use "none" unless stage demands more
4. Consider crop stage when deciding target moisture range
"""

# LLM DECISION FUNCTION

def llm_decide(observation: dict, task_id: int, day: int, max_days: int) -> tuple[str, str]:
    """
    Ask the LLM to decide how much to water today.

    Args:
        observation: Current farm state dict
        task_id:     Which task (1, 2, or 3)
        day:         Current day number
        max_days:    Total days in this task

    Returns:
        Tuple of (action, reason)
        action is one of: "none", "low", "medium", "high"
    """
    user_prompt = f"""Current farm state β€” Day {day} of {max_days} (Task {task_id}):

- Temperature:  {observation.get('temperature', 30):.1f}Β°C
- Rainfall:     {observation.get('rainfall', 0):.1f} mm today
- Soil Moisture:{observation.get('soil_moisture', 50):.1f}%
- Crop Health:  {observation.get('crop_health', 'fair')}
- Crop Stage:   {observation.get('crop_stage', 'seedling')}
- Day:          {day} / {max_days}

Based on this, how much should we water the crops today?
Respond ONLY with JSON: {{"action": "...", "reason": "..."}}"""

    try:
        response = client.chat.completions.create(
            model=MODEL_NAME,
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user",   "content": user_prompt},
            ],
            max_tokens=100,
            temperature=0.1,   # low temp for consistent, deterministic decisions
        )

        raw = response.choices[0].message.content.strip()

        # Strip markdown code blocks if model adds them
        if raw.startswith("```"):
            raw = raw.split("```")[1]
            if raw.startswith("json"):
                raw = raw[4:]
            raw = raw.strip()

        parsed = json.loads(raw)
        action = parsed.get("action", "medium").lower().strip()
        reason = parsed.get("reason", "LLM decision")

        # Validate action is one of the allowed values
        if action not in ("none", "low", "medium", "high"):
            print(f"[WARN] LLM returned invalid action '{action}', defaulting to 'medium'", file=sys.stderr)
            action = "medium"
            reason = "Defaulted to medium (invalid LLM output)"

        return action, reason

    except json.JSONDecodeError as e:
        print(f"[WARN] JSON parse error: {e}. Raw response: {raw[:200]}", file=sys.stderr)
        return "medium", "Fallback: JSON parse error"

    except Exception as e:
        print(f"[WARN] LLM call failed: {e}. Using fallback.", file=sys.stderr)
        return "medium", "Fallback: LLM call failed"

# GRADERS (local import β€” same as in graders.py)

def _import_graders():
    """Import grader functions from local graders.py."""
    root_dir   = os.path.dirname(os.path.abspath(__file__))
    my_env_dir = os.path.join(root_dir, "my_env")

    sys.path.insert(0, root_dir)
    sys.path.insert(0, my_env_dir)

    try:
        from graders import grade_task1, grade_task2, grade_task3
        return grade_task1, grade_task2, grade_task3
    except ImportError as e:
        print(f"[ERROR] Cannot import graders.py: {e}", file=sys.stderr)
        sys.exit(1)

# ENVIRONMENT IMPORT
def _import_env():
    """Import FarmEnvironment from local server module."""
    # Add my_env to path since inference.py runs from project root
    root_dir   = os.path.dirname(os.path.abspath(__file__))
    my_env_dir = os.path.join(root_dir, "my_env")
    
    sys.path.insert(0, root_dir)
    sys.path.insert(0, my_env_dir)

    try:
        from server.my_env_environment import FarmEnvironment
        return FarmEnvironment
    except ImportError as e:
        print(f"[ERROR] Cannot import FarmEnvironment: {e}", file=sys.stderr)
        sys.exit(1)

# RUN ONE TASK

def run_task(env, task_id: int, city: str = "Indore") -> dict:
    """
    Run the LLM agent through one task.
    Emits [START], [STEP], [END] structured logs as required.
    """
    task_config = {
        1: {"max_steps": 7,  "name": "Basic Moisture Control"},
        2: {"max_steps": 14, "name": "Weather Adaptive Irrigation"},
        3: {"max_steps": 30, "name": "Full Season Management"},
    }

    config    = task_config[task_id]
    max_steps = config["max_steps"]
    task_name = config["name"]

    # ── [START] log β€” required by hackathon 
    print(f"[START] task={task_name} env=smart-farm-irrigation model={MODEL_NAME}", flush=True)

    # Reset environment
    obs = env.reset(city=city)

    obs_dict = {
        "temperature":   obs.temperature,
        "rainfall":      obs.rainfall,
        "soil_moisture": obs.soil_moisture,
        "crop_health":   obs.crop_health.value,
        "day_number":    obs.day_number,
        "crop_stage":    obs.crop_stage.value,
    }

    episode_history = []
    rewards_list = []

    action_map = {"none": 0, "low": 1, "medium": 2, "high": 3}

    for step in range(max_steps):
        day = obs_dict["day_number"]

        # Ask LLM to decide
        action, reason = llm_decide(obs_dict, task_id, day, max_steps)

        # Record BEFORE taking action (matches grader expectations)
        record = {
            "day":           day,
            "day_number":    day,           # both keys for safety
            "soil_moisture": obs_dict["soil_moisture"],
            "crop_health":   obs_dict["crop_health"],
            "water_action":  action_map[action],
            "rainfall":      obs_dict["rainfall"],
            "temperature":   obs_dict["temperature"],
            "crop_stage":    obs_dict["crop_stage"],
        }
        episode_history.append(record)
        time.sleep(0.5)

        # ── [STEP] log β€” required by hackathon
        # Take action in environment
        try:
            from models import FarmAction, WaterAmount
        except ImportError:
            sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
            from models import FarmAction, WaterAmount

        farm_action = FarmAction(water_amount=WaterAmount(action))
        result = env.step(farm_action)
        rewards_list.append(result.reward if result.reward is not None else 0.0)
        reward = result.reward if result.reward is not None else 0.0
        done = result.done
        print(f"[STEP] step={step+1} action={action} reward={reward:.2f} done={str(done).lower()} error=null", flush=True)
        if result.done:
            break

        # Update observation for next step
        obs_dict = {
            "temperature":   result.temperature,
            "rainfall":      result.rainfall,
            "soil_moisture": result.soil_moisture,
            "crop_health":   result.crop_health.value,
            "day_number":    result.day_number,
            "crop_stage":    result.crop_stage.value,
        }
        time.sleep(0.5)

    # Grade the episode
    grade_task1, grade_task2, grade_task3 = _import_graders()
    graders = {1: grade_task1, 2: grade_task2, 3: grade_task3}
    score = graders[task_id](episode_history)

    # ── [END] log β€” required by hackathon
    rewards_str = ",".join(f"{r:.2f}" for r in    rewards_list)
    success = score >= 0.5
    print(f"[END] success={str(success).lower()} steps={len(episode_history)} score={score:.3f} rewards={rewards_str}", flush=True)
   
    return {
        "task_id":         task_id,
        "task_name":       task_name,
        "score":           score,
        "steps_completed": len(episode_history),
        "episode_history": episode_history,
    }

# MAIN
def main(city: str = "Indore", task_id: int = None):
    """
    Run LLM agent through all 3 tasks (or a specific task).
    """
    FarmEnvironment = _import_env()
    env = FarmEnvironment()

    tasks_to_run = [task_id] if task_id else [1, 2, 3]

    results = []
    for tid in tasks_to_run:
        result = run_task(env, tid, city=city)
        results.append(result)

    # Final summary to stderr (not stdout β€” stdout is for structured logs only)
    print("\n" + "="*50, file=sys.stderr)
    print("  SMART FARM β€” LLM AGENT FINAL SCORES",   file=sys.stderr)
    print("="*50,                                      file=sys.stderr)
    print(f"City:  {city}",                            file=sys.stderr)
    print(f"Model: {MODEL_NAME}",                      file=sys.stderr)
    for r in results:
        print(f"Task {r['task_id']} ({r['task_name']}): {r['score']}", file=sys.stderr)
    avg = sum(r["score"] for r in results) / len(results)
    print(f"Average: {round(avg, 2)}",                 file=sys.stderr)
    print("="*50,                                      file=sys.stderr)

    return results


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="LLM inference agent for Smart Farm Irrigation Environment"
    )
    parser.add_argument(
        "--city",
        type=str,
        default="Indore",
        help="City name for weather data (default: Indore)"
    )
    parser.add_argument(
        "--task",
        type=int,
        default=None,
        choices=[1, 2, 3],
        help="Run a specific task only (default: run all 3 tasks)"
    )
    args = parser.parse_args()
    main(city=args.city, task_id=args.task)