File size: 5,370 Bytes
2f8e591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e07a31
2f8e591
 
6b6921a
2e07a31
2f8e591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b6921a
2f8e591
 
 
 
6b6921a
2f8e591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b6921a
2f8e591
 
 
 
 
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
"""
inference.py — Baseline inference script for OpenENV SQL Debugging environment.

Location: project root (mandatory per OpenEnv spec).

Usage:
    export HF_TOKEN=hf_...
    export API_BASE_URL=https://router.huggingface.co/v1   # optional
    export MODEL_NAME=Qwen/Qwen2.5-72B-Instruct            # optional
    export ENV_BASE_URL=http://localhost:7860               # optional
    python inference.py

Log format:
    [START <task_name>]
    [STEP <n> | reward=<r> | done=<d>]
    [END <task_name> | final_reward=<r>]
"""

import os
import json
import sys
import requests
from openai import OpenAI

# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
API_BASE_URL = os.environ.get("API_BASE_URL", "https://router.huggingface.co/v1")
MODEL_NAME = os.environ.get("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
HF_TOKEN = os.environ.get("HF_TOKEN", "")
ENV_BASE_URL = os.environ.get("ENV_BASE_URL", "http://localhost:7860")
MAX_STEPS = int(os.environ.get("MAX_STEPS", "8"))

TASKS = ["fix-syntax", "fix-logic", "fix-and-optimize"]

if not HF_TOKEN:
    print("ERROR: HF_TOKEN environment variable is required.", file=sys.stderr)
    sys.exit(1)

# ---------------------------------------------------------------------------
# OpenAI client (pointing at HF inference router)
# ---------------------------------------------------------------------------
client = OpenAI(
    base_url=API_BASE_URL,
    api_key=HF_TOKEN,
)

# ---------------------------------------------------------------------------
# Prompt helpers
# ---------------------------------------------------------------------------

SYSTEM_PROMPT = """\
You are an expert SQL developer and debugger. Your job is to fix broken SQL queries.

You will be given:
- A database SCHEMA (CREATE TABLE statements)
- A TASK DESCRIPTION explaining what the correct query should return
- The BROKEN QUERY that you need to fix
- (After the first attempt) the ERROR or OUTPUT from your last attempt

Rules:
- Respond with ONLY the corrected SQL query — no explanations, no markdown fences, no preamble.
- Your response must be valid SQL that can be executed directly.
- Fix ALL bugs in the query, not just one at a time.
- If you receive partial credit, re-read the task description and try harder.
"""


def build_user_prompt(obs: dict) -> str:
    lines = [
        "## SCHEMA",
        obs["schema_str"],
        "",
        "## TASK DESCRIPTION",
        obs["task_description"],
        "",
        "## BROKEN QUERY (original, for reference)",
        obs["broken_query"],
        "",
        f"## STEP {obs['step_number']}",
    ]
    if obs.get("last_error"):
        lines += ["### Last Error", obs["last_error"]]
    if obs.get("last_output"):
        lines += ["### Last Output", obs["last_output"]]
    lines += ["", "Write your corrected SQL query below:"]
    return "\n".join(lines)


# ---------------------------------------------------------------------------
# Environment client helpers
# ---------------------------------------------------------------------------

def env_reset(task: str) -> dict:
    resp = requests.post(f"{ENV_BASE_URL}/reset", params={"task": task}, timeout=30)
    resp.raise_for_status()
    return resp.json()


def env_step(query: str) -> dict:
    payload = {"query": query}
    resp = requests.post(
        f"{ENV_BASE_URL}/step",
        data=json.dumps(payload),
        headers={"Content-Type": "application/json"},
        timeout=30,
    )
    resp.raise_for_status()
    return resp.json()


# ---------------------------------------------------------------------------
# Main inference loop
# ---------------------------------------------------------------------------

def run_task(task_name: str) -> float:
    print(f"[START] task={task_name}", flush=True)

    obs = env_reset(task_name)
    final_reward = 0
    step_num = 0

    for step_num in range(1, MAX_STEPS + 1):
        user_prompt = build_user_prompt(obs)

        # Call the LLM
        response = client.chat.completions.create(
            model=MODEL_NAME,
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": user_prompt},
            ],
            temperature=0.2,
            max_tokens=512,
        )
        query = response.choices[0].message.content.strip()

        # Submit to environment
        result = env_step(query)
        reward = result["reward"]
        done = result["done"]
        obs = result["observation"]

        final_reward = reward
        print(f"[STEP] step={step_num} reward={reward}", flush=True)

        if done:
            break

    print(f"[END] task={task_name} score={final_reward} steps={step_num}", flush=True)
    return final_reward


def main():
    print("=" * 60)
    print("OpenENV SQL Debugging — Baseline Inference")
    print(f"Model  : {MODEL_NAME}")
    print(f"Server : {ENV_BASE_URL}")
    print("=" * 60)

    all_scores = {}
    for task_name in TASKS:
        score = run_task(task_name)
        all_scores[task_name] = score
        print()

    print("=" * 60)
    print("Summary:")
    for task_name, score in all_scores.items():
        print(f"  {task_name}: {score}")
    print("=" * 60)


if __name__ == "__main__":
    main()