Spaces:
Sleeping

databoysu commited on
Commit
a27cb68
·
1 Parent(s): 9a026d7

Thought enabling

Browse files
Files changed (1) hide show
  1. inference.py +186 -129
inference.py CHANGED
@@ -45,46 +45,100 @@ TASK_NAME = os.getenv("TASK_NAME", "tracefix_rl")
45
  BENCHMARK = os.getenv("BENCHMARK", "tracefix_rl")
46
  MAX_STEPS = int(os.getenv("MAX_STEPS", "50"))
47
  SUCCESS_SCORE_THRESHOLD = float(os.getenv("SUCCESS_SCORE_THRESHOLD", "0.99"))
48
- MAX_PARSE_RETRIES = 3
49
-
50
- SYSTEM_PROMPT = (
51
- "You are controlling a Python debugging RL environment. "
52
- "Return only JSON for one action.\n"
53
- 'Allowed action_type values: VIEW_CODE, RUN_TESTS, REPLACE_LINES, UNDO_EDIT, RESET_TO_ORIGINAL, SUBMIT.\n'
54
- "For REPLACE_LINES include start_line, end_line, new_code_block.\n"
55
- "If available, include a 'thought' field explaining what you observed and why this is the next best action.\n"
56
- "Prefer RUN_TESTS after edits and SUBMIT only when all tests pass."
57
- )
58
-
59
- ACTION_JSON_SCHEMA: dict[str, Any] = {
60
- "type": "json_schema",
61
- "json_schema": {
62
- "name": "CodeAction",
63
- "strict": True,
64
- "schema": {
65
- "type": "object",
66
- "properties": {
67
- "thought": {"type": ["string", "null"]},
68
- "action_type": {
69
- "type": "string",
70
- "enum": [
71
- "VIEW_CODE",
72
- "RUN_TESTS",
73
- "REPLACE_LINES",
74
- "UNDO_EDIT",
75
- "RESET_TO_ORIGINAL",
76
- "SUBMIT",
77
- ],
78
- },
79
- "start_line": {"type": ["integer", "null"]},
80
- "end_line": {"type": ["integer", "null"]},
81
- "new_code_block": {"type": ["string", "null"]},
82
- },
83
- "required": ["action_type"],
84
- "additionalProperties": False,
85
- },
86
- },
87
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
 
90
  def log_start(task: str, env: str, model: str) -> None:
@@ -107,19 +161,6 @@ def log_end(success: bool, steps: int, score: float, rewards: list[float]) -> No
107
  )
108
 
109
 
110
- def _extract_json(text: str) -> dict[str, Any]:
111
- stripped = text.strip()
112
- if stripped.startswith("```") and stripped.endswith("```"):
113
- first_newline = stripped.find("\n")
114
- if first_newline == -1:
115
- raise ValueError("Invalid JSON response.")
116
- stripped = stripped[first_newline + 1 : -3].strip()
117
- try:
118
- return json.loads(stripped)
119
- except json.JSONDecodeError as exc:
120
- raise ValueError("Invalid JSON response.") from exc
121
-
122
-
123
  def _build_observation_text(observation: Any) -> str:
124
  code_dict = getattr(observation, "code_dict", {}) or {}
125
  sorted_items = sorted(
@@ -140,64 +181,63 @@ def _build_observation_text(observation: Any) -> str:
140
  )
141
 
142
 
143
- def _get_model_response(
144
- client: OpenAI, observation: Any, history: list[str]
145
- ) -> str:
146
- obs_text = _build_observation_text(observation)
147
- user_prompt = (
148
- "Pick the single best next action and return only JSON.\n\n"
149
- f"{obs_text}\n\n"
150
- f"history:\n{chr(10).join(history[-5:]) if history else 'none'}"
151
- )
152
- request_kwargs = {
153
- "model": MODEL_NAME,
154
- "messages": [
155
- {"role": "system", "content": SYSTEM_PROMPT},
156
- {"role": "user", "content": user_prompt},
157
- ],
158
- "temperature": 0.0,
159
- "stream": False,
160
- }
161
  try:
162
- completion = client.chat.completions.create(
163
- **request_kwargs,
164
- response_format=ACTION_JSON_SCHEMA,
 
 
165
  )
166
- except Exception:
167
- completion = client.chat.completions.create(**request_kwargs)
168
- return (completion.choices[0].message.content or "").strip()
169
-
170
-
171
- def _parse_model_action(response_text: str) -> dict[str, Any]:
172
- action = _extract_json(response_text)
173
-
174
- if action.get("action_type") not in {
175
- "VIEW_CODE",
176
- "RUN_TESTS",
177
- "REPLACE_LINES",
178
- "UNDO_EDIT",
179
- "RESET_TO_ORIGINAL",
180
- "SUBMIT",
181
- }:
182
- raise ValueError("Invalid action_type in model response.")
183
-
184
- return action
185
-
186
 
