SPAgent-NonFrozenLake-2K / code /spagent /vrbench_navigation_protocol.py
AIcell's picture
Upload SPAgent non-FrozenLake 2K training suite
7d90172 verified
Raw History Blame Contribute Delete
14.9 kB
"""Shared SPAgent protocol for deterministic VRBench navigation tasks.
Dataset generation samples official Beyond-MMEnv states. Training rollouts,
answer replay, rendering, and tests use the pure deterministic state machine
defined here, so distributed workers do not need Beyond-MMEnv installed.
"""
from __future__ import annotations
import json
import os
from collections import deque
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 (
DIRS,
create_tool_response,
parse_action_tokens,
)
PATHFINDER_TASK = "VRBench/Pathfinder-v0"
MAZE_TASK = "VRBench/Maze-v0"
TRAPFIELD_TASK = "VRBench/TrapField-v0"
SUPPORTED_TASKS = (PATHFINDER_TASK, MAZE_TASK, TRAPFIELD_TASK)
EMPTY = 0
WALL = 1
PLAYER = 2
GOAL = 3
TRAP = 4
TASK_LABELS = {
PATHFINDER_TASK: "Pathfinder",
MAZE_TASK: "Maze",
TRAPFIELD_TASK: "TrapField",
}
TASK_TITLES = {
PATHFINDER_TASK: "VRBench Pathfinder",
MAZE_TASK: "VRBench Maze",
TRAPFIELD_TASK: "VRBench TrapField",
}
# The current upstream TrapField generator usually disconnects start and goal.
# These seeds are verified solvable and are also used by the evaluation suite.
TRAPFIELD_SOLVABLE_SEEDS = (
173,
1126,
1553,
1701,
2596,
3860,
3962,
4296,
4736,
5098,
5206,
5805,
5839,
7126,
7856,
10060,
10741,
10748,
10751,
10995,
11073,
11089,
11155,
11194,
11918,
12206,
13519,
14715,
15212,
15265,
)
CELL_PX = 40
MARGIN = 20
PALETTE = {
"F": (210, 235, 255),
"S": (170, 225, 150),
"G": (245, 205, 70),
"#": (45, 55, 70),
"X": (190, 65, 65),
"AGENT": (220, 70, 70),
"GRID": (60, 60, 60),
}
_font: ImageFont.ImageFont | None = None
@dataclass(frozen=True)
class StepOutcome:
changed: bool
done: bool
success: bool
body_text: str
tool_result: Dict[str, Any]
def encode_initial_state(state: Mapping[str, Any]) -> str:
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 clone_state(state: Mapping[str, Any]) -> Dict[str, Any]:
return json.loads(json.dumps(state))
def canonical_state(
*,
grid: Iterable[Iterable[int]],
start: Tuple[int, int],
goal: Tuple[int, int],
) -> Dict[str, Any]:
rows = [[int(cell) for cell in row] for row in grid]
if not rows or not rows[0] or any(len(row) != len(rows[0]) for row in rows):
raise ValueError("grid must be a non-empty rectangle")
allowed = {EMPTY, WALL, PLAYER, GOAL, TRAP}
if any(cell not in allowed for row in rows for cell in row):
raise ValueError("grid contains an unsupported cell value")
sr, sc = (int(start[0]), int(start[1]))
gr, gc = (int(goal[0]), int(goal[1]))
if not (0 <= sr < len(rows) and 0 <= sc < len(rows[0])):
raise ValueError(f"start is outside the grid: {(sr, sc)}")
if not (0 <= gr < len(rows) and 0 <= gc < len(rows[0])):
raise ValueError(f"goal is outside the grid: {(gr, gc)}")
rows[sr][sc] = EMPTY
rows[gr][gc] = GOAL
return {
"grid": rows,
"start": [sr, sc],
"goal": [gr, gc],
"position": [sr, sc],
}
def symbolic_grid_lines(
state: Mapping[str, Any],
*,
initial: bool = False,
) -> List[str]:
grid = state["grid"]
position = tuple(int(value) for value in state["position"])
start = tuple(int(value) for value in state["start"])
goal = tuple(int(value) for value in state["goal"])
mapping = {EMPTY: "F", WALL: "#", GOAL: "G", TRAP: "X"}
rows: List[str] = []
for r, row in enumerate(grid):
chars: List[str] = []
for c, value in enumerate(row):
pos = (r, c)
if initial and pos == start:
chars.append("S")
elif not initial and pos == position:
chars.append("P")
elif pos == goal:
chars.append("G")
else:
chars.append(mapping[int(value)])
rows.append("".join(chars))
return rows
def state_text(state: Mapping[str, Any], *, initial: bool = False) -> str:
return "\n".join(symbolic_grid_lines(state, initial=initial))
def is_solved(state: Mapping[str, Any]) -> bool:
position = tuple(int(value) for value in state["position"])
goal = tuple(int(value) for value in state["goal"])
return position == goal
def step_state(
task_id: str,
state: MutableMapping[str, Any],
direction: Any,
) -> StepOutcome:
if task_id not in SUPPORTED_TASKS:
raise ValueError(f"Unsupported task_id: {task_id}")
if not isinstance(direction, str) or direction not in DIRS:
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,
},
)
grid = state["grid"]
r, c = (int(value) for value in state["position"])
dr, dc = DIRS[direction]
nr, nc = r + dr, c + dc
if not (0 <= nr < len(grid) and 0 <= nc < len(grid[0])):
obstacle = "wall"
else:
destination = int(grid[nr][nc])
obstacle = (
"wall"
if destination == WALL
else "trap"
if destination == TRAP
else ""
)
if obstacle:
return StepOutcome(
changed=False,
done=False,
success=False,
body_text=(
f"Blocked by {obstacle}: cannot move {direction} from "
f"({r},{c}). Position unchanged."
),
tool_result={
"success": False,
"error": obstacle,
"from": [r, c],
"direction": direction,
},
)
state["position"] = [nr, nc]
success = (nr, nc) == tuple(int(value) for value in state["goal"])
cell = "G" if success else "F"
body = f"Moved {direction} to ({nr},{nc}). Cell: {cell}."
if success:
body += " **Reached goal - success!**"
return StepOutcome(
changed=True,
done=success,
success=success,
body_text=body,
tool_result={
"success": True,
"to": [nr, nc],
"cell": cell,
"done": success,
"succeeded": success,
},
)
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(state):
return True
for direction in actions:
outcome = step_state(task_id, state, direction)
if not outcome.changed:
return False
if outcome.success:
return True
return is_solved(state)
def shortest_path(state: Mapping[str, Any]) -> List[str] | None:
grid = state["grid"]
start = tuple(int(value) for value in state["start"])
goal = tuple(int(value) for value in state["goal"])
queue = deque([(start, [])])
seen = {start}
while queue:
(r, c), path = queue.popleft()
if (r, c) == goal:
return path
for direction, (dr, dc) in DIRS.items():
nr, nc = r + dr, c + dc
if not (0 <= nr < len(grid) and 0 <= nc < len(grid[0])):
continue
if (nr, nc) in seen or int(grid[nr][nc]) in (WALL, TRAP):
continue
seen.add((nr, nc))
queue.append(((nr, nc), path + [direction]))
return None
def _font_fn() -> ImageFont.ImageFont:
global _font
if _font is None:
try:
_font = ImageFont.truetype("DejaVuSans-Bold.ttf", 18)
except OSError:
_font = ImageFont.load_default()
return _font
def render_state(
task_id: str,
state: Mapping[str, Any],
output_path: str | Path,
) -> None:
if task_id not in SUPPORTED_TASKS:
raise ValueError(f"Unsupported task_id: {task_id}")
lines = symbolic_grid_lines(state, initial=True)
rows, cols = len(lines), len(lines[0])
width = cols * CELL_PX + 2 * MARGIN
height = rows * CELL_PX + 2 * MARGIN
image = Image.new("RGB", (width, height), "white")
draw = ImageDraw.Draw(image)
font = _font_fn()
for row_index, row in enumerate(lines):
for col_index, value in enumerate(row):
x0 = MARGIN + col_index * CELL_PX
y0 = MARGIN + row_index * CELL_PX
draw.rectangle(
[x0, y0, x0 + CELL_PX, y0 + CELL_PX],
fill=PALETTE[value],
outline=PALETTE["GRID"],
width=2,
)
bbox = draw.textbbox((0, 0), value, font=font)
text_width = bbox[2] - bbox[0]
draw.text(
(
x0 + (CELL_PX - text_width) // 2,
y0 + 2,
),
value,
fill="white" if value in {"#", "X"} else "black",
font=font,
)
r, c = (int(value) for value in state["position"])
center_x = MARGIN + c * CELL_PX + CELL_PX // 2
center_y = MARGIN + r * CELL_PX + CELL_PX // 2 + 5
radius = max(6, CELL_PX // 4)
draw.ellipse(
[
center_x - radius,
center_y - radius,
center_x + radius,
center_y + radius,
],
fill=PALETTE["AGENT"],
outline="black",
width=2,
)
mode = os.environ.get("TOOL_IMAGE_MODE", "real").lower().strip()
if mode == "black":
image = Image.new("RGB", image.size, "black")
elif mode == "white":
image = Image.new("RGB", image.size, "white")
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]:
label = TASK_LABELS[task_id]
blocked = "walls and blocked traps" if task_id == TRAPFIELD_TASK else "walls"
return {
"type": "function",
"function": {
"name": "move",
"description": (
f"Move the agent one cell on the {label} grid. Moves into "
f"{blocked} are no-ops. Returns the updated complete grid "
"as a new image."
),
"parameters": {
"type": "object",
"properties": {
"direction": {
"type": "string",
"enum": ["Left", "Down", "Right", "Up"],
}
},
"required": ["direction"],
},
},
}
def build_system_prompt(task_id: str, state: Mapping[str, Any]) -> str:
if task_id not in SUPPORTED_TASKS:
raise ValueError(f"Unsupported task_id: {task_id}")
size = len(state["grid"])
label = TASK_LABELS[task_id]
cells = (
"S = start, G = goal, F = free cell, # = wall, X = blocked trap."
if task_id == TRAPFIELD_TASK
else "S = start, G = goal, F = free cell, # = wall."
)
objective = (
"Reach G while avoiding walls and every blocked trap X."
if task_id == TRAPFIELD_TASK
else "Reach G while avoiding walls."
)
schema = json.dumps(move_tool_spec(task_id), ensure_ascii=False)
return (
f"You are an agent navigating a {size}x{size} {label} grid.\n\n"
f"Cells: {cells}\n"
"The environment is deterministic and fully observed. A move succeeds "
"when its destination is traversable; blocked moves are no-ops and the "
"grid does not wrap.\n"
f"Goal: {objective}\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"{schema}\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 you reach G, 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:
label = TASK_LABELS[task_id]
lines = symbolic_grid_lines(state, initial=True)
start = state["start"]
goal = state["goal"]
objective = (
"Avoid walls and every blocked trap X."
if task_id == TRAPFIELD_TASK
else "Avoid every wall #."
)
return (
f"# Initial Grid (text view, {len(lines)}x{len(lines[0])})\n"
+ "\n".join(lines)
+ "\n\n# Images\n"
f"- Image_1 (initial {label} grid) — img_idx=0\n"
f"<image>[image: {Path(image_path).resolve()}]\n\n"
f"You are at S (row {start[0]}, col {start[1]}). Reach G at "
f"(row {goal[0]}, col {goal[1]}). {objective} Call the `move` tool "
"one step at a time. After each valid move you will see the updated "
"complete grid.\n\n"
"Output step-by-step reasoning in <think></think>. When you reach G, "
"output the full executed action sequence in <answer></answer>."
)
__all__ = [
"DIRS",
"EMPTY",
"GOAL",
"MAZE_TASK",
"PATHFINDER_TASK",
"PLAYER",
"SUPPORTED_TASKS",
"StepOutcome",
"TRAP",
"TRAPFIELD_SOLVABLE_SEEDS",
"TRAPFIELD_TASK",
"WALL",
"build_system_prompt",
"build_user_prompt",
"canonical_state",
"clone_state",
"create_tool_response",
"decode_initial_state",
"encode_initial_state",
"is_solved",
"parse_action_tokens",
"render_state",
"replay_actions",
"shortest_path",
"state_text",
"step_state",
"symbolic_grid_lines",
]