cagataydev's picture
Franka tic-tac-toe in Isaac Lab driven by a Strands Agent: 10 games, 90 episodes (LeRobot v3.0)
1ecad6a verified
Raw History Blame Contribute Delete
5.78 kB
"""Strands side: TCP client for ttt_server + Strands @tools (get_board, place_mark, reset_game, render_board).
Runs in the strands venv. The robot/sim lives in another process (Isaac Lab venv).
"""
from __future__ import annotations
import json
import os
import socket
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import ttt_game as G # noqa: E402
class Client:
def __init__(self, port: int = 8765, host: str = "127.0.0.1", timeout: float = 600):
self.s = socket.create_connection((host, port), timeout=timeout)
self.f = self.s.makefile("rwb")
def call(self, cmd: str, **kw) -> dict:
self.f.write((json.dumps({"cmd": cmd, **kw}) + "\n").encode())
self.f.flush()
line = self.f.readline()
if not line:
raise ConnectionError("ttt server closed the connection")
return json.loads(line)
def close(self):
try:
self.s.close()
except Exception: # noqa: BLE001
pass
class Game:
"""Shared game state/log across players; enforces turn order; talks to the robot server."""
def __init__(self, client: Client, log_cb=None):
self.c = client
self.moves: list[dict] = []
self.disagreements = 0
self.log_cb = log_cb or (lambda m: None)
self.board = [" "] * 9
def reset(self):
r = self.c.call("reset")
self.board = r["board"]
self.moves = []
return r
def state(self):
r = self.c.call("state")
self.board = r["board"]
if not r.get("agree", True):
self.disagreements += 1
return r
def place(self, mark: str, cell: int, by: str) -> dict:
if G.status(self.board) != "in progress":
return {"ok": False, "error": f"game over: {G.status(self.board)}"}
if G.to_move(self.board) != mark:
return {"ok": False, "error": f"it is {G.to_move(self.board)}'s turn, not {mark}'s"}
if self.board[cell] != " ":
return {"ok": False, "error": f"{G.CELL_NAMES[cell]} is already taken by {self.board[cell]}"}
r = self.c.call("place", mark=mark, cell=cell, task=f"place {mark} in the {G.CELL_NAMES[cell]} cell")
if r.get("board"):
self.board = r["board"]
if not r.get("agree", True):
self.disagreements += 1
mv = {"n": len(self.moves) + 1, "by": by, "mark": mark, "cell": cell, "cell_name": G.CELL_NAMES[cell],
**{k: r.get(k) for k in ("ok", "success", "grasp_ok", "attempts", "place_err_m", "cell_detected",
"agree", "wall_s", "sim_s", "frames", "error")},
"vision_board": (r.get("vision") or {}).get("board"), "board_after": self.board}
self.moves.append(mv)
self.log_cb(mv)
return r
def make_tools(game: Game, mark: str, name: str):
"""Strands tools bound to one player's mark."""
from strands import tool
turn = {"placed": False}
@tool
def get_board() -> dict:
"""Look at the tic-tac-toe board on the table (simulator ground truth and the overhead camera's view).
Returns the 3x3 board as text (cells numbered 1-9, top-left=1 ... bottom-right=9, as seen from above),
whose turn it is, the game status and whether the camera agrees with the simulator.
"""
r = game.state()
b = r["board"]
return {"status": "success", "content": [{"text": (
f"Board (you are {mark}):\n{G.ascii_board(b)}\n"
f"cells: {', '.join(f'{i + 1}={n}' for i, n in enumerate(G.CELL_NAMES))}\n"
f"to move: {G.to_move(b)} | status: {G.status(b)} | camera agrees with sim: {r.get('agree')}"
f"{'' if r.get('agree') else ' (camera sees ' + ''.join(r['vision']['board']).replace(' ', '.') + ')'}")}]}
@tool
def place_mark(cell: str) -> dict:
"""Have the robot arm pick one of your tokens from the tray and place it on a board cell.
Args:
cell: the target cell, e.g. "top-left", "center", "bottom-right", or a number 1-9
(1=top-left, 3=top-right, 5=center, 7=bottom-left, 9=bottom-right).
"""
try:
i = G.parse_cell(cell)
except ValueError as e:
return {"status": "error", "content": [{"text": str(e)}]}
if turn["placed"]:
return {"status": "error", "content": [{"text": "You already placed a mark this turn; wait for the opponent."}]}
r = game.place(mark, i, by=name)
if not r.get("ok") or not r.get("success"):
return {"status": "error", "content": [{"text": f"placement failed: {r.get('error') or r}"[:800]}]}
turn["placed"] = True
b = game.board
return {"status": "success", "content": [{"text": (
f"The robot placed {mark} in {G.CELL_NAMES[i]} (placement error {1000 * r['place_err_m']:.1f} mm).\n"
f"{G.ascii_board(b)}\nstatus: {G.status(b)}")}]}
@tool
def reset_game() -> dict:
"""Clear the board: the robot's tokens go back to their trays. Only use when asked to start a new game."""
game.reset()
return {"status": "success", "content": [{"text": "Board cleared.\n" + G.ascii_board(game.board)}]}
@tool
def render_board(path: str = "") -> dict:
"""Save overhead and front camera images of the table; returns the file paths."""
p = path or os.path.join(os.environ.get("TTT_RUN_DIR", "/tmp"), f"render_{len(game.moves)}")
r = game.c.call("render", path=p)
return {"status": "success", "content": [{"text": json.dumps({"files": r.get("files"), "board": r.get("board")})}]}
return [get_board, place_mark, reset_game, render_board], turn