-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinference.py
More file actions
231 lines (163 loc) Β· 6.39 KB
/
Copy pathinference.py
File metadata and controls
231 lines (163 loc) Β· 6.39 KB
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
import os
import textwrap
from typing import List, Optional
from openai import OpenAI
from env import CodeDebugEnv, Action
from tasks import TASKS
# βββββββββββββββββββββββββββββββββββββββββββββ
# CONFIG
# βββββββββββββββββββββββββββββββββββββββββββββ
API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
BENCHMARK = "code-debug-env"
MAX_STEPS = 5
TEMPERATURE = 0.3
MAX_TOKENS = 1024
# π₯ FIXED (important)
SUCCESS_SCORE_THRESHOLD = 0.9
SYSTEM_PROMPT = textwrap.dedent("""
You are an expert Python debugger.
You will be given buggy Python code and an error message.
Your job is to return the COMPLETE corrected Python code.
Rules:
- Return ONLY the fixed Python code
- No explanations
- No markdown
- No ``` blocks
- Keep structure same
""").strip()
# βββββββββββββββββββββββββββββββββββββββββββββ
# LOG FUNCTIONS (REQUIRED FORMAT)
# βββββββββββββββββββββββββββββββββββββββββββββ
def log_start(task: str, env: str, model: str):
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]):
error_val = error if error else "null"
done_val = str(done).lower()
action_short = action.replace("\n", "\\n")[:200]
print(
f"[STEP] step={step} action={action_short} "
f"reward={reward:.2f} done={done_val} error={error_val}",
flush=True
)
def log_end(success: bool, steps: int, score: float, rewards: List[float]):
rewards_str = ",".join(f"{r:.2f}" for r in rewards)
print(
f"[END] success={str(success).lower()} "
f"steps={steps} score={score:.2f} rewards={rewards_str}",
flush=True
)
# βββββββββββββββββββββββββββββββββββββββββββββ
# LLM CALL
# βββββββββββββββββββββββββββββββββββββββββββββ
def get_fixed_code(client: OpenAI, obs, history: List[str]) -> str:
history_block = "\n".join(history[-3:]) if history else "None"
prompt = textwrap.dedent(f"""
Challenge: {obs.description}
Buggy code:
{obs.buggy_code}
Error:
{obs.error_message}
Hint:
{obs.hint}
Previous attempts:
{history_block}
Return ONLY fixed Python code:
""").strip()
try:
response = client.chat.completions.create(
model=MODEL_NAME,
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": prompt}
],
temperature=TEMPERATURE,
max_tokens=MAX_TOKENS,
)
text = (response.choices[0].message.content or "").strip()
# Remove ``` if model adds
if text.startswith("```"):
text = "\n".join([l for l in text.split("\n") if not l.startswith("```")]).strip()
return text if text else obs.buggy_code
except Exception as e:
print(f"[DEBUG] LLM error: {e}", flush=True)
return obs.buggy_code
# βββββββββββββββββββββββββββββββββββββββββββββ
# RUN SINGLE TASK
# βββββββββββββββββββββββββββββββββββββββββββββ
def run_task(client: OpenAI, task_name: str):
task_cfg = TASKS[task_name]
# π₯ FIXED (removed max_steps)
env = CodeDebugEnv(
difficulty=task_cfg["difficulty"],
task=task_cfg["challenge_id"],
seed=42
)
obs = env.reset()
rewards = []
history = []
steps_taken = 0
score = 0.0
success = False
done = False
log_start(task_name, BENCHMARK, MODEL_NAME)
try:
for step in range(1, MAX_STEPS + 1):
if done:
break
error = None
fixed_code = get_fixed_code(client, obs, history)
try:
result = env.step(Action(fixed_code=fixed_code))
reward = result.reward
done = result.done
obs = result.observation
except Exception as e:
reward = 0.0
done = False
error = str(e)[:80]
rewards.append(reward)
steps_taken = step
score = max(score, reward)
# Debug (optional but useful)
print(f"[DEBUG] current score={score}", flush=True)
log_step(step, fixed_code, reward, done, error)
history.append(f"step={step} reward={reward:.2f}")
score = round(min(max(score, 0.0), 1.0), 2)
success = score >= SUCCESS_SCORE_THRESHOLD
finally:
try:
env.close() # π₯ safe now
except:
pass
log_end(success, steps_taken, score, rewards)
return {
"task": task_name,
"score": score,
"success": success,
"steps": steps_taken
}
# βββββββββββββββββββββββββββββββββββββββββββββ
# MAIN
# βββββββββββββββββββββββββββββββββββββββββββββ
def main():
client = OpenAI(
base_url=API_BASE_URL,
api_key=API_KEY
)
results = []
for task in ["easy", "medium", "hard"]:
print("\n" + "="*50, flush=True)
print(f"Running task: {task.upper()}", flush=True)
print("="*50, flush=True)
res = run_task(client, task)
results.append(res)
print("\n" + "="*50, flush=True)
print("FINAL SUMMARY", flush=True)
print("="*50, flush=True)
for r in results:
status = "PASS" if r["success"] else "FAIL"
print(f"[{status}] {r['task']} score={r['score']:.2f} steps={r['steps']}", flush=True)
if __name__ == "__main__":
main()