187
- def _to_code_action(action_dict: dict[str, Any]) -> CodeAction:
188
- payload = {
189
- "action_type": action_dict.get("action_type"),
190
- "thought": action_dict.get("thought"),
191
- "start_line": action_dict.get("start_line"),
192
- "end_line": action_dict.get("end_line"),
193
- "new_code_block": action_dict.get("new_code_block"),
194
- }
195
- return CodeAction(**payload)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
 
198
- def _print_thought(action_dict: dict[str, Any], raw_response: str) -> None:
199
- thought = action_dict.get("thought")
200
- thought_text = thought.strip() if isinstance(thought, str) else ""
201
  print("[THOUGHT]", file=sys.stderr, flush=True)
202
  print(thought_text if thought_text else raw_response, file=sys.stderr, flush=True)
203
 
@@ -219,6 +259,7 @@ async def run(difficulty: Optional[str] = None, show_thought: bool = False) -> N
219
  env: Optional[TraceFixRLEnv] = None
220
  rewards: list[float] = []
221
  history: list[str] = []
 
222
  steps_taken = 0
223
  score = 0.0
224
  success = False
@@ -244,7 +285,7 @@ async def run(difficulty: Optional[str] = None, show_thought: bool = False) -> N
244
  break
245
 
246
  action: Optional[CodeAction] = None
247
- model_response = ""
248
  if step == 1:
