Abhishek Tiwari commited on
Commit
ebcd8b6
·
1 Parent(s): 6b06b3e

fix: strictly output [START], [STEP], [END] to stdout for phase 2 validator parsing

Browse files
Files changed (1) hide show
  1. inference.py +34 -58
inference.py CHANGED
@@ -3,11 +3,13 @@ import re
3
  import json
4
  import requests
5
  from openai import OpenAI
 
6
 
7
  API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
8
  API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY", "")
9
  MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
10
  ENV_URL = os.getenv("ENV_URL", "http://localhost:7860")
 
11
  MAX_STEPS = 6
12
  TEMPERATURE = 0.1
13
  MAX_TOKENS = 500
@@ -93,25 +95,26 @@ def parse_action(response_text: str, task_type: str) -> dict:
93
 
94
  return {"action_type": task_type, "sql": "SELECT 1", "explanation": "parse failed"}
95
 
96
- def run_episode(task_id: str) -> dict:
97
  try:
98
  res = requests.post(f"{ENV_URL}/reset", json={"task_id": task_id, "difficulty": None})
99
  res.raise_for_status()
100
  obs_obj = res.json()
101
  obs = obs_obj["observation"]
102
  except Exception as e:
103
- print(f" Error resetting environment: {e}")
104
- return {"task_id": task_id, "best_reward": 0.05}
105
 
106
- print(f" Task: {task_id} | {obs.get('task_type', '')}")
107
- print(f" Desc: {obs.get('task_description', '')[:100]}...")
108
 
109
  best_reward = 0.0
110
  history = []
111
 
 
 
 
112
  for step in range(1, MAX_STEPS + 1):
113
  if obs.get("done", False):
114
- print(f" Done at step {step}")
115
  break
116
 
117
  prompt = build_prompt(obs, step, history)
@@ -128,79 +131,52 @@ def run_episode(task_id: str) -> dict:
128
  )
129
  response_text = completion.choices[0].message.content or ""
130
  except Exception as e:
131
- print(f" API Error: {e}")
132
  response_text = ""
133
 
134
  action = parse_action(response_text, obs.get("task_type", "write_query"))
135
 
136
- print(f" Step {step}: {action.get('sql', '')[:70]}...")
 
137
 
138
  try:
139
  step_res = requests.post(f"{ENV_URL}/step", json=action)
140
  step_res.raise_for_status()
141
  step_data = step_res.json()
142
  except Exception as e:
143
- print(f" Env Step Error: {e}")
144
- break
145
 
146
  reward = step_data.get("reward", 0.05)
 
 
 
 
 
147
  best_reward = max(best_reward, reward)
148
  obs = step_data.get("observation", {})
149
 
150
- history.append(f"Step {step}: reward={reward:.3f} | {obs.get('feedback', '')[:60]}")
151
- print(f" Reward: {reward:.3f} | Done: {obs.get('done', False)} | {obs.get('feedback', '')[:60]}")
 
152
 
153
- if obs.get("done", False):
 
 
 
 
154
  break
155
 
156
- return {"task_id": task_id, "best_reward": round(best_reward, 3)}
 
 
 
 
157
 
158
  def main():
159
- print("=" * 65)
160
- print("SQL Debugger OpenEnv — Baseline Inference")
161
- print(f"Model : {MODEL_NAME}")
162
- print(f"Env : {ENV_URL}")
163
- print("=" * 65)
164
-
165
- try:
166
- health_res = requests.get(f"{ENV_URL}/health")
167
- print(f"Health: {health_res.json()}")
168
- except Exception as e:
169
- print(f"Health Check Failed: {e}")
170
-
171
  task_ids = ["easy_01", "easy_02", "medium_01", "medium_02", "hard_01", "hard_02"]
