Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- ragen/env/metamathqa/__init__.py +12 -0
- ragen/env/metamathqa/__pycache__/__init__.cpython-310.pyc +0 -0
- ragen/env/metamathqa/__pycache__/env.cpython-310.pyc +0 -0
- ragen/env/metamathqa/config.py +10 -0
- ragen/env/metamathqa/env.py +68 -0
- ragen/env/rubikscube/__pycache__/__init__.cpython-310.pyc +0 -0
- ragen/env/rubikscube/__pycache__/config.cpython-310.pyc +0 -0
- ragen/env/rubikscube/__pycache__/env.cpython-310.pyc +0 -0
- ragen/env/rubikscube/env.py +248 -0
- ragen/env/search/README.md +120 -0
- ragen/env/search/__init__.py +4 -0
- ragen/env/search/__pycache__/__init__.cpython-310.pyc +0 -0
- ragen/env/search/__pycache__/config.cpython-310.pyc +0 -0
- ragen/env/search/__pycache__/env.cpython-310.pyc +0 -0
- ragen/env/search/__pycache__/retrieval_client.cpython-310.pyc +0 -0
- ragen/env/search/__pycache__/reward.cpython-310.pyc +0 -0
- ragen/env/search/config.py +38 -0
- ragen/env/search/env.py +253 -0
- ragen/env/search/retrieval_client.py +166 -0
- ragen/env/search/reward.py +199 -0
- ragen/env/sokoban/__init__.py +14 -0
- ragen/env/sokoban/__pycache__/__init__.cpython-310.pyc +0 -0
- ragen/env/sokoban/__pycache__/config.cpython-310.pyc +0 -0
- ragen/env/sokoban/__pycache__/env.cpython-310.pyc +0 -0
- ragen/env/sokoban/__pycache__/utils.cpython-310.pyc +0 -0
- ragen/env/sokoban/config.py +24 -0
- ragen/env/sokoban/env.py +104 -0
- ragen/env/sokoban/utils.py +655 -0
- ragen/env/spatial/config.py +49 -0
- ragen/env/spatial/env.py +180 -0
- ragen/env/spatial/env_old.py +335 -0
- ragen/env/spatial/prompter.py +74 -0
- ragen/env/spatial/prompts.py +71 -0
- ragen/env/static/config.py +10 -0
- ragen/env/static/env.py +111 -0
- ragen/env/static/utils.py +176 -0
- ragen/env/sudoku/__init__.py +4 -0
- ragen/env/sudoku/__pycache__/__init__.cpython-310.pyc +0 -0
- ragen/env/sudoku/__pycache__/config.cpython-310.pyc +0 -0
- ragen/env/sudoku/__pycache__/env.cpython-310.pyc +0 -0
- ragen/env/sudoku/__pycache__/utils.cpython-310.pyc +0 -0
- ragen/env/sudoku/config.py +27 -0
- ragen/env/sudoku/env.py +348 -0
- ragen/env/sudoku/utils.py +250 -0
- ragen/env/webshop/__init__.py +15 -0
- ragen/env/webshop/__pycache__/__init__.cpython-310.pyc +0 -0
- ragen/env/webshop/__pycache__/config.cpython-310.pyc +0 -0
- ragen/env/webshop/__pycache__/env.cpython-310.pyc +0 -0
- ragen/env/webshop/config.py +46 -0
- ragen/env/webshop/env.py +202 -0
ragen/env/metamathqa/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MetaMathQA environment for mathematical reasoning.
|
| 3 |
+
|
| 4 |
+
Dataset: MetaMathQA (https://huggingface.co/datasets/meta-math/MetaMathQA)
|
| 5 |
+
Citation: Yu et al. (2023). MetaMath: Bootstrap Your Own Mathematical Questions for Large Language Models
|
| 6 |
+
Paper: https://arxiv.org/abs/2309.12284
|
| 7 |
+
License: MIT
|
| 8 |
+
"""
|
| 9 |
+
from .env import MetaMathQAEnv
|
| 10 |
+
from .config import MetaMathQAEnvConfig
|
| 11 |
+
|
| 12 |
+
__all__ = ["MetaMathQAEnv", "MetaMathQAEnvConfig"]
|
ragen/env/metamathqa/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (581 Bytes). View file
|
|
|
ragen/env/metamathqa/__pycache__/env.cpython-310.pyc
ADDED
|
Binary file (2.58 kB). View file
|
|
|
ragen/env/metamathqa/config.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, List, Dict
|
| 2 |
+
from dataclasses import dataclass, field
|
| 3 |
+
|
| 4 |
+
@dataclass
|
| 5 |
+
class MetaMathQAEnvConfig:
|
| 6 |
+
"""Configuration for FrozenLake environment"""
|
| 7 |
+
# Map config
|
| 8 |
+
dataset_path: str = field(default="meta-math/MetaMathQA")
|
| 9 |
+
cache_dir:str = field(default="./data")
|
| 10 |
+
split: str = field(default="train")
|
ragen/env/metamathqa/env.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gym
|
| 2 |
+
from gym import spaces
|
| 3 |
+
import numpy as np
|
| 4 |
+
from datasets import load_dataset
|
| 5 |
+
import re
|
| 6 |
+
import random
|
| 7 |
+
from ragen.env.base import BaseLanguageBasedEnv
|
| 8 |
+
from ragen.utils import all_seed
|
| 9 |
+
from .config import MetaMathQAEnvConfig
|
| 10 |
+
class MetaMathQAEnv(BaseLanguageBasedEnv):
|
| 11 |
+
def __init__(self, config: MetaMathQAEnvConfig):
|
| 12 |
+
super(MetaMathQAEnv, self).__init__()
|
| 13 |
+
|
| 14 |
+
self.config = config
|
| 15 |
+
self.dataset = load_dataset(path=self.config.dataset_path, cache_dir=self.config.cache_dir)
|
| 16 |
+
self.current_question_idx = None
|
| 17 |
+
self.current_question = None
|
| 18 |
+
self.correct_answer = None
|
| 19 |
+
self.step_num = None
|
| 20 |
+
self.render_cache = None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _extract_answer(self, response):
|
| 24 |
+
match = re.search(r"The answer is: (.*?)$", response, re.DOTALL)
|
| 25 |
+
if match:
|
| 26 |
+
return match.group(1).strip()
|
| 27 |
+
return None
|
| 28 |
+
|
| 29 |
+
def reset(self,seed=None, mode=None):
|
| 30 |
+
dataset = self.dataset[self.config.split]
|
| 31 |
+
with all_seed(seed):
|
| 32 |
+
self.current_question_idx = random.randint(0, len(dataset) - 1)
|
| 33 |
+
question_data = dataset[self.current_question_idx]
|
| 34 |
+
self.current_question = question_data['query']
|
| 35 |
+
self.correct_answer = self._extract_answer(question_data['response'])
|
| 36 |
+
self.step_num = 0
|
| 37 |
+
self.render_cache = self.current_question
|
| 38 |
+
return self.render_cache
|
| 39 |
+
|
| 40 |
+
def step(self, action):
|
| 41 |
+
is_correct, is_valid = self._check_answer(action)
|
| 42 |
+
reward = 1.0 / (2 ** self.step_num) if is_correct else 0.0
|
| 43 |
+
if is_correct:
|
| 44 |
+
observation = "Correct!"
|
| 45 |
+
done = True
|
| 46 |
+
else:
|
| 47 |
+
observation = "Incorrect. Please think again."
|
| 48 |
+
done = False
|
| 49 |
+
self.step_num += 1
|
| 50 |
+
info = {"action_is_valid": is_valid, "success": is_correct}
|
| 51 |
+
self.render_cache = observation
|
| 52 |
+
return self.render_cache, reward, done, info
|
| 53 |
+
|
| 54 |
+
def _check_answer(self, user_answer):
|
| 55 |
+
"""Check if the user's answer matches the correct answer."""
|
| 56 |
+
user_answer = user_answer.strip()
|
| 57 |
+
normalized_answer = re.sub(r'\s+', '', user_answer.lower())
|
| 58 |
+
if self.correct_answer:
|
| 59 |
+
normalized_label = re.sub(r'\s+', '', self.correct_answer.lower())
|
| 60 |
+
is_correct = normalized_answer == normalized_label
|
| 61 |
+
else:
|
| 62 |
+
is_correct = False
|
| 63 |
+
is_valid = normalized_answer != ""
|
| 64 |
+
return is_correct, is_valid
|
| 65 |
+
|
| 66 |
+
def render(self):
|
| 67 |
+
return self.render_cache
|
| 68 |
+
|
ragen/env/rubikscube/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (248 Bytes). View file
|
|
|
ragen/env/rubikscube/__pycache__/config.cpython-310.pyc
ADDED
|
Binary file (1.08 kB). View file
|
|
|
ragen/env/rubikscube/__pycache__/env.cpython-310.pyc
ADDED
|
Binary file (7.39 kB). View file
|
|
|
ragen/env/rubikscube/env.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gymnasium as gym
|
| 2 |
+
import numpy as np
|
| 3 |
+
from typing import Tuple, Any, Dict, List
|
| 4 |
+
from ragen.env.base import BaseDiscreteActionEnv
|
| 5 |
+
from .config import RubiksCube2x2Config
|
| 6 |
+
from ragen.utils import all_seed
|
| 7 |
+
|
| 8 |
+
class RubiksCube2x2Env(BaseDiscreteActionEnv, gym.Env):
|
| 9 |
+
"""
|
| 10 |
+
2x2 Pocket Cube Environment for LLM-based RL.
|
| 11 |
+
State: 24 integers representing the stickers.
|
| 12 |
+
Reward: +1.0 for solved, 0.0 otherwise.
|
| 13 |
+
"""
|
| 14 |
+
def __init__(self, config: RubiksCube2x2Config | None = None):
|
| 15 |
+
BaseDiscreteActionEnv.__init__(self)
|
| 16 |
+
self.config = config or RubiksCube2x2Config()
|
| 17 |
+
self.ACTION_LOOKUP = self.config.action_lookup
|
| 18 |
+
self.ACTION_SPACE = gym.spaces.discrete.Discrete(12, start=1)
|
| 19 |
+
self.render_mode = self.config.render_mode
|
| 20 |
+
self.rng = np.random.default_rng()
|
| 21 |
+
|
| 22 |
+
# 6 faces, 4 stickers per face.
|
| 23 |
+
# Order: U(0), L(1), F(2), R(3), B(4), D(5)
|
| 24 |
+
# Colors: 0:White, 1:Orange, 2:Green, 3:Red, 4:Blue, 5:Yellow
|
| 25 |
+
self.state = np.zeros(24, dtype=int)
|
| 26 |
+
self.solved_state = np.zeros(24, dtype=int)
|
| 27 |
+
self._init_solved_state()
|
| 28 |
+
|
| 29 |
+
self.current_step = 0
|
| 30 |
+
|
| 31 |
+
def _init_solved_state(self):
|
| 32 |
+
# Initialize solved state: 4 of color 0, 4 of color 1, ...
|
| 33 |
+
for i in range(6):
|
| 34 |
+
self.solved_state[i*4 : (i+1)*4] = i
|
| 35 |
+
|
| 36 |
+
def reset(self, seed=None, mode=None):
|
| 37 |
+
gym.Env.reset(self, seed=seed)
|
| 38 |
+
with all_seed(seed):
|
| 39 |
+
self.rng = np.random.default_rng(seed)
|
| 40 |
+
# 重置为还原状态
|
| 41 |
+
self.state = self.solved_state.copy()
|
| 42 |
+
self.current_step = 0
|
| 43 |
+
|
| 44 |
+
# 打乱 (Scramble)
|
| 45 |
+
# 随机执行 N 个有效动作
|
| 46 |
+
depth = self.config.scramble_depth
|
| 47 |
+
for _ in range(depth):
|
| 48 |
+
action = self.rng.integers(1, 13) # 1 to 12
|
| 49 |
+
self._apply_action(action)
|
| 50 |
+
|
| 51 |
+
return self.render(done=False)
|
| 52 |
+
|
| 53 |
+
def step(self, action: int) -> Tuple[Any, float, bool, Dict]:
|
| 54 |
+
assert action in self.ACTION_LOOKUP, f"Invalid action: {action}"
|
| 55 |
+
info = {"action_is_effective": True, "action_is_valid": True, "success": False}
|
| 56 |
+
|
| 57 |
+
# 执行动作
|
| 58 |
+
self._apply_action(action)
|
| 59 |
+
self.current_step += 1
|
| 60 |
+
|
| 61 |
+
# 检查是否还原
|
| 62 |
+
is_solved = True
|
| 63 |
+
for i in range(6):
|
| 64 |
+
# 获取当前面的 4 个色块
|
| 65 |
+
face_stickers = self.state[i*4 : (i+1)*4]
|
| 66 |
+
# 如果这 4 个色块里包含不只 1 种颜色,说明没还原
|
| 67 |
+
if len(set(face_stickers)) > 1:
|
| 68 |
+
is_solved = False
|
| 69 |
+
break
|
| 70 |
+
|
| 71 |
+
truncated = self.current_step >= self.config.max_steps
|
| 72 |
+
|
| 73 |
+
done = is_solved or truncated
|
| 74 |
+
|
| 75 |
+
if is_solved:
|
| 76 |
+
reward = 1.0
|
| 77 |
+
info["success"] = True
|
| 78 |
+
msg = "Cube Solved!"
|
| 79 |
+
elif truncated:
|
| 80 |
+
# reward = -1.0 # 超时未解出给惩罚
|
| 81 |
+
reward = 0.0
|
| 82 |
+
info["success"] = False
|
| 83 |
+
msg = "Max steps reached."
|
| 84 |
+
else:
|
| 85 |
+
reward = 0.0
|
| 86 |
+
msg = ""
|
| 87 |
+
|
| 88 |
+
next_obs = self.render(done=done, result_msg=msg)
|
| 89 |
+
|
| 90 |
+
return next_obs, float(reward), done, info
|
| 91 |
+
|
| 92 |
+
def _rotate_face_clockwise(self, face_idx):
|
| 93 |
+
|
| 94 |
+
base = face_idx * 4
|
| 95 |
+
s = self.state
|
| 96 |
+
tmp = s[base + 0]
|
| 97 |
+
s[base + 0] = s[base + 2]
|
| 98 |
+
s[base + 2] = s[base + 3]
|
| 99 |
+
s[base + 3] = s[base + 1]
|
| 100 |
+
s[base + 1] = tmp
|
| 101 |
+
|
| 102 |
+
def _apply_action(self, action: int):
|
| 103 |
+
if action % 2 == 0: # Even actions are primes (inverses)
|
| 104 |
+
turns = 3
|
| 105 |
+
base_act = action - 1
|
| 106 |
+
else:
|
| 107 |
+
turns = 1
|
| 108 |
+
base_act = action
|
| 109 |
+
|
| 110 |
+
for _ in range(turns):
|
| 111 |
+
if base_act == 1: self._move_U()
|
| 112 |
+
elif base_act == 3: self._move_D()
|
| 113 |
+
elif base_act == 5: self._move_L()
|
| 114 |
+
elif base_act == 7: self._move_R()
|
| 115 |
+
elif base_act == 9: self._move_F()
|
| 116 |
+
elif base_act == 11: self._move_B()
|
| 117 |
+
|
| 118 |
+
def _move_U(self):
|
| 119 |
+
self._rotate_face_clockwise(0)
|
| 120 |
+
s = self.state
|
| 121 |
+
t0, t1 = s[8], s[9]
|
| 122 |
+
s[8], s[9] = s[12], s[13]
|
| 123 |
+
s[12], s[13] = s[16], s[17]
|
| 124 |
+
s[16], s[17] = s[4], s[5]
|
| 125 |
+
s[4], s[5] = t0, t1
|
| 126 |
+
|
| 127 |
+
def _move_D(self):
|
| 128 |
+
self._rotate_face_clockwise(5)
|
| 129 |
+
s = self.state
|
| 130 |
+
t0, t1 = s[10], s[11]
|
| 131 |
+
s[10], s[11] = s[6], s[7]
|
| 132 |
+
s[6], s[7] = s[18], s[19]
|
| 133 |
+
s[18], s[19] = s[14], s[15]
|
| 134 |
+
s[14], s[15] = t0, t1
|
| 135 |
+
|
| 136 |
+
def _move_L(self):
|
| 137 |
+
self._rotate_face_clockwise(1)
|
| 138 |
+
s = self.state
|
| 139 |
+
t0, t2 = s[0], s[2]
|
| 140 |
+
s[0], s[2] = s[19], s[17]
|
| 141 |
+
s[19], s[17] = s[20], s[22]
|
| 142 |
+
s[20], s[22] = s[8], s[10]
|
| 143 |
+
s[8], s[10] = t0, t2
|
| 144 |
+
|
| 145 |
+
def _move_R(self):
|
| 146 |
+
self._rotate_face_clockwise(3)
|
| 147 |
+
s = self.state
|
| 148 |
+
t1, t3 = s[1], s[3]
|
| 149 |
+
s[1], s[3] = s[9], s[11]
|
| 150 |
+
s[9], s[11] = s[21], s[23]
|
| 151 |
+
s[21], s[23] = s[18], s[16]
|
| 152 |
+
s[18], s[16] = t1, t3
|
| 153 |
+
|
| 154 |
+
def _move_F(self):
|
| 155 |
+
self._rotate_face_clockwise(2)
|
| 156 |
+
s = self.state
|
| 157 |
+
t2, t3 = s[2], s[3]
|
| 158 |
+
s[2], s[3] = s[7], s[5]
|
| 159 |
+
s[7], s[5] = s[21], s[20]
|
| 160 |
+
s[21], s[20] = s[12], s[14]
|
| 161 |
+
s[12], s[14] = t2, t3
|
| 162 |
+
|
| 163 |
+
def _move_B(self):
|
| 164 |
+
self._rotate_face_clockwise(4)
|
| 165 |
+
s = self.state
|
| 166 |
+
t0, t1 = s[0], s[1]
|
| 167 |
+
s[0], s[1] = s[13], s[15]
|
| 168 |
+
s[13], s[15] = s[22], s[23]
|
| 169 |
+
s[22], s[23] = s[6], s[4]
|
| 170 |
+
s[6], s[4] = t0, t1
|
| 171 |
+
|
| 172 |
+
def render(self, mode: str | None = None, done: bool = False, result_msg: str = "") -> str:
|
| 173 |
+
# Color Mapping
|
| 174 |
+
colors = {0: 'W', 1: 'O', 2: 'G', 3: 'R', 4: 'B', 5: 'Y'}
|
| 175 |
+
|
| 176 |
+
def get_face_str(face_idx):
|
| 177 |
+
base = face_idx * 4
|
| 178 |
+
c = [colors[self.state[base+i]] for i in range(4)]
|
| 179 |
+
return f"[{c[0]}, {c[1]}]\n [{c[2]}, {c[3]}]"
|
| 180 |
+
|
| 181 |
+
lines = []
|
| 182 |
+
lines.append("=== Rubik's Cube 2x2 State ===")
|
| 183 |
+
lines.append(f"Step: {self.current_step}/{self.config.max_steps}")
|
| 184 |
+
lines.append("")
|
| 185 |
+
lines.append(f"Up (U): {get_face_str(0).strip().replace(' ', ' ')}")
|
| 186 |
+
lines.append(f"Left (L): {get_face_str(1).strip().replace(' ', ' ')}")
|
| 187 |
+
lines.append(f"Front (F): {get_face_str(2).strip().replace(' ', ' ')}")
|
| 188 |
+
lines.append(f"Right (R): {get_face_str(3).strip().replace(' ', ' ')}")
|
| 189 |
+
lines.append(f"Back (B): {get_face_str(4).strip().replace(' ', ' ')}")
|
| 190 |
+
lines.append(f"Down (D): {get_face_str(5).strip().replace(' ', ' ')}")
|
| 191 |
+
|
| 192 |
+
if not done:
|
| 193 |
+
lines.append("")
|
| 194 |
+
lines.append("Available Actions:")
|
| 195 |
+
# 列出部分动作作为提示,或者全部列出
|
| 196 |
+
lines.append("U, U', D, D', L, L', R, R', F, F', B, B'")
|
| 197 |
+
# lines.append("Format: Action <id> (e.g., Action 1 for U, Action 2 for U')")
|
| 198 |
+
lines.append("\nWhat is your next move?")
|
| 199 |
+
else:
|
| 200 |
+
lines.append("")
|
| 201 |
+
lines.append(f"=== Game Over: {result_msg} ===")
|
| 202 |
+
|
| 203 |
+
return "\n".join(lines)
|
| 204 |
+
|
| 205 |
+
def close(self):
|
| 206 |
+
pass
|
| 207 |
+
|
| 208 |
+
def get_all_actions(self):
|
| 209 |
+
return list(self.ACTION_LOOKUP.keys())
|
| 210 |
+
|
| 211 |
+
if __name__ == "__main__":
|
| 212 |
+
config = RubiksCube2x2Config(scramble_depth=1, max_steps=50)
|
| 213 |
+
env = RubiksCube2x2Env(config)
|
| 214 |
+
|
| 215 |
+
print(f"Action Lookup: {env.ACTION_LOOKUP}")
|
| 216 |
+
|
| 217 |
+
# 重置并打印初始状态
|
| 218 |
+
obs = env.reset()
|
| 219 |
+
print(obs)
|
| 220 |
+
|
| 221 |
+
while True:
|
| 222 |
+
# 提示输入
|
| 223 |
+
keyboard = input("\nEnter action (1-12) or 'q' to quit: ")
|
| 224 |
+
if keyboard == 'q':
|
| 225 |
+
break
|
| 226 |
+
|
| 227 |
+
try:
|
| 228 |
+
action = int(keyboard)
|
| 229 |
+
except ValueError:
|
| 230 |
+
print("Please enter a valid integer.")
|
| 231 |
+
continue
|
| 232 |
+
|
| 233 |
+
if action not in env.ACTION_LOOKUP:
|
| 234 |
+
print(f"Invalid action: {action}. Please input 1-12.")
|
| 235 |
+
continue
|
| 236 |
+
|
| 237 |
+
# 执行动作
|
| 238 |
+
obs, reward, done, info = env.step(action)
|
| 239 |
+
|
| 240 |
+
# 打印状态和奖励信息
|
| 241 |
+
print(obs) # 这里打印的就是 render 返回的文本 Prompt
|
| 242 |
+
print(f"Reward: {reward}, Done: {done}, Info: {info}")
|
| 243 |
+
|
| 244 |
+
# 如果游戏结束(还原或超时),自动重置
|
| 245 |
+
if done:
|
| 246 |
+
print("\n=== Episode Ended. Resetting... ===")
|
| 247 |
+
obs = env.reset()
|
| 248 |
+
print(obs)
|
ragen/env/search/README.md
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Search Environment (HotpotQA + Dense Retrieval)
|
| 2 |
+
|
| 3 |
+
A multi-turn search environment for training LLM agents on multi-hop question answering. The agent interacts with a retrieval server to search Wikipedia and answer questions from HotpotQA.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
The agent receives a question and can take two types of actions:
|
| 8 |
+
- `search[query]` — retrieve relevant Wikipedia passages via dense retrieval (E5 + FAISS)
|
| 9 |
+
- `finish[answer]` — submit a final answer
|
| 10 |
+
|
| 11 |
+
Reward is computed using F1 / exact match against the HotpotQA ground truth.
|
| 12 |
+
|
| 13 |
+
## Components
|
| 14 |
+
|
| 15 |
+
| Component | Description |
|
| 16 |
+
|-----------|-------------|
|
| 17 |
+
| `env.py` | Gym environment: parses actions, calls retrieval server, computes reward |
|
| 18 |
+
| `config.py` | Dataclass config (`SearchEnvConfig`) |
|
| 19 |
+
| `reward.py` | F1 / EM reward computation |
|
| 20 |
+
| `retrieval_client.py` | HTTP client for the retrieval server |
|
| 21 |
+
| `scripts/retrieval/server.py` | Flask server: E5 encoder + FAISS index over Wikipedia |
|
| 22 |
+
|
| 23 |
+
## Setup
|
| 24 |
+
|
| 25 |
+
### 1. Prepare data
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
# Download HotpotQA → data/search/{train,val}.parquet
|
| 29 |
+
python scripts/prepare_search_data.py
|
| 30 |
+
|
| 31 |
+
# Download Wikipedia corpus + FAISS index (~74GB) → search_data/prebuilt_indices/
|
| 32 |
+
python scripts/download_search_index.py
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
### 2. Start the retrieval server
|
| 36 |
+
|
| 37 |
+
The retrieval server provides dense retrieval over ~21M Wikipedia passages using E5-base-v2 embeddings and a FAISS Flat index.
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
python scripts/retrieval/server.py \
|
| 41 |
+
--data_dir ./search_data/prebuilt_indices \
|
| 42 |
+
--port 8000 --host 127.0.0.1 \
|
| 43 |
+
--device cuda:0 --gpu_memory_limit_mb 6144
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
Loading the 61GB FAISS index takes 2-5 minutes. Verify with:
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
curl http://127.0.0.1:8000/health
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
**Important: GPU deployment recommendation**
|
| 53 |
+
|
| 54 |
+
We recommend running the retrieval server on a **dedicated GPU** separate from training. In our experiments, placing the E5 server on the same GPU as training (e.g., GPU 0) caused CUDA OOM errors — vLLM rollout and training both compete for GPU memory, squeezing out the retrieval server process.
|
| 55 |
+
|
| 56 |
+
Run the server on a GPU not used by training (e.g., `--device cuda:7`, train on GPUs 0-6). During rollout, hundreds of environments issue concurrent retrieval requests (e.g., 256 env groups can produce 1000+ requests). Running on CPU cannot keep up with this concurrency and causes timeouts. A dedicated GPU with `threading.Lock` serialization handles this load reliably.
|
| 57 |
+
|
| 58 |
+
### 3. Run training
|
| 59 |
+
|
| 60 |
+
```bash
|
| 61 |
+
# PPO, no filtering (baseline)
|
| 62 |
+
bash scripts/runs/run_search_benchmark.sh \
|
| 63 |
+
--algos PPO \
|
| 64 |
+
--gpus 0,1,2,3,4,5,6,7 --gpus-per-exp 8
|
| 65 |
+
|
| 66 |
+
# PPO, top_k filtering (keep top 25% by reward variance)
|
| 67 |
+
bash scripts/runs/run_search_benchmark.sh \
|
| 68 |
+
--algos PPO --filter-strategy top_k --filter-value 0.25 \
|
| 69 |
+
--gpus 0,1,2,3,4,5,6,7 --gpus-per-exp 8
|
| 70 |
+
|
| 71 |
+
# PPO, top_p filtering (keep 90% by reward variance)
|
| 72 |
+
bash scripts/runs/run_search_benchmark.sh \
|
| 73 |
+
--algos PPO --filter-strategy top_p --filter-value 0.9 \
|
| 74 |
+
--gpus 0,1,2,3,4,5,6,7 --gpus-per-exp 8
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
Key training parameters (pass via `run_search_benchmark.sh` flags):
|
| 78 |
+
|
| 79 |
+
| Flag | Description | Default |
|
| 80 |
+
|------|-------------|---------|
|
| 81 |
+
| `--algos` | Algorithm: PPO or GRPO | PPO |
|
| 82 |
+
| `--filter-strategy` | Rollout filter strategy: `top_p`, `top_k`, etc. | `top_p` |
|
| 83 |
+
| `--filter-value` | Filter value (1.0 = no filtering) | `1.0` |
|
| 84 |
+
| `--gpus` | Comma-separated GPU IDs | auto-detect |
|
| 85 |
+
| `--gpus-per-exp` | GPUs per experiment | 1 |
|
| 86 |
+
| `--gpu-memory-utilization` | vLLM KV cache memory fraction | 0.6 |
|
| 87 |
+
| `--micro-batch` | Micro batch size per GPU | config default |
|
| 88 |
+
| `--mini-batch` | PPO mini batch size | config default |
|
| 89 |
+
| `--save-freq` | Checkpoint save frequency | -1 (disabled) |
|
| 90 |
+
| `--steps` | Total training steps | 200 |
|
| 91 |
+
| `--retrieval-port` | Retrieval server port | 8000 |
|
| 92 |
+
|
| 93 |
+
## Config
|
| 94 |
+
|
| 95 |
+
The search environment config is at `config/_9_search.yaml`. Key settings:
|
| 96 |
+
|
| 97 |
+
```yaml
|
| 98 |
+
micro_batch_size_per_gpu: 4
|
| 99 |
+
ppo_mini_batch_size: 32
|
| 100 |
+
|
| 101 |
+
agent_proxy:
|
| 102 |
+
max_turn: 5 # up to 5 search rounds
|
| 103 |
+
max_actions_per_turn: 1 # one action per response
|
| 104 |
+
|
| 105 |
+
actor_rollout_ref:
|
| 106 |
+
rollout:
|
| 107 |
+
max_model_len: 5000
|
| 108 |
+
max_num_batched_tokens: 5000
|
| 109 |
+
|
| 110 |
+
es_manager:
|
| 111 |
+
train:
|
| 112 |
+
env_groups: 16
|
| 113 |
+
group_size: 8 # 16 × 8 = 128 samples per batch
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
Note: when using `top_k` filtering with a small value (e.g., 0.25), the effective batch size after filtering is `env_groups × group_size × filter_value`. Ensure `ppo_mini_batch_size` does not exceed this value, or training will fail with an assertion error.
|
| 117 |
+
|
| 118 |
+
## Acknowledgment
|
| 119 |
+
|
| 120 |
+
The search environment is adapted from the [RLLM](https://github.com/rllm-org/rllm) project. We thank the RLLM authors for their open-source contributions.
|
ragen/env/search/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .env import SearchEnv
|
| 2 |
+
from .config import SearchEnvConfig
|
| 3 |
+
|
| 4 |
+
__all__ = ["SearchEnv", "SearchEnvConfig"]
|
ragen/env/search/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (262 Bytes). View file
|
|
|
ragen/env/search/__pycache__/config.cpython-310.pyc
ADDED
|
Binary file (1.29 kB). View file
|
|
|
ragen/env/search/__pycache__/env.cpython-310.pyc
ADDED
|
Binary file (7.33 kB). View file
|
|
|
ragen/env/search/__pycache__/retrieval_client.cpython-310.pyc
ADDED
|
Binary file (5.39 kB). View file
|
|
|
ragen/env/search/__pycache__/reward.cpython-310.pyc
ADDED
|
Binary file (6.27 kB). View file
|
|
|
ragen/env/search/config.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Configuration for the Search (HotpotQA) environment.
|
| 3 |
+
|
| 4 |
+
The search environment is adapted from the RLLM project:
|
| 5 |
+
https://github.com/rllm-org/rllm
|
| 6 |
+
License: Apache-2.0
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass
|
| 13 |
+
class SearchEnvConfig:
|
| 14 |
+
"""Configuration for SearchEnv.
|
| 15 |
+
|
| 16 |
+
Fields under env_config in config/envs.yaml map directly to these fields.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
# --- Data ---
|
| 20 |
+
dataset_name: str = "hotpotqa"
|
| 21 |
+
train_path: str = "data/search/train.parquet"
|
| 22 |
+
max_instances: int = 20000
|
| 23 |
+
|
| 24 |
+
# --- Retrieval server ---
|
| 25 |
+
retrieval_server_url: str = "http://127.0.0.1:8000"
|
| 26 |
+
retrieval_timeout: float = 30.0
|
| 27 |
+
max_search_results: int = 5
|
| 28 |
+
max_total_chars: int = 4000 # total char limit for all docs combined (~1k tokens)
|
| 29 |
+
|
| 30 |
+
# --- Environment ---
|
| 31 |
+
max_steps: int = 10 # max search rounds before forced termination
|
| 32 |
+
render_mode: str = "text"
|
| 33 |
+
mock_mode: bool = False # True = use MockRetrievalClient (no server needed)
|
| 34 |
+
|
| 35 |
+
# --- Reward ---
|
| 36 |
+
correct_reward: float = 1.0
|
| 37 |
+
incorrect_reward: float = 0.0
|
| 38 |
+
f1_threshold: float = 0.3
|
ragen/env/search/env.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Search environment for HotpotQA-style multi-hop question answering.
|
| 3 |
+
|
| 4 |
+
This code is adapted from the RLLM project:
|
| 5 |
+
https://github.com/rllm-org/rllm
|
| 6 |
+
Original source: rllm/examples/search/ (ToolEnvironment + search example)
|
| 7 |
+
License: Apache-2.0
|
| 8 |
+
|
| 9 |
+
Architecture follows RAGEN's WebShop pattern:
|
| 10 |
+
- Inherits BaseLanguageBasedEnv + gym.Env
|
| 11 |
+
- Actions are text strings: search[query] / finish[answer]
|
| 12 |
+
- Multi-turn: agent can search multiple times before answering
|
| 13 |
+
- Requires a running retrieval server (or mock_mode for testing)
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import logging
|
| 17 |
+
import re
|
| 18 |
+
from typing import Any, Dict, Optional, Tuple
|
| 19 |
+
|
| 20 |
+
import gymnasium as gym
|
| 21 |
+
import datasets
|
| 22 |
+
|
| 23 |
+
from ragen.env.base import BaseLanguageBasedEnv
|
| 24 |
+
from .config import SearchEnvConfig
|
| 25 |
+
from .reward import SearchRewardFn
|
| 26 |
+
from .retrieval_client import RetrievalClient, MockRetrievalClient
|
| 27 |
+
|
| 28 |
+
logger = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class SearchEnv(BaseLanguageBasedEnv, gym.Env):
|
| 32 |
+
"""
|
| 33 |
+
Search-based QA environment.
|
| 34 |
+
|
| 35 |
+
The agent receives a question and can:
|
| 36 |
+
- search[query]: search for information via the retrieval server
|
| 37 |
+
- finish[answer]: submit a final answer and receive a reward
|
| 38 |
+
|
| 39 |
+
Reward is computed using F1/EM against the ground truth (HotpotQA standard).
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(self, config: Optional[SearchEnvConfig] = None):
|
| 43 |
+
BaseLanguageBasedEnv.__init__(self)
|
| 44 |
+
self.config = config if config is not None else SearchEnvConfig()
|
| 45 |
+
|
| 46 |
+
# Reward function
|
| 47 |
+
self.reward_fn = SearchRewardFn(
|
| 48 |
+
correct_reward=self.config.correct_reward,
|
| 49 |
+
incorrect_reward=self.config.incorrect_reward,
|
| 50 |
+
f1_threshold=self.config.f1_threshold,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Retrieval client
|
| 54 |
+
if self.config.mock_mode:
|
| 55 |
+
self.client = MockRetrievalClient()
|
| 56 |
+
else:
|
| 57 |
+
self.client = RetrievalClient(
|
| 58 |
+
server_url=self.config.retrieval_server_url,
|
| 59 |
+
timeout=self.config.retrieval_timeout,
|
| 60 |
+
max_results=self.config.max_search_results,
|
| 61 |
+
max_total_chars=self.config.max_total_chars,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
# Load dataset
|
| 65 |
+
self.data = self._load_data()
|
| 66 |
+
|
| 67 |
+
# Per-episode state
|
| 68 |
+
self.index = None
|
| 69 |
+
self.ground_truth = None
|
| 70 |
+
self.question = None
|
| 71 |
+
self.step_count = 0
|
| 72 |
+
self.render_cache = None
|
| 73 |
+
|
| 74 |
+
def _load_data(self):
|
| 75 |
+
"""Load HotpotQA data from parquet file."""
|
| 76 |
+
try:
|
| 77 |
+
df = datasets.load_dataset(
|
| 78 |
+
"parquet",
|
| 79 |
+
data_files=self.config.train_path,
|
| 80 |
+
)["train"]
|
| 81 |
+
if self.config.max_instances and len(df) > self.config.max_instances:
|
| 82 |
+
df = df.select(range(self.config.max_instances))
|
| 83 |
+
logger.info(f"Loaded {len(df)} search questions from {self.config.train_path}")
|
| 84 |
+
return df
|
| 85 |
+
except Exception as e:
|
| 86 |
+
logger.error(f"Failed to load data from {self.config.train_path}: {e}")
|
| 87 |
+
raise
|
| 88 |
+
|
| 89 |
+
def reset(self, seed: Optional[int] = None, mode: Optional[str] = None) -> str:
|
| 90 |
+
"""
|
| 91 |
+
Reset the environment with a new question.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
seed: Deterministic seed for question selection.
|
| 95 |
+
mode: Unused, kept for interface compatibility.
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
Initial observation string containing the question.
|
| 99 |
+
"""
|
| 100 |
+
gym.Env.reset(self, seed=seed)
|
| 101 |
+
|
| 102 |
+
# Deterministic question selection (same pattern as CountdownEnv)
|
| 103 |
+
self.index = seed % len(self.data) if seed is not None else 0
|
| 104 |
+
item = self.data[self.index]
|
| 105 |
+
|
| 106 |
+
self.question = item["question"]
|
| 107 |
+
self.ground_truth = item["ground_truth"]
|
| 108 |
+
self.step_count = 0
|
| 109 |
+
|
| 110 |
+
# Build initial observation (question only, no ground_truth exposed)
|
| 111 |
+
self.render_cache = (
|
| 112 |
+
f"Question: {self.question}\n"
|
| 113 |
+
f"Available actions: search[<query>], finish[<answer>]"
|
| 114 |
+
)
|
| 115 |
+
return self.render()
|
| 116 |
+
|
| 117 |
+
def step(self, action: str) -> Tuple[str, float, bool, Dict[str, Any]]:
|
| 118 |
+
"""
|
| 119 |
+
Execute one step in the environment.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
action: One of:
|
| 123 |
+
- "search[query text]" — perform a retrieval search
|
| 124 |
+
- "finish[answer text]" — submit final answer
|
| 125 |
+
- anything else — treated as a direct answer (fallback)
|
| 126 |
+
|
| 127 |
+
Returns:
|
| 128 |
+
(observation, reward, done, info)
|
| 129 |
+
"""
|
| 130 |
+
self.step_count += 1
|
| 131 |
+
action = action.strip() if action else ""
|
| 132 |
+
|
| 133 |
+
# --- Parse action ---
|
| 134 |
+
if action.startswith("search[") and action.endswith("]"):
|
| 135 |
+
return self._handle_search(action[7:-1])
|
| 136 |
+
elif action.startswith("finish[") and action.endswith("]"):
|
| 137 |
+
return self._handle_finish(action[7:-1])
|
| 138 |
+
else:
|
| 139 |
+
# Fallback: treat as a direct answer attempt
|
| 140 |
+
return self._handle_fallback(action)
|
| 141 |
+
|
| 142 |
+
def _handle_search(self, query: str) -> Tuple[str, float, bool, Dict[str, Any]]:
|
| 143 |
+
"""Handle a search[query] action."""
|
| 144 |
+
results = self.client.search(query, top_k=self.config.max_search_results)
|
| 145 |
+
|
| 146 |
+
# Check if max steps reached
|
| 147 |
+
done = self.step_count >= self.config.max_steps
|
| 148 |
+
reward = 0.0
|
| 149 |
+
|
| 150 |
+
if done:
|
| 151 |
+
# Forced termination — no answer provided
|
| 152 |
+
self.render_cache = (
|
| 153 |
+
f"Search results for '{query}':\n{results}\n\n"
|
| 154 |
+
f"Maximum search steps reached. Episode ended without an answer."
|
| 155 |
+
)
|
| 156 |
+
else:
|
| 157 |
+
self.render_cache = (
|
| 158 |
+
f"Search results for '{query}':\n{results}\n\n"
|
| 159 |
+
f"Available actions: search[<query>], finish[<answer>]"
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
info = {
|
| 163 |
+
"action_is_effective": True,
|
| 164 |
+
"action_is_valid": True,
|
| 165 |
+
"success": False,
|
| 166 |
+
"action_type": "search",
|
| 167 |
+
"query": query,
|
| 168 |
+
}
|
| 169 |
+
return self.render(), reward, done, info
|
| 170 |
+
|
| 171 |
+
def _handle_finish(self, answer: str) -> Tuple[str, float, bool, Dict[str, Any]]:
|
| 172 |
+
"""Handle a finish[answer] action."""
|
| 173 |
+
reward, metadata = self.compute_reward(answer, self.ground_truth)
|
| 174 |
+
done = True
|
| 175 |
+
|
| 176 |
+
self.render_cache = f"Your answer: {answer}. Reward: {reward:.2f}"
|
| 177 |
+
|
| 178 |
+
info = {
|
| 179 |
+
"action_is_effective": True,
|
| 180 |
+
"action_is_valid": True,
|
| 181 |
+
"success": metadata.get("exact_match", False) or reward > 0,
|
| 182 |
+
"action_type": "finish",
|
| 183 |
+
"answer": answer,
|
| 184 |
+
"reward_metadata": metadata,
|
| 185 |
+
}
|
| 186 |
+
return self.render(), reward, done, info
|
| 187 |
+
|
| 188 |
+
def _handle_fallback(self, action: str) -> Tuple[str, float, bool, Dict[str, Any]]:
|
| 189 |
+
"""Handle unrecognized action format — try to extract an answer from it."""
|
| 190 |
+
if not action:
|
| 191 |
+
# Empty action — invalid
|
| 192 |
+
done = self.step_count >= self.config.max_steps
|
| 193 |
+
self.render_cache = (
|
| 194 |
+
"Invalid action. Use search[<query>] to search or finish[<answer>] to answer.\n"
|
| 195 |
+
"Available actions: search[<query>], finish[<answer>]"
|
| 196 |
+
)
|
| 197 |
+
return self.render(), 0.0, done, {
|
| 198 |
+
"action_is_effective": False,
|
| 199 |
+
"action_is_valid": False,
|
| 200 |
+
"success": False,
|
| 201 |
+
"action_type": "invalid",
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
# Try to extract an answer from free-form text
|
| 205 |
+
extracted = self.reward_fn.extract_answer_from_response(action)
|
| 206 |
+
reward, metadata = self.compute_reward(extracted, self.ground_truth)
|
| 207 |
+
done = True
|
| 208 |
+
|
| 209 |
+
self.render_cache = f"Your answer (extracted): {extracted}. Reward: {reward:.2f}"
|
| 210 |
+
|
| 211 |
+
info = {
|
| 212 |
+
"action_is_effective": True,
|
| 213 |
+
"action_is_valid": False, # not in correct format
|
| 214 |
+
"success": metadata.get("exact_match", False) or reward > 0,
|
| 215 |
+
"action_type": "fallback",
|
| 216 |
+
"raw_action": action,
|
| 217 |
+
"extracted_answer": extracted,
|
| 218 |
+
"reward_metadata": metadata,
|
| 219 |
+
}
|
| 220 |
+
return self.render(), reward, done, info
|
| 221 |
+
|
| 222 |
+
def compute_reward(self, answer: str, ground_truth) -> Tuple[float, dict]:
|
| 223 |
+
"""Compute reward using F1/EM evaluation."""
|
| 224 |
+
return self.reward_fn.compute_reward(answer, ground_truth)
|
| 225 |
+
|
| 226 |
+
def render(self, mode: Optional[str] = None) -> str:
|
| 227 |
+
"""Return cached render output."""
|
| 228 |
+
return self.render_cache
|
| 229 |
+
|
| 230 |
+
def close(self):
|
| 231 |
+
"""Clean up resources."""
|
| 232 |
+
pass
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
if __name__ == "__main__":
|
| 236 |
+
# Quick smoke test with mock mode
|
| 237 |
+
config = SearchEnvConfig(
|
| 238 |
+
train_path="data/search/train.parquet",
|
| 239 |
+
mock_mode=True,
|
| 240 |
+
max_steps=5,
|
| 241 |
+
)
|
| 242 |
+
try:
|
| 243 |
+
env = SearchEnv(config)
|
| 244 |
+
obs = env.reset(seed=42)
|
| 245 |
+
print(f"=== Reset ===\n{obs}\n")
|
| 246 |
+
|
| 247 |
+
obs, reward, done, info = env.step("search[test query]")
|
| 248 |
+
print(f"=== Search ===\n{obs}\nReward: {reward}, Done: {done}\n")
|
| 249 |
+
|
| 250 |
+
obs, reward, done, info = env.step("finish[test answer]")
|
| 251 |
+
print(f"=== Finish ===\n{obs}\nReward: {reward}, Done: {done}, Info: {info}\n")
|
| 252 |
+
except Exception as e:
|
| 253 |
+
print(f"Smoke test failed (expected if no data): {e}")
|
ragen/env/search/retrieval_client.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Retrieval client for connecting to the dense retrieval server.
|
| 3 |
+
|
| 4 |
+
This code is adapted from the RLLM project:
|
| 5 |
+
https://github.com/rllm-org/rllm
|
| 6 |
+
Original source: rllm/examples/search/local_retrieval_tool.py
|
| 7 |
+
License: Apache-2.0
|
| 8 |
+
|
| 9 |
+
The retrieval server (scripts/retrieval/server.py) must be running before use.
|
| 10 |
+
Uses `requests` instead of rllm's `httpx` to minimize new dependencies.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import logging
|
| 14 |
+
import os
|
| 15 |
+
from typing import Any, List, Optional
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
import requests
|
| 21 |
+
HAS_REQUESTS = True
|
| 22 |
+
except ImportError:
|
| 23 |
+
HAS_REQUESTS = False
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RetrievalClient:
|
| 27 |
+
"""
|
| 28 |
+
HTTP client for the dense retrieval server (E5 + FAISS).
|
| 29 |
+
|
| 30 |
+
Connects to the Flask server at scripts/retrieval/server.py.
|
| 31 |
+
Designed to be fault-tolerant: logs warnings instead of crashing
|
| 32 |
+
when the server is unavailable.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
server_url: Optional[str] = None,
|
| 38 |
+
timeout: float = 30.0,
|
| 39 |
+
max_results: int = 10,
|
| 40 |
+
max_total_chars: int = 4000,
|
| 41 |
+
):
|
| 42 |
+
if not HAS_REQUESTS:
|
| 43 |
+
logger.warning("requests package not installed. RetrievalClient will not work.")
|
| 44 |
+
|
| 45 |
+
if server_url is None:
|
| 46 |
+
server_url = os.environ.get("RETRIEVAL_SERVER_URL", "http://127.0.0.1:8000")
|
| 47 |
+
|
| 48 |
+
self.server_url = server_url.rstrip("/")
|
| 49 |
+
self.timeout = timeout
|
| 50 |
+
self.max_results = max_results
|
| 51 |
+
self.max_total_chars = max_total_chars
|
| 52 |
+
self.available = False
|
| 53 |
+
|
| 54 |
+
self._test_connection()
|
| 55 |
+
|
| 56 |
+
def _test_connection(self) -> bool:
|
| 57 |
+
"""Test connection to the retrieval server. Warning only, never crashes."""
|
| 58 |
+
if not HAS_REQUESTS:
|
| 59 |
+
return False
|
| 60 |
+
try:
|
| 61 |
+
response = requests.get(f"{self.server_url}/health", timeout=5)
|
| 62 |
+
if response.status_code == 200:
|
| 63 |
+
logger.info(f"Connected to retrieval server at {self.server_url}")
|
| 64 |
+
self.available = True
|
| 65 |
+
return True
|
| 66 |
+
else:
|
| 67 |
+
logger.warning(f"Retrieval server returned status {response.status_code}")
|
| 68 |
+
return False
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.warning(f"Could not connect to retrieval server at {self.server_url}: {e}")
|
| 71 |
+
return False
|
| 72 |
+
|
| 73 |
+
def search(self, query: str, top_k: Optional[int] = None) -> str:
|
| 74 |
+
"""
|
| 75 |
+
Execute a search query against the retrieval server.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
query: The search query string.
|
| 79 |
+
top_k: Number of results to return (default: self.max_results).
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
Formatted search results as a string, or an error message.
|
| 83 |
+
"""
|
| 84 |
+
if not HAS_REQUESTS:
|
| 85 |
+
return "Search service unavailable: requests package not installed."
|
| 86 |
+
|
| 87 |
+
top_k = top_k or self.max_results
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
payload = {
|
| 91 |
+
"query": query,
|
| 92 |
+
"top_k": min(top_k, 50),
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
response = requests.post(
|
| 96 |
+
f"{self.server_url}/retrieve",
|
| 97 |
+
json=payload,
|
| 98 |
+
timeout=self.timeout,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
if not response.ok:
|
| 102 |
+
error_msg = f"Retrieval server error (status {response.status_code})"
|
| 103 |
+
try:
|
| 104 |
+
error_data = response.json()
|
| 105 |
+
error_msg += f": {error_data.get('error', 'Unknown error')}"
|
| 106 |
+
except Exception:
|
| 107 |
+
pass
|
| 108 |
+
return error_msg
|
| 109 |
+
|
| 110 |
+
response_data = response.json()
|
| 111 |
+
results = response_data.get("results", [])
|
| 112 |
+
|
| 113 |
+
if not results:
|
| 114 |
+
return "No relevant documents found for the query."
|
| 115 |
+
|
| 116 |
+
return self._format_results(results)
|
| 117 |
+
|
| 118 |
+
except requests.exceptions.Timeout:
|
| 119 |
+
return f"Search request timed out after {self.timeout} seconds."
|
| 120 |
+
except requests.exceptions.ConnectionError:
|
| 121 |
+
return f"Could not connect to retrieval server at {self.server_url}. Is it running?"
|
| 122 |
+
except Exception as e:
|
| 123 |
+
return f"Search error: {str(e)}"
|
| 124 |
+
|
| 125 |
+
def _format_results(self, results: List[dict]) -> str:
|
| 126 |
+
"""Format search results for LLM consumption. Truncates long documents."""
|
| 127 |
+
formatted = []
|
| 128 |
+
for i, result in enumerate(results[:self.max_results], 1):
|
| 129 |
+
doc_id = result.get("id", f"doc_{i}")
|
| 130 |
+
content = result.get("content", "")
|
| 131 |
+
score = result.get("score", 0.0)
|
| 132 |
+
|
| 133 |
+
# Truncate content to 300 chars (same as rllm)
|
| 134 |
+
if len(content) > 800:
|
| 135 |
+
content = content[:800] + "..."
|
| 136 |
+
|
| 137 |
+
formatted.append(f"[Document {i}] (ID: {doc_id}, Score: {score:.3f})\n{content}")
|
| 138 |
+
|
| 139 |
+
output = "\n\n".join(formatted)
|
| 140 |
+
|
| 141 |
+
# Cap total output to max_total_chars (~1k tokens) to prevent context overflow
|
| 142 |
+
if len(output) > self.max_total_chars:
|
| 143 |
+
output = output[:self.max_total_chars] + "..."
|
| 144 |
+
|
| 145 |
+
return output
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class MockRetrievalClient:
|
| 149 |
+
"""
|
| 150 |
+
Mock retrieval client for development/testing without a running server.
|
| 151 |
+
Returns placeholder results so the environment can be tested end-to-end.
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
def __init__(self, **kwargs):
|
| 155 |
+
self.available = True
|
| 156 |
+
logger.info("Using MockRetrievalClient (no real retrieval server)")
|
| 157 |
+
|
| 158 |
+
def search(self, query: str, top_k: Optional[int] = None) -> str:
|
| 159 |
+
return (
|
| 160 |
+
f"[Document 1] (ID: mock_1, Score: 0.900)\n"
|
| 161 |
+
f"Mock search result for query: '{query}'. "
|
| 162 |
+
f"This is a placeholder document for testing purposes.\n\n"
|
| 163 |
+
f"[Document 2] (ID: mock_2, Score: 0.750)\n"
|
| 164 |
+
f"Another mock document related to: '{query}'. "
|
| 165 |
+
f"Replace with real retrieval server for actual training."
|
| 166 |
+
)
|
ragen/env/search/reward.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Search reward function for HotpotQA-style question answering.
|
| 3 |
+
|
| 4 |
+
This code is adapted from the RLLM project:
|
| 5 |
+
https://github.com/rllm-org/rllm
|
| 6 |
+
Original source: rllm/rewards/search_reward.py
|
| 7 |
+
License: Apache-2.0
|
| 8 |
+
|
| 9 |
+
RLLM-specific dependencies have been removed.
|
| 10 |
+
|
| 11 |
+
Evaluation uses:
|
| 12 |
+
- Exact Match (EM): normalized string comparison
|
| 13 |
+
- F1 Score: token-level precision/recall
|
| 14 |
+
|
| 15 |
+
Reference: HotpotQA / SQuAD evaluation standards.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import re
|
| 19 |
+
import string
|
| 20 |
+
from collections import Counter
|
| 21 |
+
from typing import Any, List, Tuple, Union
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class SearchRewardFn:
|
| 25 |
+
"""Reward function for search-based QA tasks using F1 and Exact Match."""
|
| 26 |
+
|
| 27 |
+
def __init__(self, correct_reward: float = 1.0, incorrect_reward: float = 0.0, f1_threshold: float = 0.3):
|
| 28 |
+
self.correct_reward = correct_reward
|
| 29 |
+
self.incorrect_reward = incorrect_reward
|
| 30 |
+
self.f1_threshold = f1_threshold
|
| 31 |
+
|
| 32 |
+
def normalize_answer(self, s: str) -> str:
|
| 33 |
+
"""Normalize answer text for evaluation (following HotpotQA/SQuAD standards)."""
|
| 34 |
+
|
| 35 |
+
def remove_articles(text):
|
| 36 |
+
return re.sub(r"\b(a|an|the)\b", " ", text)
|
| 37 |
+
|
| 38 |
+
def white_space_fix(text):
|
| 39 |
+
return " ".join(text.split())
|
| 40 |
+
|
| 41 |
+
def remove_punc(text):
|
| 42 |
+
exclude = set(string.punctuation)
|
| 43 |
+
return "".join(ch for ch in text if ch not in exclude)
|
| 44 |
+
|
| 45 |
+
def lower(text):
|
| 46 |
+
return text.lower()
|
| 47 |
+
|
| 48 |
+
return white_space_fix(remove_articles(remove_punc(lower(s))))
|
| 49 |
+
|
| 50 |
+
def f1_score(self, prediction: str, ground_truth: str) -> Tuple[float, float, float]:
|
| 51 |
+
"""Calculate token-level F1 score between prediction and ground truth."""
|
| 52 |
+
normalized_prediction = self.normalize_answer(prediction)
|
| 53 |
+
normalized_ground_truth = self.normalize_answer(ground_truth)
|
| 54 |
+
|
| 55 |
+
ZERO_METRIC = (0.0, 0.0, 0.0)
|
| 56 |
+
|
| 57 |
+
if normalized_prediction in ["yes", "no", "noanswer"] and normalized_prediction != normalized_ground_truth:
|
| 58 |
+
return ZERO_METRIC
|
| 59 |
+
if normalized_ground_truth in ["yes", "no", "noanswer"] and normalized_prediction != normalized_ground_truth:
|
| 60 |
+
return ZERO_METRIC
|
| 61 |
+
|
| 62 |
+
prediction_tokens = normalized_prediction.split()
|
| 63 |
+
ground_truth_tokens = normalized_ground_truth.split()
|
| 64 |
+
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
|
| 65 |
+
num_same = sum(common.values())
|
| 66 |
+
if num_same == 0:
|
| 67 |
+
return ZERO_METRIC
|
| 68 |
+
precision = 1.0 * num_same / len(prediction_tokens)
|
| 69 |
+
recall = 1.0 * num_same / len(ground_truth_tokens)
|
| 70 |
+
f1 = (2 * precision * recall) / (precision + recall)
|
| 71 |
+
return f1, precision, recall
|
| 72 |
+
|
| 73 |
+
def exact_match_score(self, prediction: str, ground_truth: str) -> bool:
|
| 74 |
+
"""Calculate exact match score after normalization."""
|
| 75 |
+
return self.normalize_answer(prediction) == self.normalize_answer(ground_truth)
|
| 76 |
+
|
| 77 |
+
def extract_answer_from_response(self, response: str) -> str:
|
| 78 |
+
"""
|
| 79 |
+
Fallback: extract answer from free-form LLM response text.
|
| 80 |
+
Used when the agent doesn't follow the finish[...] format.
|
| 81 |
+
Migrated from rllm's RewardSearchFn.extract_answer_from_response().
|
| 82 |
+
"""
|
| 83 |
+
response = response.strip()
|
| 84 |
+
|
| 85 |
+
# Remove thinking tags
|
| 86 |
+
response = re.sub(r"<think>.*?</think>", "", response, flags=re.DOTALL)
|
| 87 |
+
response = re.sub(r"\s+", " ", response).strip()
|
| 88 |
+
|
| 89 |
+
if not response:
|
| 90 |
+
return ""
|
| 91 |
+
|
| 92 |
+
# 1. Look for \boxed{} content (rllm format)
|
| 93 |
+
boxed_match = re.search(r"\\boxed\{([^}]+)\}", response)
|
| 94 |
+
if boxed_match:
|
| 95 |
+
return boxed_match.group(1).strip()
|
| 96 |
+
|
| 97 |
+
# 2. Bold text
|
| 98 |
+
bold_patterns = [r"\*\*([^*]+)\*\*", r"\*([^*]+)\*"]
|
| 99 |
+
for pattern in bold_patterns:
|
| 100 |
+
matches = re.findall(pattern, response)
|
| 101 |
+
substantive = [m.strip() for m in matches if len(m.strip()) > 2 and not re.match(r"^[^\w]*$", m.strip())]
|
| 102 |
+
if substantive:
|
| 103 |
+
return substantive[0]
|
| 104 |
+
|
| 105 |
+
# 3. Direct answer patterns
|
| 106 |
+
answer_patterns = [
|
| 107 |
+
r"(?:the\s+)?(?:correct\s+)?answer\s+is\s*:?\s*([^.!?]+)",
|
| 108 |
+
r"(?:therefore|thus|so|hence)\s*,?\s*([^.!?]+)",
|
| 109 |
+
]
|
| 110 |
+
for pattern in answer_patterns:
|
| 111 |
+
match = re.search(pattern, response, re.IGNORECASE)
|
| 112 |
+
if match:
|
| 113 |
+
answer = match.group(1).strip()
|
| 114 |
+
answer = re.sub(r"^\W+|\W+$", "", answer)
|
| 115 |
+
if len(answer) > 3:
|
| 116 |
+
return answer
|
| 117 |
+
|
| 118 |
+
# 4. Fallback: first substantial sentence
|
| 119 |
+
sentences = [s.strip() for s in re.split(r"[.!?]+", response) if len(s.strip()) > 5]
|
| 120 |
+
if sentences:
|
| 121 |
+
return sentences[0]
|
| 122 |
+
|
| 123 |
+
return response[:100].strip()
|
| 124 |
+
|
| 125 |
+
def evaluate_answer(self, model_answer: str, ground_truth: Union[str, List[str]]) -> Tuple[bool, float, dict]:
|
| 126 |
+
"""
|
| 127 |
+
Evaluate model answer against ground truth(s).
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
(is_correct, max_f1, metadata_dict)
|
| 131 |
+
"""
|
| 132 |
+
if isinstance(ground_truth, str):
|
| 133 |
+
ground_truths = [ground_truth]
|
| 134 |
+
else:
|
| 135 |
+
ground_truths = ground_truth
|
| 136 |
+
|
| 137 |
+
max_f1 = 0.0
|
| 138 |
+
max_em = False
|
| 139 |
+
best_match = ""
|
| 140 |
+
best_precision = 0.0
|
| 141 |
+
best_recall = 0.0
|
| 142 |
+
eval_method = None
|
| 143 |
+
|
| 144 |
+
for gt in ground_truths:
|
| 145 |
+
gt_str = str(gt).strip()
|
| 146 |
+
|
| 147 |
+
em = self.exact_match_score(model_answer, gt_str)
|
| 148 |
+
if em:
|
| 149 |
+
max_em = True
|
| 150 |
+
max_f1 = 1.0
|
| 151 |
+
best_match = gt_str
|
| 152 |
+
best_precision = 1.0
|
| 153 |
+
best_recall = 1.0
|
| 154 |
+
eval_method = "exact_match"
|
| 155 |
+
break
|
| 156 |
+
|
| 157 |
+
f1, precision, recall = self.f1_score(model_answer, gt_str)
|
| 158 |
+
if f1 > max_f1:
|
| 159 |
+
max_f1 = f1
|
| 160 |
+
best_match = gt_str
|
| 161 |
+
best_precision = precision
|
| 162 |
+
best_recall = recall
|
| 163 |
+
eval_method = "f1_score"
|
| 164 |
+
|
| 165 |
+
is_correct = max_em or max_f1 >= self.f1_threshold
|
| 166 |
+
|
| 167 |
+
metadata = {
|
| 168 |
+
"extracted_answer": model_answer,
|
| 169 |
+
"ground_truths": ground_truths,
|
| 170 |
+
"best_match": best_match,
|
| 171 |
+
"f1_score": max_f1,
|
| 172 |
+
"precision": best_precision,
|
| 173 |
+
"recall": best_recall,
|
| 174 |
+
"exact_match": max_em,
|
| 175 |
+
"evaluation_method": eval_method,
|
| 176 |
+
"f1_threshold": self.f1_threshold,
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
return is_correct, max_f1, metadata
|
| 180 |
+
|
| 181 |
+
def compute_reward(self, model_answer: str, ground_truth: Union[str, List[str]]) -> Tuple[float, dict]:
|
| 182 |
+
"""
|
| 183 |
+
Compute reward for a model answer.
|
| 184 |
+
|
| 185 |
+
Returns:
|
| 186 |
+
(reward_float, metadata_dict)
|
| 187 |
+
"""
|
| 188 |
+
is_correct, f1, metadata = self.evaluate_answer(model_answer, ground_truth)
|
| 189 |
+
|
| 190 |
+
if is_correct:
|
| 191 |
+
if metadata.get("exact_match", False):
|
| 192 |
+
reward = self.correct_reward
|
| 193 |
+
else:
|
| 194 |
+
reward = self.correct_reward * f1
|
| 195 |
+
else:
|
| 196 |
+
reward = self.incorrect_reward
|
| 197 |
+
|
| 198 |
+
metadata["reward"] = reward
|
| 199 |
+
return reward, metadata
|
ragen/env/sokoban/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Sokoban grid puzzle environment for multi-turn planning with irreversible dynamics.
|
| 3 |
+
|
| 4 |
+
Original Source: gym-sokoban (https://github.com/mpSchrader/gym-sokoban)
|
| 5 |
+
Citation: Schrader, M. P. B. (2018). gym_sokoban
|
| 6 |
+
License: MIT
|
| 7 |
+
|
| 8 |
+
Modifications: Added text-based observation format and custom reward shaping
|
| 9 |
+
for LLM agent reinforcement learning.
|
| 10 |
+
"""
|
| 11 |
+
from .env import SokobanEnv
|
| 12 |
+
from .config import SokobanEnvConfig
|
| 13 |
+
|
| 14 |
+
__all__ = ["SokobanEnv", "SokobanEnvConfig"]
|
ragen/env/sokoban/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (622 Bytes). View file
|
|
|
ragen/env/sokoban/__pycache__/config.cpython-310.pyc
ADDED
|
Binary file (1.82 kB). View file
|
|
|
ragen/env/sokoban/__pycache__/env.cpython-310.pyc
ADDED
|
Binary file (4.55 kB). View file
|
|
|
ragen/env/sokoban/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (13.9 kB). View file
|
|
|
ragen/env/sokoban/config.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, field
|
| 2 |
+
from typing import Tuple, Optional, Dict
|
| 3 |
+
|
| 4 |
+
@dataclass
|
| 5 |
+
class SokobanEnvConfig:
|
| 6 |
+
dim_room: Tuple[int, int] = (6, 6)
|
| 7 |
+
max_steps: int = 100
|
| 8 |
+
num_boxes: int = 3
|
| 9 |
+
search_depth: int = 300
|
| 10 |
+
grid_lookup: Optional[Dict[int, str]] = field(default_factory=lambda: {0:"#", 1:"_", 2:"O", 3:"√", 4:"X", 5:"P", 6:"S"})
|
| 11 |
+
grid_vocab: Optional[Dict[str, str]] = field(default_factory=lambda: {"#": "wall", "_": "empty", "O": "target", "√": "box on target", "X": "box", "P": "player", "S": "player on target"})
|
| 12 |
+
action_lookup: Optional[Dict[int, str]] = field(default_factory=lambda: {1:"Up", 2:"Down", 3:"Left", 4:"Right"})
|
| 13 |
+
dim_x: Optional[int] = None
|
| 14 |
+
dim_y: Optional[int] = None
|
| 15 |
+
render_mode: str = "text"
|
| 16 |
+
observation_format: str = "grid"
|
| 17 |
+
|
| 18 |
+
def __post_init__(self):
|
| 19 |
+
if self.dim_x is not None and self.dim_y is not None:
|
| 20 |
+
self.dim_room = (self.dim_x, self.dim_y)
|
| 21 |
+
delattr(self, 'dim_x')
|
| 22 |
+
delattr(self, 'dim_y')
|
| 23 |
+
if self.observation_format not in {"grid", "coord", "grid_coord"}:
|
| 24 |
+
raise ValueError(f"Unsupported observation_format: {self.observation_format}")
|
ragen/env/sokoban/env.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gym
|
| 2 |
+
from gym_sokoban.envs.sokoban_env import SokobanEnv as GymSokobanEnv
|
| 3 |
+
import numpy as np
|
| 4 |
+
from .utils import (
|
| 5 |
+
generate_room,
|
| 6 |
+
collect_entity_coordinates,
|
| 7 |
+
format_coordinate_render,
|
| 8 |
+
)
|
| 9 |
+
# from gym_sokoban.envs.sokoban_env.utils import generate_room
|
| 10 |
+
from ragen.env.base import BaseDiscreteActionEnv
|
| 11 |
+
from ragen.env.sokoban.config import SokobanEnvConfig
|
| 12 |
+
from ragen.utils import all_seed
|
| 13 |
+
|
| 14 |
+
class SokobanEnv(BaseDiscreteActionEnv, GymSokobanEnv):
|
| 15 |
+
def __init__(self, config=None, **kwargs):
|
| 16 |
+
self.config = config or SokobanEnvConfig()
|
| 17 |
+
self.GRID_LOOKUP = self.config.grid_lookup
|
| 18 |
+
self.ACTION_LOOKUP = self.config.action_lookup
|
| 19 |
+
self.search_depth = self.config.search_depth
|
| 20 |
+
self.ACTION_SPACE = gym.spaces.discrete.Discrete(4, start=1)
|
| 21 |
+
self.render_mode = self.config.render_mode
|
| 22 |
+
self.observation_format = self.config.observation_format
|
| 23 |
+
|
| 24 |
+
BaseDiscreteActionEnv.__init__(self)
|
| 25 |
+
GymSokobanEnv.__init__(
|
| 26 |
+
self,
|
| 27 |
+
dim_room=self.config.dim_room,
|
| 28 |
+
max_steps=self.config.max_steps,
|
| 29 |
+
num_boxes=self.config.num_boxes,
|
| 30 |
+
**kwargs
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
def reset(self, seed=None, mode=None):
|
| 34 |
+
try:
|
| 35 |
+
with all_seed(seed):
|
| 36 |
+
self.room_fixed, self.room_state, self.box_mapping, action_sequence = generate_room(
|
| 37 |
+
dim=self.dim_room,
|
| 38 |
+
num_steps=self.num_gen_steps,
|
| 39 |
+
num_boxes=self.num_boxes,
|
| 40 |
+
search_depth=self.search_depth
|
| 41 |
+
)
|
| 42 |
+
self.num_env_steps, self.reward_last, self.boxes_on_target = 0, 0, 0
|
| 43 |
+
self.player_position = np.argwhere(self.room_state == 5)[0]
|
| 44 |
+
return self.render()
|
| 45 |
+
except (RuntimeError, RuntimeWarning) as e:
|
| 46 |
+
next_seed = abs(hash(str(seed))) % (2 ** 32) if seed is not None else None
|
| 47 |
+
return self.reset(next_seed)
|
| 48 |
+
|
| 49 |
+
def step(self, action: int):
|
| 50 |
+
previous_pos = self.player_position
|
| 51 |
+
_, reward, done, _ = GymSokobanEnv.step(self, action)
|
| 52 |
+
next_obs = self.render()
|
| 53 |
+
action_effective = not np.array_equal(previous_pos, self.player_position)
|
| 54 |
+
info = {"action_is_effective": action_effective, "action_is_valid": True, "success": self.boxes_on_target == self.num_boxes}
|
| 55 |
+
return next_obs, reward, done, info
|
| 56 |
+
|
| 57 |
+
def render(self, mode=None):
|
| 58 |
+
if mode in {'grid', 'coord', 'grid_coord'}:
|
| 59 |
+
return self._render_text(mode)
|
| 60 |
+
|
| 61 |
+
render_mode = mode if mode is not None else self.render_mode
|
| 62 |
+
if render_mode == 'text':
|
| 63 |
+
return self._render_text(self.observation_format)
|
| 64 |
+
if render_mode == 'rgb_array':
|
| 65 |
+
return self.get_image(mode='rgb_array', scale=1)
|
| 66 |
+
raise ValueError(f"Invalid mode: {render_mode}")
|
| 67 |
+
|
| 68 |
+
def _render_text(self, observation_format: str) -> str:
|
| 69 |
+
if observation_format == 'grid':
|
| 70 |
+
room = np.where((self.room_state == 5) & (self.room_fixed == 2), 6, self.room_state)
|
| 71 |
+
return '\n'.join(''.join(self.GRID_LOOKUP.get(cell, "?") for cell in row) for row in room.tolist())
|
| 72 |
+
if observation_format == 'coord':
|
| 73 |
+
entity_coords = collect_entity_coordinates(self.room_state, self.room_fixed)
|
| 74 |
+
return format_coordinate_render(entity_coords, self.dim_room)
|
| 75 |
+
if observation_format == 'grid_coord':
|
| 76 |
+
entity_coords = collect_entity_coordinates(self.room_state, self.room_fixed)
|
| 77 |
+
return "Coordinates: \n" + format_coordinate_render(entity_coords, self.dim_room) + "\n" + "Grid Map: \n" + self._render_text('grid')
|
| 78 |
+
raise ValueError(f"Invalid observation_format: {observation_format}")
|
| 79 |
+
|
| 80 |
+
def get_all_actions(self):
|
| 81 |
+
return list([k for k in self.ACTION_LOOKUP.keys()])
|
| 82 |
+
|
| 83 |
+
def close(self):
|
| 84 |
+
self.render_cache = None
|
| 85 |
+
super(SokobanEnv, self).close()
|
| 86 |
+
|
| 87 |
+
if __name__ == '__main__':
|
| 88 |
+
import matplotlib.pyplot as plt
|
| 89 |
+
config = SokobanEnvConfig(dim_room=(6, 6), num_boxes=1, max_steps=100, search_depth=10)
|
| 90 |
+
env = SokobanEnv(config)
|
| 91 |
+
for i in range(10):
|
| 92 |
+
print(env.reset(seed=1010 + i))
|
| 93 |
+
print()
|
| 94 |
+
while True:
|
| 95 |
+
keyboard = input("Enter action: ")
|
| 96 |
+
if keyboard == 'q':
|
| 97 |
+
break
|
| 98 |
+
action = int(keyboard)
|
| 99 |
+
assert action in env.ACTION_LOOKUP, f"Invalid action: {action}"
|
| 100 |
+
obs, reward, done, info = env.step(action)
|
| 101 |
+
print(obs, reward, done, info)
|
| 102 |
+
np_img = env.get_image('rgb_array')
|
| 103 |
+
# save the image
|
| 104 |
+
plt.imsave('sokoban1.png', np_img)
|
ragen/env/sokoban/utils.py
ADDED
|
@@ -0,0 +1,655 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# these code are adapted from the gym_sokoban repo at https://github.com/mpSchrader/gym-sokoban
|
| 2 |
+
import random
|
| 3 |
+
import numpy as np
|
| 4 |
+
import marshal
|
| 5 |
+
import copy
|
| 6 |
+
from collections import deque
|
| 7 |
+
from typing import Dict, List, Tuple
|
| 8 |
+
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
import matplotlib.animation as animation
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
CoordDict = Dict[str, List[Tuple[int, int]]]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _to_tuple_list(array: np.ndarray, index_origin: int = 0) -> List[Tuple[int, int]]:
|
| 17 |
+
if array.size == 0:
|
| 18 |
+
return []
|
| 19 |
+
return [(int(r) + index_origin, int(c) + index_origin) for r, c in array]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def collect_entity_coordinates(room_state: np.ndarray, room_fixed: np.ndarray, index_origin: int = 0) -> CoordDict:
|
| 23 |
+
"""Collect coordinates for key Sokoban entities using the given origin."""
|
| 24 |
+
|
| 25 |
+
coords: CoordDict = {
|
| 26 |
+
# "walls": _to_tuple_list(np.argwhere(room_fixed == 0), index_origin), # do not render wall since it's too heavy
|
| 27 |
+
"targets": _to_tuple_list(np.argwhere(room_fixed == 2), index_origin),
|
| 28 |
+
"boxes_on_target": _to_tuple_list(np.argwhere(room_state == 3), index_origin),
|
| 29 |
+
"boxes": _to_tuple_list(np.argwhere(room_state == 4), index_origin),
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
player_positions = np.argwhere(room_state == 5)
|
| 33 |
+
player_on_target = []
|
| 34 |
+
player_regular = []
|
| 35 |
+
for pos in player_positions:
|
| 36 |
+
r, c = int(pos[0]), int(pos[1])
|
| 37 |
+
if room_fixed[r, c] == 2:
|
| 38 |
+
player_on_target.append((r + index_origin, c + index_origin))
|
| 39 |
+
else:
|
| 40 |
+
player_regular.append((r + index_origin, c + index_origin))
|
| 41 |
+
|
| 42 |
+
coords["player"] = player_regular
|
| 43 |
+
coords["player_on_target"] = player_on_target
|
| 44 |
+
return coords
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def format_coordinate_render(entity_coords: CoordDict, board_shape: Tuple[int, int], index_origin: int = 0) -> str:
|
| 48 |
+
"""Format Sokoban entities as a coordinate-based description."""
|
| 49 |
+
|
| 50 |
+
rows, cols = board_shape
|
| 51 |
+
origin_str = "zero-indexed" if index_origin == 0 else f"origin at {index_origin}"
|
| 52 |
+
lines = [f"Board size: {rows} rows x {cols} cols ({origin_str})."]
|
| 53 |
+
ordered_labels = [
|
| 54 |
+
("walls", "Walls"),
|
| 55 |
+
("targets", "Targets"),
|
| 56 |
+
("boxes", "Boxes"),
|
| 57 |
+
("boxes_on_target", "Boxes on target"),
|
| 58 |
+
("player", "Player"),
|
| 59 |
+
("player_on_target", "Player on target"),
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
for key, label in ordered_labels:
|
| 63 |
+
coords = entity_coords.get(key, [])
|
| 64 |
+
if not coords:
|
| 65 |
+
continue
|
| 66 |
+
coord_str = ", ".join(f"({r}, {c})" for r, c in coords)
|
| 67 |
+
lines.append(f"{label}: {coord_str}")
|
| 68 |
+
|
| 69 |
+
return "\n".join(lines)
|
| 70 |
+
|
| 71 |
+
def get_shortest_action_path(room_fixed, room_state, MAX_DEPTH=100):
|
| 72 |
+
"""
|
| 73 |
+
Get the shortest action path to push all boxes to the target spots.
|
| 74 |
+
Use BFS to find the shortest path.
|
| 75 |
+
NOTE currently only support one player, only one shortest solution
|
| 76 |
+
=========================================================
|
| 77 |
+
Parameters:
|
| 78 |
+
room_state (np.ndarray): the state of the room
|
| 79 |
+
- 0: wall
|
| 80 |
+
- 1: empty space
|
| 81 |
+
- 2: box target
|
| 82 |
+
- 3: box on target
|
| 83 |
+
- 4: box not on target
|
| 84 |
+
- 5: player
|
| 85 |
+
room_fixed (np.ndarray): the fixed part of the room
|
| 86 |
+
- 0: wall
|
| 87 |
+
- 1: empty space
|
| 88 |
+
- 2: box target
|
| 89 |
+
MAX_DEPTH (int): the maximum depth of the search
|
| 90 |
+
=========================================================
|
| 91 |
+
Returns:
|
| 92 |
+
action_sequence (list): the action sequence to push all boxes to the target spots
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
# BFS queue stores (room_state, path)
|
| 96 |
+
queue = deque([(copy.deepcopy(room_state), [])])
|
| 97 |
+
explored_states = set()
|
| 98 |
+
|
| 99 |
+
# Possible moves: up, down, left, right
|
| 100 |
+
moves = [(-1,0), (1,0), (0,-1), (0,1)]
|
| 101 |
+
actions = [1, 2, 3, 4] # Corresponding action numbers
|
| 102 |
+
|
| 103 |
+
while queue:
|
| 104 |
+
room_state, path = queue.popleft()
|
| 105 |
+
if len(path) > MAX_DEPTH:
|
| 106 |
+
return [] # No solution found
|
| 107 |
+
|
| 108 |
+
# reduce the search space by checking if the state has been explored
|
| 109 |
+
state_tohash = marshal.dumps(room_state)
|
| 110 |
+
if state_tohash in explored_states:
|
| 111 |
+
continue
|
| 112 |
+
explored_states.add(state_tohash)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# get information of the room
|
| 116 |
+
player_pos = tuple(np.argwhere(room_state == 5)[0])
|
| 117 |
+
boxes_on_target = set(map(tuple, np.argwhere((room_state == 3))))
|
| 118 |
+
boxes_not_on_target = set(map(tuple, np.argwhere((room_state == 4))))
|
| 119 |
+
boxes = boxes_on_target | boxes_not_on_target
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# Check if all boxes are on targets
|
| 123 |
+
if not boxes_not_on_target:
|
| 124 |
+
return path
|
| 125 |
+
|
| 126 |
+
# Try each direction
|
| 127 |
+
for move, action in zip(moves, actions):
|
| 128 |
+
new_room_state = copy.deepcopy(room_state)
|
| 129 |
+
new_player_pos = (player_pos[0] + move[0], player_pos[1] + move[1])
|
| 130 |
+
|
| 131 |
+
# Check is new player position is wall or out of bound
|
| 132 |
+
if new_player_pos[0] < 0 or new_player_pos[0] >= room_fixed.shape[0] \
|
| 133 |
+
or new_player_pos[1] < 0 or new_player_pos[1] >= room_fixed.shape[1] \
|
| 134 |
+
or room_fixed[new_player_pos] == 0:
|
| 135 |
+
continue
|
| 136 |
+
|
| 137 |
+
# If there's a box, check if we can push it
|
| 138 |
+
if new_player_pos in boxes:
|
| 139 |
+
box_pos = new_player_pos # the original box position
|
| 140 |
+
new_box_pos = (new_player_pos[0] + move[0], new_player_pos[1] + move[1])
|
| 141 |
+
|
| 142 |
+
# Can't push if hitting wall or another box or out of bound
|
| 143 |
+
if room_fixed[new_box_pos] == 0 or new_box_pos in boxes \
|
| 144 |
+
or new_box_pos[0] < 0 or new_box_pos[0] >= room_fixed.shape[0] \
|
| 145 |
+
or new_box_pos[1] < 0 or new_box_pos[1] >= room_fixed.shape[1]:
|
| 146 |
+
continue
|
| 147 |
+
|
| 148 |
+
# move the box
|
| 149 |
+
|
| 150 |
+
new_room_state[box_pos] = room_fixed[box_pos]
|
| 151 |
+
if room_fixed[new_box_pos] == 2:
|
| 152 |
+
new_room_state[new_box_pos] = 3
|
| 153 |
+
else:
|
| 154 |
+
new_room_state[new_box_pos] = 4
|
| 155 |
+
|
| 156 |
+
# player moves
|
| 157 |
+
new_room_state[player_pos] = room_fixed[player_pos]
|
| 158 |
+
new_room_state[new_player_pos] = 5
|
| 159 |
+
queue.append((new_room_state, path + [action]))
|
| 160 |
+
|
| 161 |
+
return [] # No solution found
|
| 162 |
+
|
| 163 |
+
# def plot_animation(imgs):
|
| 164 |
+
# fig, ax = plt.subplots()
|
| 165 |
+
# im = ax.imshow(imgs[0])
|
| 166 |
+
# def init():
|
| 167 |
+
# im.set_data(imgs[0])
|
| 168 |
+
# return [im]
|
| 169 |
+
# def update(i):
|
| 170 |
+
# im.set_data(imgs[i])
|
| 171 |
+
# return [im]
|
| 172 |
+
# ani = animation.FuncAnimation(fig, update, frames=len(imgs), init_func=init, blit=True)
|
| 173 |
+
# return ani
|
| 174 |
+
|
| 175 |
+
def plot_animation(imgs):
|
| 176 |
+
height, width = imgs[0].shape[:2]
|
| 177 |
+
fig = plt.figure(figsize=(width/100, height/100), dpi=500)
|
| 178 |
+
|
| 179 |
+
ax = fig.add_axes([0, 0, 1, 1])
|
| 180 |
+
|
| 181 |
+
ax.set_xticks([])
|
| 182 |
+
ax.set_yticks([])
|
| 183 |
+
ax.set_frame_on(False)
|
| 184 |
+
|
| 185 |
+
im = ax.imshow(imgs[0])
|
| 186 |
+
def init():
|
| 187 |
+
im.set_data(imgs[0])
|
| 188 |
+
return [im]
|
| 189 |
+
def update(i):
|
| 190 |
+
im.set_data(imgs[i])
|
| 191 |
+
return [im]
|
| 192 |
+
ani = animation.FuncAnimation(fig, update, frames=len(imgs), init_func=init, blit=True)
|
| 193 |
+
return ani
|
| 194 |
+
|
| 195 |
+
def solve_sokoban(env, saved_animation_path):
|
| 196 |
+
"""
|
| 197 |
+
Solve the given sokoban environment and save the animation
|
| 198 |
+
"""
|
| 199 |
+
actions = get_shortest_action_path(env.room_fixed, env.room_state)
|
| 200 |
+
print(f"Found {len(actions)} actions: {actions}")
|
| 201 |
+
imgs = []
|
| 202 |
+
img_before_action = env.render('rgb_array')
|
| 203 |
+
imgs.append(img_before_action)
|
| 204 |
+
for action in actions:
|
| 205 |
+
env.step(action)
|
| 206 |
+
img_after_action = env.render('rgb_array')
|
| 207 |
+
imgs.append(img_after_action)
|
| 208 |
+
ani = plot_animation(imgs)
|
| 209 |
+
ani.save(saved_animation_path)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def add_random_player_movement(room_state, room_structure, move_probability=0.5, continue_probability=0.5, max_steps=3):
|
| 213 |
+
"""
|
| 214 |
+
Randomly move the player after reverse_playing to make the level more challenging, also fix the problem that in generated map, the player is always adjacent to the box
|
| 215 |
+
|
| 216 |
+
Parameters:
|
| 217 |
+
room_state (np.ndarray): Current state of the room
|
| 218 |
+
room_structure (np.ndarray): Fixed structure of the room
|
| 219 |
+
move_probability (float): Probability of moving the player at all (0.0-1.0)
|
| 220 |
+
continue_probability (float): Probability of continuing to move after each step (0.0-1.0)
|
| 221 |
+
max_steps (int): Maximum number of steps the player can move (1-3)
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
np.ndarray: Updated room state with randomly moved player
|
| 225 |
+
"""
|
| 226 |
+
# Check if we should move the player at all
|
| 227 |
+
if random.random() > move_probability:
|
| 228 |
+
return room_state
|
| 229 |
+
|
| 230 |
+
# Find player position
|
| 231 |
+
player_pos = np.where(room_state == 5)
|
| 232 |
+
player_pos = np.array([player_pos[0][0], player_pos[1][0]])
|
| 233 |
+
|
| 234 |
+
# Keep track of previous positions to avoid moving back
|
| 235 |
+
previous_positions = [tuple(player_pos)]
|
| 236 |
+
|
| 237 |
+
# Make 1-3 random moves
|
| 238 |
+
steps_taken = 0
|
| 239 |
+
while steps_taken < max_steps:
|
| 240 |
+
# Get all valid moves (can't move into walls or boxes)
|
| 241 |
+
valid_moves = []
|
| 242 |
+
for action in range(4): # 0: up, 1: down, 2: left, 3: right
|
| 243 |
+
change = CHANGE_COORDINATES[action]
|
| 244 |
+
next_pos = player_pos + change
|
| 245 |
+
|
| 246 |
+
# Check if next position is valid (empty space or target) and not a previous position
|
| 247 |
+
if (room_state[next_pos[0], next_pos[1]] in [1, 2] and
|
| 248 |
+
tuple(next_pos) not in previous_positions):
|
| 249 |
+
valid_moves.append((action, next_pos))
|
| 250 |
+
|
| 251 |
+
# If no valid moves, break
|
| 252 |
+
if not valid_moves:
|
| 253 |
+
break
|
| 254 |
+
|
| 255 |
+
# Choose a random valid move
|
| 256 |
+
chosen_action, next_pos = random.choice(valid_moves)
|
| 257 |
+
# print(f"player_pos: {player_pos}, next_pos: {next_pos}")
|
| 258 |
+
|
| 259 |
+
# Move player
|
| 260 |
+
room_state[player_pos[0], player_pos[1]] = room_structure[player_pos[0], player_pos[1]]
|
| 261 |
+
room_state[next_pos[0], next_pos[1]] = 5
|
| 262 |
+
|
| 263 |
+
# Update player position and track previous position
|
| 264 |
+
player_pos = next_pos
|
| 265 |
+
previous_positions.append(tuple(player_pos))
|
| 266 |
+
|
| 267 |
+
steps_taken += 1
|
| 268 |
+
|
| 269 |
+
# Decide whether to continue moving
|
| 270 |
+
if steps_taken >= max_steps or random.random() > continue_probability:
|
| 271 |
+
break
|
| 272 |
+
|
| 273 |
+
return room_state
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
"""
|
| 278 |
+
Following code is adapted from the nicely written gym_sokoban repo
|
| 279 |
+
"""
|
| 280 |
+
|
| 281 |
+
def generate_room(dim=(13, 13), p_change_directions=0.35, num_steps=25, num_boxes=3, tries=4, second_player=False, search_depth=100):
|
| 282 |
+
"""
|
| 283 |
+
Generates a Sokoban room, represented by an integer matrix. The elements are encoded as follows:
|
| 284 |
+
wall = 0
|
| 285 |
+
empty space = 1
|
| 286 |
+
box target = 2
|
| 287 |
+
box not on target = 3
|
| 288 |
+
box on target = 4
|
| 289 |
+
player = 5
|
| 290 |
+
|
| 291 |
+
:param dim:
|
| 292 |
+
:param p_change_directions:
|
| 293 |
+
:param num_steps:
|
| 294 |
+
:param num_boxes:
|
| 295 |
+
:param tries:
|
| 296 |
+
:param second_player:
|
| 297 |
+
:return: Numpy 2d Array, box mapping, action sequence
|
| 298 |
+
"""
|
| 299 |
+
room_state = np.zeros(shape=dim)
|
| 300 |
+
room_structure = np.zeros(shape=dim)
|
| 301 |
+
|
| 302 |
+
# Some times rooms with a score == 0 are the only possibility.
|
| 303 |
+
# In these case, we try another model.
|
| 304 |
+
for t in range(tries):
|
| 305 |
+
room = room_topology_generation(dim, p_change_directions, num_steps)
|
| 306 |
+
room = place_boxes_and_player(room, num_boxes=num_boxes, second_player=second_player)
|
| 307 |
+
|
| 308 |
+
# Room fixed represents all not movable parts of the room
|
| 309 |
+
room_structure = np.copy(room)
|
| 310 |
+
room_structure[room_structure == 5] = 1
|
| 311 |
+
|
| 312 |
+
# Room structure represents the current state of the room including movable parts
|
| 313 |
+
room_state = room.copy()
|
| 314 |
+
room_state[room_state == 2] = 4
|
| 315 |
+
|
| 316 |
+
room_state, box_mapping, action_sequence = reverse_playing(room_state, room_structure, search_depth)
|
| 317 |
+
room_state[room_state == 3] = 4
|
| 318 |
+
|
| 319 |
+
if box_displacement_score(box_mapping) > 0:
|
| 320 |
+
break
|
| 321 |
+
|
| 322 |
+
if box_displacement_score(box_mapping) == 0:
|
| 323 |
+
raise RuntimeWarning('Generated Model with score == 0')
|
| 324 |
+
|
| 325 |
+
# Add random player movement after reverse_playing
|
| 326 |
+
if box_displacement_score(box_mapping) == 1:
|
| 327 |
+
move_probability = 0.8
|
| 328 |
+
else:
|
| 329 |
+
move_probability = 0.5
|
| 330 |
+
room_state = add_random_player_movement(
|
| 331 |
+
room_state,
|
| 332 |
+
room_structure,
|
| 333 |
+
move_probability=move_probability, # 50% chance the player will move
|
| 334 |
+
continue_probability=0.5, # 50% chance to continue moving after each step
|
| 335 |
+
max_steps=3 # Maximum of 3 steps
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
return room_structure, room_state, box_mapping, action_sequence
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def room_topology_generation(dim=(10, 10), p_change_directions=0.35, num_steps=15):
|
| 342 |
+
"""
|
| 343 |
+
Generate a room topology, which consits of empty floors and walls.
|
| 344 |
+
|
| 345 |
+
:param dim:
|
| 346 |
+
:param p_change_directions:
|
| 347 |
+
:param num_steps:
|
| 348 |
+
:return:
|
| 349 |
+
"""
|
| 350 |
+
dim_x, dim_y = dim
|
| 351 |
+
|
| 352 |
+
# The ones in the mask represent all fields which will be set to floors
|
| 353 |
+
# during the random walk. The centered one will be placed over the current
|
| 354 |
+
# position of the walk.
|
| 355 |
+
masks = [
|
| 356 |
+
[
|
| 357 |
+
[0, 0, 0],
|
| 358 |
+
[1, 1, 1],
|
| 359 |
+
[0, 0, 0]
|
| 360 |
+
],
|
| 361 |
+
[
|
| 362 |
+
[0, 1, 0],
|
| 363 |
+
[0, 1, 0],
|
| 364 |
+
[0, 1, 0]
|
| 365 |
+
],
|
| 366 |
+
[
|
| 367 |
+
[0, 0, 0],
|
| 368 |
+
[1, 1, 0],
|
| 369 |
+
[0, 1, 0]
|
| 370 |
+
],
|
| 371 |
+
[
|
| 372 |
+
[0, 0, 0],
|
| 373 |
+
[1, 1, 0],
|
| 374 |
+
[1, 1, 0]
|
| 375 |
+
],
|
| 376 |
+
[
|
| 377 |
+
[0, 0, 0],
|
| 378 |
+
[0, 1, 1],
|
| 379 |
+
[0, 1, 0]
|
| 380 |
+
]
|
| 381 |
+
]
|
| 382 |
+
|
| 383 |
+
# Possible directions during the walk
|
| 384 |
+
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
|
| 385 |
+
direction = random.sample(directions, 1)[0]
|
| 386 |
+
|
| 387 |
+
# Starting position of random walk
|
| 388 |
+
position = np.array([
|
| 389 |
+
random.randint(1, dim_x - 1),
|
| 390 |
+
random.randint(1, dim_y - 1)]
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
level = np.zeros(dim, dtype=int)
|
| 394 |
+
|
| 395 |
+
for s in range(num_steps):
|
| 396 |
+
|
| 397 |
+
# Change direction randomly
|
| 398 |
+
if random.random() < p_change_directions:
|
| 399 |
+
direction = random.sample(directions, 1)[0]
|
| 400 |
+
|
| 401 |
+
# Update position
|
| 402 |
+
position = position + direction
|
| 403 |
+
position[0] = max(min(position[0], dim_x - 2), 1)
|
| 404 |
+
position[1] = max(min(position[1], dim_y - 2), 1)
|
| 405 |
+
|
| 406 |
+
# Apply mask
|
| 407 |
+
mask = random.sample(masks, 1)[0]
|
| 408 |
+
mask_start = position - 1
|
| 409 |
+
level[mask_start[0]:mask_start[0] + 3, mask_start[1]:mask_start[1] + 3] += mask
|
| 410 |
+
|
| 411 |
+
level[level > 0] = 1
|
| 412 |
+
level[:, [0, dim_y - 1]] = 0
|
| 413 |
+
level[[0, dim_x - 1], :] = 0
|
| 414 |
+
|
| 415 |
+
return level
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def place_boxes_and_player(room, num_boxes, second_player):
|
| 419 |
+
"""
|
| 420 |
+
Places the player and the boxes into the floors in a room.
|
| 421 |
+
|
| 422 |
+
:param room:
|
| 423 |
+
:param num_boxes:
|
| 424 |
+
:return:
|
| 425 |
+
"""
|
| 426 |
+
# Get all available positions
|
| 427 |
+
possible_positions = np.where(room == 1)
|
| 428 |
+
num_possible_positions = possible_positions[0].shape[0]
|
| 429 |
+
num_players = 2 if second_player else 1
|
| 430 |
+
|
| 431 |
+
if num_possible_positions <= num_boxes + num_players:
|
| 432 |
+
raise RuntimeError('Not enough free spots (#{}) to place {} player and {} boxes.'.format(
|
| 433 |
+
num_possible_positions,
|
| 434 |
+
num_players,
|
| 435 |
+
num_boxes)
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
# Place player(s)
|
| 439 |
+
ind = np.random.randint(num_possible_positions)
|
| 440 |
+
player_position = possible_positions[0][ind], possible_positions[1][ind]
|
| 441 |
+
room[player_position] = 5
|
| 442 |
+
|
| 443 |
+
if second_player:
|
| 444 |
+
ind = np.random.randint(num_possible_positions)
|
| 445 |
+
player_position = possible_positions[0][ind], possible_positions[1][ind]
|
| 446 |
+
room[player_position] = 5
|
| 447 |
+
|
| 448 |
+
# Place boxes
|
| 449 |
+
for n in range(num_boxes):
|
| 450 |
+
possible_positions = np.where(room == 1)
|
| 451 |
+
num_possible_positions = possible_positions[0].shape[0]
|
| 452 |
+
|
| 453 |
+
ind = np.random.randint(num_possible_positions)
|
| 454 |
+
box_position = possible_positions[0][ind], possible_positions[1][ind]
|
| 455 |
+
room[box_position] = 2
|
| 456 |
+
|
| 457 |
+
return room
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# Global variables used for reverse playing.
|
| 461 |
+
explored_states = set()
|
| 462 |
+
num_boxes = 0
|
| 463 |
+
best_room_score = -1
|
| 464 |
+
best_room = None
|
| 465 |
+
best_box_mapping = None
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def reverse_playing(room_state, room_structure, search_depth=100):
|
| 469 |
+
"""
|
| 470 |
+
This function plays Sokoban reverse in a way, such that the player can
|
| 471 |
+
move and pull boxes.
|
| 472 |
+
It ensures a solvable level with all boxes not being placed on a box target.
|
| 473 |
+
:param room_state:
|
| 474 |
+
:param room_structure:
|
| 475 |
+
:param search_depth:
|
| 476 |
+
:return: 2d array, box mapping, action sequence
|
| 477 |
+
"""
|
| 478 |
+
global explored_states, num_boxes, best_room_score, best_room, best_box_mapping, best_action_sequence
|
| 479 |
+
|
| 480 |
+
# Box_Mapping is used to calculate the box displacement for every box
|
| 481 |
+
box_mapping = {}
|
| 482 |
+
box_locations = np.where(room_structure == 2)
|
| 483 |
+
num_boxes = len(box_locations[0])
|
| 484 |
+
for l in range(num_boxes):
|
| 485 |
+
box = (box_locations[0][l], box_locations[1][l])
|
| 486 |
+
box_mapping[box] = box
|
| 487 |
+
|
| 488 |
+
# explored_states globally stores the best room state and score found during search
|
| 489 |
+
explored_states = set()
|
| 490 |
+
best_room_score = -1
|
| 491 |
+
best_room = None
|
| 492 |
+
best_box_mapping = box_mapping
|
| 493 |
+
best_action_sequence = []
|
| 494 |
+
|
| 495 |
+
depth_first_search(room_state, room_structure, box_mapping, box_swaps=0, last_pull=(-1, -1), ttl=search_depth, action_sequence=[])
|
| 496 |
+
|
| 497 |
+
return best_room, best_box_mapping, best_action_sequence
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def depth_first_search(room_state, room_structure, box_mapping, box_swaps=0, last_pull=(-1, -1), ttl=300, action_sequence=None):
|
| 501 |
+
"""
|
| 502 |
+
Searches through all possible states of the room.
|
| 503 |
+
This is a recursive function, which stops if the ttl is reduced to 0 or
|
| 504 |
+
over 1.000.000 states have been explored.
|
| 505 |
+
:param room_state:
|
| 506 |
+
:param room_structure:
|
| 507 |
+
:param box_mapping:
|
| 508 |
+
:param box_swaps:
|
| 509 |
+
:param last_pull:
|
| 510 |
+
:param ttl:
|
| 511 |
+
:param action_sequence:
|
| 512 |
+
:return:
|
| 513 |
+
"""
|
| 514 |
+
if action_sequence is None:
|
| 515 |
+
action_sequence = []
|
| 516 |
+
global explored_states, num_boxes, best_room_score, best_room, best_box_mapping, best_action_sequence
|
| 517 |
+
|
| 518 |
+
ttl -= 1
|
| 519 |
+
if ttl <= 0 or len(explored_states) >= 300000:
|
| 520 |
+
return
|
| 521 |
+
|
| 522 |
+
state_tohash = marshal.dumps(room_state)
|
| 523 |
+
|
| 524 |
+
# Only search this state, if it not yet has been explored
|
| 525 |
+
if not (state_tohash in explored_states):
|
| 526 |
+
|
| 527 |
+
# Add current state and its score to explored states
|
| 528 |
+
room_score = box_swaps * box_displacement_score(box_mapping)
|
| 529 |
+
if np.where(room_state == 2)[0].shape[0] != num_boxes:
|
| 530 |
+
room_score = 0
|
| 531 |
+
|
| 532 |
+
if room_score > best_room_score:
|
| 533 |
+
best_room = room_state.copy()
|
| 534 |
+
best_room_score = room_score
|
| 535 |
+
best_box_mapping = box_mapping.copy()
|
| 536 |
+
best_action_sequence = action_sequence.copy()
|
| 537 |
+
|
| 538 |
+
explored_states.add(state_tohash)
|
| 539 |
+
|
| 540 |
+
for action in ACTION_LOOKUP.keys():
|
| 541 |
+
# The state and box mapping need to be copied to ensure
|
| 542 |
+
# every action starts from a similar state.
|
| 543 |
+
|
| 544 |
+
# TODO: A tentitive try here to make less moves
|
| 545 |
+
if action >= 4:
|
| 546 |
+
continue
|
| 547 |
+
|
| 548 |
+
room_state_next = room_state.copy()
|
| 549 |
+
box_mapping_next = box_mapping.copy()
|
| 550 |
+
|
| 551 |
+
room_state_next, box_mapping_next, last_pull_next = \
|
| 552 |
+
reverse_move(room_state_next, room_structure, box_mapping_next, last_pull, action)
|
| 553 |
+
|
| 554 |
+
box_swaps_next = box_swaps
|
| 555 |
+
if last_pull_next != last_pull:
|
| 556 |
+
box_swaps_next += 1
|
| 557 |
+
|
| 558 |
+
action_sequence_next = action_sequence + [action]
|
| 559 |
+
# action_sequence_next = action_sequence + [(action, box_mapping_next != box_mapping)] # add whether a box is moved
|
| 560 |
+
depth_first_search(room_state_next, room_structure, box_mapping_next, box_swaps_next, last_pull_next, ttl, action_sequence_next)
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
def reverse_move(room_state, room_structure, box_mapping, last_pull, action):
|
| 564 |
+
"""
|
| 565 |
+
Perform reverse action. Where all actions in the range [0, 3] correspond to
|
| 566 |
+
push actions and the ones greater 3 are simmple move actions.
|
| 567 |
+
:param room_state:
|
| 568 |
+
:param room_structure:
|
| 569 |
+
:param box_mapping:
|
| 570 |
+
:param last_pull:
|
| 571 |
+
:param action:
|
| 572 |
+
:return:
|
| 573 |
+
"""
|
| 574 |
+
player_position = np.where(room_state == 5)
|
| 575 |
+
player_position = np.array([player_position[0][0], player_position[1][0]])
|
| 576 |
+
|
| 577 |
+
change = CHANGE_COORDINATES[action % 4]
|
| 578 |
+
next_position = player_position + change
|
| 579 |
+
|
| 580 |
+
# Check if next position is an empty floor or an empty box target
|
| 581 |
+
if room_state[next_position[0], next_position[1]] in [1, 2]:
|
| 582 |
+
|
| 583 |
+
# Move player, independent of pull or move action.
|
| 584 |
+
room_state[player_position[0], player_position[1]] = room_structure[player_position[0], player_position[1]]
|
| 585 |
+
room_state[next_position[0], next_position[1]] = 5
|
| 586 |
+
|
| 587 |
+
# In addition try to pull a box if the action is a pull action
|
| 588 |
+
if action < 4:
|
| 589 |
+
possible_box_location = change[0] * -1, change[1] * -1
|
| 590 |
+
possible_box_location += player_position
|
| 591 |
+
|
| 592 |
+
if room_state[possible_box_location[0], possible_box_location[1]] in [3, 4]:
|
| 593 |
+
# Perform pull of the adjacent box
|
| 594 |
+
room_state[player_position[0], player_position[1]] = 3
|
| 595 |
+
room_state[possible_box_location[0], possible_box_location[1]] = room_structure[
|
| 596 |
+
possible_box_location[0], possible_box_location[1]]
|
| 597 |
+
|
| 598 |
+
# Update the box mapping
|
| 599 |
+
for k in box_mapping.keys():
|
| 600 |
+
if box_mapping[k] == (possible_box_location[0], possible_box_location[1]):
|
| 601 |
+
box_mapping[k] = (player_position[0], player_position[1])
|
| 602 |
+
last_pull = k
|
| 603 |
+
|
| 604 |
+
return room_state, box_mapping, last_pull
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
def box_displacement_score(box_mapping):
|
| 608 |
+
"""
|
| 609 |
+
Calculates the sum of all Manhattan distances, between the boxes
|
| 610 |
+
and their origin box targets.
|
| 611 |
+
:param box_mapping:
|
| 612 |
+
:return:
|
| 613 |
+
"""
|
| 614 |
+
score = 0
|
| 615 |
+
|
| 616 |
+
for box_target in box_mapping.keys():
|
| 617 |
+
box_location = np.array(box_mapping[box_target])
|
| 618 |
+
box_target = np.array(box_target)
|
| 619 |
+
dist = np.sum(np.abs(box_location - box_target))
|
| 620 |
+
score += dist
|
| 621 |
+
|
| 622 |
+
return score
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
TYPE_LOOKUP = {
|
| 626 |
+
0: 'wall',
|
| 627 |
+
1: 'empty space',
|
| 628 |
+
2: 'box target',
|
| 629 |
+
3: 'box on target',
|
| 630 |
+
4: 'box not on target',
|
| 631 |
+
5: 'player'
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
ACTION_LOOKUP = {
|
| 635 |
+
0: 'push up',
|
| 636 |
+
1: 'push down',
|
| 637 |
+
2: 'push left',
|
| 638 |
+
3: 'push right',
|
| 639 |
+
4: 'move up',
|
| 640 |
+
5: 'move down',
|
| 641 |
+
6: 'move left',
|
| 642 |
+
7: 'move right',
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
# Moves are mapped to coordinate changes as follows
|
| 646 |
+
# 0: Move up
|
| 647 |
+
# 1: Move down
|
| 648 |
+
# 2: Move left
|
| 649 |
+
# 3: Move right
|
| 650 |
+
CHANGE_COORDINATES = {
|
| 651 |
+
0: (-1, 0),
|
| 652 |
+
1: (1, 0),
|
| 653 |
+
2: (0, -1),
|
| 654 |
+
3: (0, 1)
|
| 655 |
+
}
|
ragen/env/spatial/config.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, field
|
| 2 |
+
from typing import List, Dict, Any, Optional, Tuple
|
| 3 |
+
from ragen.env.spatial.Base.tos_base.evaluation.task_types import EvalTaskType
|
| 4 |
+
|
| 5 |
+
@dataclass
|
| 6 |
+
class SpatialGymConfig:
|
| 7 |
+
"""
|
| 8 |
+
Configuration for the SpatialGym environment.
|
| 9 |
+
"""
|
| 10 |
+
# Environment specific configuration
|
| 11 |
+
name: str = 'unnamed_env'
|
| 12 |
+
render_mode: str = "text"
|
| 13 |
+
|
| 14 |
+
# Room configuration
|
| 15 |
+
room_size: List[int] = field(default_factory=lambda: [10, 10])
|
| 16 |
+
n_objects: int = 3
|
| 17 |
+
level: int = 0
|
| 18 |
+
main: int = 6
|
| 19 |
+
|
| 20 |
+
# Exploration configuration
|
| 21 |
+
max_exp_steps: int = 10
|
| 22 |
+
|
| 23 |
+
# Evaluation configuration
|
| 24 |
+
eval_tasks: List[str] = field(default_factory=lambda: [
|
| 25 |
+
"dir", "rot", "rot_dual", "pov", "bwd_pov",
|
| 26 |
+
"e2a", "fwd_loc", "bwd_loc", "fwd_fov", "bwd_nav"
|
| 27 |
+
])
|
| 28 |
+
|
| 29 |
+
prompt_config: Dict[str, Any] = field(default_factory=lambda: {"topdown": False, "oblique": False, "type": "shorter"})
|
| 30 |
+
|
| 31 |
+
def __post_init__(self):
|
| 32 |
+
"""Validate configuration parameters."""
|
| 33 |
+
# Validate room size
|
| 34 |
+
assert self.room_size[0] > 0 and self.room_size[1] > 0, "room_size must be positive"
|
| 35 |
+
self._validate_eval_tasks()
|
| 36 |
+
assert self.render_mode == 'text', "Only text render mode is supported in RAGEN"
|
| 37 |
+
|
| 38 |
+
def _validate_eval_tasks(self):
|
| 39 |
+
"""Validate eval_tasks parameter."""
|
| 40 |
+
valid_eval_tasks = EvalTaskType.get_short_names()
|
| 41 |
+
|
| 42 |
+
if not self.eval_tasks:
|
| 43 |
+
raise ValueError("eval_tasks must be non-empty")
|
| 44 |
+
|
| 45 |
+
for task_name in self.eval_tasks:
|
| 46 |
+
if not isinstance(task_name, str):
|
| 47 |
+
raise ValueError(f"eval_tasks must be a list of strings, got {type(task_name)}")
|
| 48 |
+
if task_name not in valid_eval_tasks:
|
| 49 |
+
raise ValueError(f"task_type '{task_name}' must be one of {valid_eval_tasks}")
|
ragen/env/spatial/env.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gymnasium as gym
|
| 2 |
+
import numpy as np
|
| 3 |
+
from typing import Any, Dict, Tuple, Optional, List
|
| 4 |
+
|
| 5 |
+
from ragen.env.base import BaseLanguageBasedEnv
|
| 6 |
+
from ragen.env.spatial.config import SpatialGymConfig
|
| 7 |
+
from ragen.env.spatial.Base.tos_base.utils.room_utils import RoomGenerator
|
| 8 |
+
from ragen.env.spatial.Base.tos_base.actions.actions import ActionSequence, ACTION_REMINDER
|
| 9 |
+
from ragen.env.spatial.Base.tos_base.evaluation.task_types import EvalTaskType
|
| 10 |
+
from ragen.env.spatial.Base.tos_base.managers.exploration_manager import ExplorationManager
|
| 11 |
+
from ragen.env.spatial.prompter import SpatialPrompter
|
| 12 |
+
|
| 13 |
+
class SpatialGym(BaseLanguageBasedEnv, gym.Env):
|
| 14 |
+
def __init__(self, config: SpatialGymConfig = None):
|
| 15 |
+
super().__init__()
|
| 16 |
+
self.config = config or SpatialGymConfig()
|
| 17 |
+
print(f"Config: {self.config}")
|
| 18 |
+
self.render_mode = self.config.render_mode
|
| 19 |
+
# User requirement: max steps should be 1 step more than max exp steps
|
| 20 |
+
self.max_steps = self.config.max_exp_steps + 1
|
| 21 |
+
|
| 22 |
+
self.room = None
|
| 23 |
+
self.agent = None
|
| 24 |
+
self.current_answer = None
|
| 25 |
+
self.current_step_count = 0
|
| 26 |
+
self.last_obs = ""
|
| 27 |
+
self.last_info = {}
|
| 28 |
+
|
| 29 |
+
self.exploration_manager = None
|
| 30 |
+
self.prompter = SpatialPrompter(self.config, np.random.RandomState(42))
|
| 31 |
+
self._rendered = False
|
| 32 |
+
|
| 33 |
+
def reset(self, seed: Optional[int] = None, mode=None) -> str:
|
| 34 |
+
gym.Env.reset(self, seed=seed) # Sets self.np_random
|
| 35 |
+
|
| 36 |
+
self.prompter.np_random = self.np_random
|
| 37 |
+
|
| 38 |
+
# Convert eval_tasks (List[str]) to List[Dict] for RoomGenerator validation
|
| 39 |
+
eval_tasks_dicts = [{"task_type": t} for t in self.config.eval_tasks]
|
| 40 |
+
|
| 41 |
+
# Generate room
|
| 42 |
+
self.room, self.agent = RoomGenerator.generate_room(
|
| 43 |
+
room_size=self.config.room_size,
|
| 44 |
+
n_objects=self.config.n_objects,
|
| 45 |
+
np_random=self.np_random,
|
| 46 |
+
level=self.config.level,
|
| 47 |
+
main=self.config.main,
|
| 48 |
+
eval_tasks=eval_tasks_dicts,
|
| 49 |
+
same_room_size=True
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# Initialize ExplorationManager
|
| 53 |
+
self.exploration_manager = ExplorationManager(self.room, self.agent)
|
| 54 |
+
|
| 55 |
+
# Select evaluation task
|
| 56 |
+
task_name = self.np_random.choice(self.config.eval_tasks)
|
| 57 |
+
|
| 58 |
+
# Create task
|
| 59 |
+
current_task = EvalTaskType.create_task(
|
| 60 |
+
task_name,
|
| 61 |
+
np_random=self.np_random,
|
| 62 |
+
room=self.room,
|
| 63 |
+
agent=self.agent
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# Generate question
|
| 67 |
+
current_question = current_task.generate_question()
|
| 68 |
+
self.current_answer = current_task.answer
|
| 69 |
+
|
| 70 |
+
# Generate initial prompt
|
| 71 |
+
obs_dict = self.prompter.get_initial_observation_prompt(
|
| 72 |
+
self.room,
|
| 73 |
+
self.agent,
|
| 74 |
+
question=current_question
|
| 75 |
+
)
|
| 76 |
+
prompt = obs_dict['obs_str'] + "\n" + ACTION_REMINDER
|
| 77 |
+
|
| 78 |
+
self.current_step_count = 0
|
| 79 |
+
self.last_obs = prompt
|
| 80 |
+
self.last_info = {}
|
| 81 |
+
self._rendered = False
|
| 82 |
+
return prompt
|
| 83 |
+
|
| 84 |
+
def step(self, action: str) -> Tuple[str, float, bool, Dict[str, Any]]:
|
| 85 |
+
self._rendered = False
|
| 86 |
+
self.current_step_count += 1
|
| 87 |
+
|
| 88 |
+
# Parse action
|
| 89 |
+
seq = ActionSequence.parse(action)
|
| 90 |
+
if seq is None:
|
| 91 |
+
return self._step_result(
|
| 92 |
+
obs="Invalid action format." + "\n" + ACTION_REMINDER,
|
| 93 |
+
reward=-1.0,
|
| 94 |
+
done=False,
|
| 95 |
+
info={"error": "Invalid action format", "success": False}
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
# Execute actions
|
| 99 |
+
results = self.exploration_manager.execute_action_sequence(seq)
|
| 100 |
+
feedback_list = [res.message for res in results]
|
| 101 |
+
|
| 102 |
+
terminated = False
|
| 103 |
+
term_answer = None
|
| 104 |
+
|
| 105 |
+
# Check for TermAction
|
| 106 |
+
for res in results:
|
| 107 |
+
if res.success and res.action_type == 'term':
|
| 108 |
+
terminated = True
|
| 109 |
+
term_answer = res.data.get('answer')
|
| 110 |
+
break
|
| 111 |
+
|
| 112 |
+
# Calculate reward and done
|
| 113 |
+
reward = -0.1
|
| 114 |
+
done = False
|
| 115 |
+
info = {}
|
| 116 |
+
|
| 117 |
+
if terminated:
|
| 118 |
+
done = True
|
| 119 |
+
if term_answer == self.current_answer:
|
| 120 |
+
reward = 10.0
|
| 121 |
+
info["success"] = True
|
| 122 |
+
else:
|
| 123 |
+
reward = -1
|
| 124 |
+
info["success"] = False
|
| 125 |
+
info["answer"] = term_answer
|
| 126 |
+
info["correct_answer"] = self.current_answer
|
| 127 |
+
|
| 128 |
+
if self.current_step_count >= self.max_steps:
|
| 129 |
+
done = True
|
| 130 |
+
|
| 131 |
+
obs = "\n".join(feedback_list) + "\n" + ACTION_REMINDER
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
return self._step_result(obs, reward, done, info)
|
| 135 |
+
|
| 136 |
+
def _step_result(self, obs, reward, done, info):
|
| 137 |
+
self.last_obs = obs
|
| 138 |
+
self.last_info = info
|
| 139 |
+
return obs, reward, done, info
|
| 140 |
+
|
| 141 |
+
def render(self, mode=None):
|
| 142 |
+
if self._rendered:
|
| 143 |
+
return "invalid format" + "\n" + ACTION_REMINDER
|
| 144 |
+
self._rendered = True
|
| 145 |
+
return self.last_obs
|
| 146 |
+
|
| 147 |
+
def close(self):
|
| 148 |
+
pass
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
config = SpatialGymConfig(room_size=[20, 20], n_objects=5, level=0, main=6)
|
| 152 |
+
env = SpatialGym(config)
|
| 153 |
+
obs = env.reset(seed=42)
|
| 154 |
+
print("Initial Observation:")
|
| 155 |
+
print(obs)
|
| 156 |
+
|
| 157 |
+
from ragen.env.spatial.Base.tos_base.utils.room_utils import RoomPlotter
|
| 158 |
+
RoomPlotter.plot(env.room, env.agent, mode='img', save_path='room.png')
|
| 159 |
+
|
| 160 |
+
# Test a few steps
|
| 161 |
+
print("\nStep 0: Invalid action")
|
| 162 |
+
obs, reward, done, info = env.step("Actions: [Rotate(45)]")
|
| 163 |
+
obs = env.render()
|
| 164 |
+
print(f"Reward: {reward}, Done: {done}, Info: {info}, Obs: {obs}")
|
| 165 |
+
|
| 166 |
+
print("\nStep 1: Rotate and Observe")
|
| 167 |
+
obs, reward, done, info = env.step("Actions: [Rotate(90), Observe()]")
|
| 168 |
+
obs = env.render()
|
| 169 |
+
print(f"Reward: {reward}, Done: {done}, Info: {info}, Obs: {obs}")
|
| 170 |
+
|
| 171 |
+
print("\nStep 2: Jump to red door and Observe")
|
| 172 |
+
obs, reward, done, info = env.step("Actions: [JumpTo(red door), Observe()]")
|
| 173 |
+
obs = env.render()
|
| 174 |
+
print(f"Reward: {reward}, Done: {done}, Info: {info}, Obs: {obs}")
|
| 175 |
+
|
| 176 |
+
print("\nStep 3: Terminate with answer")
|
| 177 |
+
obs, reward, done, info = env.step("Actions: [Term(C)]")
|
| 178 |
+
obs = env.render()
|
| 179 |
+
print(f"Reward: {reward}, Done: {done}, Info: {info}, Obs: {obs}")
|
| 180 |
+
|
ragen/env/spatial/env_old.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gymnasium as gym
|
| 2 |
+
import numpy as np
|
| 3 |
+
from typing import List, Dict, Any
|
| 4 |
+
|
| 5 |
+
from vagen.env.spatial.env_config import SpatialGymConfig
|
| 6 |
+
from vagen.env.spatial.Base.tos_base import (
|
| 7 |
+
EvaluationManager,
|
| 8 |
+
ActionSequence,
|
| 9 |
+
ExplorationManager,
|
| 10 |
+
HistoryManager,
|
| 11 |
+
RoomGenerator,
|
| 12 |
+
BaseAction,
|
| 13 |
+
EvalTaskType,
|
| 14 |
+
)
|
| 15 |
+
from vagen.env.spatial.Base.tos_base.managers.agent_proxy import get_agent_proxy
|
| 16 |
+
from vagen.env.spatial.Base.tos_base.prompts import Prompter
|
| 17 |
+
from vagen.env.spatial.Base.tos_base.utils.action_utils import action_results_to_text
|
| 18 |
+
from vagen.env.spatial.Base.tos_base.utils.room_utils import initialize_room_from_json
|
| 19 |
+
from vagen.env.spatial.Base.tos_base.utils.env_logger import EnvTurnLog
|
| 20 |
+
from vagen.env.spatial.Base.tos_base.utils.utils import parse_llm_response
|
| 21 |
+
from vagen.env.spatial.Base.tos_base.utils.image_handler import ImageHandler
|
| 22 |
+
from vagen.env.spatial.Base.tos_base.actions.actions import ForcedTermAction, ActionSequence
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class SpatialGym(gym.Env):
|
| 26 |
+
"""
|
| 27 |
+
Spatial Gym Environment with exploration and evaluation phases.
|
| 28 |
+
|
| 29 |
+
This environment uses an EvaluationManager to handle all evaluation tasks,
|
| 30 |
+
separating evaluation logic from the main environment logic.
|
| 31 |
+
"""
|
| 32 |
+
def __init__(self, config: SpatialGymConfig):
|
| 33 |
+
super().__init__()
|
| 34 |
+
self.config = config
|
| 35 |
+
self.prompter: Prompter = None
|
| 36 |
+
|
| 37 |
+
self.is_exploration_phase = None
|
| 38 |
+
self.remaining_exp_steps = None
|
| 39 |
+
self.render_cache = None
|
| 40 |
+
|
| 41 |
+
# Room state management
|
| 42 |
+
self.initial_room = None
|
| 43 |
+
self.initial_agent = None
|
| 44 |
+
|
| 45 |
+
# Managers
|
| 46 |
+
self.exploration_manager = None
|
| 47 |
+
self.evaluation_manager = None
|
| 48 |
+
self.cognitive_map_manager = None
|
| 49 |
+
self.history_manager = None
|
| 50 |
+
|
| 51 |
+
# Turn logging
|
| 52 |
+
self.turn_logs: List[EnvTurnLog] = None
|
| 53 |
+
self.current_turn_number = None
|
| 54 |
+
self.observed_image_paths: List[str] = None
|
| 55 |
+
|
| 56 |
+
def _generate_initial_observation(self) -> str:
|
| 57 |
+
"""Generate initial observation based on exploration type."""
|
| 58 |
+
exp_history = {}
|
| 59 |
+
images = []
|
| 60 |
+
if self.config.exp_type == 'passive' and not self.config.prompt_config['topdown']:
|
| 61 |
+
proxy = get_agent_proxy(
|
| 62 |
+
self.config.proxy_agent,
|
| 63 |
+
self.initial_room,
|
| 64 |
+
self.agent,
|
| 65 |
+
grid_size=self.config.grid_size if hasattr(self.config, 'grid_size') else None,
|
| 66 |
+
)
|
| 67 |
+
proxy.run()
|
| 68 |
+
# Only collect multi-modal data if render_mode is vision
|
| 69 |
+
if self.config.render_mode == 'vision':
|
| 70 |
+
obs_str = proxy.to_text(self.config.image_placeholder)
|
| 71 |
+
for t in proxy.turns:
|
| 72 |
+
if any('observe' in result.action_type for result in t.actions):
|
| 73 |
+
image, image_path = self._get_multi_modal_data(proxy.mgr, t.pos, t.ori)
|
| 74 |
+
images.append(image)
|
| 75 |
+
self.observed_image_paths.append(image_path)
|
| 76 |
+
assert images is not []
|
| 77 |
+
exp_history['multi_modal_data'] = {self.config.image_placeholder: images}
|
| 78 |
+
else:
|
| 79 |
+
obs_str = proxy.to_text()
|
| 80 |
+
exp_history['obs_str'] = obs_str
|
| 81 |
+
# expose proxy manager so metrics are available via env.get_exp_summary()
|
| 82 |
+
self.exploration_manager = proxy.mgr
|
| 83 |
+
|
| 84 |
+
return self.prompter.get_initial_observation_prompt(
|
| 85 |
+
room=self.initial_room,
|
| 86 |
+
agent=self.agent,
|
| 87 |
+
eval_manager=self.evaluation_manager,
|
| 88 |
+
exp_history=exp_history,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
def system_prompt(self) -> str:
|
| 92 |
+
return "You are an AI assistant that answers visual questions based on images."
|
| 93 |
+
|
| 94 |
+
def reset(self, seed: int = None):
|
| 95 |
+
"""Reset environment for a new episode."""
|
| 96 |
+
super().reset(seed=seed)
|
| 97 |
+
|
| 98 |
+
self.image_handler = ImageHandler(self.config.data_dir, seed, self.config.image_size)
|
| 99 |
+
self.json_data = self.image_handler.json_data
|
| 100 |
+
|
| 101 |
+
self.prompter = Prompter(self.config, self.np_random, self.image_handler)
|
| 102 |
+
# Generate initial room
|
| 103 |
+
# self.initial_room, self.agent = RoomGenerator.generate_room(
|
| 104 |
+
# **self.config.get_room_config(),
|
| 105 |
+
# np_random=self.np_random,
|
| 106 |
+
# )
|
| 107 |
+
self.initial_room, self.agent = initialize_room_from_json(self.json_data)
|
| 108 |
+
self.initial_agent = self.agent.copy()
|
| 109 |
+
|
| 110 |
+
# Initialize episode state
|
| 111 |
+
self.remaining_exp_steps = self.config.max_exp_steps
|
| 112 |
+
|
| 113 |
+
# Initialize turn logs
|
| 114 |
+
self.turn_logs = []
|
| 115 |
+
self.current_turn_number = 0
|
| 116 |
+
self.observed_image_paths = []
|
| 117 |
+
# Set exploration phase
|
| 118 |
+
self.is_exploration_phase = self.config.exp_type == 'active'
|
| 119 |
+
|
| 120 |
+
# Set field of view for all actions
|
| 121 |
+
BaseAction.set_field_of_view(self.config.field_of_view)
|
| 122 |
+
self.exploration_manager = ExplorationManager(
|
| 123 |
+
self.initial_room, self.agent,
|
| 124 |
+
grid_size=(self.config.grid_size if hasattr(self.config, 'grid_size') else None),
|
| 125 |
+
)
|
| 126 |
+
self.history_manager = HistoryManager(
|
| 127 |
+
self.config.get_observation_config(), self.config.get_model_config(),
|
| 128 |
+
self.initial_room.to_dict(), self.agent.to_dict(),
|
| 129 |
+
image_dir=self.image_handler.image_dir,
|
| 130 |
+
output_dir=self.config.kwargs['output_dir'],
|
| 131 |
+
eval_override=self._should_eval_override(),
|
| 132 |
+
all_override=self.config.kwargs.get('all_override', False),
|
| 133 |
+
task_type=EvalTaskType.from_short_name(self.config.eval_tasks[0]['task_type']).class_name
|
| 134 |
+
)
|
| 135 |
+
# Initialize EvaluationManager with knowledge of existing eval counts
|
| 136 |
+
self.evaluation_manager = EvaluationManager(
|
| 137 |
+
self.config.eval_tasks, self.np_random, self.initial_room, self.agent, history_manager=self.history_manager, seed=seed
|
| 138 |
+
) if len(self.config.eval_tasks) > 0 else None
|
| 139 |
+
info = {}
|
| 140 |
+
if self.history_manager:
|
| 141 |
+
info['history'] = self.history_manager.get_responses()
|
| 142 |
+
# If evaluation tasks already fully completed per config, indicate finish
|
| 143 |
+
if self.evaluation_manager and self.config.exp_type == 'passive':
|
| 144 |
+
info['finish'] = self.evaluation_manager.check_and_prune_completed_tasks()
|
| 145 |
+
|
| 146 |
+
obs = self._generate_initial_observation() if not info.get('finish', False) else {"obs_str":"Task finished"}
|
| 147 |
+
self.render_cache = obs
|
| 148 |
+
return obs, info
|
| 149 |
+
|
| 150 |
+
def _should_eval_override(self) -> bool:
|
| 151 |
+
"""Decide if we should override evaluation logs for this specific task."""
|
| 152 |
+
override_flag = self.config.kwargs.get('eval_override', False)
|
| 153 |
+
if not override_flag:
|
| 154 |
+
return False
|
| 155 |
+
selected = set(self.config.kwargs.get('eval_override_tasks', []) or [])
|
| 156 |
+
if not selected:
|
| 157 |
+
return True
|
| 158 |
+
# Accept both short names and class names
|
| 159 |
+
current_short = self.config.eval_tasks[0]['task_type']
|
| 160 |
+
current_class = EvalTaskType.from_short_name(current_short).class_name
|
| 161 |
+
return (current_short in selected) or (current_class in selected)
|
| 162 |
+
|
| 163 |
+
def _step_exploration(self, action: str):
|
| 164 |
+
"""
|
| 165 |
+
Handle exploration phase step with parsed result and shared info.
|
| 166 |
+
"""
|
| 167 |
+
obs_str = ""
|
| 168 |
+
reward = -0.1
|
| 169 |
+
self.remaining_exp_steps -= 1
|
| 170 |
+
exp_log = None
|
| 171 |
+
obs={}
|
| 172 |
+
info = {'is_valid_action': True}
|
| 173 |
+
action_sequence = ActionSequence.parse(action)
|
| 174 |
+
if self.remaining_exp_steps < 0:
|
| 175 |
+
action_sequence = ActionSequence(motion_actions=[], final_action=ForcedTermAction())
|
| 176 |
+
if not action:
|
| 177 |
+
obs_str += "Invalid action. You should provide only one final action\n"
|
| 178 |
+
info['is_valid_action'] = False
|
| 179 |
+
reward += -0.5 # invalid action penalty
|
| 180 |
+
elif not action_sequence:
|
| 181 |
+
obs_str += "Invalid output format.\n"
|
| 182 |
+
info['is_valid_action'] = False
|
| 183 |
+
reward += -0.5 # invalid action penalty
|
| 184 |
+
else:
|
| 185 |
+
# execute action
|
| 186 |
+
action_results = self.exploration_manager.execute_action_sequence(action_sequence)
|
| 187 |
+
obs_str += action_results_to_text(action_results, self.config.image_placeholder if self.config.render_mode == 'vision' else None)
|
| 188 |
+
exp_log = self.exploration_manager.turn_logs[-1]
|
| 189 |
+
if action_sequence.final_action and action_sequence.final_action.is_term():
|
| 190 |
+
self.is_exploration_phase = False
|
| 191 |
+
# to ensure cogmap override working correctly
|
| 192 |
+
if self.evaluation_manager.check_and_prune_completed_tasks():
|
| 193 |
+
return {'obs_str': "Task finished"}, 0, True, info, exp_log
|
| 194 |
+
obs_str += self.prompter.get_evaluation_prompt(self.evaluation_manager)
|
| 195 |
+
else:
|
| 196 |
+
obs_str += f"\nYou have a maximum of {self.remaining_exp_steps} exploration steps left."
|
| 197 |
+
# Only get multi-modal data if render_mode is vision
|
| 198 |
+
if self.config.render_mode == 'vision':
|
| 199 |
+
image, image_path = self._get_multi_modal_data(self.exploration_manager, self.exploration_manager.agent.pos, self.exploration_manager.agent.ori)
|
| 200 |
+
obs = {'multi_modal_data': {self.config.image_placeholder: [image]}}
|
| 201 |
+
self.observed_image_paths.append(image_path)
|
| 202 |
+
return {**obs, 'obs_str': obs_str}, reward, False, info, exp_log
|
| 203 |
+
|
| 204 |
+
def _get_multi_modal_data(self, room: ExplorationManager, pos: np.ndarray, ori: np.ndarray):
|
| 205 |
+
"""Get multi-modal data (images) for current state."""
|
| 206 |
+
# Find position: which object is at same location as agent
|
| 207 |
+
position_name = None if not np.allclose(room.init_pos, pos) else 'agent'
|
| 208 |
+
if position_name is None:
|
| 209 |
+
for obj in room.base_room.all_objects:
|
| 210 |
+
if np.allclose(obj.pos, pos):
|
| 211 |
+
position_name = obj.name
|
| 212 |
+
break
|
| 213 |
+
assert position_name is not None, "Agent position not found"
|
| 214 |
+
|
| 215 |
+
direction = {(0, 1): 'north', (-1, 0): 'west', (0, -1): 'south', (1, 0): 'east'}[tuple(ori)]
|
| 216 |
+
|
| 217 |
+
img = self.image_handler.get_image(position_name, direction)
|
| 218 |
+
img_path = self.image_handler.get_image_path(position_name, direction)
|
| 219 |
+
return img, img_path
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _step_evaluation(self, action: str):
|
| 223 |
+
"""Handle evaluation phase step with parsed result and shared info."""
|
| 224 |
+
correct, _ = self.evaluation_manager.evaluate_answer(action)
|
| 225 |
+
eval_log = self.evaluation_manager.turn_logs[-1]
|
| 226 |
+
reward = 1 if correct else 0
|
| 227 |
+
|
| 228 |
+
return {'obs_str': "Task finished"}, reward, True, {}, eval_log
|
| 229 |
+
|
| 230 |
+
def step(self, llm_response: str):
|
| 231 |
+
"""Process agent actions in the spatial gym environment."""
|
| 232 |
+
self.current_turn_number += 1
|
| 233 |
+
exp_log, eval_log = None, None
|
| 234 |
+
think_content, action, parsed_ok = parse_llm_response(
|
| 235 |
+
llm_response, enable_think=bool(self.config.prompt_config.get('enable_think', True))
|
| 236 |
+
)
|
| 237 |
+
room_state = None
|
| 238 |
+
agent_state = None
|
| 239 |
+
|
| 240 |
+
# Log turn at start with current state
|
| 241 |
+
current_obs = self.render_cache
|
| 242 |
+
is_exploration_phase = self.is_exploration_phase # so termiante action is included in exploration log
|
| 243 |
+
# step the environment
|
| 244 |
+
if self.is_exploration_phase:
|
| 245 |
+
obs, reward, done, step_info, exp_log = self._step_exploration(action)
|
| 246 |
+
if exp_log:
|
| 247 |
+
room_state, agent_state = exp_log.room_state, exp_log.agent_state
|
| 248 |
+
exp_log.room_state = None
|
| 249 |
+
exp_log.agent_state = None
|
| 250 |
+
else:
|
| 251 |
+
obs, reward, done, step_info, eval_log = self._step_evaluation(action)
|
| 252 |
+
room_state, agent_state = eval_log.room_state, eval_log.agent_state
|
| 253 |
+
eval_log.room_state = None
|
| 254 |
+
eval_log.agent_state = None
|
| 255 |
+
|
| 256 |
+
obs['obs_str'] += '\n' + self.prompter.get_format_footer(self.is_exploration_phase)
|
| 257 |
+
self.render_cache = obs
|
| 258 |
+
|
| 259 |
+
turn_log = EnvTurnLog(
|
| 260 |
+
turn_number=self.current_turn_number,
|
| 261 |
+
user_message=current_obs['obs_str'],
|
| 262 |
+
assistant_raw_message=llm_response,
|
| 263 |
+
assistant_think_message=think_content,
|
| 264 |
+
assistant_parsed_message=action,
|
| 265 |
+
is_exploration_phase=is_exploration_phase,
|
| 266 |
+
is_last_exp=is_exploration_phase != self.is_exploration_phase,
|
| 267 |
+
exploration_log=exp_log,
|
| 268 |
+
evaluation_log=eval_log,
|
| 269 |
+
room_state=room_state,
|
| 270 |
+
agent_state=agent_state,
|
| 271 |
+
message_images=self.observed_image_paths,
|
| 272 |
+
info={"reward": reward, "is_done": done, **step_info}
|
| 273 |
+
)
|
| 274 |
+
if is_exploration_phase:
|
| 275 |
+
if not self.history_manager.has_exploration(self.current_turn_number - 1):
|
| 276 |
+
self.history_manager.update_turn_log(turn_log.to_dict())
|
| 277 |
+
self.history_manager.save_exploration()
|
| 278 |
+
else:
|
| 279 |
+
self.history_manager.update_turn_log(turn_log.to_dict())
|
| 280 |
+
self.history_manager.save()
|
| 281 |
+
self.observed_image_paths = []
|
| 282 |
+
self.turn_logs.append(turn_log)
|
| 283 |
+
return obs, reward, done, step_info
|
| 284 |
+
|
| 285 |
+
def render(self):
|
| 286 |
+
return self.render_cache
|
| 287 |
+
|
| 288 |
+
def close(self):
|
| 289 |
+
return
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
# =================== Analysis ===================
|
| 296 |
+
|
| 297 |
+
def get_exp_summary(self):
|
| 298 |
+
"""Get exploration efficiency metrics."""
|
| 299 |
+
return self.exploration_manager.get_exp_summary() if self.exploration_manager else ExplorationManager.DEFAULT_EXP_SUMMARY
|
| 300 |
+
|
| 301 |
+
def get_eval_summary(self):
|
| 302 |
+
"""Get evaluation performance metrics."""
|
| 303 |
+
return self.evaluation_manager.get_eval_summary() if self.evaluation_manager else EvaluationManager.DEFAULT_EVAL_SUMMARY.copy()
|
| 304 |
+
|
| 305 |
+
def get_env_summary(self) -> Dict[str, Any]:
|
| 306 |
+
"""Aggregate environment metrics from all turns."""
|
| 307 |
+
|
| 308 |
+
return {
|
| 309 |
+
'env_info': self._get_env_info(),
|
| 310 |
+
'env_turn_logs': [turn_log.to_dict() for turn_log in self.turn_logs],
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
def _get_env_info(self):
|
| 314 |
+
"""Get environment state information."""
|
| 315 |
+
return {
|
| 316 |
+
"config": self.config.to_dict(),
|
| 317 |
+
"initial_room": self.initial_room.to_dict(),
|
| 318 |
+
"initial_agent": self.initial_agent.to_dict(),
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
if __name__ == "__main__":
|
| 332 |
+
# Simple test cases for SpatialGym environment
|
| 333 |
+
|
| 334 |
+
# TODO: add test cases
|
| 335 |
+
pass
|
ragen/env/spatial/prompter.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from typing import Optional, Any
|
| 3 |
+
from ragen.env.spatial.Base.tos_base.prompts.prompter import Prompter
|
| 4 |
+
from ragen.env.spatial.Base.tos_base.actions.actions import ActionSequence
|
| 5 |
+
from ragen.env.spatial.Base.tos_base.utils.room_utils import get_room_description
|
| 6 |
+
from ragen.env.spatial.Base.tos_base.core.relationship import (
|
| 7 |
+
PairwiseRelationship, PairwiseRelationshipDiscrete, ProximityRelationship, DegreeRel, OrientationRel
|
| 8 |
+
)
|
| 9 |
+
from .prompts import (
|
| 10 |
+
INSTRUCTION_TEMPLATE_TEXT, SHARED_INTRO_TEXT,
|
| 11 |
+
SHARED_MULTIROOM_RULES, SHARED_RULES_COMMON, ACTIVE_RULES_EXTRA
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
class SpatialPrompter(Prompter):
|
| 15 |
+
def __init__(self, config, np_random: np.random.RandomState):
|
| 16 |
+
# Initialize without image_handler
|
| 17 |
+
super().__init__(config, np_random, image_handler=None)
|
| 18 |
+
|
| 19 |
+
def get_initial_observation_prompt(
|
| 20 |
+
self,
|
| 21 |
+
room,
|
| 22 |
+
agent,
|
| 23 |
+
question: str,
|
| 24 |
+
exp_history = None
|
| 25 |
+
) -> dict:
|
| 26 |
+
"""
|
| 27 |
+
Generates the initial observation prompt.
|
| 28 |
+
Forces active exploration instructions and sets the goal to answering the evaluation question.
|
| 29 |
+
Removes all vision-related logic.
|
| 30 |
+
"""
|
| 31 |
+
obs = {}
|
| 32 |
+
topdown = self.config.prompt_config['topdown']
|
| 33 |
+
|
| 34 |
+
room_desc = get_room_description(room, agent, with_topdown=topdown)
|
| 35 |
+
|
| 36 |
+
observation_instructions = (
|
| 37 |
+
PairwiseRelationship.prompt()
|
| 38 |
+
+ f"\n{DegreeRel.prompt()}"
|
| 39 |
+
+ f"\n{OrientationRel.prompt()}"
|
| 40 |
+
+ f"\n{PairwiseRelationshipDiscrete.prompt()}"
|
| 41 |
+
+ f"\n{ProximityRelationship.prompt()}"
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# Always include action instructions (text only)
|
| 45 |
+
exp_instructions = f"Action Instructions:\n{ActionSequence.get_usage_instructions(vision=False)}"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
template = INSTRUCTION_TEMPLATE_TEXT
|
| 49 |
+
|
| 50 |
+
# Custom goal
|
| 51 |
+
goal_lines = "Explore the environment with given actions to answer the evaluation question."
|
| 52 |
+
|
| 53 |
+
fmt_kwargs = {
|
| 54 |
+
'title': 'Spatial Exploration Task',
|
| 55 |
+
'intro': SHARED_INTRO_TEXT,
|
| 56 |
+
'goal_lines': goal_lines,
|
| 57 |
+
'format_rules': "", # No format rules
|
| 58 |
+
'observation_instructions': observation_instructions,
|
| 59 |
+
'exp_instructions': exp_instructions,
|
| 60 |
+
'room_info': room_desc,
|
| 61 |
+
'multiroom_rules': SHARED_MULTIROOM_RULES if self.config.level != 0 else "",
|
| 62 |
+
'active_rules_extra': ACTIVE_RULES_EXTRA,
|
| 63 |
+
'rules_common': SHARED_RULES_COMMON,
|
| 64 |
+
'exp_history': "", # Initial prompt has no history
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
obs_str = template.format(**fmt_kwargs)
|
| 68 |
+
|
| 69 |
+
# Append evaluation question
|
| 70 |
+
if question:
|
| 71 |
+
obs_str += f"\n## Evaluation Question\n{question}"
|
| 72 |
+
|
| 73 |
+
obs['obs_str'] = obs_str
|
| 74 |
+
return obs
|
ragen/env/spatial/prompts.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ragen/env/spatial/prompts.py
|
| 2 |
+
|
| 3 |
+
SHARED_INTRO_TEXT = "You are a spatial reasoner in indoor environment, a 2D, text-only N×M grid. Every object including you is a point at integer (x, y) coordinates."
|
| 4 |
+
|
| 5 |
+
SHARED_INTRO_VISION = (
|
| 6 |
+
"You are a spatial reasoner in a 3D simulated environment. "
|
| 7 |
+
"The world is rendered in 3D but abstracted into a discrete 2D grid of size N×M. "
|
| 8 |
+
"Every entity, including yourself, is represented by integer coordinates (x, y) on this grid."
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
SHARED_MULTIROOM_RULES = """\
|
| 12 |
+
Multi-room rules (may exist multiple rooms):
|
| 13 |
+
- Your vision is confined to your current room.
|
| 14 |
+
- Doors block vision between rooms.
|
| 15 |
+
- Exception: When located in a doorway, door is open and invisible, you can see into both connected rooms.
|
| 16 |
+
- Rooms connect via doors on vertical (front/back) or horizontal (left/right) walls.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
SHARED_RULES_COMMON = """\
|
| 20 |
+
- Field of view: 90°
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
# Optimized: Emphasize answering evaluation question, remove coverage goals.
|
| 24 |
+
ACTIVE_RULES_EXTRA = ""
|
| 25 |
+
|
| 26 |
+
VISION_EXAMPLE = """\
|
| 27 |
+
Here is an example of your observation: blue cylinder 1 m straight ahead; red cylinder 2 m straight ahead; yellow cylinder 2 m at 45° to your front-left; green cylinder 3 m at 22.5° to your front-slight-right:
|
| 28 |
+
{image_placeholder}
|
| 29 |
+
|
| 30 |
+
The image shows all objects in the room. Each tile is numbered (1-N) in the top-left, matching the object order in the room layout.
|
| 31 |
+
For items with a facing direction, two copies are shown side-by-side: the left copy has its front facing the camera; the right copy has its front facing left.
|
| 32 |
+
Items without a meaningful facing direction are shown once.
|
| 33 |
+
{image_placeholder}
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
_BASE_TEMPLATE = """\
|
| 37 |
+
# {title}
|
| 38 |
+
|
| 39 |
+
{intro}
|
| 40 |
+
|
| 41 |
+
{goal_lines}
|
| 42 |
+
|
| 43 |
+
{multiroom_rules}
|
| 44 |
+
|
| 45 |
+
Relationship instructions:
|
| 46 |
+
{observation_instructions}
|
| 47 |
+
|
| 48 |
+
{exp_instructions}
|
| 49 |
+
|
| 50 |
+
{format_rules}
|
| 51 |
+
|
| 52 |
+
Rules:
|
| 53 |
+
{active_rules_extra}{rules_common}
|
| 54 |
+
|
| 55 |
+
Room Layout and initial state:
|
| 56 |
+
{room_info}
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
INSTRUCTION_TEMPLATE_TEXT = _BASE_TEMPLATE + """
|
| 60 |
+
{exp_history}
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
INSTRUCTION_TEMPLATE_VISION = _BASE_TEMPLATE + """
|
| 64 |
+
{vision_example}
|
| 65 |
+
|
| 66 |
+
{exp_history}
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
EVALUATION_INSTRUCTION = "{eval_question}"
|
| 70 |
+
SHORT_EXPLORATION_PROMPT = "Please respond with valid actions to explore the rooms."
|
| 71 |
+
SHORT_EVALUATION_PROMPT = "Please respond with a valid answer to the question."
|
ragen/env/static/config.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, List, Dict
|
| 2 |
+
from dataclasses import dataclass, field
|
| 3 |
+
|
| 4 |
+
@dataclass
|
| 5 |
+
class StaticEnvConfig:
|
| 6 |
+
"""Configuration for StaticEnv environment"""
|
| 7 |
+
# Dataset config
|
| 8 |
+
dataset_name: str = field(default="metamathqa") #metamathqa, gsm8k,theoremqa,mmlu
|
| 9 |
+
cache_dir: str = field(default="./data")
|
| 10 |
+
split: Optional[str] = field(default=None)
|
ragen/env/static/env.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from datasets import load_dataset
|
| 3 |
+
import re
|
| 4 |
+
import random
|
| 5 |
+
from typing import Dict, Any, Optional, List, Tuple, Callable
|
| 6 |
+
from ragen.env.base import BaseLanguageBasedEnv
|
| 7 |
+
from ragen.utils import all_seed
|
| 8 |
+
from .config import StaticEnvConfig
|
| 9 |
+
from .utils import REGISTERD_STATIC_ENV
|
| 10 |
+
class StaticEnv(BaseLanguageBasedEnv):
|
| 11 |
+
"""
|
| 12 |
+
A general environment for evaluating language models on Hugging Face datasets.
|
| 13 |
+
Supports multiple datasets: MetaMathQA, TheoremQA, MATH, MMLU-STEM, GSM8K, etc.
|
| 14 |
+
"""
|
| 15 |
+
def __init__(self, config: StaticEnvConfig):
|
| 16 |
+
super(StaticEnv, self).__init__()
|
| 17 |
+
|
| 18 |
+
self.config = config
|
| 19 |
+
dataset_config=getattr(config, "dataset_config", None)
|
| 20 |
+
if dataset_config is None:
|
| 21 |
+
dataset_config=REGISTERD_STATIC_ENV[self.config.dataset_name]["config"]
|
| 22 |
+
self.dataset = load_dataset(**dataset_config, cache_dir=self.config.cache_dir)
|
| 23 |
+
|
| 24 |
+
if self.config.split is None:
|
| 25 |
+
self.split = list(self.dataset.keys())[0]
|
| 26 |
+
else:
|
| 27 |
+
self.split = self.config.split
|
| 28 |
+
|
| 29 |
+
self.current_question_idx = None
|
| 30 |
+
self.current_question = None
|
| 31 |
+
self.correct_answer = None
|
| 32 |
+
self.step_num = None
|
| 33 |
+
|
| 34 |
+
self.processor = REGISTERD_STATIC_ENV[self.config.dataset_name]["processor"]
|
| 35 |
+
self.compute_score= REGISTERD_STATIC_ENV[self.config.dataset_name]["compute_score"]
|
| 36 |
+
|
| 37 |
+
def reset(self, seed=None, mode=None):
|
| 38 |
+
"""Reset the environment and get a new question."""
|
| 39 |
+
dataset_split = self.dataset[self.split]
|
| 40 |
+
with all_seed(seed):
|
| 41 |
+
self.current_question_idx = random.randint(0, len(dataset_split) - 1)
|
| 42 |
+
question_data = dataset_split[self.current_question_idx]
|
| 43 |
+
self.current_question, self.correct_answer = self.processor(question_data)
|
| 44 |
+
self.step_num = 0
|
| 45 |
+
|
| 46 |
+
return self.current_question
|
| 47 |
+
|
| 48 |
+
def step(self, action):
|
| 49 |
+
"""Take a step in the environment with the given action (answer)."""
|
| 50 |
+
score_result = self.compute_score(action,self.correct_answer)
|
| 51 |
+
is_correct = score_result["is_correct"]
|
| 52 |
+
is_valid = score_result["is_valid"]
|
| 53 |
+
reward = 1.0 / (2 ** self.step_num) if is_correct else 0.0
|
| 54 |
+
if is_correct:
|
| 55 |
+
observation = "Correct!"
|
| 56 |
+
done = True
|
| 57 |
+
else:
|
| 58 |
+
observation = "Incorrect. Please think again."
|
| 59 |
+
done = False
|
| 60 |
+
|
| 61 |
+
self.step_num += 1
|
| 62 |
+
info = {
|
| 63 |
+
"success": is_correct,
|
| 64 |
+
"is_valid": is_valid,
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
return observation, reward, done, info
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
if __name__ == "__main__":
|
| 71 |
+
# Example usage
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
for dataset_name in REGISTERD_STATIC_ENV.keys():
|
| 76 |
+
config = StaticEnvConfig(
|
| 77 |
+
dataset_name=dataset_name,
|
| 78 |
+
cache_dir="./data",
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# Initialize the environment
|
| 82 |
+
env = StaticEnv(config)
|
| 83 |
+
|
| 84 |
+
# Reset the environment to get the first question
|
| 85 |
+
print("\n--- New Question ---")
|
| 86 |
+
obs = env.reset(seed=42)
|
| 87 |
+
print(obs)
|
| 88 |
+
|
| 89 |
+
print("\n--- Correct Answer ---")
|
| 90 |
+
print(env.correct_answer)
|
| 91 |
+
|
| 92 |
+
# Interactive loop for testing
|
| 93 |
+
while True:
|
| 94 |
+
user_answer = input("\nEnter your answer (or 'q' to quit): ")
|
| 95 |
+
if user_answer.lower() == 'q':
|
| 96 |
+
break
|
| 97 |
+
|
| 98 |
+
# Take a step in the environment with the user's answer
|
| 99 |
+
obs, reward, done, info = env.step(user_answer)
|
| 100 |
+
|
| 101 |
+
# Print the results
|
| 102 |
+
print(f"\n{obs}")
|
| 103 |
+
|
| 104 |
+
# If the episode is done, reset the environment for a new question
|
| 105 |
+
if done:
|
| 106 |
+
print(f"\ntotal step: {env.step_num}, reward: {reward}")
|
| 107 |
+
print("\n--- New Question ---")
|
| 108 |
+
question = env.reset()
|
| 109 |
+
print(question)
|
| 110 |
+
print("\n--- Correct Answer ---")
|
| 111 |
+
print(env.correct_answer)
|
ragen/env/static/utils.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import string
|
| 3 |
+
from typing import Dict, Any, Optional, List, Tuple, Callable
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
############################Tool Fuctions############################
|
| 7 |
+
def normalize_text(text: str) -> str:
|
| 8 |
+
"""Normalize text by removing whitespace, punctuation, and converting to lowercase."""
|
| 9 |
+
text = text.lower()
|
| 10 |
+
text = re.sub(r'\s+', '', text)
|
| 11 |
+
text = text.translate(str.maketrans('', '', string.punctuation))
|
| 12 |
+
return text
|
| 13 |
+
|
| 14 |
+
def extract_answer_from_text(text: str) -> str:
|
| 15 |
+
"""Extract answer from text with various patterns."""
|
| 16 |
+
patterns = [
|
| 17 |
+
r"The answer is:?\s*(.*?)(?:\n|$)",
|
| 18 |
+
r"Answer:?\s*(.*?)(?:\n|$)",
|
| 19 |
+
r"Final answer:?\s*(.*?)(?:\n|$)",
|
| 20 |
+
r"Therefore,\s*(.*?)(?:\n|$)",
|
| 21 |
+
r"Thus,\s*(.*?)(?:\n|$)",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
for pattern in patterns:
|
| 25 |
+
match = re.search(pattern, text, re.DOTALL)
|
| 26 |
+
if match:
|
| 27 |
+
return match.group(1).strip()
|
| 28 |
+
|
| 29 |
+
# If no pattern matches, return the last line as a fallback
|
| 30 |
+
lines = text.strip().split('\n')
|
| 31 |
+
return lines[-1].strip()
|
| 32 |
+
# ====== Dataset Processors ======
|
| 33 |
+
|
| 34 |
+
def process_metamathqa(item: Dict[str, Any]) -> Tuple[str, str]:
|
| 35 |
+
"""Process MetaMathQA dataset item."""
|
| 36 |
+
question = item["query"]
|
| 37 |
+
answer = extract_answer_from_text(item["response"])
|
| 38 |
+
return question, answer
|
| 39 |
+
|
| 40 |
+
def process_gsm8k(item: Dict[str, Any]) -> Tuple[str, str]:
|
| 41 |
+
"""Process GSM8K dataset item."""
|
| 42 |
+
question = item["question"]
|
| 43 |
+
answer = item["answer"]
|
| 44 |
+
answer=answer.split("####")[1].strip().lower()
|
| 45 |
+
return question, answer
|
| 46 |
+
|
| 47 |
+
def process_theoremqa(item: Dict[str, Any]) -> Tuple[str, str]:
|
| 48 |
+
"""Process TheoremQA dataset item."""
|
| 49 |
+
question = item["Question"]
|
| 50 |
+
answer = str(item["Answer"])
|
| 51 |
+
return question, answer
|
| 52 |
+
|
| 53 |
+
def process_mmlu(item: Dict[str, Any]) -> Tuple[str, str]:
|
| 54 |
+
"""Process MMLU dataset with multiple choice format."""
|
| 55 |
+
question = item['question']
|
| 56 |
+
choices = [item['choices'][i] for i in range(len(item['choices']))]
|
| 57 |
+
formatted_question = question + "\n" + "\n".join([f"{chr(65+i)}. {choice}" for i, choice in enumerate(choices)])
|
| 58 |
+
answer = chr(65 + item['answer']) # Convert to A, B, C, D format
|
| 59 |
+
return formatted_question, answer
|
| 60 |
+
|
| 61 |
+
def process_gpqa(item: Dict[str, Any]) -> Tuple[str, str]:
|
| 62 |
+
"""Process GPQA dataset item."""
|
| 63 |
+
question = item["Question"]
|
| 64 |
+
answer = extract_answer_from_text(item["Correct Answer"])
|
| 65 |
+
return question, answer
|
| 66 |
+
|
| 67 |
+
# ====== Scoring Functions ======
|
| 68 |
+
|
| 69 |
+
def compute_score_exact_match(prediction: str, label: str) -> Dict[str, Any]:
|
| 70 |
+
"""Basic exact match after normalization."""
|
| 71 |
+
norm_pred = normalize_text(prediction)
|
| 72 |
+
norm_label = normalize_text(label)
|
| 73 |
+
|
| 74 |
+
is_correct = norm_pred == norm_label
|
| 75 |
+
is_valid = len(norm_pred) > 0 # Simple validity check
|
| 76 |
+
|
| 77 |
+
return {
|
| 78 |
+
"is_correct": is_correct,
|
| 79 |
+
"is_valid": is_valid,
|
| 80 |
+
"normalized_prediction": norm_pred,
|
| 81 |
+
"normalized_label": norm_label
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
def compute_score_numeric(prediction: str, label: str) -> Dict[str, Any]:
|
| 85 |
+
"""Extract numeric values and compare them."""
|
| 86 |
+
# Extract the first numeric value from both prediction and label
|
| 87 |
+
pred_match = re.search(r'(\d+(?:\.\d+)?)', prediction)
|
| 88 |
+
label_match = re.search(r'(\d+(?:\.\d+)?)', label)
|
| 89 |
+
|
| 90 |
+
is_valid = pred_match is not None
|
| 91 |
+
|
| 92 |
+
if pred_match and label_match:
|
| 93 |
+
pred_answer = pred_match.group(0)
|
| 94 |
+
label_answer = label_match.group(0)
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
is_correct = float(pred_answer) == float(label_answer)
|
| 98 |
+
except ValueError:
|
| 99 |
+
is_correct = False
|
| 100 |
+
else:
|
| 101 |
+
is_correct = False
|
| 102 |
+
|
| 103 |
+
# Also try text match as fallback
|
| 104 |
+
text_match = normalize_text(prediction) == normalize_text(label)
|
| 105 |
+
is_correct = is_correct or text_match
|
| 106 |
+
|
| 107 |
+
return {
|
| 108 |
+
"is_correct": is_correct,
|
| 109 |
+
"is_valid": is_valid,
|
| 110 |
+
"numeric_match": is_correct and not text_match,
|
| 111 |
+
"text_match": text_match
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
def compute_score_multiple_choice(prediction: str, label: str) -> Dict[str, Any]:
|
| 115 |
+
"""Score multiple choice answers (A, B, C, D)."""
|
| 116 |
+
pred_match = re.search(r'([A-D])', prediction.upper())
|
| 117 |
+
label_match = re.search(r'([A-D])', label.upper())
|
| 118 |
+
|
| 119 |
+
is_valid = pred_match is not None
|
| 120 |
+
|
| 121 |
+
if pred_match and label_match:
|
| 122 |
+
pred_choice = pred_match.group(0)
|
| 123 |
+
label_choice = label_match.group(0)
|
| 124 |
+
is_correct = pred_choice == label_choice
|
| 125 |
+
else:
|
| 126 |
+
# Fallback to text comparison
|
| 127 |
+
is_correct = normalize_text(prediction) == normalize_text(label)
|
| 128 |
+
|
| 129 |
+
return {
|
| 130 |
+
"is_correct": is_correct,
|
| 131 |
+
"is_valid": is_valid,
|
| 132 |
+
"extracted_prediction": pred_match.group(0) if pred_match else None,
|
| 133 |
+
"extracted_label": label_match.group(0) if label_match else None
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
##########################registration###########################
|
| 137 |
+
REGISTERD_STATIC_ENV = {
|
| 138 |
+
"metamathqa": {
|
| 139 |
+
"config": {
|
| 140 |
+
"path": "meta-math/MetaMathQA",
|
| 141 |
+
},
|
| 142 |
+
"processor": process_metamathqa,
|
| 143 |
+
"compute_score": compute_score_exact_match
|
| 144 |
+
},
|
| 145 |
+
"gsm8k": {
|
| 146 |
+
"config": {
|
| 147 |
+
"path": "openai/gsm8k",
|
| 148 |
+
"name":"main"
|
| 149 |
+
},
|
| 150 |
+
"processor": process_gsm8k,
|
| 151 |
+
"compute_score": compute_score_numeric
|
| 152 |
+
},
|
| 153 |
+
# "theoremqa": {
|
| 154 |
+
# "config": {
|
| 155 |
+
# "path": "TIGER-Lab/TheoremQA",
|
| 156 |
+
# },
|
| 157 |
+
# "processor": process_theoremqa,
|
| 158 |
+
# "compute_score": compute_score_numeric
|
| 159 |
+
# },
|
| 160 |
+
"mmlu": {
|
| 161 |
+
"config": {
|
| 162 |
+
"path": "cais/mmlu",
|
| 163 |
+
"name": "abstract_algebra",
|
| 164 |
+
},
|
| 165 |
+
"processor": process_mmlu,
|
| 166 |
+
"compute_score": compute_score_multiple_choice
|
| 167 |
+
},
|
| 168 |
+
# "gpqa":{
|
| 169 |
+
# "config": {
|
| 170 |
+
# "path": "Idavidrein/gpqa",
|
| 171 |
+
# "name": "gpqa_main",
|
| 172 |
+
# },
|
| 173 |
+
# "processor": process_gpqa,
|
| 174 |
+
# "compute_score": compute_score_exact_match
|
| 175 |
+
# }
|
| 176 |
+
}
|
ragen/env/sudoku/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .env import SudokuEnv
|
| 2 |
+
from .config import SudokuEnvConfig
|
| 3 |
+
|
| 4 |
+
__all__ = ['SudokuEnv', 'SudokuEnvConfig']
|
ragen/env/sudoku/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (262 Bytes). View file
|
|
|
ragen/env/sudoku/__pycache__/config.cpython-310.pyc
ADDED
|
Binary file (1.42 kB). View file
|
|
|
ragen/env/sudoku/__pycache__/env.cpython-310.pyc
ADDED
|
Binary file (8.61 kB). View file
|
|
|
ragen/env/sudoku/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (6.04 kB). View file
|
|
|
ragen/env/sudoku/config.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, field
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
@dataclass
|
| 5 |
+
class SudokuEnvConfig:
|
| 6 |
+
"""Configuration for Sudoku environment with enhanced feedback."""
|
| 7 |
+
grid_size: int = 9 # Standard 9x9 Sudoku
|
| 8 |
+
max_steps: int = 81 # Maximum number of steps (one per cell)
|
| 9 |
+
difficulty: str = "easy" # Difficulty level: easy, medium, hard
|
| 10 |
+
render_mode: str = "text"
|
| 11 |
+
show_conflicts: bool = True # Show row/column/box conflicts in render
|
| 12 |
+
show_valid_numbers: bool = True # Show valid numbers for each empty cell
|
| 13 |
+
show_candidates: bool = False # Show all candidate numbers for empty cells
|
| 14 |
+
render_format: str = "detailed" # "simple", "detailed", "with_feedback"
|
| 15 |
+
|
| 16 |
+
# Scoring
|
| 17 |
+
correct_placement_score: float = 1.0
|
| 18 |
+
invalid_action_score: float = -0.1 # Penalty for invalid placements
|
| 19 |
+
completion_bonus: float = 10.0 # Bonus for solving the puzzle
|
| 20 |
+
|
| 21 |
+
def __post_init__(self):
|
| 22 |
+
if self.grid_size not in {4, 9, 16}:
|
| 23 |
+
raise ValueError(f"Unsupported grid_size: {self.grid_size}. Must be 4, 9, or 16.")
|
| 24 |
+
if self.render_format not in {"simple", "detailed", "with_feedback"}:
|
| 25 |
+
raise ValueError(f"Unsupported render_format: {self.render_format}")
|
| 26 |
+
if self.difficulty not in {"easy", "medium", "hard"}:
|
| 27 |
+
raise ValueError(f"Unsupported difficulty: {self.difficulty}")
|
ragen/env/sudoku/env.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gymnasium as gym
|
| 2 |
+
import numpy as np
|
| 3 |
+
import re
|
| 4 |
+
from typing import Tuple, Dict, Any
|
| 5 |
+
from ragen.env.base import BaseLanguageBasedEnv
|
| 6 |
+
from .config import SudokuEnvConfig
|
| 7 |
+
from .utils import (
|
| 8 |
+
generate_sudoku_puzzle,
|
| 9 |
+
is_valid_placement,
|
| 10 |
+
get_valid_numbers,
|
| 11 |
+
find_conflicts,
|
| 12 |
+
is_solved,
|
| 13 |
+
format_grid_simple,
|
| 14 |
+
format_grid_with_conflicts,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SudokuEnv(BaseLanguageBasedEnv, gym.Env):
|
| 19 |
+
"""
|
| 20 |
+
Sudoku environment with enhanced feedback for better exploration efficiency.
|
| 21 |
+
|
| 22 |
+
Key features to address low exploration efficiency:
|
| 23 |
+
1. Clear feedback on valid vs invalid moves
|
| 24 |
+
2. Conflict detection and visualization
|
| 25 |
+
3. Valid number suggestions for each cell
|
| 26 |
+
4. Detailed action validation info
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, config=None):
|
| 30 |
+
BaseLanguageBasedEnv.__init__(self)
|
| 31 |
+
self.config = config if config is not None else SudokuEnvConfig()
|
| 32 |
+
self.grid_size = self.config.grid_size
|
| 33 |
+
self.max_steps = self.config.max_steps
|
| 34 |
+
|
| 35 |
+
# State variables
|
| 36 |
+
self.current_grid = None
|
| 37 |
+
self.initial_grid = None
|
| 38 |
+
self.solution_grid = None
|
| 39 |
+
self.num_steps = 0
|
| 40 |
+
self.render_cache = None
|
| 41 |
+
self.last_action_feedback = ""
|
| 42 |
+
|
| 43 |
+
self.render_mode = self.config.render_mode
|
| 44 |
+
assert self.render_mode == 'text'
|
| 45 |
+
|
| 46 |
+
def reset(self, seed=None, mode=None):
|
| 47 |
+
"""Reset the environment with a new Sudoku puzzle."""
|
| 48 |
+
gym.Env.reset(self, seed=seed)
|
| 49 |
+
|
| 50 |
+
# Generate a new puzzle
|
| 51 |
+
self.initial_grid, self.solution_grid = generate_sudoku_puzzle(
|
| 52 |
+
grid_size=self.grid_size,
|
| 53 |
+
difficulty=self.config.difficulty,
|
| 54 |
+
seed=seed
|
| 55 |
+
)
|
| 56 |
+
self.current_grid = self.initial_grid.copy()
|
| 57 |
+
self.num_steps = 0
|
| 58 |
+
self.last_action_feedback = ""
|
| 59 |
+
|
| 60 |
+
return self.render()
|
| 61 |
+
|
| 62 |
+
def parse_action(self, action: str) -> Tuple[bool, int, int, int, str]:
|
| 63 |
+
"""
|
| 64 |
+
Parse action string into (success, row, col, number, error_msg).
|
| 65 |
+
|
| 66 |
+
Supported formats:
|
| 67 |
+
- "place 5 at row 2 col 3"
|
| 68 |
+
- "place 5 at (2,3)"
|
| 69 |
+
- "place 5 at 2,3"
|
| 70 |
+
- "5 at 2,3"
|
| 71 |
+
- "(2,3,5)"
|
| 72 |
+
- "2,3,5"
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
Tuple of (success, row, col, number, error_message)
|
| 76 |
+
"""
|
| 77 |
+
action = action.strip().lower()
|
| 78 |
+
|
| 79 |
+
# Try different patterns
|
| 80 |
+
patterns = [
|
| 81 |
+
r'place\s+(\d+)\s+at\s+row\s+(\d+)\s+col\s+(\d+)',
|
| 82 |
+
r'place\s+(\d+)\s+at\s+\((\d+),\s*(\d+)\)',
|
| 83 |
+
r'place\s+(\d+)\s+at\s+(\d+),\s*(\d+)',
|
| 84 |
+
r'(\d+)\s+at\s+(\d+),\s*(\d+)',
|
| 85 |
+
r'\((\d+),\s*(\d+),\s*(\d+)\)',
|
| 86 |
+
r'(\d+),\s*(\d+),\s*(\d+)',
|
| 87 |
+
]
|
| 88 |
+
|
| 89 |
+
for pattern in patterns:
|
| 90 |
+
match = re.search(pattern, action)
|
| 91 |
+
if match:
|
| 92 |
+
groups = match.groups()
|
| 93 |
+
if len(groups) == 3:
|
| 94 |
+
# Determine if first number is the value or row
|
| 95 |
+
# For "place NUM at ROW,COL", first is number
|
| 96 |
+
if 'place' in action or 'at' in action:
|
| 97 |
+
num, row, col = map(int, groups)
|
| 98 |
+
else:
|
| 99 |
+
# For "ROW,COL,NUM", assume positional format
|
| 100 |
+
row, col, num = map(int, groups)
|
| 101 |
+
|
| 102 |
+
# Convert to 0-indexed
|
| 103 |
+
row -= 1
|
| 104 |
+
col -= 1
|
| 105 |
+
|
| 106 |
+
# Validate ranges
|
| 107 |
+
if not (0 <= row < self.grid_size):
|
| 108 |
+
return False, -1, -1, -1, f"Row {row+1} is out of range (1-{self.grid_size})"
|
| 109 |
+
if not (0 <= col < self.grid_size):
|
| 110 |
+
return False, -1, -1, -1, f"Column {col+1} is out of range (1-{self.grid_size})"
|
| 111 |
+
if not (1 <= num <= self.grid_size):
|
| 112 |
+
return False, -1, -1, -1, f"Number {num} is out of range (1-{self.grid_size})"
|
| 113 |
+
|
| 114 |
+
return True, row, col, num, ""
|
| 115 |
+
|
| 116 |
+
return False, -1, -1, -1, f"Could not parse action: '{action}'. Expected format: 'place 5 at row 2 col 3' or '2,3,5'"
|
| 117 |
+
|
| 118 |
+
def step(self, action: str) -> Tuple[str, float, bool, Dict[str, Any]]:
|
| 119 |
+
"""
|
| 120 |
+
Execute one step in the environment.
|
| 121 |
+
|
| 122 |
+
Returns:
|
| 123 |
+
Tuple of (observation, reward, done, info)
|
| 124 |
+
"""
|
| 125 |
+
self.num_steps += 1
|
| 126 |
+
|
| 127 |
+
# Parse the action
|
| 128 |
+
success, row, col, num, error_msg = self.parse_action(action)
|
| 129 |
+
|
| 130 |
+
if not success:
|
| 131 |
+
self.last_action_feedback = f"❌ Invalid action format: {error_msg}"
|
| 132 |
+
reward = self.config.invalid_action_score
|
| 133 |
+
info = {
|
| 134 |
+
"action_is_effective": False,
|
| 135 |
+
"action_is_valid": False,
|
| 136 |
+
"success": False,
|
| 137 |
+
"error": error_msg
|
| 138 |
+
}
|
| 139 |
+
return self.render(), reward, False, info
|
| 140 |
+
|
| 141 |
+
# Check if cell is modifiable (not part of initial puzzle)
|
| 142 |
+
if self.initial_grid[row, col] != 0:
|
| 143 |
+
self.last_action_feedback = f"�� Cannot modify initial cell at ({row+1},{col+1})"
|
| 144 |
+
reward = self.config.invalid_action_score
|
| 145 |
+
info = {
|
| 146 |
+
"action_is_effective": False,
|
| 147 |
+
"action_is_valid": False,
|
| 148 |
+
"success": False,
|
| 149 |
+
"error": "Cannot modify initial cells"
|
| 150 |
+
}
|
| 151 |
+
return self.render(), reward, False, info
|
| 152 |
+
|
| 153 |
+
# Check if placement is valid according to Sudoku rules
|
| 154 |
+
if not is_valid_placement(self.current_grid, row, col, num):
|
| 155 |
+
# Get the specific conflict reason
|
| 156 |
+
conflicts = []
|
| 157 |
+
if num in self.current_grid[row, :]:
|
| 158 |
+
conflicts.append(f"row {row+1}")
|
| 159 |
+
if num in self.current_grid[:, col]:
|
| 160 |
+
conflicts.append(f"column {col+1}")
|
| 161 |
+
|
| 162 |
+
# Check box
|
| 163 |
+
box_size = int(np.sqrt(self.grid_size))
|
| 164 |
+
box_row = (row // box_size) * box_size
|
| 165 |
+
box_col = (col // box_size) * box_size
|
| 166 |
+
if num in self.current_grid[box_row:box_row+box_size, box_col:box_col+box_size]:
|
| 167 |
+
conflicts.append(f"box ({box_row//box_size+1},{box_col//box_size+1})")
|
| 168 |
+
|
| 169 |
+
conflict_str = ", ".join(conflicts)
|
| 170 |
+
self.last_action_feedback = f"❌ Invalid placement: {num} conflicts with {conflict_str}"
|
| 171 |
+
|
| 172 |
+
# Get valid numbers for this cell
|
| 173 |
+
valid_nums = get_valid_numbers(self.current_grid, row, col)
|
| 174 |
+
if valid_nums:
|
| 175 |
+
self.last_action_feedback += f"\n Valid numbers for ({row+1},{col+1}): {sorted(valid_nums)}"
|
| 176 |
+
|
| 177 |
+
reward = self.config.invalid_action_score
|
| 178 |
+
info = {
|
| 179 |
+
"action_is_effective": False,
|
| 180 |
+
"action_is_valid": False,
|
| 181 |
+
"success": False,
|
| 182 |
+
"error": f"Number {num} conflicts with {conflict_str}",
|
| 183 |
+
"valid_numbers": sorted(valid_nums)
|
| 184 |
+
}
|
| 185 |
+
return self.render(), reward, False, info
|
| 186 |
+
|
| 187 |
+
# Place the number
|
| 188 |
+
old_value = self.current_grid[row, col]
|
| 189 |
+
self.current_grid[row, col] = num
|
| 190 |
+
|
| 191 |
+
# Check if the placement is correct according to solution
|
| 192 |
+
correct_placement = (num == self.solution_grid[row, col])
|
| 193 |
+
|
| 194 |
+
if correct_placement:
|
| 195 |
+
self.last_action_feedback = f"✓ Correct! Placed {num} at ({row+1},{col+1})"
|
| 196 |
+
reward = self.config.correct_placement_score
|
| 197 |
+
else:
|
| 198 |
+
self.last_action_feedback = f"⚠ Placed {num} at ({row+1},{col+1}) - Valid but not optimal"
|
| 199 |
+
reward = self.config.correct_placement_score * 0.5
|
| 200 |
+
|
| 201 |
+
# Check if puzzle is solved
|
| 202 |
+
solved = is_solved(self.current_grid)
|
| 203 |
+
if solved:
|
| 204 |
+
self.last_action_feedback += "\n🎉 Congratulations! Puzzle solved!"
|
| 205 |
+
reward += self.config.completion_bonus
|
| 206 |
+
|
| 207 |
+
# Check for max steps
|
| 208 |
+
done = solved or (self.num_steps >= self.max_steps)
|
| 209 |
+
|
| 210 |
+
info = {
|
| 211 |
+
"action_is_effective": True,
|
| 212 |
+
"action_is_valid": True,
|
| 213 |
+
"success": solved,
|
| 214 |
+
"correct_placement": correct_placement,
|
| 215 |
+
"steps_remaining": self.max_steps - self.num_steps,
|
| 216 |
+
"cells_filled": np.count_nonzero(self.current_grid),
|
| 217 |
+
"cells_remaining": np.count_nonzero(self.current_grid == 0)
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
return self.render(), reward, done, info
|
| 221 |
+
|
| 222 |
+
def render(self) -> str:
|
| 223 |
+
"""
|
| 224 |
+
Render the current state with enhanced feedback.
|
| 225 |
+
|
| 226 |
+
The render function provides:
|
| 227 |
+
1. Current grid state with visual distinction between:
|
| 228 |
+
- Initial cells [N]
|
| 229 |
+
- User-placed valid cells N
|
| 230 |
+
- Conflicting cells *N*
|
| 231 |
+
- Empty cells .
|
| 232 |
+
2. Last action feedback
|
| 233 |
+
3. Current conflicts (if any)
|
| 234 |
+
4. Valid numbers for empty cells (if enabled)
|
| 235 |
+
"""
|
| 236 |
+
if self.config.render_format == "simple":
|
| 237 |
+
return self._render_simple()
|
| 238 |
+
elif self.config.render_format == "detailed":
|
| 239 |
+
return self._render_detailed()
|
| 240 |
+
else: # "with_feedback"
|
| 241 |
+
return self._render_with_feedback()
|
| 242 |
+
|
| 243 |
+
def _render_simple(self) -> str:
|
| 244 |
+
"""Simple grid rendering."""
|
| 245 |
+
return format_grid_simple(self.current_grid)
|
| 246 |
+
|
| 247 |
+
def _render_detailed(self) -> str:
|
| 248 |
+
"""Detailed rendering with conflicts highlighted."""
|
| 249 |
+
conflicts = find_conflicts(self.current_grid, self.initial_grid)
|
| 250 |
+
grid_str = format_grid_with_conflicts(self.current_grid, self.initial_grid, conflicts)
|
| 251 |
+
|
| 252 |
+
output = ["=" * 50]
|
| 253 |
+
output.append("SUDOKU PUZZLE")
|
| 254 |
+
output.append("=" * 50)
|
| 255 |
+
output.append(grid_str)
|
| 256 |
+
output.append("")
|
| 257 |
+
output.append("Legend: [N]=initial cell, N=user-placed, *N*=conflict, .=empty")
|
| 258 |
+
|
| 259 |
+
if self.last_action_feedback:
|
| 260 |
+
output.append("")
|
| 261 |
+
output.append(self.last_action_feedback)
|
| 262 |
+
|
| 263 |
+
return "\n".join(output)
|
| 264 |
+
|
| 265 |
+
def _render_with_feedback(self) -> str:
|
| 266 |
+
"""Full rendering with conflicts and valid numbers."""
|
| 267 |
+
conflicts = find_conflicts(self.current_grid, self.initial_grid)
|
| 268 |
+
grid_str = format_grid_with_conflicts(self.current_grid, self.initial_grid, conflicts)
|
| 269 |
+
|
| 270 |
+
output = ["=" * 50]
|
| 271 |
+
output.append("SUDOKU PUZZLE")
|
| 272 |
+
output.append("=" * 50)
|
| 273 |
+
output.append(grid_str)
|
| 274 |
+
output.append("")
|
| 275 |
+
output.append("Legend: [N]=initial cell, N=user-placed, *N*=conflict, .=empty")
|
| 276 |
+
|
| 277 |
+
if self.last_action_feedback:
|
| 278 |
+
output.append("")
|
| 279 |
+
output.append(self.last_action_feedback)
|
| 280 |
+
|
| 281 |
+
# Show conflicts if any
|
| 282 |
+
if self.config.show_conflicts:
|
| 283 |
+
all_conflicts = set(conflicts['row'] + conflicts['col'] + conflicts['box'])
|
| 284 |
+
if all_conflicts:
|
| 285 |
+
output.append("")
|
| 286 |
+
output.append("⚠ CONFLICTS DETECTED:")
|
| 287 |
+
for r, c in sorted(all_conflicts):
|
| 288 |
+
output.append(f" - Cell ({r+1},{c+1}): {self.current_grid[r,c]}")
|
| 289 |
+
|
| 290 |
+
# Show valid numbers for empty cells
|
| 291 |
+
if self.config.show_valid_numbers:
|
| 292 |
+
empty_cells = list(zip(*np.where(self.current_grid == 0)))
|
| 293 |
+
if empty_cells and len(empty_cells) <= 10: # Only show for first 10 empty cells
|
| 294 |
+
output.append("")
|
| 295 |
+
output.append("💡 VALID NUMBERS FOR EMPTY CELLS:")
|
| 296 |
+
for row, col in empty_cells[:10]:
|
| 297 |
+
if self.initial_grid[row, col] == 0: # Only show for non-initial cells
|
| 298 |
+
valid = get_valid_numbers(self.current_grid, row, col)
|
| 299 |
+
if valid:
|
| 300 |
+
output.append(f" - ({row+1},{col+1}): {sorted(valid)}")
|
| 301 |
+
|
| 302 |
+
# Show statistics
|
| 303 |
+
cells_filled = np.count_nonzero(self.current_grid)
|
| 304 |
+
cells_total = self.grid_size * self.grid_size
|
| 305 |
+
initial_filled = np.count_nonzero(self.initial_grid)
|
| 306 |
+
output.append("")
|
| 307 |
+
output.append(f"Progress: {cells_filled}/{cells_total} cells filled ({initial_filled} initial, {cells_filled - initial_filled} placed)")
|
| 308 |
+
output.append(f"Steps: {self.num_steps}/{self.max_steps}")
|
| 309 |
+
|
| 310 |
+
return "\n".join(output)
|
| 311 |
+
|
| 312 |
+
def close(self):
|
| 313 |
+
"""Clean up resources."""
|
| 314 |
+
pass
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
if __name__ == "__main__":
|
| 318 |
+
# Test the environment
|
| 319 |
+
config = SudokuEnvConfig(
|
| 320 |
+
grid_size=9,
|
| 321 |
+
difficulty="easy",
|
| 322 |
+
render_format="with_feedback"
|
| 323 |
+
)
|
| 324 |
+
env = SudokuEnv(config)
|
| 325 |
+
|
| 326 |
+
print("Testing Sudoku Environment")
|
| 327 |
+
print("=" * 50)
|
| 328 |
+
|
| 329 |
+
obs = env.reset(seed=42)
|
| 330 |
+
print(obs)
|
| 331 |
+
print("\n")
|
| 332 |
+
|
| 333 |
+
# Test some actions
|
| 334 |
+
test_actions = [
|
| 335 |
+
"place 5 at row 1 col 1", # This might be valid or invalid depending on puzzle
|
| 336 |
+
"1,2,3", # Positional format
|
| 337 |
+
"place 9 at (3,3)", # Another format
|
| 338 |
+
]
|
| 339 |
+
|
| 340 |
+
for action in test_actions:
|
| 341 |
+
print(f"\nAction: {action}")
|
| 342 |
+
obs, reward, done, info = env.step(action)
|
| 343 |
+
print(obs)
|
| 344 |
+
print(f"Reward: {reward}, Done: {done}")
|
| 345 |
+
print(f"Info: {info}")
|
| 346 |
+
|
| 347 |
+
if done:
|
| 348 |
+
break
|
ragen/env/sudoku/utils.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import random
|
| 3 |
+
from typing import Set, Tuple, List, Dict
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def get_box_size(grid_size: int) -> int:
|
| 7 |
+
"""Get the box size for a given grid size."""
|
| 8 |
+
return int(np.sqrt(grid_size))
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def get_box_index(row: int, col: int, grid_size: int) -> Tuple[int, int]:
|
| 12 |
+
"""Get the box indices for a given cell."""
|
| 13 |
+
box_size = get_box_size(grid_size)
|
| 14 |
+
return row // box_size, col // box_size
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def is_valid_placement(grid: np.ndarray, row: int, col: int, num: int) -> bool:
|
| 18 |
+
"""
|
| 19 |
+
Check if placing a number at (row, col) is valid according to Sudoku rules.
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
True if placement is valid, False otherwise
|
| 23 |
+
"""
|
| 24 |
+
grid_size = grid.shape[0]
|
| 25 |
+
box_size = get_box_size(grid_size)
|
| 26 |
+
|
| 27 |
+
# Check if number already exists in row
|
| 28 |
+
if num in grid[row, :]:
|
| 29 |
+
return False
|
| 30 |
+
|
| 31 |
+
# Check if number already exists in column
|
| 32 |
+
if num in grid[:, col]:
|
| 33 |
+
return False
|
| 34 |
+
|
| 35 |
+
# Check if number already exists in box
|
| 36 |
+
box_row, box_col = get_box_index(row, col, grid_size)
|
| 37 |
+
box_start_row = box_row * box_size
|
| 38 |
+
box_start_col = box_col * box_size
|
| 39 |
+
if num in grid[box_start_row:box_start_row + box_size, box_start_col:box_start_col + box_size]:
|
| 40 |
+
return False
|
| 41 |
+
|
| 42 |
+
return True
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def get_valid_numbers(grid: np.ndarray, row: int, col: int) -> Set[int]:
|
| 46 |
+
"""
|
| 47 |
+
Get all valid numbers that can be placed at (row, col).
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
Set of valid numbers (1 to grid_size)
|
| 51 |
+
"""
|
| 52 |
+
if grid[row, col] != 0:
|
| 53 |
+
return set()
|
| 54 |
+
|
| 55 |
+
grid_size = grid.shape[0]
|
| 56 |
+
all_numbers = set(range(1, grid_size + 1))
|
| 57 |
+
|
| 58 |
+
# Remove numbers in same row
|
| 59 |
+
all_numbers -= set(grid[row, :]) - {0}
|
| 60 |
+
|
| 61 |
+
# Remove numbers in same column
|
| 62 |
+
all_numbers -= set(grid[:, col]) - {0}
|
| 63 |
+
|
| 64 |
+
# Remove numbers in same box
|
| 65 |
+
box_size = get_box_size(grid_size)
|
| 66 |
+
box_row, box_col = get_box_index(row, col, grid_size)
|
| 67 |
+
box_start_row = box_row * box_size
|
| 68 |
+
box_start_col = box_col * box_size
|
| 69 |
+
box_numbers = grid[box_start_row:box_start_row + box_size, box_start_col:box_start_col + box_size]
|
| 70 |
+
all_numbers -= set(box_numbers.flatten()) - {0}
|
| 71 |
+
|
| 72 |
+
return all_numbers
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def find_conflicts(grid: np.ndarray, initial_grid: np.ndarray) -> Dict[str, List[Tuple[int, int]]]:
|
| 76 |
+
"""
|
| 77 |
+
Find all conflicts in the current grid state.
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
Dictionary with 'row', 'col', 'box' keys mapping to lists of conflicting cells
|
| 81 |
+
"""
|
| 82 |
+
conflicts = {'row': [], 'col': [], 'box': []}
|
| 83 |
+
grid_size = grid.shape[0]
|
| 84 |
+
box_size = get_box_size(grid_size)
|
| 85 |
+
|
| 86 |
+
# Check row conflicts
|
| 87 |
+
for i in range(grid_size):
|
| 88 |
+
row = grid[i, :]
|
| 89 |
+
for num in range(1, grid_size + 1):
|
| 90 |
+
positions = np.where(row == num)[0]
|
| 91 |
+
if len(positions) > 1:
|
| 92 |
+
for pos in positions:
|
| 93 |
+
conflicts['row'].append((i, pos))
|
| 94 |
+
|
| 95 |
+
# Check column conflicts
|
| 96 |
+
for j in range(grid_size):
|
| 97 |
+
col = grid[:, j]
|
| 98 |
+
for num in range(1, grid_size + 1):
|
| 99 |
+
positions = np.where(col == num)[0]
|
| 100 |
+
if len(positions) > 1:
|
| 101 |
+
for pos in positions:
|
| 102 |
+
conflicts['col'].append((pos, j))
|
| 103 |
+
|
| 104 |
+
# Check box conflicts
|
| 105 |
+
for box_row in range(box_size):
|
| 106 |
+
for box_col in range(box_size):
|
| 107 |
+
start_row = box_row * box_size
|
| 108 |
+
start_col = box_col * box_size
|
| 109 |
+
box = grid[start_row:start_row + box_size, start_col:start_col + box_size]
|
| 110 |
+
for num in range(1, grid_size + 1):
|
| 111 |
+
positions = np.argwhere(box == num)
|
| 112 |
+
if len(positions) > 1:
|
| 113 |
+
for pos in positions:
|
| 114 |
+
conflicts['box'].append((start_row + pos[0], start_col + pos[1]))
|
| 115 |
+
|
| 116 |
+
# Remove duplicates
|
| 117 |
+
conflicts['row'] = list(set(conflicts['row']))
|
| 118 |
+
conflicts['col'] = list(set(conflicts['col']))
|
| 119 |
+
conflicts['box'] = list(set(conflicts['box']))
|
| 120 |
+
|
| 121 |
+
return conflicts
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def is_solved(grid: np.ndarray) -> bool:
|
| 125 |
+
"""Check if the Sudoku puzzle is completely solved."""
|
| 126 |
+
grid_size = grid.shape[0]
|
| 127 |
+
|
| 128 |
+
# Check if all cells are filled
|
| 129 |
+
if np.any(grid == 0):
|
| 130 |
+
return False
|
| 131 |
+
|
| 132 |
+
# Check if there are any conflicts
|
| 133 |
+
conflicts = find_conflicts(grid, grid)
|
| 134 |
+
return len(conflicts['row']) == 0 and len(conflicts['col']) == 0 and len(conflicts['box']) == 0
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def generate_sudoku_puzzle(grid_size: int = 9, difficulty: str = "easy", seed: int = None) -> Tuple[np.ndarray, np.ndarray]:
|
| 138 |
+
"""
|
| 139 |
+
Generate a Sudoku puzzle with a unique solution.
|
| 140 |
+
|
| 141 |
+
Args:
|
| 142 |
+
grid_size: Size of the grid (4, 9, or 16)
|
| 143 |
+
difficulty: Difficulty level ("easy", "medium", "hard")
|
| 144 |
+
seed: Random seed for reproducibility
|
| 145 |
+
|
| 146 |
+
Returns:
|
| 147 |
+
Tuple of (puzzle_grid, solution_grid) where puzzle_grid has some cells filled
|
| 148 |
+
and solution_grid is the complete solution
|
| 149 |
+
"""
|
| 150 |
+
if seed is not None:
|
| 151 |
+
random.seed(seed)
|
| 152 |
+
np.random.seed(seed)
|
| 153 |
+
|
| 154 |
+
# Create a solved grid first
|
| 155 |
+
solution_grid = np.zeros((grid_size, grid_size), dtype=int)
|
| 156 |
+
|
| 157 |
+
# Fill the grid using backtracking
|
| 158 |
+
def fill_grid(grid):
|
| 159 |
+
empty_cells = list(zip(*np.where(grid == 0)))
|
| 160 |
+
if not empty_cells:
|
| 161 |
+
return True
|
| 162 |
+
|
| 163 |
+
row, col = empty_cells[0]
|
| 164 |
+
numbers = list(range(1, grid_size + 1))
|
| 165 |
+
random.shuffle(numbers)
|
| 166 |
+
|
| 167 |
+
for num in numbers:
|
| 168 |
+
if is_valid_placement(grid, row, col, num):
|
| 169 |
+
grid[row, col] = num
|
| 170 |
+
if fill_grid(grid):
|
| 171 |
+
return True
|
| 172 |
+
grid[row, col] = 0
|
| 173 |
+
|
| 174 |
+
return False
|
| 175 |
+
|
| 176 |
+
fill_grid(solution_grid)
|
| 177 |
+
|
| 178 |
+
# Create puzzle by removing numbers based on difficulty
|
| 179 |
+
puzzle_grid = solution_grid.copy()
|
| 180 |
+
cells_to_remove = {
|
| 181 |
+
"easy": int(grid_size * grid_size * 0.4), # Remove 40% of cells
|
| 182 |
+
"medium": int(grid_size * grid_size * 0.5), # Remove 50% of cells
|
| 183 |
+
"hard": int(grid_size * grid_size * 0.6), # Remove 60% of cells
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
num_to_remove = cells_to_remove.get(difficulty, cells_to_remove["easy"])
|
| 187 |
+
cells = [(i, j) for i in range(grid_size) for j in range(grid_size)]
|
| 188 |
+
random.shuffle(cells)
|
| 189 |
+
|
| 190 |
+
for i in range(num_to_remove):
|
| 191 |
+
row, col = cells[i]
|
| 192 |
+
puzzle_grid[row, col] = 0
|
| 193 |
+
|
| 194 |
+
return puzzle_grid, solution_grid
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def format_grid_simple(grid: np.ndarray) -> str:
|
| 198 |
+
"""Format the grid as a simple string representation."""
|
| 199 |
+
grid_size = grid.shape[0]
|
| 200 |
+
box_size = get_box_size(grid_size)
|
| 201 |
+
lines = []
|
| 202 |
+
|
| 203 |
+
for i, row in enumerate(grid):
|
| 204 |
+
if i > 0 and i % box_size == 0:
|
| 205 |
+
lines.append("-" * (grid_size * 2 + box_size - 1))
|
| 206 |
+
|
| 207 |
+
row_str = ""
|
| 208 |
+
for j, val in enumerate(row):
|
| 209 |
+
if j > 0 and j % box_size == 0:
|
| 210 |
+
row_str += "| "
|
| 211 |
+
row_str += (str(val) if val != 0 else ".") + " "
|
| 212 |
+
lines.append(row_str.rstrip())
|
| 213 |
+
|
| 214 |
+
return "\n".join(lines)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def format_grid_with_conflicts(grid: np.ndarray, initial_grid: np.ndarray,
|
| 218 |
+
conflicts: Dict[str, List[Tuple[int, int]]]) -> str:
|
| 219 |
+
"""Format the grid with conflict markers."""
|
| 220 |
+
grid_size = grid.shape[0]
|
| 221 |
+
box_size = get_box_size(grid_size)
|
| 222 |
+
lines = []
|
| 223 |
+
|
| 224 |
+
# Collect all conflicting cells
|
| 225 |
+
all_conflicts = set(conflicts['row'] + conflicts['col'] + conflicts['box'])
|
| 226 |
+
|
| 227 |
+
for i, row in enumerate(grid):
|
| 228 |
+
if i > 0 and i % box_size == 0:
|
| 229 |
+
lines.append("-" * (grid_size * 3 + box_size - 1))
|
| 230 |
+
|
| 231 |
+
row_str = ""
|
| 232 |
+
for j, val in enumerate(row):
|
| 233 |
+
if j > 0 and j % box_size == 0:
|
| 234 |
+
row_str += "| "
|
| 235 |
+
|
| 236 |
+
if val == 0:
|
| 237 |
+
row_str += " . "
|
| 238 |
+
elif initial_grid[i, j] != 0:
|
| 239 |
+
# Initial cell (immutable)
|
| 240 |
+
row_str += f"[{val}]"
|
| 241 |
+
elif (i, j) in all_conflicts:
|
| 242 |
+
# Conflict cell
|
| 243 |
+
row_str += f"*{val}*"
|
| 244 |
+
else:
|
| 245 |
+
# User-placed cell (valid)
|
| 246 |
+
row_str += f" {val} "
|
| 247 |
+
|
| 248 |
+
lines.append(row_str.rstrip())
|
| 249 |
+
|
| 250 |
+
return "\n".join(lines)
|
ragen/env/webshop/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
WebShop environment for interactive e-commerce task.
|
| 3 |
+
|
| 4 |
+
Original Source: WebShop (https://github.com/princeton-nlp/WebShop)
|
| 5 |
+
Citation: Yao et al. (2022). WebShop: Towards Scalable Real-World Web Interaction with Grounded Language Agents
|
| 6 |
+
Paper: https://arxiv.org/abs/2207.01206
|
| 7 |
+
License: MIT
|
| 8 |
+
|
| 9 |
+
This implementation uses a minimal version of the WebShop environment
|
| 10 |
+
adapted for the RAGEN framework.
|
| 11 |
+
"""
|
| 12 |
+
from .env import WebShopEnv
|
| 13 |
+
from .config import WebShopEnvConfig
|
| 14 |
+
|
| 15 |
+
__all__ = ["WebShopEnv", "WebShopEnvConfig"]
|
ragen/env/webshop/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (677 Bytes). View file
|
|
|
ragen/env/webshop/__pycache__/config.cpython-310.pyc
ADDED
|
Binary file (1.48 kB). View file
|
|
|
ragen/env/webshop/__pycache__/env.cpython-310.pyc
ADDED
|
Binary file (6.33 kB). View file
|
|
|
ragen/env/webshop/config.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, field
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from webshop_minimal.utils import (
|
| 5 |
+
DEFAULT_FILE_PATH,
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
@dataclass
|
| 9 |
+
class WebShopEnvConfig:
|
| 10 |
+
"""Configuration for WebAgentText environment"""
|
| 11 |
+
dataset: str = field(
|
| 12 |
+
default="small",
|
| 13 |
+
metadata={"description": "Small or full dataset"}
|
| 14 |
+
)
|
| 15 |
+
observation_mode: str = field(
|
| 16 |
+
default="text",
|
| 17 |
+
metadata={"choices": ["html", "text"]}
|
| 18 |
+
)
|
| 19 |
+
file_path: str = field(
|
| 20 |
+
default=DEFAULT_FILE_PATH,
|
| 21 |
+
metadata={"description": "File path for SimServer"}
|
| 22 |
+
) # TODO: Remove hardcoded file path
|
| 23 |
+
server: Any = field(
|
| 24 |
+
default=None,
|
| 25 |
+
metadata={"description": "If None, use SimServer"}
|
| 26 |
+
)
|
| 27 |
+
filter_goals: Any = field(
|
| 28 |
+
default=None,
|
| 29 |
+
metadata={"description": "SimServer arg: Custom function to filter specific goals for consideration"}
|
| 30 |
+
)
|
| 31 |
+
limit_goals: int = field(
|
| 32 |
+
default=-1,
|
| 33 |
+
metadata={"description": "SimServer arg: Limit the number of goals available"}
|
| 34 |
+
)
|
| 35 |
+
num_products: int = field(
|
| 36 |
+
default=None,
|
| 37 |
+
metadata={"description": "SimServer arg: Number of products to search across"}
|
| 38 |
+
)
|
| 39 |
+
human_goals: bool = field(
|
| 40 |
+
default=False,
|
| 41 |
+
metadata={"description": "SimServer arg: Load human goals if True, otherwise synthetic goals"}
|
| 42 |
+
)
|
| 43 |
+
show_attrs: bool = field(
|
| 44 |
+
default=False,
|
| 45 |
+
metadata={"description": "SimServer arg: Whether to show additional attributes"}
|
| 46 |
+
)
|
ragen/env/webshop/env.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ragen.env.base import BaseLanguageBasedEnv
|
| 2 |
+
from ragen.env.webshop.config import WebShopEnvConfig
|
| 3 |
+
from webshop_minimal import WebAgentTextEnv, init_basedir
|
| 4 |
+
from webshop_minimal.engine import parse_action
|
| 5 |
+
from typing import Optional, Union
|
| 6 |
+
from ragen.utils import all_seed
|
| 7 |
+
import random
|
| 8 |
+
import string
|
| 9 |
+
import uuid
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Define global constant for render instructions
|
| 13 |
+
RENDER_INSTRUCTIONS = [
|
| 14 |
+
"We must buy a product within 10 actions. It doesn't have to match perfectly with description.",
|
| 15 |
+
"Search term should not include details like size, color.",
|
| 16 |
+
"Never search for more than 2 times.",
|
| 17 |
+
"Do not be too strict about the description, it's more important to buy one that is close enough within action limit.",
|
| 18 |
+
"Prioritize click a product in the current page over going to next page.",
|
| 19 |
+
"Almost never click[next >] for more than 2 times.",
|
| 20 |
+
"Almost never click[< prev] unless you are sure the product is on one of the previous pages.",
|
| 21 |
+
"If you have less than 3 actions left, just buy the first product you see in the current page.",
|
| 22 |
+
"If an matching option exists, make sure to click[size] then click[color], one at a time, before click[buy now], but don't have to if only 1 action left, in that case you just click[buy now]. Never click description."
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class WebShopEnv(BaseLanguageBasedEnv, WebAgentTextEnv):
|
| 27 |
+
def __init__(self, config: Optional[WebShopEnvConfig] = None, **kwargs: any) -> None:
|
| 28 |
+
"""
|
| 29 |
+
Adapter for WebAgentTextEnv to conform to the BaseLanguageBasedEnv interface.
|
| 30 |
+
"""
|
| 31 |
+
self.config = config or WebShopEnvConfig()
|
| 32 |
+
self.observation_mode = self.config.observation_mode
|
| 33 |
+
self.file_path = self.config.file_path
|
| 34 |
+
self.server = self.config.server
|
| 35 |
+
self.filter_goals = self.config.filter_goals
|
| 36 |
+
self.limit_goals = self.config.limit_goals
|
| 37 |
+
self.num_products = self.config.num_products
|
| 38 |
+
self.human_goals = self.config.human_goals
|
| 39 |
+
self.show_attrs = self.config.show_attrs
|
| 40 |
+
self.render_cache = None
|
| 41 |
+
if self.config.dataset:
|
| 42 |
+
init_basedir(self.config.dataset)
|
| 43 |
+
|
| 44 |
+
BaseLanguageBasedEnv.__init__(self)
|
| 45 |
+
WebAgentTextEnv.__init__(
|
| 46 |
+
self,
|
| 47 |
+
observation_mode=self.observation_mode,
|
| 48 |
+
file_path=self.file_path,
|
| 49 |
+
server=self.server,
|
| 50 |
+
filter_goals=self.filter_goals,
|
| 51 |
+
limit_goals=self.limit_goals,
|
| 52 |
+
num_products=self.num_products,
|
| 53 |
+
human_goals=self.human_goals,
|
| 54 |
+
show_attrs=self.show_attrs,
|
| 55 |
+
session_prefix=str(uuid.uuid4().hex), # we use a random session prefix to avoid collision
|
| 56 |
+
**kwargs
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
def _get_permuted_index(self, idx, seed=42):
|
| 60 |
+
"""Map index to a deterministically permuted index in the same range.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
idx: The original index
|
| 64 |
+
seed: Random seed to ensure deterministic permutation
|
| 65 |
+
|
| 66 |
+
Returns:
|
| 67 |
+
int: The permuted index
|
| 68 |
+
"""
|
| 69 |
+
# Create a cache key based on goals length and seed
|
| 70 |
+
cache_key = f"perm_{len(self.server.goals)}_{seed}"
|
| 71 |
+
|
| 72 |
+
# Create or retrieve the permutation map
|
| 73 |
+
if not hasattr(self, cache_key):
|
| 74 |
+
# Initialize with fixed seed
|
| 75 |
+
rng = random.Random(seed)
|
| 76 |
+
|
| 77 |
+
# Generate the full permutation
|
| 78 |
+
indices = list(range(len(self.server.goals)))
|
| 79 |
+
rng.shuffle(indices)
|
| 80 |
+
|
| 81 |
+
# Store the permutation as an instance attribute
|
| 82 |
+
setattr(self, cache_key, indices)
|
| 83 |
+
|
| 84 |
+
# Look up the permuted index
|
| 85 |
+
permutation = getattr(self, cache_key)
|
| 86 |
+
return permutation[idx]
|
| 87 |
+
|
| 88 |
+
def reset(self, seed=None, mode="train", session: Optional[Union[str, int]] = None, instruction_text: Optional[str] = None) -> any:
|
| 89 |
+
"""
|
| 90 |
+
Reset the environment and return the initial observation.
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
session (str|int|None): The new session ID.
|
| 94 |
+
instruction_text (str|None): Optional new instruction text.
|
| 95 |
+
|
| 96 |
+
Returns:
|
| 97 |
+
The initial observation.
|
| 98 |
+
"""
|
| 99 |
+
if seed is None:
|
| 100 |
+
# This is from within webshop_minimal. Need to reset with seed later.
|
| 101 |
+
return None
|
| 102 |
+
if mode == "test":
|
| 103 |
+
goal_idx = seed % 500
|
| 104 |
+
elif mode == "val":
|
| 105 |
+
goal_idx = seed % 1000 + 500
|
| 106 |
+
elif mode == "train":
|
| 107 |
+
goal_idx = seed % (len(self.server.goals) - 1500) + 1500
|
| 108 |
+
session = self._get_permuted_index(goal_idx) if session is None else session
|
| 109 |
+
obs, _ = WebAgentTextEnv.reset(self, session=session, instruction_text=instruction_text)
|
| 110 |
+
self.prepare_render_cache(WebAgentTextEnv.get_instruction_text(self))
|
| 111 |
+
return obs
|
| 112 |
+
|
| 113 |
+
def step(self, action):
|
| 114 |
+
"""
|
| 115 |
+
Take an action in the environment and return the next observation, reward, done, and info.
|
| 116 |
+
"""
|
| 117 |
+
orig_available_actions = WebAgentTextEnv.get_available_actions(self)
|
| 118 |
+
action_name, action_arg = parse_action(action)
|
| 119 |
+
if action_arg is not None:
|
| 120 |
+
action_arg = action_arg.lower()
|
| 121 |
+
action_is_valid = (
|
| 122 |
+
action_name == "search"
|
| 123 |
+
and orig_available_actions["has_search_bar"]
|
| 124 |
+
and action_arg is not None
|
| 125 |
+
and action_arg != ""
|
| 126 |
+
) or (
|
| 127 |
+
action_name == "click"
|
| 128 |
+
and action_arg in orig_available_actions["clickables"]
|
| 129 |
+
and action_arg != "search"
|
| 130 |
+
)
|
| 131 |
+
last_observation = self.observation
|
| 132 |
+
state, raw_reward, done, info = WebAgentTextEnv.step(self, action)
|
| 133 |
+
reward = 1.0 if raw_reward >= 1.0 else 0.0
|
| 134 |
+
self.prepare_render_cache(self.observation)
|
| 135 |
+
|
| 136 |
+
info = (info or {}).copy()
|
| 137 |
+
info.update({
|
| 138 |
+
"reward": reward,
|
| 139 |
+
"raw_reward": raw_reward,
|
| 140 |
+
"action_is_effective": self.observation != last_observation,
|
| 141 |
+
"action_is_valid": action_is_valid,
|
| 142 |
+
"success": 1 if reward == 1 else 0,
|
| 143 |
+
"success_purchase": 1 if done else 0,
|
| 144 |
+
"success_find": 1 if reward == 1 else 0,
|
| 145 |
+
"end_of_page": 1 if tuple(self.get_available_actions()) == ('click[back to search]', 'click[< prev]') else 0,
|
| 146 |
+
})
|
| 147 |
+
return self.observation, reward, done, info
|
| 148 |
+
|
| 149 |
+
def render(self, mode=None):
|
| 150 |
+
"""
|
| 151 |
+
Render the environment.
|
| 152 |
+
"""
|
| 153 |
+
return self.render_cache
|
| 154 |
+
|
| 155 |
+
def close(self):
|
| 156 |
+
"""
|
| 157 |
+
Close the environment.
|
| 158 |
+
"""
|
| 159 |
+
WebAgentTextEnv.close(self)
|
| 160 |
+
|
| 161 |
+
def prepare_render_cache(self, observation: str):
|
| 162 |
+
"""
|
| 163 |
+
Prepare the render cache for the environment.
|
| 164 |
+
"""
|
| 165 |
+
available_actions = self.get_available_actions()
|
| 166 |
+
self.render_cache = observation + "."
|
| 167 |
+
self.render_cache += "\n".join(RENDER_INSTRUCTIONS)
|
| 168 |
+
self.render_cache += "\n You must choose from these actions:" + ", ".join(available_actions) + "."
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def get_available_actions(self):
|
| 172 |
+
"""
|
| 173 |
+
Parse the available actions in the environment to a list of strings.
|
| 174 |
+
"""
|
| 175 |
+
orig_available_actions = WebAgentTextEnv.get_available_actions(self)
|
| 176 |
+
available_actions = []
|
| 177 |
+
|
| 178 |
+
if orig_available_actions['has_search_bar']:
|
| 179 |
+
available_actions.append('search[<content>]')
|
| 180 |
+
|
| 181 |
+
for clickable in orig_available_actions['clickables']:
|
| 182 |
+
if clickable != 'search':
|
| 183 |
+
available_actions.append(f'click[{clickable}]')
|
| 184 |
+
# TODO: we may need to purge the case when available_actions == ['click[back to search]', 'click[< prev]', 'click[next >]']
|
| 185 |
+
is_end_of_page = tuple(available_actions) == ('click[back to search]', 'click[< prev]', 'click[next >]')
|
| 186 |
+
if is_end_of_page:
|
| 187 |
+
available_actions.remove('click[next >]')
|
| 188 |
+
return available_actions
|
| 189 |
+
|
| 190 |
+
if __name__ == '__main__':
|
| 191 |
+
env = WebShopEnv()
|
| 192 |
+
print(env.reset())
|
| 193 |
+
while True:
|
| 194 |
+
print(env.observation)
|
| 195 |
+
print(env.server.user_sessions[env.session]['goal']['asin'])
|
| 196 |
+
print(f"Available actions: {env.get_available_actions()}")
|
| 197 |
+
action = input("Enter action: ")
|
| 198 |
+
if action == 'q':
|
| 199 |
+
break
|
| 200 |
+
obs, reward, done, info = env.step(action)
|
| 201 |
+
print(obs, reward, done, info)
|
| 202 |
+
env.close()
|