File size: 20,161 Bytes
7d90172 | 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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 | """Shared protocol for SPAgent Sokoban and FifteenPuzzle training.
This module has no ms-swift or Beyond-MMEnv dependency. Dataset generation,
GRPO rollout stepping, answer replay, rendering, and future evaluation adapters
can therefore use the same deterministic transition rules.
"""
from __future__ import annotations
import json
import os
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Tuple
from PIL import Image, ImageDraw, ImageFont
from spagent.frozenlake_v3_protocol import create_tool_response
SOKOBAN_TASK = "Games/Sokoban-v0"
FIFTEEN_TASK = "Games/FifteenPuzzle-v0"
SUPPORTED_TASKS = (SOKOBAN_TASK, FIFTEEN_TASK)
DIRECTIONS: Dict[str, Tuple[int, int]] = {
"Left": (0, -1),
"Down": (1, 0),
"Right": (0, 1),
"Up": (-1, 0),
}
ANSWER_TOKEN_RE = re.compile(r"[\s,;]+")
SOKOBAN_CELL_PX = 64
FIFTEEN_CELL_PX = 80
MARGIN = 20
SOKOBAN_COLORS = {
"#": (54, 59, 68),
"_": (232, 235, 239),
"O": (250, 208, 91),
"X": (164, 105, 57),
"*": (104, 176, 93),
"P": (70, 135, 210),
"+": (92, 183, 211),
}
_font_cache: Dict[Tuple[str, int], ImageFont.ImageFont] = {}
@dataclass(frozen=True)
class StepOutcome:
changed: bool
done: bool
success: bool
body_text: str
tool_result: Dict[str, Any]
def _font(size: int, *, bold: bool = False) -> ImageFont.ImageFont:
key = ("bold" if bold else "regular", size)
if key not in _font_cache:
filename = "DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf"
try:
_font_cache[key] = ImageFont.truetype(filename, size)
except OSError:
_font_cache[key] = ImageFont.load_default()
return _font_cache[key]
def parse_action_tokens(answer_text: str) -> List[str]:
"""Parse a lenient, space/comma/semicolon-separated direction sequence."""
if not answer_text:
return []
actions: List[str] = []
for token in ANSWER_TOKEN_RE.split(answer_text.strip()):
normalized = re.sub(r"[^A-Za-z]", "", token).capitalize()
if normalized in DIRECTIONS:
actions.append(normalized)
return actions
def encode_initial_state(state: Mapping[str, Any]) -> str:
"""Return a stable JSON representation suitable for a JSONL column."""
return json.dumps(state, sort_keys=True, separators=(",", ":"))
def decode_initial_state(value: str | Mapping[str, Any]) -> Dict[str, Any]:
if isinstance(value, str):
state = json.loads(value)
elif isinstance(value, Mapping):
state = dict(value)
else:
raise TypeError(
"initial_state must be JSON text or a mapping, "
f"got {type(value)}"
)
if not isinstance(state, dict):
raise ValueError("initial_state must decode to an object")
return state
def canonical_sokoban_state(
*,
rows: int,
cols: int,
walls: Iterable[Tuple[int, int]],
goals: Iterable[Tuple[int, int]],
boxes: Iterable[Tuple[int, int]],
player: Tuple[int, int],
) -> Dict[str, Any]:
return {
"rows": int(rows),
"cols": int(cols),
"walls": [list(pos) for pos in sorted(set(walls))],
"goals": [list(pos) for pos in sorted(set(goals))],
"boxes": [list(pos) for pos in sorted(set(boxes))],
"player": list(player),
}
def canonical_fifteen_state(board: Iterable[int], *, size: int = 4) -> Dict[str, Any]:
values = [int(value) for value in board]
expected = set(range(size * size))
if len(values) != size * size or set(values) != expected:
raise ValueError(
f"FifteenPuzzle board must contain each value 0..{size * size - 1} once"
)
return {"size": int(size), "board": values}
def clone_state(state: Mapping[str, Any]) -> Dict[str, Any]:
return json.loads(json.dumps(state))
def _pairs(values: Iterable[Iterable[int]]) -> set[Tuple[int, int]]:
return {tuple(int(x) for x in value) for value in values}
def sokoban_grid_lines(state: Mapping[str, Any]) -> List[str]:
rows = int(state["rows"])
cols = int(state["cols"])
walls = _pairs(state["walls"])
goals = _pairs(state["goals"])
boxes = _pairs(state["boxes"])
player = tuple(int(x) for x in state["player"])
lines: List[str] = []
for r in range(rows):
chars: List[str] = []
for c in range(cols):
pos = (r, c)
if pos in walls:
char = "#"
elif pos == player and pos in goals:
char = "+"
elif pos in boxes and pos in goals:
char = "*"
elif pos == player:
char = "P"
elif pos in boxes:
char = "X"
elif pos in goals:
char = "O"
else:
char = "_"
chars.append(char)
lines.append("".join(chars))
return lines
def fifteen_grid_lines(state: Mapping[str, Any]) -> List[str]:
size = int(state.get("size", 4))
board = [int(value) for value in state["board"]]
return [
" ".join(
"__" if value == 0 else f"{value:02d}"
for value in board[row * size : (row + 1) * size]
)
for row in range(size)
]
def state_text(task_id: str, state: Mapping[str, Any]) -> str:
if task_id == SOKOBAN_TASK:
return "\n".join(sokoban_grid_lines(state))
if task_id == FIFTEEN_TASK:
return "\n".join(fifteen_grid_lines(state))
raise ValueError(f"Unsupported task_id: {task_id}")
def is_solved(task_id: str, state: Mapping[str, Any]) -> bool:
if task_id == SOKOBAN_TASK:
return _pairs(state["boxes"]).issubset(_pairs(state["goals"]))
if task_id == FIFTEEN_TASK:
size = int(state.get("size", 4))
solved = list(range(1, size * size)) + [0]
return [int(value) for value in state["board"]] == solved
raise ValueError(f"Unsupported task_id: {task_id}")
def _step_sokoban(state: MutableMapping[str, Any], direction: str) -> StepOutcome:
rows = int(state["rows"])
cols = int(state["cols"])
walls = _pairs(state["walls"])
goals = _pairs(state["goals"])
boxes = _pairs(state["boxes"])
player = tuple(int(x) for x in state["player"])
dr, dc = DIRECTIONS[direction]
dest = (player[0] + dr, player[1] + dc)
if not (0 <= dest[0] < rows and 0 <= dest[1] < cols) or dest in walls:
return StepOutcome(
changed=False,
done=False,
success=False,
body_text=(
f"Blocked: cannot move {direction} from {player}. "
"Position unchanged."
),
tool_result={
"success": False,
"error": "wall",
"from": list(player),
"direction": direction,
},
)
pushed = False
if dest in boxes:
beyond = (dest[0] + dr, dest[1] + dc)
if (
not (0 <= beyond[0] < rows and 0 <= beyond[1] < cols)
or beyond in walls
or beyond in boxes
):
return StepOutcome(
changed=False,
done=False,
success=False,
body_text=(
f"Blocked: the box at {dest} cannot be pushed {direction}. "
"Position unchanged."
),
tool_result={
"success": False,
"error": "blocked_box",
"box": list(dest),
"direction": direction,
},
)
boxes.remove(dest)
boxes.add(beyond)
pushed = True
state["player"] = list(dest)
state["boxes"] = [list(pos) for pos in sorted(boxes)]
success = boxes.issubset(goals)
verb = "Pushed a box and moved" if pushed else "Moved"
body = f"{verb} {direction} to ({dest[0]},{dest[1]})."
if success:
body += " **All boxes are on targets - success!**"
return StepOutcome(
changed=True,
done=success,
success=success,
body_text=body,
tool_result={
"success": True,
"to": list(dest),
"pushed_box": pushed,
"boxes_on_targets": len(boxes & goals),
"total_boxes": len(boxes),
"done": success,
"succeeded": success,
},
)
def _step_fifteen(state: MutableMapping[str, Any], direction: str) -> StepOutcome:
size = int(state.get("size", 4))
board = [int(value) for value in state["board"]]
blank_index = board.index(0)
blank_r, blank_c = divmod(blank_index, size)
# Directions describe the numbered tile's motion into the blank, matching
# Games/FifteenPuzzle-v0. Therefore the blank moves in the opposite visual
# direction.
source_delta = {
"Up": (1, 0),
"Down": (-1, 0),
"Left": (0, 1),
"Right": (0, -1),
}
dr, dc = source_delta[direction]
source_r, source_c = blank_r + dr, blank_c + dc
if not (0 <= source_r < size and 0 <= source_c < size):
return StepOutcome(
changed=False,
done=False,
success=False,
body_text=(
f"Blocked: no tile can move {direction} into the blank at "
f"({blank_r},{blank_c}). Board unchanged."
),
tool_result={
"success": False,
"error": "invalid_slide",
"blank": [blank_r, blank_c],
"direction": direction,
},
)
source_index = source_r * size + source_c
tile = board[source_index]
board[blank_index], board[source_index] = board[source_index], board[blank_index]
state["board"] = board
success = board == list(range(1, size * size)) + [0]
body = (
f"Slid tile {tile} {direction} into the blank. "
f"Blank is now at ({source_r},{source_c})."
)
if success:
body += " **Puzzle solved - success!**"
return StepOutcome(
changed=True,
done=success,
success=success,
body_text=body,
tool_result={
"success": True,
"moved_tile": tile,
"direction": direction,
"blank": [source_r, source_c],
"done": success,
"succeeded": success,
},
)
def step_state(
task_id: str,
state: MutableMapping[str, Any],
direction: Any,
) -> StepOutcome:
if not isinstance(direction, str) or direction not in DIRECTIONS:
return StepOutcome(
changed=False,
done=False,
success=False,
body_text=(
f"Invalid direction {direction!r}. "
"Use one of: Left, Down, Right, Up."
),
tool_result={
"success": False,
"error": "invalid_direction",
"direction": direction,
},
)
if task_id == SOKOBAN_TASK:
return _step_sokoban(state, direction)
if task_id == FIFTEEN_TASK:
return _step_fifteen(state, direction)
raise ValueError(f"Unsupported task_id: {task_id}")
def replay_actions(
task_id: str,
initial_state: str | Mapping[str, Any],
actions: Iterable[Any],
) -> bool:
state = clone_state(decode_initial_state(initial_state))
if is_solved(task_id, state):
return True
for direction in actions:
if not isinstance(direction, str) or direction not in DIRECTIONS:
return False
outcome = step_state(task_id, state, direction)
if not outcome.changed:
return False
if outcome.success:
return True
return is_solved(task_id, state)
def _apply_image_mode(image: Image.Image) -> Image.Image:
mode = os.environ.get("TOOL_IMAGE_MODE", "real").lower().strip()
if mode == "black":
return Image.new("RGB", image.size, "black")
if mode == "white":
return Image.new("RGB", image.size, "white")
return image
def _render_sokoban(state: Mapping[str, Any]) -> Image.Image:
lines = sokoban_grid_lines(state)
rows = len(lines)
cols = len(lines[0])
width = cols * SOKOBAN_CELL_PX + 2 * MARGIN
height = rows * SOKOBAN_CELL_PX + 2 * MARGIN
image = Image.new("RGB", (width, height), "white")
draw = ImageDraw.Draw(image)
label_font = _font(24, bold=True)
for r, line in enumerate(lines):
for c, char in enumerate(line):
x0 = MARGIN + c * SOKOBAN_CELL_PX
y0 = MARGIN + r * SOKOBAN_CELL_PX
draw.rectangle(
[x0, y0, x0 + SOKOBAN_CELL_PX, y0 + SOKOBAN_CELL_PX],
fill=SOKOBAN_COLORS[char],
outline=(65, 65, 65),
width=2,
)
if char != "_":
bbox = draw.textbbox((0, 0), char, font=label_font)
text_w = bbox[2] - bbox[0]
text_h = bbox[3] - bbox[1]
draw.text(
(
x0 + (SOKOBAN_CELL_PX - text_w) // 2,
y0 + (SOKOBAN_CELL_PX - text_h) // 2 - bbox[1],
),
char,
fill="white" if char in {"#", "X", "*", "P", "+"} else "black",
font=label_font,
)
return image
def _render_fifteen(state: Mapping[str, Any]) -> Image.Image:
size = int(state.get("size", 4))
board = [int(value) for value in state["board"]]
width = size * FIFTEEN_CELL_PX + 2 * MARGIN
image = Image.new("RGB", (width, width), (242, 244, 247))
draw = ImageDraw.Draw(image)
number_font = _font(30, bold=True)
for index, value in enumerate(board):
r, c = divmod(index, size)
x0 = MARGIN + c * FIFTEEN_CELL_PX
y0 = MARGIN + r * FIFTEEN_CELL_PX
fill = (90, 98, 110) if value == 0 else (250, 250, 250)
draw.rectangle(
[x0, y0, x0 + FIFTEEN_CELL_PX, y0 + FIFTEEN_CELL_PX],
fill=fill,
outline=(100, 106, 115),
width=2,
)
if value:
text = str(value)
bbox = draw.textbbox((0, 0), text, font=number_font)
text_w = bbox[2] - bbox[0]
text_h = bbox[3] - bbox[1]
draw.text(
(
x0 + (FIFTEEN_CELL_PX - text_w) // 2,
y0 + (FIFTEEN_CELL_PX - text_h) // 2 - bbox[1],
),
text,
fill=(25, 28, 32),
font=number_font,
)
return image
def render_state(
task_id: str,
state: Mapping[str, Any],
output_path: str | Path,
) -> None:
if task_id == SOKOBAN_TASK:
image = _render_sokoban(state)
elif task_id == FIFTEEN_TASK:
image = _render_fifteen(state)
else:
raise ValueError(f"Unsupported task_id: {task_id}")
image = _apply_image_mode(image)
output_path = Path(output_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
image.save(output_path, format="PNG")
def move_tool_spec(task_id: str) -> Dict[str, Any]:
if task_id == SOKOBAN_TASK:
description = (
"Move the player one cell in the given direction. If a box is in "
"that cell and the next cell is free, the box is pushed. Returns "
"the updated complete board as a new image."
)
elif task_id == FIFTEEN_TASK:
description = (
"Slide one numbered tile into the blank. Direction names describe "
"the tile's motion: Up moves the tile below the blank upward, Down "
"moves the tile above downward, Left moves the tile to the right "
"leftward, and Right moves the tile to the left rightward. Returns "
"the updated complete board as a new image."
)
else:
raise ValueError(f"Unsupported task_id: {task_id}")
return {
"type": "function",
"function": {
"name": "move",
"description": description,
"parameters": {
"type": "object",
"properties": {
"direction": {
"type": "string",
"enum": ["Left", "Down", "Right", "Up"],
}
},
"required": ["direction"],
},
},
}
def build_system_prompt(task_id: str) -> str:
if task_id == SOKOBAN_TASK:
intro = (
"You are an agent solving a deterministic Sokoban board.\n\n"
"Cells: # = wall, _ = floor, O = target, X = box, * = box on "
"target, P = player, + = player on target.\n"
"Goal: push every box onto a target. Boxes can be pushed but never "
"pulled. The full board is always visible."
)
elif task_id == FIFTEEN_TASK:
intro = (
"You are an agent solving a deterministic 4x4 Fifteen Puzzle.\n\n"
"The board contains tiles 1 through 15 and one blank shown as __.\n"
"Goal: arrange tiles in row-major order 1..15 with the blank in the "
"bottom-right corner. The full board is always visible."
)
else:
raise ValueError(f"Unsupported task_id: {task_id}")
tool_json = json.dumps(move_tool_spec(task_id), ensure_ascii=False)
return (
f"{intro}\n\n"
"# Tools\n\n"
"You may call one or more functions to assist with the user query.\n\n"
"You are provided with function signatures within <tools></tools> XML tags:\n"
"<tools>\n"
f"{tool_json}\n"
"</tools>\n\n"
"For each function call, return a JSON object with function name and "
"arguments within <tool_call></tool_call> XML tags:\n"
"<tool_call>\n"
'{"name": <function-name>, "arguments": <args-json-object>}\n'
"</tool_call>\n\n"
"Reason step-by-step in <think></think>. When the puzzle is solved, "
"output the full executed direction sequence in <answer></answer>, "
"space-separated."
)
def build_user_prompt(
task_id: str,
state: Mapping[str, Any],
image_path: str | Path,
) -> str:
lines = state_text(task_id, state)
if task_id == SOKOBAN_TASK:
rows = int(state["rows"])
cols = int(state["cols"])
label = "initial Sokoban board"
task_instruction = (
"Push every X box onto an O target. Call the `move` tool one step "
"at a time. After each valid move you will see the updated board."
)
elif task_id == FIFTEEN_TASK:
rows = cols = int(state.get("size", 4))
label = "initial Fifteen Puzzle board"
task_instruction = (
"Arrange the tiles as 01 02 03 04 / 05 06 07 08 / "
"09 10 11 12 / 13 14 15 __. Call the `move` tool one slide at a "
"time. Direction names describe the numbered tile's motion into "
"the blank."
)
else:
raise ValueError(f"Unsupported task_id: {task_id}")
return (
f"# Initial Grid (text view, {rows}x{cols})\n"
f"{lines}\n\n"
"# Images\n"
f"- Image_1 ({label}) — img_idx=0\n"
f"<image>[image: {Path(image_path).resolve()}]\n\n"
f"{task_instruction}\n\n"
"Output step-by-step reasoning in <think></think>. When solved, output "
"the full executed action sequence in <answer></answer>."
)
__all__ = [
"DIRECTIONS",
"FIFTEEN_TASK",
"SOKOBAN_TASK",
"SUPPORTED_TASKS",
"StepOutcome",
"build_system_prompt",
"build_user_prompt",
"canonical_fifteen_state",
"canonical_sokoban_state",
"clone_state",
"create_tool_response",
"decode_initial_state",
"encode_initial_state",
"fifteen_grid_lines",
"is_solved",
"move_tool_spec",
"parse_action_tokens",
"render_state",
"replay_actions",
"sokoban_grid_lines",
"state_text",
"step_state",
]
|