Vishvam10 commited on
Commit
6a7d2f5
·
1 Parent(s): de39529

debug: (inference) yeah, given up

Browse files
Files changed (1) hide show
  1. inference.py +1 -272
inference.py CHANGED
@@ -1,272 +1 @@
1
- import asyncio
2
- import os
3
- import sys
4
- import json
5
- import subprocess
6
- import time
7
- import threading
8
- from pathlib import Path
9
-
10
- try :
11
-
12
- import httpx
13
- from dotenv import load_dotenv
14
- from openai import OpenAI
15
- except Exception as e:
16
- print("WHATTTTT : ", e)
17
- sys.exit(0)
18
-
19
- try:
20
- ROOT = Path(__file__).parent.resolve()
21
- if str(ROOT) not in sys.path:
22
- sys.path.insert(0, str(ROOT))
23
-
24
- except Exception as e:
25
- print("BRUH : ", e)
26
- sys.exit(0)
27
-
28
-
29
- try:
30
- TASK_DIR = ROOT / "tasks"
31
- from cloudenv.client import ClientEnvironment
32
- from cloudenv.models import CloudEnvAction, CloudEnvObservation
33
-
34
- load_dotenv()
35
-
36
- HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
37
- API_BASE_URL = os.getenv("API_BASE_URL", "https://api.openai.com/v1")
38
- MODEL_NAME = os.getenv("MODEL_NAME", "gpt-4o")
39
-
40
- MAX_STEPS = int(os.getenv("MAX_STEPS", "20"))
41
- TEMPERATURE = float(os.getenv("TEMPERATURE", "0.3"))
42
- MAX_TOKENS = int(os.getenv("MAX_TOKENS", "300"))
43
-
44
- SERVER_URL = "http://127.0.0.1:8000"
45
-
46
- TASK_ORDER = ["easy-task", "medium-task", "hard-task"]
47
-
48
- client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)
49
- SYSTEM_PROMPT = 'Return ONLY JSON: {"service":"","operation":"","instance_id":null,"payload":{}}'
50
- except Exception as e:
51
- print("At this point, I give up : ", e)
52
- sys.exit(0)
53
-
54
-
55
- def start_ministack():
56
- try:
57
- proc = subprocess.Popen(
58
- ["uv", "run", "ministack"],
59
- cwd=ROOT,
60
- stdout=subprocess.DEVNULL,
61
- stderr=subprocess.DEVNULL,
62
- )
63
- time.sleep(3)
64
- return proc
65
- except Exception as e:
66
- print(f"[MINISTACK START ERROR] {e}", flush=True)
67
- raise
68
-
69
-
70
- def start_server():
71
- try:
72
- proc = subprocess.Popen(
73
- ["uv", "run", "server"],
74
- cwd=ROOT,
75
- stdout=subprocess.PIPE,
76
- stderr=subprocess.STDOUT,
77
- text=True,
78
- bufsize=1,
79
- )
80
-
81
- def stream():
82
- try:
83
- for line in proc.stdout:
84
- print(f"[SERVER] {line}", end="")
85
- except Exception as e:
86
- print(f"[SERVER STREAM ERROR] {e}", flush=True)
87
-
88
- threading.Thread(target=stream, daemon=True).start()
89
-
90
- for _ in range(40):
91
- try:
92
- r = httpx.get(f"{SERVER_URL}/docs", timeout=1)
93
- if r.status_code == 200:
94
- print("[INFO] server ready", flush=True)
95
- return proc
96
- except Exception:
97
- time.sleep(1)
98
-
99
- raise RuntimeError("server failed to start")
100
-
101
- except Exception as e:
102
- print(f"[SERVER START ERROR] {e}", flush=True)
103
- raise
104
-
105
-
106
- def load_task(name: str):
107
- try:
108
- return json.loads((TASK_DIR / f"{name}.json").read_text())
109
- except Exception as e:
110
- print(f"[TASK LOAD ERROR] {name}: {e}", flush=True)
111
- raise
112
-
113
-
114
- def register_pipeline(task):
115
- try:
116
- url = f"{SERVER_URL}/api/pipelines"
117
- with httpx.Client(timeout=20) as http:
118
- r = http.post(url, json=task)
119
-
120
- if r.status_code == 400:
121
- try:
122
- detail = r.json().get("detail", "")
123
- if "already exists" in detail:
124
- http.delete(f"{url}/{task['pipeline_id']}")
125
- http.post(url, json=task)
126
- except Exception:
127
- pass
128
-
129
- r.raise_for_status()
130
- except Exception as e:
131
- print(f"[REGISTER ERROR] {e}", flush=True)
132
-
133
-
134
- def parse_action(raw: str, task_id: str, episode_id: str) -> CloudEnvAction:
135
- try:
136
- raw = raw.strip()
137
- raw = raw[raw.find("{") : raw.rfind("}") + 1]
138
- d = json.loads(raw)
139
- return CloudEnvAction(
140
- task_id=task_id,
141
- episode_id=episode_id,
142
- service=d.get("service", "internal"),
143
- instance_id=d.get("instance_id"),
144
- operation=d.get("operation", "GetCallerIdentity"),
145
- payload=d.get("payload", {}),
146
- principal_arn=d.get("principal_arn"),
147
- intent=d.get("intent"),
148
- )
149
- except Exception:
150
- return CloudEnvAction(
151
- task_id=task_id,
152
- episode_id=episode_id,
153
- service="internal",
154
- operation="GetCallerIdentity",
155
- payload={},
156
- )
157
-
158
-
159
- def call_model(step, state, broken, ideal, history):
160
- try:
161
- prompt = f"""
162
- STEP {step}
163
- STATE {json.dumps(state)[:1000]}
164
- BROKEN {json.dumps(broken)[:1000]}
165
- IDEAL {json.dumps(ideal)[:1000]}
166
- HISTORY {history[-5:]}
167
- """
168
- res = client.chat.completions.create(
169
- model=MODEL_NAME,
170
- messages=[
171
- {"role": "system", "content": SYSTEM_PROMPT},
172
- {"role": "user", "content": prompt},
173
- ],
174
- temperature=TEMPERATURE,
175
- max_tokens=MAX_TOKENS,
176
- )
177
- return (res.choices[0].message.content or "").strip()
178
- except Exception as e:
179
- print(f"[MODEL ERROR] {e}", flush=True)
180
- return "{}"
181
-
182
-
183
- async def run_episode(task):
184
- try:
185
- pipeline_id = task["pipeline_id"]
186
- task_id = pipeline_id
187
- episode_id = f"{pipeline_id}-episode-1"
188
-
189
- env = ClientEnvironment(base_url=SERVER_URL)
190
-
191
- try:
192
- register_pipeline(task)
193
- except Exception as e:
194
- print(f"[REGISTER ERROR] {e}", flush=True)
195
-
196
- try:
197
- result = await env.initialize_environment(
198
- task_id=task_id,
199
- episode_id=episode_id,
200
- )
201
- except Exception as e:
202
- print(f"[INIT ERROR] {e}", flush=True)
203
- return
204
-
205
- obs = result.observation
206
-
207
- history = []
208
- rewards = []
209
-
210
- for step in range(MAX_STEPS):
211
- try:
212
- if obs.done:
213
- break
214
-
215
- raw = call_model(
216
- step,
217
- obs.current_pipeline_state,
218
- task["broken_pipeline"],
219
- task["ideal_pipeline"],
220
- history,
221
- )
222
-
223
- action = parse_action(raw, task_id, episode_id)
224
-
225
- result = await env.step(action)
226
- obs = result.observation
227
-
228
- rewards.append(float(obs.reward or 0))
229
- history.append(raw)
230
-
231
- except Exception as e:
232
- print(f"[STEP ERROR] {e}", flush=True)
233
- break
234
-
235
- score = sum(rewards) / (len(rewards) or 1)
236
- print(f"[END] task={task_id} score={score:.3f}", flush=True)
237
-
238
- except Exception as e:
239
- print(f"[EPISODE ERROR] {e}", flush=True)
240
-
241
-
242
- async def main():
243
- try:
244
- miniproc = start_ministack()
245
- serverproc = start_server()
246
-
247
- try:
248
- for name in TASK_ORDER:
249
- try:
250
- task = load_task(name)
251
- await run_episode(task)
252
- except Exception as e:
253
- print(f"[TASK ERROR] {name}: {e}", flush=True)
254
- finally:
255
- try:
256
- miniproc.terminate()
257
- except Exception:
258
- pass
259
- try:
260
- serverproc.terminate()
261
- except Exception:
262
- pass
263
-
264
- except Exception as e:
265
- print(f"[FATAL ERROR] {e}", flush=True)
266
-
267
-
268
- if __name__ == "__main__":
269
- try:
270
- asyncio.run(main())
271
- except Exception as e:
272
- print(f"[UNHANDLED TOP LEVEL ERROR] {e}", flush=True)
 
1
+ print("REACHED")