File size: 11,995 Bytes
bbc1784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d20aef
bbc1784
 
bbe8627
bbc1784
 
 
 
 
 
 
 
 
bbe8627
 
 
 
 
bbc1784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d20aef
 
bbc1784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d20aef
bbc1784
 
 
bbe8627
bbc1784
5d20aef
 
bbc1784
 
 
5d20aef
 
 
 
bbc1784
5d20aef
bbc1784
 
5d20aef
 
bbc1784
 
 
 
 
 
5d20aef
6a5b308
 
5d20aef
 
 
 
 
 
bbc1784
 
 
5d20aef
 
 
 
 
bbc1784
 
5d20aef
bbc1784
5d20aef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a5b308
 
5d20aef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a5b308
 
bbc1784
 
 
 
5d20aef
 
 
 
 
 
 
bbe8627
bbc1784
 
 
 
 
bbe8627
bbc1784
 
 
 
 
5d20aef
 
 
bbc1784
5d20aef
bbc1784
 
5d20aef
 
bbc1784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d20aef
bbc1784
 
 
 
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
#!/usr/bin/env python3
# Copyright (c) 2026 CtrlAltWin Team
"""
Tiffin Packer β€” OpenEnv Inference Script.

Runs an LLM agent against the tiffin packing environment using the
OpenAI Client API with environment variables:
    API_BASE_URL  β€” The API endpoint for the LLM
    MODEL_NAME    β€” The model identifier for inference
    HF_TOKEN      β€” Hugging Face / API key

Usage:
    API_BASE_URL=https://api.openai.com/v1 \
    MODEL_NAME=gpt-4o \
    HF_TOKEN=your-key \
    python inference.py
"""

import json
import os
import sys
import time
import traceback

import requests
from openai import OpenAI

# ---------------------------------------------------------------------------
# Required environment variables
# ---------------------------------------------------------------------------
API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o")
HF_TOKEN = os.environ.get("HF_TOKEN", "")
ENV_URL = os.environ.get("ENV_URL", "http://localhost:7860")

if not HF_TOKEN:
    print("WARNING: HF_TOKEN not set. LLM calls will fail.", flush=True)

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

# ---------------------------------------------------------------------------
# System prompt
# ---------------------------------------------------------------------------
SYSTEM_PROMPT = """You are a tiffin packing assistant that controls a robotic arm.
Your goal: pack Indian meal items into the correct tiffin containers.

COMMANDS β€” respond with ONLY a JSON object, no other text:
  {"command": "observe"}                    β€” See the full scene
  {"command": "identify", "target_id": N}   β€” Classify food item N using VLM
  {"command": "pick", "target_id": N}       β€” Pick up food item N
  {"command": "place", "target_id": N}      β€” Place held item into container N
  {"command": "pour", "target_id": N}       β€” Pour held liquid into container N

PACKING RULES:
1. ALWAYS identify items before packing (you cannot see food properties otherwise)
2. Liquids (sambar, dal, rasam, curry) β†’ sealed containers only
3. Solids (rice, chapati, idli) β†’ any container type
4. Semi-solids (curd, pickle, chutney) β†’ sealed containers preferred
5. FRAGILE items (papad=0.9, chapati=0.7) β†’ don't crush under heavy items
6. HOT and COLD food must NOT share a container
7. Don't overflow containers β€” check volume math!
8. Strong-flavor items (pickle, chutney) should be isolated

STRATEGY:
1. First: observe the scene
2. Then: identify ALL food items (one by one)
3. Then: plan which food goes where based on constraints
4. Finally: pick and place/pour each item

Respond with ONLY valid JSON. No explanation, no markdown, no extra text."""




