Spaces:
Sleeping
Sleeping
databoysu commited on
Commit ·
a27cb68
1
Parent(s): 9a026d7
Thought enabling
Browse files- 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 |
-
|
| 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 |
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
|
| 144 |
-
client: OpenAI,
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 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.
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
| 165 |
)
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
raise ValueError("Invalid action_type in model response.")
|
| 183 |
-
|
| 184 |
-
return action
|
| 185 |
-
|
| 186 |
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
|
| 198 |
-
def _print_thought(
|
| 199 |
-
|
| 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 |
-
|
| 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 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
action = CodeAction(
|
| 279 |
action_type="RUN_TESTS",
|
| 280 |
-
thought=
|
|
|
|
|
|
|
|
|
|
| 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
|