ashoka0402 commited on
Commit
d2d2b9f
·
1 Parent(s): d919ed1

major changes expermental

Browse files
Files changed (1) hide show
  1. inference.py +27 -59
inference.py CHANGED
@@ -34,13 +34,12 @@ from openai import OpenAI
34
 
35
  API_BASE_URL = os.getenv("API_BASE_URL", "https://api.openai.com/v1")
36
  MODEL_NAME = os.getenv("MODEL_NAME", "gpt-4o-mini")
37
- HF_TOKEN = os.getenv("HF_TOKEN") # no default — injected at runtime
38
 
39
  SERVER_URL = os.getenv("ENV_SERVER_URL", "http://localhost:7860")
40
  BENCHMARK = "sql-repair"
41
 
42
  # Tasks to run in the baseline evaluation
43
- # Edit this list to run a subset; default runs 3 representative tasks
44
  EVAL_TASKS = [
45
  ("easy_001", "easy"),
46
  ("easy_007", "easy"),
@@ -51,7 +50,7 @@ EVAL_TASKS = [
51
  ]
52
 
53
  MAX_STEPS = 8
54
- TEMPERATURE = 0.2 # low temperature for deterministic repair
55
  MAX_TOKENS = 400
56
 
57
  # ---------------------------------------------------------------------------
@@ -63,9 +62,8 @@ def log_start(task: str, env: str, model: str) -> None:
63
 
64
 
65
  def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:
66
- error_val = error if error else "null"
67
- done_val = str(done).lower()
68
- # Sanitise action string: strip newlines so it stays on one line
69
  action_clean = action.replace("\n", " ").replace("\r", "")
70
  print(
71
  f"[STEP] step={step} action={action_clean!r} "
@@ -84,7 +82,7 @@ def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> No
84
 
85
 
86
  # ---------------------------------------------------------------------------
87
- # HTTP helpers (thin wrapper around requests)
88
  # ---------------------------------------------------------------------------
89
 
90
  def _post(path: str, body: dict) -> dict:
@@ -119,25 +117,19 @@ SYSTEM_PROMPT = textwrap.dedent("""
119
  """).strip()
120
 
121
 
122
- def _ask_llm(client: Optional[OpenAI], user_prompt: str) -> str:
123
- """Call the LLM and return the text response, falling back to empty string on error."""
124
- if client is None:
125
- return "" # fallback mode
126
- try:
127
- completion = client.chat.completions.create(
128
- model=MODEL_NAME,
129
- messages=[
130
- {"role": "system", "content": SYSTEM_PROMPT},
131
- {"role": "user", "content": user_prompt},
132
- ],
133
- temperature=TEMPERATURE,
134
- max_tokens=MAX_TOKENS,
135
- stream=False,
136
- )
137
- return (completion.choices[0].message.content or "").strip()
138
- except Exception as exc:
139
- print(f"[DEBUG] LLM call failed: {exc}", flush=True)
140
- return ""
141
 
142
 
143
  def build_repair_prompt(
@@ -181,11 +173,8 @@ def build_clarify_prompt(intent: str, schema_hint: str, broken_query: str) -> st
181
  # Single episode runner
182
  # ---------------------------------------------------------------------------
183
 
184
- def run_episode(client: Optional[OpenAI], task_id: str, difficulty: str) -> tuple[float, int, List[float]]:
185
- """
186
- Run one episode for the given task.
187
- Returns (score, steps_taken, rewards_list).
188
- """
189
  rewards: List[float] = []
190
  steps_taken: int = 0
191
  score: float = 0.0
@@ -195,50 +184,40 @@ def run_episode(client: Optional[OpenAI], task_id: str, difficulty: str) -> tupl
195
  log_start(task=task_id, env=BENCHMARK, model=MODEL_NAME)
196
 
197
  try:
198
- # ── reset ────────────────────────────────────────────────────
199
- obs_raw = _post("/reset", {"task_id": task_id, "difficulty": difficulty})
200
  intent = obs_raw["intent"]
201
  schema_hint = obs_raw["schema_hint"]
202
  broken_q = obs_raw["broken_query"]
203
- max_turns = obs_raw.get("max_turns", MAX_STEPS)
204
  clarif_resp: Optional[str] = None
205
  last_error: Optional[str] = None
206
 
207
  for step in range(1, MAX_STEPS + 1):
208
  steps_taken = step
209
 
210
- # ── decide action ────────────────────────────────────────
211
  if step == 1:
212
- # Always start with a clarification question
213
  question = _ask_llm(
214
  client,
215
  build_clarify_prompt(intent, schema_hint, broken_q),
216
- ) or "what are the correct table and column names?"
217
-
218
  action_body = {"type": "ask_clarification", "question": question}
219
  action_str = f"ask_clarification({question!r})"
220
 
221
  elif step == 2:
222
- # Run partial to probe for syntax errors
223
  fixed_q = _ask_llm(
224
  client,
225
  build_repair_prompt(intent, schema_hint, broken_q, clarif_resp, last_error, history),
226
  ) or broken_q
227
-
228
  action_body = {"type": "run_partial", "query": fixed_q}
229
  action_str = f"run_partial({fixed_q!r})"
230
 
231
  else:
232
- # Submit the best repair we have
233
  fixed_q = _ask_llm(
234
  client,
235
  build_repair_prompt(intent, schema_hint, broken_q, clarif_resp, last_error, history),
236
  ) or broken_q
237
-
238
  action_body = {"type": "submit_query", "query": fixed_q}
239
  action_str = f"submit_query({fixed_q!r})"
240
 
241
- # ── step ─────────────────────────────────────────────────
242
  result = _post("/step", action_body)
243
  obs = result["observation"]
244
  reward = float(result["reward"])
@@ -247,8 +226,6 @@ def run_episode(client: Optional[OpenAI], task_id: str, difficulty: str) -> tupl
247
  error = obs.get("error_message")
248
 
249
  rewards.append(reward)
250
-
251
- # Update state for next turn
252
  clarif_resp = obs.get("clarification_response")
253
  last_error = error
254
 
@@ -262,7 +239,6 @@ def run_episode(client: Optional[OpenAI], task_id: str, difficulty: str) -> tupl
262
  if done:
263
  break
264
 
265
- # ── final score ───────────────────────────────────────────────
266
  grade = _get("/grader")
267
  score = float(grade["score"])
268
  success = bool(grade["solved"])
@@ -276,24 +252,16 @@ def run_episode(client: Optional[OpenAI], task_id: str, difficulty: str) -> tupl
276
  return score, steps_taken, rewards
277
 
278
 
279
- def get_client() -> Optional[OpenAI]:
280
- """Initialise the OpenAI-compatible client using injected env vars."""
281
- try:
282
- return OpenAI(
283
- base_url=API_BASE_URL,
284
- api_key=HF_TOKEN or "no-key",
285
- )
286
- except Exception as e:
287
- print(f"[WARN] Failed to init OpenAI client: {e}", flush=True)
288
- return None
289
-
290
-
291
  # ---------------------------------------------------------------------------
292
  # Main
293
  # ---------------------------------------------------------------------------
294
 
295
  def main() -> None:
296
- client = get_client()
 
 
 
 
297
 
298
  all_scores: List[float] = []
299
 
 
34
 
35
  API_BASE_URL = os.getenv("API_BASE_URL", "https://api.openai.com/v1")
36
  MODEL_NAME = os.getenv("MODEL_NAME", "gpt-4o-mini")
37
+ API_KEY = os.environ["API_KEY"] # injected by validator — must be present
38
 
39
  SERVER_URL = os.getenv("ENV_SERVER_URL", "http://localhost:7860")
40
  BENCHMARK = "sql-repair"
41
 
42
  # Tasks to run in the baseline evaluation
 
43
  EVAL_TASKS = [
44
  ("easy_001", "easy"),
45
  ("easy_007", "easy"),
 
50
  ]
51
 
52
  MAX_STEPS = 8
53
+ TEMPERATURE = 0.2
54
  MAX_TOKENS = 400
55
 
56
  # ---------------------------------------------------------------------------
 
62
 
63
 
64
  def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:
65
+ error_val = error if error else "null"
66
+ done_val = str(done).lower()
 
67
  action_clean = action.replace("\n", " ").replace("\r", "")
68
  print(
69
  f"[STEP] step={step} action={action_clean!r} "
 
82
 
83
 
84
  # ---------------------------------------------------------------------------
85
+ # HTTP helpers
86
  # ---------------------------------------------------------------------------
87
 
88
  def _post(path: str, body: dict) -> dict:
 
117
  """).strip()
118
 
119
 
120
+ def _ask_llm(client: OpenAI, user_prompt: str) -> str:
121
+ """Call the LLM and return the text response."""
122
+ completion = client.chat.completions.create(
123
+ model=MODEL_NAME,
124
+ messages=[
125
+ {"role": "system", "content": SYSTEM_PROMPT},
126
+ {"role": "user", "content": user_prompt},
127
+ ],
128
+ temperature=TEMPERATURE,
129
+ max_tokens=MAX_TOKENS,
130
+ stream=False,
131
+ )
132
+ return (completion.choices[0].message.content or "").strip()
 
 
 
 
 
 
133
 
134
 
135
  def build_repair_prompt(
 
173
  # Single episode runner
174
  # ---------------------------------------------------------------------------
175
 
176
+ def run_episode(client: OpenAI, task_id: str, difficulty: str) -> tuple[float, int, List[float]]:
177
+ """Run one episode. Returns (score, steps_taken, rewards_list)."""
 
 
 
178
  rewards: List[float] = []
179
  steps_taken: int = 0
180
  score: float = 0.0
 
184
  log_start(task=task_id, env=BENCHMARK, model=MODEL_NAME)
185
 
186
  try:
187
+ obs_raw = _post("/reset", {"task_id": task_id, "difficulty": difficulty})
 
188
  intent = obs_raw["intent"]
189
  schema_hint = obs_raw["schema_hint"]
190
  broken_q = obs_raw["broken_query"]
 
191
  clarif_resp: Optional[str] = None
192
  last_error: Optional[str] = None
193
 
194
  for step in range(1, MAX_STEPS + 1):
195
  steps_taken = step
196
 
 
197
  if step == 1:
 
198
  question = _ask_llm(
199
  client,
200
  build_clarify_prompt(intent, schema_hint, broken_q),
201
+ ) or "What are the correct table and column names?"
 
202
  action_body = {"type": "ask_clarification", "question": question}
203
  action_str = f"ask_clarification({question!r})"
204
 
205
  elif step == 2:
 
206
  fixed_q = _ask_llm(
207
  client,
208
  build_repair_prompt(intent, schema_hint, broken_q, clarif_resp, last_error, history),
209
  ) or broken_q
 
210
  action_body = {"type": "run_partial", "query": fixed_q}
211
  action_str = f"run_partial({fixed_q!r})"
212
 
213
  else:
 
214
  fixed_q = _ask_llm(
215
  client,
216
  build_repair_prompt(intent, schema_hint, broken_q, clarif_resp, last_error, history),
217
  ) or broken_q
 
218
  action_body = {"type": "submit_query", "query": fixed_q}
219
  action_str = f"submit_query({fixed_q!r})"
220
 
 
221
  result = _post("/step", action_body)
222
  obs = result["observation"]
223
  reward = float(result["reward"])
 
226
  error = obs.get("error_message")
227
 
228
  rewards.append(reward)
 
 
229
  clarif_resp = obs.get("clarification_response")
230
  last_error = error
231
 
 
239
  if done:
240
  break
241
 
 
242
  grade = _get("/grader")
243
  score = float(grade["score"])
244
  success = bool(grade["solved"])
 
252
  return score, steps_taken, rewards
253
 
254
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  # ---------------------------------------------------------------------------
256
  # Main
257
  # ---------------------------------------------------------------------------
258
 
259
  def main() -> None:
260
+ # Initialise client exactly as the validator requires
261
+ client = OpenAI(
262
+ base_url=API_BASE_URL,
263
+ api_key=API_KEY,
264
+ )
265
 
266
  all_scores: List[float] = []
267