def parse_action(text: str) -> dict:
    """Parse LLM output into an action dict."""
    text = text.strip()

    # Try to extract JSON from the text
    if text.startswith("```"):
        # Handle markdown code blocks
        lines = text.split("\n")
        json_lines = [l for l in lines if not l.startswith("```")]
        text = "\n".join(json_lines).strip()

    # Try direct JSON parse
    try:
        action = json.loads(text)
        if "command" in action:
            return action
    except json.JSONDecodeError:
        pass

    # Try to find JSON in the text
    for i in range(len(text)):
        if text[i] == "{":
            for j in range(len(text) - 1, i, -1):
                if text[j] == "}":
                    try:
                        action = json.loads(text[i : j + 1])
                        if "command" in action:
                            return action
                    except json.JSONDecodeError:
                        continue

    # Fallback
    print(f"  [WARN] Could not parse action: {text[:100]}", flush=True)
    return {"command": "observe"}


def run_episode(task_id: str) -> dict:
    """Run one episode of the tiffin packing task."""
    # Emit [START] structured output for the validator
    print(f"[START] task={task_id}", flush=True)

    step = 0

    try:
        print(f"\n{'='*60}", flush=True)
        print(f"  TASK: {task_id.upper()}", flush=True)
        print(f"{'='*60}", flush=True)

        # Reset the environment
        try:
            resp = requests.post(
                f"{ENV_URL}/reset",
                json={"task_id": task_id, "seed": 42},
                timeout=30,
            )
            resp.raise_for_status()
            result = resp.json()
            obs = result.get("observation", result)
        except Exception as e:
            print(f"  ERROR: Failed to reset environment: {e}", flush=True)
            print(f"[END] task={task_id} score=0.0001 steps=0", flush=True)
            return {"task_id": task_id, "total_reward": 0.0, "reward": 0.0, "score": 0.0001, "steps": 0, "error": str(e)}

        # Initialize conversation
        init_scene = obs.get("scene_description", "")
        init_feedback = obs.get("step_feedback", "")
        messages = [
            {"role": "system", "content": SYSTEM_PROMPT},
            {
                "role": "user",
                "content": (
                    f"Task: {task_id}\n\n"
                    f"{init_feedback}\n\n"
                    f"Scene:\n{init_scene}\n\n"
                    f"Available commands: {obs.get('available_commands', [])}\n\n"
                    f"What is your first action? Respond with JSON only."
                ),
            },
        ]

        total_reward = 0.0
        max_steps = 35  # safety limit

        while not obs.get("done", False) and step < max_steps:
            step += 1

            # Get LLM decision
            try:
                response = client.chat.completions.create(
                    model=MODEL_NAME,
                    messages=messages,
                    temperature=0.0,
                    max_tokens=200,
                )
                action_text = response.choices[0].message.content.strip()
            except Exception as e:
                print(f"  [Step {step}] LLM error: {e}", flush=True)
                action_text = '{"command": "observe"}'

            action = parse_action(action_text)
            print(f"  [Step {step}] Action: {json.dumps(action)}", flush=True)

            # Execute step
            try:
                resp = requests.post(
                    f"{ENV_URL}/step",
                    json={"action": action},
                    timeout=30,
                )
                resp.raise_for_status()
                result = resp.json()
                obs = result.get("observation", result)
                reward = result.get("reward", obs.get("reward", 0.0))
                total_reward += reward or 0
                # Emit [STEP] structured output for the validator
                print(f"[STEP] step={step} reward={reward}", flush=True)
            except Exception as e:
                print(f"  [Step {step}] Step error: {e}", flush=True)
                break

            # Print feedback
            feedback = obs.get("step_feedback", "")[:200]
            print(f"           Reward: {reward:+.2f} | Feedback: {feedback}", flush=True)

            # Update conversation with assistant response and new observation
            messages.append({"role": "assistant", "content": action_text})

            # Build concise next observation for LLM
            held = obs.get("held_item")
            held_str = (
                f"Holding: {held.get('name', 'unknown')}" if held else "Arm: idle"
            )
            items_status = [
                f"[{i['id']}] {i.get('name', '?')} ({i['status']})"
                for i in obs.get("food_items", [])
            ]
            containers_status = [
                f"[{c['id']}] {c['name']} {c.get('fill_percentage',0):.0f}% full"
                for c in obs.get("containers", [])
            ]

            messages.append(
                {
                    "role": "user",
                    "content": (
                        f"Step {step} result (reward={reward:+.2f}):\n"
                        f"Feedback: {obs.get('step_feedback', '')}\n\n"
                        f"{held_str}\n"
                        f"Items: {', '.join(items_status)}\n"
                        f"Containers: {', '.join(containers_status)}\n"
                        f"Available: {obs.get('available_commands', [])}\n\n"
                        f"{'VLM Result: ' + json.dumps(obs.get('vlm_result')) if obs.get('vlm_result') else ''}\n\n"
                        f"Next action? JSON only."
                    ),
                },
            )

        # Extract final score
        final_score = obs.get("metadata", {}).get("final_score", 0.0)
        # Ensure score is strictly between 0 and 1 (exclusive) for the validator
        final_score = max(0.0001, min(0.9999, float(final_score)))
        grade_breakdown = obs.get("metadata", {}).get("grade_breakdown", {})

        print(f"\n  {'─'*40}", flush=True)
        print(f"  Steps taken:  {step}", flush=True)
        print(f"  Total reward: {total_reward:+.2f}", flush=True)
        print(f"  Final score:  {final_score:.4f}", flush=True)
        if grade_breakdown:
            print(f"  Breakdown:", flush=True)
            print(f"    Validity:    {grade_breakdown.get('validity', 0):.4f} (x0.4)", flush=True)
            print(f"    Efficiency:  {grade_breakdown.get('efficiency', 0):.4f} (x0.3)", flush=True)
            print(f"    Constraints: {grade_breakdown.get('constraints', 0):.4f} (x0.2)", flush=True)
            print(f"    Neatness:    {grade_breakdown.get('neatness', 0):.4f} (x0.1)", flush=True)

        # Emit [END] structured output for the validator
        print(f"[END] task={task_id} score={final_score} steps={step}", flush=True)

        return {
            "task_id": task_id,
            "steps": step,
            "total_reward": round(total_reward, 4),
            "score": final_score,
            "grade_breakdown": grade_breakdown,
        }

    except Exception as e:
        # Catch-all: ensure [END] is ALWAYS emitted even on unexpected errors
        print(f"  FATAL ERROR in episode {task_id}: {e}", flush=True)
        traceback.print_exc()
        print(f"[END] task={task_id} score=0.0001 steps={step}", flush=True)
        return {"task_id": task_id, "total_reward": 0.0, "reward": 0.0, "score": 0.0001, "steps": step, "error": str(e)}


