#!/usr/bin/env python3 """ Baseline inference script for the SQL Debug Environment. Runs all 3 tasks using an OpenAI-compatible LLM to iteratively fix broken SQL. Talks to the environment server via WebSocket (the standard OpenEnv way). Logs follow the OpenEnv format: [START] task= env= model= [STEP] step= action= reward= done= error= [END] success= steps= score= rewards= Required environment variables (set before running): HF_TOKEN — your HuggingFace / NVIDIA API key (no default — must be set) API_BASE_URL — OpenAI-compatible endpoint (defaults to openai) MODEL_NAME — model identifier (defaults to gpt-4o) ENV_URL — environment server URL (default: http://localhost:7860) """ from __future__ import annotations import json import os import sys from openai import OpenAI from sql_debug_env.client import SQLDebugEnv from sql_debug_env.models import SQLAction # ── config ────────────────────────────────────────────────────────── # # Checklist requirements: # - API_BASE_URL and MODEL_NAME have defaults (allowed) # - HF_TOKEN has NO default — must be injected via environment # - LOCAL_IMAGE_NAME is optional (only needed with from_docker_image()) # # Using NVIDIA NIM (OpenAI-compatible endpoint): # API_BASE_URL → https://integrate.api.nvidia.com/v1 # MODEL_NAME → meta/llama-3.3-70b-instruct (or any NVIDIA NIM model) # HF_TOKEN → your NVIDIA API key from build.nvidia.com API_BASE_URL = os.getenv("API_BASE_URL", "https://integrate.api.nvidia.com/v1") MODEL_NAME = os.getenv("MODEL_NAME", "meta/llama-3.3-70b-instruct") HF_TOKEN = os.getenv("HF_TOKEN") # no default — required at runtime LOCAL_IMAGE_NAME = os.getenv("LOCAL_IMAGE_NAME") # optional ENV_URL = os.getenv("ENV_URL", "http://localhost:7860") BENCHMARK_NAME = "sql-debug-env" TASK_IDS = ["fix_syntax", "fix_join", "optimize_query"] MAX_STEPS = 8 # All LLM calls go through the OpenAI client — configured via the variables above llm = OpenAI( base_url=API_BASE_URL, api_key=HF_TOKEN or "sk-placeholder", ) # ── prompts ───────────────────────────────────────────────────────── SYSTEM_PROMPT = """\ You are an expert SQL developer. You'll receive a broken or slow SQL query \ along with the database schema. Your job is to fix it. Rules: 1. Return ONLY the corrected SQL — no explanations, no markdown, nothing else. 2. Must be valid SQLite SQL. 3. Keep the original intent (same columns, same ordering) unless fixing it requires changes. 4. For optimization tasks: prefer CTEs and JOINs over correlated subqueries.\ """ def build_user_prompt(observation, history: list[dict]) -> str: """Assemble the prompt from the current observation + recent history.""" obs = observation parts = [ f"## Task: {obs.task_id}", f"\n## Schema\n{obs.schema_description}", f"\n## Broken Query\n```sql\n{obs.broken_query}\n```", f"\nExpected row count: {obs.expected_row_count}", ] if obs.error_message: parts.append(f"\n## Error from last attempt\n{obs.error_message}") if obs.result_preview: preview = json.dumps(obs.result_preview[:5], indent=2) parts.append(f"\n## Last result (first 5 rows)\n```json\n{preview}\n```") parts.append(f"Rows returned: {obs.current_row_count or '?'}") if obs.hint: parts.append(f"\n## Hint\n{obs.hint}") # Show the last few attempts so the model doesn't repeat mistakes if history: parts.append("\n## Previous attempts") for h in history[-3:]: parts.append(f"- Step {h['step']}: reward={h['reward']:.2f}") if h.get("error"): parts.append(f" Error: {h['error']}") parts.append(f" Query: {h['query'][:200]}...") parts.append("\nReturn the fixed SQL query. Nothing else.") return "\n".join(parts) # ── main loop ─────────────────────────────────────────────────────── def run_task(env, task_id: str) -> dict: """Run one task end-to-end and return a summary.""" print(f"[START] task={task_id} env={BENCHMARK_NAME} model={MODEL_NAME}") result = env.reset(task_id=task_id) observation = result.observation history: list[dict] = [] rewards: list[float] = [] done = False best_score = 0.0 steps_taken = 0 messages = [{"role": "system", "content": SYSTEM_PROMPT}] for step in range(1, MAX_STEPS + 1): if done: break user_msg = build_user_prompt(observation, history) msgs = messages + [{"role": "user", "content": user_msg}] # Ask the LLM for a fix try: resp = llm.chat.completions.create( model=MODEL_NAME, messages=msgs, temperature=0.0, max_tokens=1024, ) query = resp.choices[0].message.content.strip() # Strip markdown fences if the model can't help itself if query.startswith("```"): lines = query.split("\n") query = "\n".join(l for l in lines if not l.strip().startswith("```")) query = query.strip() except Exception as e: # If the LLM call fails, just resubmit the broken query # (it'll get a bad score but at least the loop continues) query = observation.broken_query print( f"[STEP] step={step} action={query[:80]} " f"reward=0.00 done=false error=LLM_ERROR:{e}" ) continue # Send the query to the environment try: result = env.step(SQLAction(query=query)) observation = result.observation reward = result.reward or 0.0 done = result.done error_msg = observation.error_message except Exception as e: reward = 0.0 done = False error_msg = str(e) rewards.append(reward) best_score = max(best_score, reward) steps_taken = step history.append({ "step": step, "query": query, "reward": reward, "error": error_msg, }) err_display = error_msg if error_msg else "null" query_short = query.replace("\n", " ")[:100] print( f"[STEP] step={step} action={query_short} " f"reward={reward:.2f} done={str(done).lower()} error={err_display}" ) # optimize_query requires the efficiency bonus too (threshold 0.95) # otherwise the broken query itself scores 0.90 and looks "solved" threshold = 0.95 if task_id == "optimize_query" else 0.89 success = best_score >= threshold rewards_str = ",".join(f"{r:.2f}" for r in rewards) print( f"[END] success={str(success).lower()} steps={steps_taken} " f"score={best_score:.2f} rewards={rewards_str}" ) return { "task_id": task_id, "success": success, "steps": steps_taken, "score": best_score, "rewards": rewards, } def main(): """Run all tasks and print a summary.""" with SQLDebugEnv(base_url=ENV_URL).sync() as env: results = [] for task_id in TASK_IDS: result = run_task(env, task_id) results.append(result) print() # Print overall results total = sum(r["score"] for r in results) solved = sum(1 for r in results if r["success"]) print( f"=== DONE: {solved}/{len(results)} solved, " f"total score: {total:.2f}/{len(results):.2f} ===" ) return 0 if solved == len(results) else 1 if __name__ == "__main__": sys.exit(main())