"""Play full tic-tac-toe games: Strands Agent (X) vs minimax, or Strands Agent vs Strands Agent. PYTHONPATH=$T/isaaclab-wt $T/.venv/bin/python play_games.py --port 8765 --mode agent_vs_minimax --games 6 \ --out ../runs/batch1 [--video_first] [--record ROOT --repo_id cagataydev/x] """ from __future__ import annotations import argparse import json import os import sys import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import ttt_game as G # noqa: E402 from ttt_tools import Client, Game, make_tools # noqa: E402 SYSTEM = ( "You are playing tic-tac-toe against an opponent on a real table in a robot simulator. A Franka robot arm " "moves the pieces for you: red cubes are X, blue cylinders are O. Use get_board to look at the board, then " "call place_mark exactly once per turn with the cell you choose. Play to win; if you cannot win, block and " "play for a draw. After placing your mark, reply with one short sentence explaining your move." ) def make_agent(mark: str, game: Game, name: str): from strands import Agent from strands.models import BedrockModel tools, turn = make_tools(game, mark, name) model = BedrockModel(model_id=os.environ["STRANDS_MODEL_ID"], max_tokens=2000) agent = Agent(model=model, tools=tools, system_prompt=SYSTEM, callback_handler=None) return agent, turn def agent_turn(agent, turn, game: Game, mark: str, prompt: str, tries: int = 3) -> dict: turn["placed"] = False n0 = len(game.moves) msgs = [] for k in range(tries): t0 = time.time() res = agent(prompt if k == 0 else f"You have not placed an {mark} yet this turn. Call place_mark now.") msgs.append({"prompt": prompt if k == 0 else "(nudge)", "reply": str(res).strip(), "llm_s": round(time.time() - t0, 1)}) if turn["placed"]: break return {"placed": turn["placed"], "moves_added": len(game.moves) - n0, "msgs": msgs} def transcript_md(agent, title: str) -> str: out = [f"# {title}\n"] for m in agent.messages: role = m.get("role") for c in m.get("content", []): if "text" in c and c["text"].strip(): out.append(f"**{role}:** {c['text'].strip()}\n") elif "toolUse" in c: tu = c["toolUse"] out.append(f"**{role} → tool `{tu['name']}`** `{json.dumps(tu.get('input', {}))}`\n") elif "toolResult" in c: tr = c["toolResult"] txt = " ".join(x.get("text", "") for x in tr.get("content", []) if isinstance(x, dict)) out.append(f"**tool result ({tr.get('status')}):**\n```\n{txt.strip()}\n```\n") return "\n".join(out) def play_one(client: Client, mode: str, gid: str, out: str, agent_mark: str = "X") -> dict: gdir = os.path.join(out, gid) os.makedirs(gdir, exist_ok=True) os.environ["TTT_RUN_DIR"] = gdir mlog = open(os.path.join(gdir, "moves.jsonl"), "w", buffering=1) game = Game(client, log_cb=lambda mv: mlog.write(json.dumps(mv) + "\n")) game.reset() t0 = time.time() players = {} if mode == "agent_vs_minimax": a, t = make_agent(agent_mark, game, f"agent-{agent_mark}") players[agent_mark] = ("agent", a, t) players["O" if agent_mark == "X" else "X"] = ("minimax", None, None) elif mode == "agent_vs_agent": for m in ("X", "O"): a, t = make_agent(m, game, f"agent-{m}") players[m] = ("agent", a, t) else: raise ValueError(mode) llm = [] last = None first = {m: True for m in "XO"} stuck = 0 while G.status(game.board) == "in progress" and stuck < 3: m = G.to_move(game.board) kind, a, t = players[m] n0 = len(game.moves) if kind == "minimax": i = G.minimax_move(game.board, m) r = game.place(m, i, by="minimax") if not r.get("success"): stuck += 1 else: opp = "O" if m == "X" else "X" if first[m]: p = (f"Let's play tic-tac-toe. You are {m}. Place your marks with the robot. " + ("You go first." if m == "X" else f"Your opponent ({opp}) went first: {last}." if last else "")) first[m] = False else: p = f"Your opponent ({opp}) moved: {last}. Your turn." r = agent_turn(a, t, game, m, p) llm.append({"mark": m, **r}) if not r["placed"]: stuck += 1 if len(game.moves) > n0 and game.moves[-1].get("success"): mv = game.moves[-1] last = f"the robot placed {mv['mark']} in the {mv['cell_name']} cell" stuck = 0 game.state() res = { "game": gid, "mode": mode, "agent_mark": agent_mark if mode == "agent_vs_minimax" else "XO", "result": G.status(game.board), "winner": G.winner(game.board), "final_board": game.board, "n_moves": len(game.moves), "placements_ok": sum(bool(m.get("success")) for m in game.moves), "grasp_ok": sum(bool(m.get("grasp_ok")) for m in game.moves), "mean_err_mm": round(1000 * sum(m.get("place_err_m") or 0 for m in game.moves) / max(1, len(game.moves)), 2), "max_err_mm": round(1000 * max([m.get("place_err_m") or 0 for m in game.moves] or [0]), 2), "vision_disagreements": game.disagreements, "wall_s": round(time.time() - t0, 1), "robot_s": round(sum(m.get("wall_s") or 0 for m in game.moves), 1), "llm_s": round(sum(x["llm_s"] for r in llm for x in r["msgs"]), 1), "agent_turns_without_move": sum(not r["placed"] for r in llm), "complete": G.status(game.board) != "in progress", } with open(os.path.join(gdir, "transcript.md"), "w") as f: for m, (kind, a, _) in players.items(): if kind == "agent": f.write(transcript_md(a, f"{gid} — agent playing {m}") + "\n\n") f.write(f"## Result: {res['result']}\n\n```\n{G.ascii_board(game.board)}\n```\n") json.dump({"result": res, "llm_turns": llm}, open(os.path.join(gdir, "game.json"), "w"), indent=1) client.call("render", path=os.path.join(gdir, "final")) return res def main(): ap = argparse.ArgumentParser() ap.add_argument("--port", type=int, default=8765) ap.add_argument("--mode", default="agent_vs_minimax", choices=["agent_vs_minimax", "agent_vs_agent"]) ap.add_argument("--games", type=int, default=1) ap.add_argument("--agent_mark", default="X") ap.add_argument("--alternate", action="store_true", help="agent alternates X/O each game (vs minimax)") ap.add_argument("--out", required=True) ap.add_argument("--prefix", default="g") ap.add_argument("--video", default="first", choices=["none", "first", "all"]) ap.add_argument("--record", default=None, help="dataset root (strands DatasetRecorder in the server)") ap.add_argument("--repo_id", default="local/ttt") ap.add_argument("--shutdown", action="store_true") ap.add_argument("--schedule", default=None, help='e.g. "agent_vs_minimax:6,agent_vs_agent:4" (overrides --mode/--games)') a = ap.parse_args() a.out = os.path.abspath(a.out) a.record = os.path.abspath(a.record) if a.record else None os.makedirs(a.out, exist_ok=True) c = Client(a.port) print(c.call("ping"), flush=True) if a.record: print(c.call("record_open", root=a.record, repo_id=a.repo_id), flush=True) results = [] plan = [] for part in (a.schedule.split(",") if a.schedule else [f"{a.mode}:{a.games}"]): md, n = part.split(":") plan += [(md, j) for j in range(int(n))] for k, (mode, j) in enumerate(plan): a.mode = mode gid = f"{a.prefix}{k:02d}_{a.mode}" mark = ("X" if j % 2 == 0 else "O") if a.alternate else a.agent_mark vid = a.video == "all" or (a.video == "first" and j == 0) if vid: c.call("video_open", path=os.path.join(a.out, gid, "game.mp4"), every=2) try: r = play_one(c, a.mode, gid, a.out, mark) except Exception as e: # noqa: BLE001 r = {"game": gid, "mode": a.mode, "error": f"{type(e).__name__}: {e}", "complete": False} if vid: r["video"] = c.call("video_close").get("video") results.append(r) print(json.dumps(r), flush=True) json.dump(results, open(os.path.join(a.out, "results.json"), "w"), indent=1) if a.record: print(c.call("record_close"), flush=True) if a.shutdown: c.call("shutdown") if __name__ == "__main__": main()