def main():
    """Run all 3 tasks and report results."""
    print("=" * 60, flush=True)
    print("  TIFFIN PACKER β€” INFERENCE SCRIPT", flush=True)
    print(f"  Model: {MODEL_NAME}", flush=True)
    print(f"  API:   {API_BASE_URL}", flush=True)
    print(f"  Env:   {ENV_URL}", flush=True)
    print("=" * 60, flush=True)



    start_time = time.time()
    results = {}

    for task_id in ["easy", "medium", "hard"]:
        result = run_episode(task_id)
        results[task_id] = result

    elapsed = time.time() - start_time

    # Summary
    print("\n" + "=" * 60, flush=True)
    print("  FINAL RESULTS", flush=True)
    print("=" * 60, flush=True)
    for task_id, r in results.items():
        print(f"  {task_id:8s}: score={r['score']:.4f}  reward={r['total_reward']:+.2f}  steps={r.get('steps', '?')}", flush=True)

    avg_score = sum(r["score"] for r in results.values()) / max(len(results), 1)
    print(f"\n  Average score: {avg_score:.4f}", flush=True)
    print(f"  Total time:    {elapsed:.1f}s", flush=True)

    # Save results
    os.makedirs("outputs/evals", exist_ok=True)
    with open("outputs/evals/results.json", "w") as f:
        json.dump(
            {
                "model": MODEL_NAME,
                "api_base_url": API_BASE_URL,
                "results": results,
                "average_score": avg_score,
                "elapsed_seconds": round(elapsed, 1),
            },
            f,
            indent=2,
        )
    print(f"\n  Results saved to outputs/evals/results.json", flush=True)


if __name__ == "__main__":
    main()