172
- results = []
173
-
174
- for i, tid in enumerate(task_ids):
175
- print(f"\\n[{i+1}/6] Running {tid}...")
176
- try:
177
- res = run_episode(tid)
178
- except Exception as e:
179
- print(f" Error running {tid}: {e}")
180
- res = {"task_id": tid, "best_reward": 0.05}
181
- results.append(res)
182
-
183
- print("\n" + "=" * 65)
184
- print("BASELINE SCORES")
185
- print("=" * 65)
186
-
187
- for r in results:
188
- print(f" {r['task_id']:15s}: {r['best_reward']:.3f}")
189
-
190
- easy_scores = [r['best_reward'] for r in results if r['task_id'].startswith('easy')]
191
- medium_scores = [r['best_reward'] for r in results if r['task_id'].startswith('medium')]
192
- hard_scores = [r['best_reward'] for r in results if r['task_id'].startswith('hard')]
193
-
194
- easy_avg = sum(easy_scores)/len(easy_scores) if easy_scores else 0.0
195
- medium_avg = sum(medium_scores)/len(medium_scores) if medium_scores else 0.0
196
- hard_avg = sum(hard_scores)/len(hard_scores) if hard_scores else 0.0
197
- overall = sum(r['best_reward'] for r in results) / len(results) if results else 0.0
198
-
199
- print(f"\\nEasy average : {easy_avg:.3f}")
200
- print(f"Medium average : {medium_avg:.3f}")
201
- print(f"Hard average : {hard_avg:.3f}")
202
- print(f"Overall average : {overall:.3f}")
203
- print("=" * 65)
204
 
205
  if __name__ == "__main__":
206
  main()
 
3
  import json
4
  import requests
5
  from openai import OpenAI
6
+ import sys
7
 
8
  API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
9
  API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY", "")
10
  MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
11
  ENV_URL = os.getenv("ENV_URL", "http://localhost:7860")
12
+ ENV_NAME = "sql_debugger"
13
  MAX_STEPS = 6
14
  TEMPERATURE = 0.1
15
  MAX_TOKENS = 500
 
95
 
96
  return {"action_type": task_type, "sql": "SELECT 1", "explanation": "parse failed"}
97
 
98
+ def run_episode(task_id: str):
99
  try:
100
  res = requests.post(f"{ENV_URL}/reset", json={"task_id": task_id, "difficulty": None})
101
  res.raise_for_status()
102
  obs_obj = res.json()
103
  obs = obs_obj["observation"]
104
  except Exception as e:
105
+ # Failsafe reset
106
+ obs = {"task_type": "write_query"}
107
 
108
+ print(f"[START] task={task_id} env={ENV_NAME} model={MODEL_NAME}", flush=True)
 
109
 
110
  best_reward = 0.0
111
  history = []
112
 
113
+ step = 0
114
+ done = False
115
+
116
  for step in range(1, MAX_STEPS + 1):
117
  if obs.get("done", False):
 
118
  break
119
 
120
  prompt = build_prompt(obs, step, history)
 
131
  )
132
  response_text = completion.choices[0].message.content or ""
133
  except Exception as e:
 
134
  response_text = ""
135
 
136
  action = parse_action(response_text, obs.get("task_type", "write_query"))
137
 
138
+ # Safe JSON stringification for the action output in the log
139
+ action_str = json.dumps(action)
140
 
141
  try:
142
  step_res = requests.post(f"{ENV_URL}/step", json=action)
143
  step_res.raise_for_status()
144
  step_data = step_res.json()
145
  except Exception as e:
146
+ # Fallback if step errors
147
+ step_data = {"reward": 0.05, "observation": {"done": True}, "done": True, "error": str(e)}
148
 
149
  reward = step_data.get("reward", 0.05)
150
+ done = step_data.get("done", False)
151
+ err = step_data.get("error")
152
+ # Format the numbers cleanly
153
+ reward_formatted = f"{reward:.2f}"
154
+
155
  best_reward = max(best_reward, reward)
156
  obs = step_data.get("observation", {})
157
 
158
+ # Convert flags to lowercase 'true' or 'false' for validator tracking
159
+ done_str = "true" if done else "false"
160
+ err_str = "null" if not err else f'"{str(err)}"'
161
 
162
+ print(f"[STEP] step={step} action={action_str} reward={reward_formatted} done={done_str} error={err_str}", flush=True)
163
+
164
+ history.append(f"Step {step}: reward={reward_formatted}")
165
+
166
+ if done:
167
  break
168
 
169
+ # Track final outcome: successes usually represent the max reward crossing some threshold
170
+ success_str = "true" if best_reward > 0.8 else "false"
171
+ best_reward_formatted = f"{best_reward:.2f}"
172
+
173
+ print(f"[END] success={success_str} steps={step} rewards={best_reward_formatted}", flush=True)
174
 
175
  def main():
176
+ # Only process the tasks quietly!
 
 
 
 
 
 
 
 
 
 
 
177
  task_ids = ["easy_01", "easy_02", "medium_01", "medium_02", "hard_01", "hard_02"]
178
+ for tid in task_ids:
179
+ run_episode(tid)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
  if __name__ == "__main__":
182
  main()