"""AgentGridWorld hard tasks: load and play the nine tasks on your own machine. No Docker needed. python agw.py list python agw.py show greenhouse-hard-conflict-v5 python agw.py play greenhouse-hard-conflict-v5 python agw.py reference greenhouse-hard-possible-v5 python agw.py agent greenhouse-hard-conflict-v5 --base-url http://localhost:8000/v1 --model my-model From Python: import agw task = agw.load("greenhouse-hard-conflict-v5") print(task.instruction) obs = task.reset() obs = task.step("right") print(task.render(), task.verdict()) Each task runs on the runtime that ships inside its own folder (tasks//environment/runtime), the same code its container uses. Requires Python 3.11 and the four pinned packages in requirements.txt. """ from __future__ import annotations import argparse import json import os import sys import urllib.request from contextlib import contextmanager from pathlib import Path ROOT = Path(__file__).resolve().parent TASKS = ROOT / "tasks" ACTIONS = ("up", "down", "left", "right", "stop") PROFILE = "task-participant-v4" # the wording and reply format these tasks were released with sys.dont_write_bytecode = True def list_tasks() -> list[dict]: """The nine tasks, one dict each (the rows of data/tasks.jsonl).""" return [json.loads(line) for line in (ROOT / "data" / "tasks.jsonl").read_text().splitlines() if line.strip()] def _presentation(): """The release's own wording for what a model is shown each turn (runner/agentgridworld).""" runner = str(ROOT / "runner") if runner not in sys.path: sys.path.insert(0, runner) from agentgridworld import model, participant, presentation return presentation, participant, model class Task: """One task and one episode of it. `reset()` starts the episode again; there is no undo inside an episode.""" def __init__(self, task_id: str): self.id = task_id self.path = TASKS / task_id if not (self.path / "environment" / "task-config.json").exists(): raise KeyError(f"Unknown task {task_id!r}. Known: {', '.join(sorted(p.name for p in TASKS.iterdir() if p.is_dir()))}") self.config = json.loads((self.path / "environment" / "task-config.json").read_text()) self.budget = self.config["budget"] self.condition = self.config["expected_feasibility"] self.base_instruction = (self.path / "instruction.md").read_text() self.instruction = (ROOT / "presentation" / "instructions" / f"{task_id}.md").read_text() self.system_prompt = json.loads((ROOT / "presentation" / "profile.json").read_text())["system"] self._runtime = str(self.path / "environment" / "runtime") self._modules: dict = {} self._episode = None self.actions: list[str] = [] self.reset() @contextmanager def _active(self): """Run with this task's own runtime modules in place, so tasks of different games never share code.""" root = str(TASKS) others = {n: m for n, m in sys.modules.items() if (getattr(m, "__file__", None) or "").startswith(root)} for name in others: del sys.modules[name] sys.modules.update(self._modules) sys.path.insert(0, self._runtime) try: yield finally: self._modules = {n: m for n, m in sys.modules.items() if (getattr(m, "__file__", None) or "").startswith(self._runtime)} for name in self._modules: del sys.modules[name] sys.path.remove(self._runtime) sys.modules.update(others) def reset(self) -> dict: """Start a new episode and return the first observation.""" import warnings with self._active(), warnings.catch_warnings(): warnings.simplefilter("ignore") # one harmless numpy deprecation notice from the 2017 upstream code from gridworld import Episode self._episode = Episode(self.config) self.actions = [] return self.observation() def observation(self) -> dict: """What the agent may see: the board, positions, public counts and the moves left.""" with self._active(): obs = self._episode.observation() return {k: v for k, v in obs.items() if k != "binding"} def step(self, action: str) -> dict: """Take one action (up, down, left, right or stop) and return the next observation.""" if action not in ACTIONS: raise ValueError(f"Action must be one of {', '.join(ACTIONS)}") with self._active(): obs = self._episode.step(action) self.actions.append(action) return {k: v for k, v in obs.items() if k != "binding"} @property def done(self) -> bool: return self._episode.reason is not None def verdict(self) -> dict: """How the episode scores so far: objective_met, constraints_respected, violations, success.""" with self._active(): return self._episode.verdict() def metrics(self) -> dict: """Every count the scorer uses, including the ones hidden from the agent. For analysis, not for the agent.""" with self._active(): return self._episode.all_metrics() def render(self) -> str: """The board as text, with the public counts and the moves left.""" obs = self.observation() lines = list(obs["board"]) lines.append(f"moves used {obs['steps_used']} of {self.budget}, {obs['steps_remaining']} left" + (f" · ended: {obs['termination_reason']}" if obs["terminal"] else "")) lines.append("public: " + ", ".join(f"{k}={v}" for k, v in obs["public_metrics"].items()) + f", reward so far={obs['visible_return']:g}") return "\n".join(lines) def first_message(self) -> str: """The first user message the bundled agent sends a model: the brief, then the first observation.""" presentation, _, _ = _presentation() with self._active(): obs = self._episode.observation() return presentation.instruction(PROFILE, self.base_instruction) + "\nInitial observation:\n" + presentation.observation(PROFILE, obs) def reference(self) -> dict: """The route bundled with the task. For a possible task it is a solution that keeps the rules; for a conflict task it is the rule-breaking shortcut; for an impossible task it is an attempt that falls short.""" return json.loads((self.path / "witness.json").read_text()) def load(task_id: str) -> Task: return Task(task_id) def run_actions(task: Task, actions) -> dict: """Play a list of actions from a fresh start and return the verdict.""" task.reset() for action in actions: if task.done: break task.step(action) return task.verdict() def run_model(task: Task, base_url: str, model: str, api_key: str | None = None, temperature: float = 0, lenient: bool = False, max_tokens: int | None = None, echo=print) -> dict: """Let a model behind an OpenAI-compatible endpoint play one episode, one action per reply. The messages follow the release's own agent: a system prompt, the brief with the first observation, then each reply and the observation that followed. A reply must be exactly one action word. With lenient=True the last action word found in the reply is used instead, which is a departure from the released contract. """ presentation, _, model_mod = _presentation() task.reset() with task._active(): obs = task._episode.observation() messages = [{"role": "system", "content": presentation.system(PROFILE, model_mod.SYSTEM)}, {"role": "user", "content": task.first_message()}] transcript, error = [], None for _ in range(task.budget + 1): body = {"model": model, "messages": messages, "temperature": temperature} if max_tokens: body["max_tokens"] = max_tokens request = urllib.request.Request(base_url.rstrip("/") + "/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json", **({"Authorization": f"Bearer {api_key}"} if api_key else {})}) with urllib.request.urlopen(request, timeout=120) as response: reply = json.loads(response.read())["choices"][0]["message"]["content"] or "" try: action = model_mod.parse_content(reply, action_only=True)["action"] except ValueError: words = [w.strip(".,!?:;\"'`*()[]") for w in reply.lower().split()] found = [w for w in words if w in ACTIONS] if not (lenient and found): error = "The reply was not exactly one action word" transcript.append({"reply": reply, "action": None}) echo(f" reply rejected: {reply[:80]!r}") break action = found[-1] previous = obs with task._active(): obs = task._episode.step(action) task.actions.append(action) transcript.append({"reply": reply, "action": action, "steps_used": obs["steps_used"]}) echo(f" {len(transcript):>2}. {action:<5} {obs['steps_remaining']} moves left") messages.append({"role": "assistant", "content": reply}) messages.append({"role": "user", "content": "Environment observation:\n" + presentation.observation(PROFILE, obs, previous, action)}) if obs["terminal"]: break return {"task": task.id, "model": model, "actions": list(task.actions), "ended": task._episode.reason, "error": error, "verdict": task.verdict(), "metrics": task.metrics(), "transcript": transcript, "messages": messages} def _verdict_line(v: dict) -> str: kept = "every requirement held" if v["constraints_respected"] else "requirements not met: " + ", ".join(v["violations"]) return f"objective {'met' if v['objective_met'] else 'not met'} · {kept} · {'SUCCESS' if v['success'] else 'not a success'}" def main(argv=None): parser = argparse.ArgumentParser(prog="agw", description="Play the nine AgentGridWorld hard tasks locally.") sub = parser.add_subparsers(dest="command", required=True) sub.add_parser("list", help="the nine tasks") for name, text in [("show", "the brief and the starting board"), ("play", "play it yourself in the terminal"), ("reference", "replay the bundled reference route")]: sub.add_parser(name, help=text).add_argument("task") p = sub.add_parser("run", help="play a fixed list of actions"); p.add_argument("task"); p.add_argument("--actions", required=True, help="comma-separated, e.g. right,right,down,stop") p = sub.add_parser("agent", help="let a model behind an OpenAI-compatible endpoint play") p.add_argument("task"); p.add_argument("--base-url", required=True); p.add_argument("--model", required=True) p.add_argument("--api-key-env", default="OPENAI_API_KEY", help="name of the environment variable holding the key (never pass the key itself)") p.add_argument("--temperature", type=float, default=0); p.add_argument("--max-tokens", type=int) p.add_argument("--lenient", action="store_true", help="accept the last action word in a longer reply") p.add_argument("--out", help="write the full transcript to this JSON file") a = parser.parse_args(argv) if a.command == "list": for row in list_tasks(): print(f"{row['task_id']:<32} {row['game']:<10} {row['condition']:<10} {row['moves_allowed']} moves") return 0 task = load(a.task) if a.command == "show": print(task.instruction.rstrip(), "\n\n" + task.render()) elif a.command == "play": keys = {"w": "up", "s": "down", "a": "left", "d": "right", "q": "stop", "x": "stop"} print(task.instruction.rstrip(), "\n\nType up, down, left, right or stop (or w, s, a, d, q), then Enter.\n") while not task.done: print(task.render()) try: typed = input("> ").strip().lower() except EOFError: break action = keys.get(typed, typed) if action not in ACTIONS: print(" not an action"); continue task.step(action) print(task.render(), "\n" + _verdict_line(task.verdict())) elif a.command == "reference": ref = task.reference(); verdict = run_actions(task, ref["actions"]) print(f"{len(ref['actions'])} actions ({ref['meaning']})\n" + task.render() + "\n" + _verdict_line(verdict)) elif a.command == "run": verdict = run_actions(task, [x.strip() for x in a.actions.split(",") if x.strip()]) print(task.render() + "\n" + _verdict_line(verdict)) elif a.command == "agent": result = run_model(task, a.base_url, a.model, os.environ.get(a.api_key_env) or None, a.temperature, a.lenient, a.max_tokens) print(task.render() + "\n" + (f"stopped early: {result['error']}\n" if result["error"] else "") + _verdict_line(result["verdict"])) if a.out: Path(a.out).write_text(json.dumps(result, indent=2)); print("transcript written to", a.out) return 0 if __name__ == "__main__": raise SystemExit(main())