ashoka0402 commited on
Commit
887fd28
·
1 Parent(s): 60eafd1

experimental 3

Browse files
Files changed (1) hide show
  1. inference.py +22 -39
inference.py CHANGED
@@ -22,7 +22,6 @@ clarification answers accumulated so far.
22
  from __future__ import annotations
23
 
24
  import os
25
- import sys
26
  import textwrap
27
  from typing import List, Optional
28
 
@@ -34,12 +33,11 @@ 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
- API_KEY = os.getenv("API_KEY", "no-key") # validator injects this 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
  EVAL_TASKS = [
44
  ("easy_001", "easy"),
45
  ("easy_007", "easy"),
@@ -118,7 +116,7 @@ SYSTEM_PROMPT = textwrap.dedent("""
118
 
119
 
120
  def _ask_llm(client: OpenAI, user_prompt: str) -> str:
121
- """Call the LLM and return the text response, falling back to empty string on error."""
122
  try:
123
  completion = client.chat.completions.create(
124
  model=MODEL_NAME,
@@ -145,15 +143,12 @@ def build_repair_prompt(
145
  history: List[str],
146
  ) -> str:
147
  hist_block = "\n".join(history[-4:]) if history else "None"
148
- clarif = clarification or "None"
149
- error = last_error or "None"
150
-
151
  return textwrap.dedent(f"""
152
  Task intent : {intent}
153
  Schema : {schema_hint}
154
  Broken query : {broken_query}
155
- Clarification : {clarif}
156
- Last error : {error}
157
  History :
158
  {hist_block}
159
 
@@ -199,35 +194,29 @@ def run_episode(client: OpenAI, task_id: str, difficulty: str) -> tuple[float, i
199
  steps_taken = step
200
 
201
  if step == 1:
202
- question = _ask_llm(
203
- client,
204
- build_clarify_prompt(intent, schema_hint, broken_q),
205
- ) or "What are the correct table and column names?"
206
  action_body = {"type": "ask_clarification", "question": question}
207
  action_str = f"ask_clarification({question!r})"
208
 
209
  elif step == 2:
210
- fixed_q = _ask_llm(
211
- client,
212
- build_repair_prompt(intent, schema_hint, broken_q, clarif_resp, last_error, history),
213
- ) or broken_q
214
  action_body = {"type": "run_partial", "query": fixed_q}
215
  action_str = f"run_partial({fixed_q!r})"
216
 
217
  else:
218
- fixed_q = _ask_llm(
219
- client,
220
- build_repair_prompt(intent, schema_hint, broken_q, clarif_resp, last_error, history),
221
- ) or broken_q
222
  action_body = {"type": "submit_query", "query": fixed_q}
223
  action_str = f"submit_query({fixed_q!r})"
224
 
225
- result = _post("/step", action_body)
226
- obs = result["observation"]
227
- reward = float(result["reward"])
228
- done = bool(result["done"])
229
- info = result["info"]
230
- error = obs.get("error_message")
231
 
232
  rewards.append(reward)
233
  clarif_resp = obs.get("clarification_response")
@@ -249,8 +238,6 @@ def run_episode(client: OpenAI, task_id: str, difficulty: str) -> tuple[float, i
249
 
250
  except Exception as exc:
251
  print(f"[DEBUG] Episode error: {exc}", flush=True)
252
- score = 0.0
253
- success = False
254
 
255
  log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
256
  return score, steps_taken, rewards
@@ -261,24 +248,20 @@ def run_episode(client: OpenAI, task_id: str, difficulty: str) -> tuple[float, i
261
  # ---------------------------------------------------------------------------
262
 
263
  def main() -> None:
264
- try:
265
- client = OpenAI(
266
- base_url=API_BASE_URL,
267
- api_key=API_KEY,
268
- )
269
- except Exception as exc:
270
- print(f"[DEBUG] Failed to init OpenAI client: {exc}", flush=True)
271
- sys.exit(1)
272
 
273
  all_scores: List[float] = []
274
 
275
  for task_id, difficulty in EVAL_TASKS:
276
  try:
277
  score, steps, rewards = run_episode(client, task_id, difficulty)
278
- all_scores.append(score)
279
  except Exception as exc:
280
  print(f"[DEBUG] Task {task_id} failed: {exc}", flush=True)
281
- all_scores.append(0.0)
 
282
 
283
  avg = sum(all_scores) / len(all_scores) if all_scores else 0.0
284
  print(f"\n[SUMMARY] tasks={len(all_scores)} avg_score={avg:.3f}", flush=True)
 
22
  from __future__ import annotations
23
 
24
  import os
 
25
  import textwrap
26
  from typing import List, Optional
27
 
 
33
 
34
  API_BASE_URL = os.getenv("API_BASE_URL", "https://api.openai.com/v1")
35
  MODEL_NAME = os.getenv("MODEL_NAME", "gpt-4o-mini")
36
+ API_KEY = os.getenv("API_KEY", "no-key") # validator injects real key at runtime
37
 
38
  SERVER_URL = os.getenv("ENV_SERVER_URL", "http://localhost:7860")
39
  BENCHMARK = "sql-repair"
40
 
 
41
  EVAL_TASKS = [
42
  ("easy_001", "easy"),
43
  ("easy_007", "easy"),
 
116
 
117
 
118
  def _ask_llm(client: OpenAI, user_prompt: str) -> str:
119
+ """Call the LLM via the injected proxy. Returns empty string on error."""
120
  try:
121
  completion = client.chat.completions.create(
122
  model=MODEL_NAME,
 
143
  history: List[str],
144
  ) -> str:
145
  hist_block = "\n".join(history[-4:]) if history else "None"
 
 
 
146
  return textwrap.dedent(f"""
147
  Task intent : {intent}
148
  Schema : {schema_hint}
149
  Broken query : {broken_query}
150
+ Clarification : {clarification or "None"}
151
+ Last error : {last_error or "None"}
152
  History :
153
  {hist_block}
154
 
 
194
  steps_taken = step
195
 
196
  if step == 1:
197
+ question = _ask_llm(client, build_clarify_prompt(intent, schema_hint, broken_q)) \
198
+ or "What are the correct table and column names?"
 
 
199
  action_body = {"type": "ask_clarification", "question": question}
200
  action_str = f"ask_clarification({question!r})"
201
 
202
  elif step == 2:
203
+ fixed_q = _ask_llm(client, build_repair_prompt(intent, schema_hint, broken_q, clarif_resp, last_error, history)) \
204
+ or broken_q
 
 
205
  action_body = {"type": "run_partial", "query": fixed_q}
206
  action_str = f"run_partial({fixed_q!r})"
207
 
208
  else:
209
+ fixed_q = _ask_llm(client, build_repair_prompt(intent, schema_hint, broken_q, clarif_resp, last_error, history)) \
210
+ or broken_q
 
 
211
  action_body = {"type": "submit_query", "query": fixed_q}
212
  action_str = f"submit_query({fixed_q!r})"
213
 
214
+ result = _post("/step", action_body)
215
+ obs = result["observation"]
216
+ reward = float(result["reward"])
217
+ done = bool(result["done"])
218
+ info = result["info"]
219
+ error = obs.get("error_message")
220
 
221
  rewards.append(reward)
222
  clarif_resp = obs.get("clarification_response")
 
238
 
239
  except Exception as exc:
240
  print(f"[DEBUG] Episode error: {exc}", flush=True)
 
 
241
 
242
  log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
243
  return score, steps_taken, rewards
 
248
  # ---------------------------------------------------------------------------
249
 
250
  def main() -> None:
251
+ client = OpenAI(
252
+ base_url=API_BASE_URL,
253
+ api_key=API_KEY,
254
+ )
 
 
 
 
255
 
256
  all_scores: List[float] = []
257
 
258
  for task_id, difficulty in EVAL_TASKS:
259
  try:
260
  score, steps, rewards = run_episode(client, task_id, difficulty)
 
261
  except Exception as exc:
262
  print(f"[DEBUG] Task {task_id} failed: {exc}", flush=True)
263
+ score = 0.0
264
+ all_scores.append(score)
265
 
266
  avg = sum(all_scores) / len(all_scores) if all_scores else 0.0
267
  print(f"\n[SUMMARY] tasks={len(all_scores)} avg_score={avg:.3f}", flush=True)