249
  action = CodeAction(
250
  action_type="VIEW_CODE",
@@ -254,30 +295,44 @@ async def run(difficulty: Optional[str] = None, show_thought: bool = False) -> N
254
  print("[THOUGHT]", file=sys.stderr, flush=True)
255
  print(action.thought, file=sys.stderr, flush=True)
256
  else:
257
- for attempt in range(1, MAX_PARSE_RETRIES + 1):
258
- try:
259
- model_response = _get_model_response(client, result.observation, history)
260
- action_dict = _parse_model_action(model_response)
261
- if show_thought:
262
- _print_thought(action_dict, model_response)
263
- action = _to_code_action(action_dict)
264
- break
265
- except Exception as exc:
266
- cause = str(exc).replace("\n", " ")
267
- history.append(
268
- (
269
- f"parse_failure attempt={attempt} cause={cause}. "
270
- "Error: Invalid JSON or schema. Return a complete valid JSON object "
271
- "with fields: thought, action_type, start_line, end_line, new_code_block."
272
- )
273
- )
274
- if model_response:
275
- history.append(f"raw_response={model_response[:500]}")
276
-
277
- if action is None:
 
 
 
 
 
 
 
 
 
 
 
278
  action = CodeAction(
279
  action_type="RUN_TESTS",
280
- thought="Fallback after repeated invalid JSON/schema responses.",
 
 
 
281
  )
282
 
283
  result = await env.step(action)
@@ -290,6 +345,8 @@ async def run(difficulty: Optional[str] = None, show_thought: bool = False) -> N
290
  error = obs_meta.get("last_action_error")
291
  if error is not None:
292
  error = str(error).replace("\n", " ")
 
 
293
 
294
  rewards.append(reward)
295
  steps_taken = step
 
45
  BENCHMARK = os.getenv("BENCHMARK", "tracefix_rl")
46
  MAX_STEPS = int(os.getenv("MAX_STEPS", "50"))
47
  SUCCESS_SCORE_THRESHOLD = float(os.getenv("SUCCESS_SCORE_THRESHOLD", "0.99"))
48
+
49
+ SYSTEM_PROMPT = """\
50
+ You are the policy controller for a Python debugging RL environment.
51
+
52
+ Operating contract:
53
+ 1. Output exactly one CodeAction object per turn.
54
+ 2. Use the prior conversation history, especially your earlier thoughts and failed outputs, to avoid repeating mistakes.
55
+ 3. Treat PARSE_ERROR feedback as hard constraints that must be corrected on the next turn.
56
+
57
+ Reasoning procedure (must be reflected in thought):
58
+ 1. Read localized_context and last_execution_output first.
59
+ 2. If tests failed, identify the most likely failing line and root cause.
60
+ 3. Decide the next single best action that maximizes test progress.
61
+ 4. If editing, reference exact line keys from code_dict and provide correctly indented replacement code.
62
+ 5. Only SUBMIT when current evidence shows all tests pass.
63
+
64
+ Action policy:
65
+ - VIEW_CODE: only when you need to re-orient line mapping.
66
+ - RUN_TESTS: use to obtain fresh traceback evidence and validate edits.
67
+ - REPLACE_LINES: apply a focused fix for one concrete bug.
68
+ - UNDO_EDIT: use when latest edit regressed behavior.
69
+ - RESET_TO_ORIGINAL: last resort recovery.
70
+ - SUBMIT: only after explicit all-pass confirmation.
71
+
72
+ Formatting policy:
73
+ - Return a valid CodeAction object only.
74
+ - No markdown, no prose outside the action fields.
75
+ - Use EXACT keys: thought, action_type, start_line, end_line, new_code_block.
76
+ - NEVER use legacy keys such as type, lines, or source.
77
+
78
+ Valid JSON examples:
79
+ {"thought":"I need traceback details before editing.","action_type":"RUN_TESTS","start_line":null,"end_line":null,"new_code_block":null}
80
+ {"thought":"Line 2 slicing step is wrong; replace only that line.","action_type":"REPLACE_LINES","start_line":2,"end_line":2,"new_code_block":" return s[::-1]"}
81
+ """
82
+
83
+
84
+ class ModelParseError(Exception):
85
+ """Raised when model output cannot be parsed into CodeAction."""
86
+
87
+ def __init__(self, message: str, raw_response: str = "") -> None:
88
+ super().__init__(message)
89
+ self.raw_response = raw_response
90
+
91
+
92
+ def _decode_action_json(raw_text: str) -> dict[str, Any]:
93
+ stripped = raw_text.strip()
94
+ if stripped.startswith("```") and stripped.endswith("```"):
95
+ first_newline = stripped.find("\n")
96
+ if first_newline == -1:
97
+ raise ValueError("Invalid fenced JSON response.")
98
+ stripped = stripped[first_newline + 1 : -3].strip()
99
+ return json.loads(stripped)
100
+
101
+
102
+ def _coerce_legacy_action_payload(payload: dict[str, Any]) -> dict[str, Any]:
103
+ """
104
+ Normalize common legacy output shapes into strict CodeAction fields.
105
+
106
+ This keeps runtime resilient across weaker model backends while still
107
+ validating the final payload with strict Pydantic rules.
108
+ """
109
+ normalized = dict(payload)
110
+
111
+ if "action_type" not in normalized and isinstance(normalized.get("type"), str):
112
+ normalized["action_type"] = normalized["type"]
113
+
114
+ if "thought" not in normalized or normalized.get("thought") in (None, ""):
115
+ normalized["thought"] = (
116
+ "Recovered malformed action payload and mapped legacy fields "
117
+ "to strict CodeAction schema."
118
+ )
119
+
120
+ if "lines" in normalized and isinstance(normalized["lines"], list):
121
+ line_items = []
122
+ for item in normalized["lines"]:
123
+ if not isinstance(item, dict):
124
+ continue
125
+ line_no = item.get("line")
126
+ code_text = item.get("code")
127
+ if isinstance(line_no, int) and isinstance(code_text, str):
128
+ line_items.append((line_no, code_text))
129
+ if line_items:
130
+ line_items.sort(key=lambda x: x[0])
131
+ if "start_line" not in normalized:
132
+ normalized["start_line"] = line_items[0][0]
133
+ if "end_line" not in normalized:
134
+ normalized["end_line"] = line_items[-1][0]
135
+ if "new_code_block" not in normalized:
136
+ normalized["new_code_block"] = "\n".join(code for _, code in line_items)
137
+
138
+ normalized.pop("type", None)
139
+ normalized.pop("lines", None)
140
+ normalized.pop("source", None)
141
+ return normalized
142
 
143
 
144
  def log_start(task: str, env: str, model: str) -> None:
 
161
  )
162
 
163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  def _build_observation_text(observation: Any) -> str:
165
  code_dict = getattr(observation, "code_dict", {}) or {}
166
  sorted_items = sorted(
 
181
  )
182
 
183
 
184
+ def _get_model_action(
185
+ client: OpenAI,
186
+ history_messages: list[dict[str, str]],
187
+ ) -> tuple[CodeAction, str]:
188
+ request_messages = [{"role": "system", "content": SYSTEM_PROMPT}] + history_messages
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  try:
190
+ completion = client.beta.chat.completions.parse(
191
+ model=MODEL_NAME,
192
+ messages=request_messages,
193
+ temperature=0.0,
194
+ response_format=CodeAction,
195
  )
