File size: 17,825 Bytes
64ccc23
ba7ad90
 
64ccc23
ba7ad90
64ccc23
 
ba7ad90
 
 
 
 
 
 
 
 
64ccc23
 
ba7ad90
64ccc23
0abb8ee
869e51a
a064080
869e51a
ba7ad90
64ccc23
 
ba7ad90
0abb8ee
 
423d452
 
ba7ad90
423d452
 
 
ba7ad90
 
423d452
ba7ad90
 
423d452
 
ba7ad90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423d452
ba7ad90
423d452
 
ba7ad90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423d452
 
 
 
 
 
ba7ad90
 
 
 
 
 
 
 
 
 
a064080
ba7ad90
869e51a
 
64ccc23
a064080
 
869e51a
ba7ad90
64ccc23
ba7ad90
 
64ccc23
 
 
a064080
 
869e51a
64ccc23
 
869e51a
64ccc23
 
 
869e51a
423d452
 
 
0abb8ee
423d452
 
 
 
 
 
0abb8ee
423d452
 
 
 
 
 
 
 
 
 
 
 
 
a064080
869e51a
423d452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64ccc23
a064080
423d452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a064080
64ccc23
ba7ad90
423d452
ba7ad90
 
423d452
 
ba7ad90
423d452
 
 
 
 
 
 
 
 
0abb8ee
 
423d452
60eafd1
ba7ad90
60eafd1
869e51a
 
ba7ad90
869e51a
74ed166
 
869e51a
60eafd1
0abb8ee
423d452
 
 
 
 
 
ba7ad90
423d452
 
 
4727cae
423d452
 
ba7ad90
423d452
 
ba7ad90
 
 
423d452
 
ef720ae
423d452
 
ba7ad90
423d452
 
 
 
 
 
ba7ad90
 
423d452
 
869e51a
423d452
 
 
 
ba7ad90
 
 
423d452
 
ba7ad90
 
 
 
 
 
423d452
 
ba7ad90
 
 
423d452
ba7ad90
 
423d452
ba7ad90
 
423d452
ba7ad90
 
 
423d452
869e51a
0abb8ee
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7ad90
 
 
 
 
423d452
ba7ad90
 
423d452
 
0abb8ee
423d452
0abb8ee
423d452
 
 
0abb8ee
423d452
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7ad90
423d452
ba7ad90
0abb8ee
423d452
 
ba7ad90
 
423d452
 
 
 
 
 
 
ba7ad90
423d452
 
 
 
 
 
 
 
 
 
ba7ad90
423d452
 
 
 
 
 
 
 
 
 
 
 
 
 
ba7ad90
 
 
 
 
 
 
423d452
 
ba7ad90
 
 
0abb8ee
ba7ad90
 
423d452
ba7ad90
0abb8ee
ba7ad90
 
 
0abb8ee
ba7ad90
423d452
ba7ad90
 
 
 
423d452
 
0abb8ee
 
ba7ad90
423d452
0abb8ee
423d452
64ccc23
a064080
64ccc23
869e51a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
"""
Inference Script β€” Interactive SQL Query Repair Environment
===========================================================

STDOUT FORMAT
  [START] task=<task_id> env=sql-repair model=<model_name>
  [STEP]  step=<n> action=<action_str> reward=<0.00> done=<true|false> error=<msg|null>
  [END]   success=<true|false> steps=<n> score=<score> rewards=<r1,r2,...,rn>

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": "<your question>"}

    To test a query:
      {"action": "run_partial", "query": "<SELECT ...>"}

    To submit your final fix:
      {"action": "submit_query", "query": "<SELECT ...>"}
""").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()