""" Inference Script — Interactive SQL Query Repair Environment =========================================================== STDOUT FORMAT [START] task= env=sql-repair model= [STEP] step= action= reward=<0.00> done= error= [END] success= steps= score= rewards= ENV VARS HF_TOKEN / API_KEY — LLM API key API_BASE_URL — LLM endpoint (default: HF router) MODEL_NAME — Model ID (default: Qwen2.5-72B-Instruct) ENV_SERVER_URL — Running server (default: http://localhost:8000) SQL_TASK_ID — Task to run (default: easy_001) SQL_DIFFICULTY — Difficulty (default: easy) """ import json import os import sys import textwrap from typing import List, Optional import httpx from openai import OpenAI # ── Environment configuration ───────────────────────────────────────────────── API_KEY: str = os.environ.get("API_KEY", "") API_BASE_URL: str = os.environ.get("API_BASE_URL", "") MODEL_NAME: str = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct") ENV_SERVER_URL: str = os.getenv("ENV_SERVER_URL", "http://localhost:8000").rstrip("/") TASK_ID: str = os.getenv("SQL_TASK_ID", "easy_001") DIFFICULTY: str = os.getenv("SQL_DIFFICULTY", "easy") BENCHMARK: str = "sql-repair" # Max turns per difficulty (mirrors env rules) MAX_TURNS_MAP = {"easy": 3, "medium": 5, "hard": 8} TEMPERATURE = 0.3 # Low temp → more deterministic SQL generation MAX_TOKENS = 512 SUCCESS_SCORE_THRESHOLD = 0.5 # score in [0, 1] # ── Prompts ─────────────────────────────────────────────────────────────────── SYSTEM_PROMPT = textwrap.dedent(""" You are an expert SQL debugger. Your job is to fix a broken SQL query. DATABASE SCHEMA (SQLite): users (id, name, email, age, city, active) orders (id, user_id, product_id, amount, created_at) products (id, name, price, category, stock) reviews (id, user_id, product_id, rating, comment) tags (id, product_id, tag) RULES: - You have a limited number of turns. Use them wisely. - You have THREE action types: 1. ask_clarification — ask ONE focused question about schema or intent. Use ONLY when the intent is genuinely ambiguous. 2. run_partial — test a candidate query to see if it runs without error. Use to validate your fix before submitting. 3. submit_query — your final corrected query. Ends the episode. STRATEGY: - Read the broken query and the intent carefully. - Identify the exact bug (wrong table name, wrong operator, bad join key, etc.) - For easy tasks: fix directly and submit. - For medium/hard tasks: run_partial once to verify, then submit. - Only ask_clarification if you truly cannot determine the schema/intent. - Never submit a query you have not at least mentally validated. RESPONSE FORMAT — respond with a JSON object and nothing else. Do NOT wrap in markdown fences. To ask a clarification: {"action": "ask_clarification", "question": ""} To test a query: {"action": "run_partial", "query": ""} """).strip() def build_user_prompt(obs: dict, history: List[str]) -> str: history_block = "\n".join(history) if history else "None" clarification = obs.get("clarification_response") or "None" error_msg = obs.get("error_message") or "None" return textwrap.dedent(f""" TASK ID: {obs.get('task_id', TASK_ID)} DIFFICULTY: {obs.get('difficulty', DIFFICULTY)} INTENT: {obs.get('intent', '')} SCHEMA HINT: {obs.get('schema_hint', '')} BROKEN QUERY: {obs.get('broken_query', '')} TURN: {obs.get('turn', '?')} / {obs.get('max_turns', '?')} LAST ERROR: {error_msg} LAST CLARIFICATION RESPONSE: {clarification} LAST ACTION TYPE: {obs.get('last_action_type') or 'None'} HISTORY: {history_block} Respond with a JSON object for your next action. """).strip() # ── Logging ─────────────────────────────────────────────────────────────────── def log_start(task: str, env: str, model: str) -> None: print(f"[START] task={task} env={env} model={model}", flush=True) def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None: error_val = error if error else "null" action_clean = action.replace("\n", " ").replace("\r", "")[:200] print( f"[STEP] step={step} action={action_clean} reward={reward:.2f} " f"done={str(done).lower()} error={error_val}", flush=True, ) def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None: rewards_str = ",".join(f"{r:.2f}" for r in rewards) print( f"[END] success={str(success).lower()} steps={steps} " f"score={score:.3f} rewards={rewards_str}", flush=True, ) # ── HTTP helpers ────────────────────────────────────────────────────────────── def api_reset(http: httpx.Client, task_id: str, difficulty: str) -> dict: try: print(f"[DEBUG] Resetting environment: {ENV_SERVER_URL}/reset", flush=True) resp = http.post( f"{ENV_SERVER_URL}/reset", json={"task_id": task_id, "difficulty": difficulty}, timeout=30, ) resp.raise_for_status() print(f"[DEBUG] Reset successful", flush=True) return resp.json() except httpx.TimeoutException as exc: print(f"[DEBUG] /reset timed out: {exc}", flush=True) raise except httpx.HTTPStatusError as exc: print(f"[DEBUG] /reset HTTP {exc.response.status_code}: {exc.response.text[:300]}", flush=True) raise except httpx.RequestError as exc: print(f"[DEBUG] /reset connection error: {exc}", flush=True) raise except Exception as exc: print(f"[DEBUG] /reset unexpected error: {exc}", flush=True) raise def api_step(http: httpx.Client, payload: dict) -> dict: try: resp = http.post( f"{ENV_SERVER_URL}/step", json=payload, timeout=30, ) resp.raise_for_status() return resp.json() except httpx.TimeoutException as exc: print(f"[DEBUG] /step timed out: {exc}", flush=True) raise except httpx.HTTPStatusError as exc: print(f"[DEBUG] /step HTTP {exc.response.status_code}: {exc.response.text[:300]}", flush=True) raise except httpx.RequestError as exc: print(f"[DEBUG] /step connection error: {exc}", flush=True) raise except Exception as exc: print(f"[DEBUG] /step unexpected error: {exc}", flush=True) raise def api_grader(http: httpx.Client) -> dict: try: resp = http.get(f"{ENV_SERVER_URL}/grader", timeout=30) resp.raise_for_status() return resp.json() except httpx.TimeoutException as exc: print(f"[DEBUG] /grader timed out: {exc}", flush=True) raise except httpx.HTTPStatusError as exc: print(f"[DEBUG] /grader HTTP {exc.response.status_code}: {exc.response.text[:300]}", flush=True) raise except httpx.RequestError as exc: print(f"[DEBUG] /grader connection error: {exc}", flush=True) raise except Exception as exc: print(f"[DEBUG] /grader unexpected error: {exc}", flush=True) raise # ── LLM call ───────────────────────────────────────────────────────────────── def get_model_action(llm: OpenAI, obs: dict, history: List[str]) -> dict: """ Ask the LLM what action to take. Always returns a valid action dict — never raises. Falls back to submitting the broken query on any failure. """ fallback = {"action": "submit_query", "query": obs.get("broken_query", "SELECT 1")} # Build prompt try: user_prompt = build_user_prompt(obs, history) except Exception as exc: print(f"[DEBUG] prompt build error: {exc}", flush=True) return fallback print(f"[DEBUG] Calling LLM: {MODEL_NAME} at {API_BASE_URL}", flush=True) # Call LLM try: completion = llm.chat.completions.create( model=MODEL_NAME, messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_prompt}, ], temperature=TEMPERATURE, max_tokens=MAX_TOKENS, stream=False, ) print(f"[DEBUG] LLM call successful", flush=True) except Exception as exc: print(f"[DEBUG] LLM API call failed: {exc}", flush=True) return fallback # Extract text try: raw = (completion.choices[0].message.content or "").strip() except Exception as exc: print(f"[DEBUG] LLM response read failed: {exc}", flush=True) return fallback # Strip markdown fences if present try: if raw.startswith("```"): parts = raw.split("```") raw = parts[1] if len(parts) > 1 else raw if raw.startswith("json"): raw = raw[4:] raw = raw.strip() except Exception as exc: print(f"[DEBUG] fence strip failed: {exc}", flush=True) # Parse JSON try: parsed = json.loads(raw) except json.JSONDecodeError as exc: print(f"[DEBUG] JSON parse failed ({exc}): {raw[:200]}", flush=True) return fallback # Validate action field try: action = parsed.get("action", "") if action not in ("ask_clarification", "run_partial", "submit_query"): print(f"[DEBUG] unknown action from model: {action!r}", flush=True) return fallback except Exception as exc: print(f"[DEBUG] action validation error: {exc}", flush=True) return fallback return parsed def action_to_payload(parsed: dict) -> dict: """Convert LLM response dict to the JSON shape /step expects.""" action = parsed.get("action", "") if action == "submit_query": return {"type": "submit_query", "query": parsed.get("query", "")} elif action == "run_partial": return {"type": "run_partial", "query": parsed.get("query", "")} elif action == "ask_clarification": return {"type": "ask_clarification", "question": parsed.get("question", "")} # Safe fallback (should not be reached after validation) return {"type": "submit_query", "query": parsed.get("query", "SELECT 1")} def action_repr(parsed: dict) -> str: """One-line string for [STEP] logging.""" action = parsed.get("action", "unknown") if action in ("submit_query", "run_partial"): q = parsed.get("query", "").replace("\n", " ") return f'{action}("{q}")' elif action == "ask_clarification": return f'ask_clarification("{parsed.get("question", "")}")' return action # ── Main ────────────────────────────────────────────────────────────────────── def main() -> None: # Validate environment variables first print(f"[DEBUG] Checking environment variables...", flush=True) print(f"[DEBUG] API_KEY present: {bool(API_KEY)}", flush=True) print(f"[DEBUG] API_BASE_URL: {API_BASE_URL[:50] if API_BASE_URL else 'MISSING'}...", flush=True) print(f"[DEBUG] ENV_SERVER_URL: {ENV_SERVER_URL}", flush=True) print(f"[DEBUG] MODEL_NAME: {MODEL_NAME}", flush=True) if not API_KEY or not API_BASE_URL: print("[ERROR] Missing required environment variables: API_KEY and API_BASE_URL must be set", flush=True) # Still emit start/end for validator log_start(task=TASK_ID, env=BENCHMARK, model=MODEL_NAME) log_end(success=False, steps=0, score=0.0, rewards=[]) sys.exit(1) rewards: List[float] = [] steps_taken = 0 score = 0.0 success = False # Emit [START] before anything that can fail so the validator always sees it log_start(task=TASK_ID, env=BENCHMARK, model=MODEL_NAME) # Initialise LLM client try: print(f"[DEBUG] Initializing OpenAI client with base_url={API_BASE_URL}", flush=True) llm = OpenAI(base_url=API_BASE_URL, api_key=API_KEY) print(f"[DEBUG] OpenAI client initialized successfully", flush=True) except Exception as exc: print(f"[DEBUG] OpenAI client init failed: {exc}", flush=True) log_end(success=False, steps=0, score=0.0, rewards=[]) sys.exit(1) max_turns = MAX_TURNS_MAP.get(DIFFICULTY, 5) history: List[str] = [] try: with httpx.Client() as http: # ── Reset ───────────────────────────────────────────────────── try: obs: dict = api_reset(http, TASK_ID, DIFFICULTY) except Exception as exc: print(f"[DEBUG] Fatal: could not reset environment: {exc}", flush=True) log_end(success=False, steps=0, score=0.0, rewards=[]) return # ── Episode loop ─────────────────────────────────────────────── for step in range(1, max_turns + 1): print(f"[DEBUG] Starting step {step}/{max_turns}", flush=True) # Get action from LLM (never raises) parsed = get_model_action(llm, obs, history) try: payload = action_to_payload(parsed) action_str = action_repr(parsed) except Exception as exc: print(f"[DEBUG] payload build error at step {step}: {exc}", flush=True) payload = {"type": "submit_query", "query": obs.get("broken_query", "SELECT 1")} action_str = "submit_query(fallback)" # Send action to environment try: step_result = api_step(http, payload) except Exception as exc: print(f"[DEBUG] /step failed at step {step}: {exc}", flush=True) # Log a failed step and end the episode log_step(step=step, action=action_str, reward=0.0, done=True, error=str(exc)) rewards.append(0.0) steps_taken = step break # Parse step result try: reward: float = float(step_result.get("reward") or 0.0) done: bool = bool(step_result.get("done", False)) info: dict = step_result.get("info") or {} new_obs = step_result.get("observation") if isinstance(new_obs, dict): obs = new_obs except Exception as exc: print(f"[DEBUG] step result parse error: {exc}", flush=True) reward, done, info = 0.0, True, {} error_msg: Optional[str] = obs.get("error_message") if isinstance(obs, dict) else None feedback: str = info.get("feedback", "") if isinstance(info, dict) else "" rewards.append(reward) steps_taken = step log_step(step=step, action=action_str, reward=reward, done=done, error=error_msg) history.append( f"Step {step} [{parsed.get('action', '?')}]: {action_str} " f"-> reward={reward:+.2f} | feedback: {feedback}" ) if done: print(f"[DEBUG] Episode done at step {step}", flush=True) break # ── Grader ──────────────────────────────────────────────────── try: print(f"[DEBUG] Getting final score from grader", flush=True) grader_result = api_grader(http) score = float(grader_result.get("score", 0.0)) score = min(max(score, 0.0), 1.0) print(f"[DEBUG] Grader score: {score}", flush=True) except Exception as exc: print(f"[DEBUG] /grader failed, falling back to reward sum: {exc}", flush=True) score = min(max(sum(rewards), 0.0), 1.0) success = score >= SUCCESS_SCORE_THRESHOLD except Exception as exc: print(f"[DEBUG] Unhandled episode error: {exc}", flush=True) import traceback traceback.print_exc() finally: print(f"[DEBUG] Episode complete. Success: {success}, Steps: {steps_taken}, Score: {score}", flush=True) log_end(success=success, steps=steps_taken, score=score, rewards=rewards) if __name__ == "__main__": main()