|
| 1 | +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import re |
| 17 | +from dataclasses import dataclass, field |
| 18 | +from typing import Any, Dict, Optional |
| 19 | + |
| 20 | +from fastapi import HTTPException |
| 21 | +from pydantic import Field |
| 22 | + |
| 23 | +from nemo_gym.base_resources_server import BaseResourcesServerConfig |
| 24 | +from nemo_gym.openai_utils import NeMoGymResponse |
| 25 | +from resources_servers.base_gymnasium import GymnasiumServer, extract_text |
| 26 | +from resources_servers.grl_sokoban.sokoban_env import SokobanEnv |
| 27 | + |
| 28 | + |
| 29 | +DEFAULT_GRID_LOOKUP = {0: "#", 1: "_", 2: "O", 3: "√", 4: "X", 5: "P", 6: "S"} |
| 30 | +DEFAULT_ACTION_LOOKUP = {1: "Up", 2: "Down", 3: "Left", 4: "Right"} |
| 31 | +ACTION_TAG_PATTERN = re.compile(r"<action>\s*(up|down|left|right|[1-4])\s*</action>", re.IGNORECASE) |
| 32 | +ACTION_WORD_PATTERN = re.compile(r"\b(up|down|left|right|[1-4])\b", re.IGNORECASE) |
| 33 | + |
| 34 | + |
| 35 | +class GrlSokobanResourcesServerConfig(BaseResourcesServerConfig): |
| 36 | + env_config: Dict[str, Any] = Field( |
| 37 | + default_factory=lambda: { |
| 38 | + "grid_lookup": DEFAULT_GRID_LOOKUP, |
| 39 | + "action_lookup": DEFAULT_ACTION_LOOKUP, |
| 40 | + "search_depth": 100, |
| 41 | + "dim_room": (6, 6), |
| 42 | + "max_steps": 100, |
| 43 | + "num_boxes": 1, |
| 44 | + "render_mode": "text", |
| 45 | + } |
| 46 | + ) |
| 47 | + |
| 48 | + |
| 49 | +@dataclass |
| 50 | +class SokobanSessionState: |
| 51 | + env: Any |
| 52 | + observation: str |
| 53 | + total_reward: float = 0.0 |
| 54 | + done: bool = False |
| 55 | + last_info: Dict[str, Any] = field(default_factory=dict) |
| 56 | + |
| 57 | + |
| 58 | +class GrlSokobanResourcesServer(GymnasiumServer): |
| 59 | + config: GrlSokobanResourcesServerConfig |
| 60 | + session_id_to_state: Dict[str, SokobanSessionState] = Field(default_factory=dict) |
| 61 | + |
| 62 | + async def reset(self, metadata: dict, session_id: Optional[str] = None) -> tuple[Optional[str], dict]: |
| 63 | + if session_id is None: |
| 64 | + raise HTTPException(status_code=400, detail="Missing session id.") |
| 65 | + |
| 66 | + self._close_env(session_id) |
| 67 | + |
| 68 | + env = SokobanEnv(self._env_config_from_metadata(metadata)) |
| 69 | + observation = env.reset(seed=metadata.get("seed")) |
| 70 | + self.session_id_to_state[session_id] = SokobanSessionState(env=env, observation=observation) |
| 71 | + return self._format_observation(observation), {} |
| 72 | + |
| 73 | + async def step( |
| 74 | + self, action: NeMoGymResponse, metadata: dict, session_id: Optional[str] = None |
| 75 | + ) -> tuple[Optional[str], float, bool, bool, dict]: |
| 76 | + if session_id is None or session_id not in self.session_id_to_state: |
| 77 | + raise HTTPException(status_code=400, detail="Session not initialized. Call /reset first.") |
| 78 | + |
| 79 | + session_state = self.session_id_to_state[session_id] |
| 80 | + if session_state.done: |
| 81 | + return session_state.observation, 0.0, True, False, dict(session_state.last_info) |
| 82 | + |
| 83 | + env = session_state.env |
| 84 | + action_id = self._parse_action(action, env.ACTION_LOOKUP) |
| 85 | + next_obs, reward, done, info = env.step(action_id) |
| 86 | + |
| 87 | + session_state.total_reward += reward |
| 88 | + session_state.observation = next_obs |
| 89 | + session_state.last_info = info | { |
| 90 | + "action_id": action_id, |
| 91 | + "action_label": env.ACTION_LOOKUP[action_id], |
| 92 | + "total_reward": session_state.total_reward, |
| 93 | + } |
| 94 | + session_state.done = bool(done) |
| 95 | + |
| 96 | + return ( |
| 97 | + self._format_observation(next_obs) if not session_state.done else next_obs, |
| 98 | + reward, |
| 99 | + session_state.done, |
| 100 | + False, |
| 101 | + dict(session_state.last_info), |
| 102 | + ) |
| 103 | + |
| 104 | + def _env_config_from_metadata(self, metadata: dict) -> dict[str, Any]: |
| 105 | + env_config = dict(self.config.env_config) |
| 106 | + for key in ( |
| 107 | + "grid_lookup", |
| 108 | + "action_lookup", |
| 109 | + "search_depth", |
| 110 | + "dim_room", |
| 111 | + "max_steps", |
| 112 | + "num_boxes", |
| 113 | + "render_mode", |
| 114 | + ): |
| 115 | + if key in metadata: |
| 116 | + env_config[key] = metadata[key] |
| 117 | + return env_config |
| 118 | + |
| 119 | + def _close_env(self, session_id: str) -> None: |
| 120 | + session_state = self.session_id_to_state.pop(session_id, None) |
| 121 | + if session_state is None: |
| 122 | + return |
| 123 | + try: |
| 124 | + session_state.env.close() |
| 125 | + except Exception: |
| 126 | + pass |
| 127 | + |
| 128 | + @staticmethod |
| 129 | + def _format_observation(observation: str) -> str: |
| 130 | + return ( |
| 131 | + "Sokoban board:\n" |
| 132 | + f"{observation}\n\n" |
| 133 | + "Legend: #=wall, _=floor, O=target, X=box, √=box on target, P=player, S=player on target.\n" |
| 134 | + "Respond with exactly one move using <action>Up</action>, <action>Down</action>, " |
| 135 | + "<action>Left</action>, or <action>Right</action>." |
| 136 | + ) |
| 137 | + |
| 138 | + @staticmethod |
| 139 | + def _parse_action(response: NeMoGymResponse, action_lookup: Dict[int, str]) -> int: |
| 140 | + text = extract_text(response).strip() |
| 141 | + match = ACTION_TAG_PATTERN.search(text) or ACTION_WORD_PATTERN.search(text) |
| 142 | + if match is None: |
| 143 | + raise HTTPException(status_code=400, detail=f"Unable to parse action from response: {text!r}") |
| 144 | + |
| 145 | + token = match.group(1).strip() |
| 146 | + if token.isdigit(): |
| 147 | + action_id = int(token) |
| 148 | + if action_id in action_lookup: |
| 149 | + return action_id |
| 150 | + raise HTTPException(status_code=400, detail=f"Invalid action identifier: {action_id}") |
| 151 | + |
| 152 | + reverse_lookup = {label.lower(): idx for idx, label in action_lookup.items()} |
| 153 | + action_id = reverse_lookup.get(token.lower()) |
| 154 | + if action_id is None: |
| 155 | + raise HTTPException(status_code=400, detail=f"Invalid action identifier: {token}") |
| 156 | + return action_id |
| 157 | + |
| 158 | + |
| 159 | +GrlSokobanEnv = GrlSokobanResourcesServer |
| 160 | + |
| 161 | + |
| 162 | +if __name__ == "__main__": |
| 163 | + GrlSokobanResourcesServer.run_webserver() |
0 commit comments