196
+ message = completion.choices[0].message
197
+ refusal_text = getattr(message, "refusal", None)
198
+ if refusal_text:
199
+ raise ModelParseError(f"Model refusal: {refusal_text}", raw_response=str(refusal_text))
200
+
201
+ parsed = getattr(message, "parsed", None)
202
+ if parsed is None:
203
+ content = getattr(message, "content", "")
204
+ if isinstance(content, str):
205
+ raw_response = content
206
+ else:
207
+ raw_response = json.dumps(content, ensure_ascii=True, default=str)
208
+ raise ModelParseError(
209
+ "Model response was not parsed into CodeAction.",
210
+ raw_response=raw_response,
211
+ )
 
 
 
 
212
 
213
+ action = CodeAction.model_validate(parsed)
214
+ assistant_json = action.model_dump_json(exclude_none=False)
215
+ return action, assistant_json
216
+ except Exception as parse_exc:
217
+ try:
218
+ completion = client.chat.completions.create(
219
+ model=MODEL_NAME,
220
+ messages=request_messages,
221
+ temperature=0.0,
222
+ stream=False,
223
+ )
224
+ raw_text = (completion.choices[0].message.content or "").strip()
225
+ parsed_dict = _decode_action_json(raw_text)
226
+ parsed_dict = _coerce_legacy_action_payload(parsed_dict)
227
+ action = CodeAction.model_validate(parsed_dict)
228
+ assistant_json = action.model_dump_json(exclude_none=False)
229
+ return action, assistant_json
230
+ except Exception as fallback_exc:
231
+ raise ModelParseError(
232
+ (
233
+ f"Model parse call failed: {str(parse_exc).strip()} | "
234
+ f"fallback create path failed: {str(fallback_exc).strip()}"
235
+ )
236
+ ) from fallback_exc
237
 
238
 
239
+ def _print_thought(action: CodeAction, raw_response: str) -> None:
240
+ thought_text = (action.thought or "").strip()
 
241
  print("[THOUGHT]", file=sys.stderr, flush=True)
242
  print(thought_text if thought_text else raw_response, file=sys.stderr, flush=True)
243
 
 
259
  env: Optional[TraceFixRLEnv] = None
260
  rewards: list[float] = []
261
  history: list[str] = []
262
+ history_messages: list[dict[str, str]] = []
263
  steps_taken = 0
264
  score = 0.0
265
  success = False
 
285
  break
286
 
287
  action: Optional[CodeAction] = None
288
+ parse_error_note: Optional[str] = None
289
  if step == 1:
290
  action = CodeAction(
291
  action_type="VIEW_CODE",
 
295
  print("[THOUGHT]", file=sys.stderr, flush=True)
296
  print(action.thought, file=sys.stderr, flush=True)
297
  else:
298
+ obs_text = _build_observation_text(result.observation)
299
+ history_messages.append(
300
+ {
301
+ "role": "user",
302
+ "content": (
303
+ "Pick the single best next action and return only a CodeAction JSON object.\n\n"
304
+ f"{obs_text}"
305
+ ),
306
+ }
307
+ )
308
+ try:
309
+ action, assistant_json = _get_model_action(client, history_messages)
310
+ history_messages.append({"role": "assistant", "content": assistant_json})
311
+ if show_thought:
312
+ _print_thought(action, assistant_json)
313
+ except ModelParseError as exc:
314
+ cause = str(exc).replace("\n", " ")
315
+ parse_error_note = cause
316
+ raw_response = (exc.raw_response or "").strip()
317
+ if raw_response:
318
+ history_messages.append({"role": "assistant", "content": raw_response})
319
+ history_messages.append(
320
+ {
321
+ "role": "user",
322
+ "content": (
323
+ f"PARSE_ERROR: {cause}. "
324
+ "Return one valid CodeAction object only. "
325
+ "Include thought and ensure strict field types."
326
+ ),
327
+ }
328
+ )
329
+ history.append(f"PARSE_ERROR: {cause}")
330
  action = CodeAction(
331
  action_type="RUN_TESTS",
332
+ thought=(
333
+ "PARSE_ERROR recovery step: run tests so the step is explicit and "
334
+ "collect fresh traceback context for the next valid action."
335
+ ),
336
  )
337
 
338
  result = await env.step(action)
 
345
  error = obs_meta.get("last_action_error")
346
  if error is not None:
347
  error = str(error).replace("\n", " ")
348
+ if parse_error_note:
349
+ error = f"PARSE_ERROR: {parse_error_note}"
350
 
351
  rewards.append(reward)
352
  steps_taken = step