PEFT
Safetensors
English
chess
lora
sarvam
fta-mark-1
FTA-Mark-1 / mark1 /api_match.py
atal-ai's picture
FTA Mark-1 release: card and code
4a86fc3 verified
Raw History Blame Contribute Delete
11.2 kB
"""Play Mark-1 against OpenAI or Google Gemini, under the same rules as the recorded matches.
from mark1 import load, play_vs_api
mark1 = load()
play_vs_api(mark1, provider="gemini", model="gemini-3.8-flash", mark1_color="white", opening="op01")
The rules (the same as the matches, and the same for both sides):
- Both players are shown the same position. The opponent gets the matches' prompt move_v4 word for word
(the position, a board picture, the legal moves and some board facts). Mark-1 answers with its own
think-ahead, which always gives a legal move.
- One reading rule for both: the first word after the last "Move:" in the answer.
- The referee: after an illegal or unreadable answer, up to 2 more tries with the referee's fixed
sentences. If all 3 fail, the referee plays the player's OWN top legal move (from the win% numbers
in its own answers). Never a forfeit. Every step-in is saved in the game record.
- The opponent runs at its maker's default settings: only the model name and the conversation are sent
(no temperature, thinking level or tools).
- No clock for either side. A game ends at checkmate, stalemate, too little material, fivefold
repetition or 75 moves, or when a position has actually occurred 3 times or 50 moves have actually
passed without a capture or pawn move.
- When the API brings no answer at all (server error, rate limit, timeout, dropped connection), it is
asked again after 10 s, 30 s, 60 s, then every 2 minutes; that is not one of the opponent's tries.
After 2 hours with no answer the game stops, saved, and can carry on later from the same position.
A refused request (wrong key, wrong model name) stops at once.
The game itself is played by chess_eval/games.py (copied unchanged from the match code) with the same
settings the match runner used: headline "full_system", Mark-1 the tested side, the own-pick referee
for both colours. Your API key is read from the environment (OPENAI_API_KEY or GEMINI_API_KEY) and is
never written to any file.
"""
import http.client
import json
import os
import socket
import time
import urllib.error
from typing import Callable, Optional
import chess
PROMPT = "move_v4" # the matches' shared prompt
KEY_VARIABLES = {"openai": "OPENAI_API_KEY", "gemini": "GEMINI_API_KEY"}
# Suggested models: the ones Mark-1 played in the recorded matches. Any model name the provider offers works.
DEFAULT_MODELS = {"openai": "gpt-6-astra", "gemini": "gemini-3.8-flash"}
# Prices only for the cost line printed after each game (US dollars per million tokens, as recorded in the
# match manifests in November 2026). Check the provider's price page: prices change.
PRICES_USD = {"gpt-6-astra": (10.0, 50.0), "gemini-4-argon": (2.0, 10.0), "gemini-3.8-flash": (0.75, 3.75)}
USD_TO_INR = 90.0
RETRY_WAITS = (10, 30, 60) # then every 2 minutes (the matches' outage rule)
RETRY_EVERY = 120
PAUSE_AFTER = 30 * 60 # after 30 minutes: tried every 5 minutes
PAUSED_EVERY = 300
STOP_AFTER = 2 * 3600 # after 2 hours with no answer: the game stops (saved)
class Stopped(BaseException):
"""Stops the game (not caught as a bad answer): a long outage, or a refused request. The game is saved."""
def no_answer(error: BaseException) -> bool:
"""True for a call that brought no answer (ask again); False for a refused request (stop)."""
if isinstance(error, urllib.error.HTTPError):
return error.code == 429 or error.code >= 500
return isinstance(error, (urllib.error.URLError, http.client.HTTPException, socket.timeout, OSError))
class PatientGenerator:
"""Wraps the API player's generate(): a call with no answer is asked again and never reaches the game
as an answer. The same rule as the match runner (chess_eval/match.py at the lock commits)."""
def __init__(self, inner, clock: Callable[[], float] = time.time, sleep: Callable[[float], None] = time.sleep,
log: Callable = print):
self.inner, self.clock, self.sleep, self.log = inner, clock, sleep, log
self.last_meta = None
self.service = {"openai": "OpenAI", "gemini": "Google"}.get(getattr(inner, "provider", ""), "The API")
def __getattr__(self, name):
return getattr(self.inner, name)
def generate(self, messages) -> str:
first_try = self.clock()
failed, waited, paused, n = [], 0.0, False, 0
while True:
try:
text = self.inner.generate(messages)
break
except BaseException as error:
if isinstance(error, Stopped) or not isinstance(error, Exception):
raise
if not no_answer(error):
code = getattr(error, "code", None)
raise Stopped(f"{self.service} refused the request ({type(error).__name__}"
f"{' ' + str(code) if code else ''}: {str(error)[:200]}). Check the key and the "
"model name. The game is saved at this position.")
row = {"utc": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
"error": f"{type(error).__name__}: {error}"[:300]}
failed.append(row)
down = self.clock() - first_try
if down >= STOP_AFTER:
raise Stopped(f"No answer from {self.service} for {down / 60:.0f} minutes. The game is saved at "
"this position; run it again later to carry on.")
if down >= PAUSE_AFTER:
paused = True
wait = PAUSED_EVERY if paused else (RETRY_WAITS[n] if n < len(RETRY_WAITS) else RETRY_EVERY)
n += 1
self.log(f" {self.service} gave no answer ({row['error'][:80]}); asking again in {wait} s.")
self.sleep(wait)
waited = self.clock() - first_try
meta = dict(getattr(self.inner, "last_meta", None) or {})
meta.update(failed_calls=failed, outage_seconds=round(waited, 1), paused=paused)
self.last_meta = meta
return text
def opponent_player(provider: str, model: str, generator=None, log: Callable = print):
"""The API opponent as a game player: the matches' prompt, reading rule and referee."""
from chess_eval import fair_play
from chess_eval.api_players import APIPlayer
from chess_eval.games import LLMGamePlayer
if provider not in KEY_VARIABLES:
raise ValueError(f"provider must be one of {sorted(KEY_VARIABLES)}")
usd_in, usd_out = PRICES_USD.get(model, (0.0, 0.0))
inner = generator or APIPlayer(provider, model, name=model, prompt_version=PROMPT, usd_per_million_in=str(usd_in),
usd_per_million_out=str(usd_out), usd_to_inr=str(USD_TO_INR))
if generator is None:
if not os.environ.get(KEY_VARIABLES[provider]):
raise SystemExit(f"No API key: set {KEY_VARIABLES[provider]} first (the notebook asks for it).")
os.environ["ATAL_ALLOW_PAID_API"] = "yes" # the copied API code sends nothing without this switch
patient = PatientGenerator(inner, log=log)
player = LLMGamePlayer(patient, name=model)
fair_play.apply([player], PROMPT)
return player
def opening_of(opening: Optional[str]) -> dict:
"""One of the fixed openings (op01 to op10, chess_eval/openings.py), or "start" for the normal start."""
from chess_eval.openings import OPENINGS
if opening in (None, "", "start"):
return {"id": "start", "eco": "-", "name": "Starting position", "moves": ""}
for o in OPENINGS:
if o["id"] == opening:
return o
raise ValueError(f"Unknown opening {opening!r}: use 'start' or one of {[o['id'] for o in OPENINGS]}")
def play_vs_api(mark1, provider: str = "gemini", model: Optional[str] = None, mark1_color: str = "white",
opening: str = "op01", level: Optional[str] = None, out_dir: str = "my_games",
game_id: Optional[str] = None, say: Callable = print, opponent=None) -> dict:
"""Play one full game; save it as PGN and JSON in out_dir; return the game record.
A game that stopped (a long outage, a refused request) carries on from its saved position when
this is run again with the same game_id and out_dir."""
from chess_eval import fair_play
from chess_eval import games as G
model = model or DEFAULT_MODELS[provider]
book = opening_of(opening)
mark1_white = mark1_color.lower().startswith("w")
game_id = game_id or f"mark1-vs-{model}-{book['id']}-mark1-{'white' if mark1_white else 'black'}"
me = mark1.game_player(level)
them = opponent or opponent_player(provider, model, log=say)
fair_play.apply([me, them], PROMPT)
white, black = (me, them) if mark1_white else (them, me)
os.makedirs(os.path.join(out_dir, "partial"), exist_ok=True)
partial_path = os.path.join(out_dir, "partial", f"{game_id}.json")
resume = None
if os.path.isfile(partial_path):
with open(partial_path, encoding="utf-8") as f:
resume = json.load(f)
say(f"Carrying on from the saved position after {len(resume['plies'])} moves.")
def on_move(state):
with open(partial_path + ".part", "w", encoding="utf-8") as f:
json.dump(state, f)
os.replace(partial_path + ".part", partial_path)
ply = state["plies"][-1]
who = "Mark-1" if (ply["color"] == "white") == mark1_white else model
secs = sum(a.get("seconds") or 0 for a in ply["attempts"])
note = "" if ply["by"] == "player" else " (referee: the player's own top legal move)"
say(f"{ply['move_number']} {ply['san']:<7} {who} ({secs:.0f} s){note}")
top, deeper = mark1.player(level).top_moves, mark1.player(level).deeper
say(f"{'Mark-1' if mark1_white else model} (White) vs {model if mark1_white else 'Mark-1'} (Black), "
f"opening {book['id']} ({book['name']}). Mark-1 thinks ahead: top {top}, deeper {deeper}.")
record = G.play_game(white, black, book, game_id, event=f"FTA Mark-1 vs {model}", round_label="1",
extra_settings={"rules": "as in the FTA Mark-1 matches", "clock": "none",
"mark1_search": {"top_moves": top, "deeper": deeper},
"opponent_provider": provider, "opponent_model": model},
headline="full_system", tested_color=chess.WHITE if mark1_white else chess.BLACK,
own_pick_colors=(chess.WHITE, chess.BLACK), resume=resume, on_move=on_move)
paths = G.save_game(record, out_dir)
if os.path.isfile(partial_path):
os.remove(partial_path)
cost = them.cost_rupees() if hasattr(them, "cost_rupees") else 0.0
say(f"Result: {record['result_full_system']} ({record['termination']}), {len(record['plies'])} moves. "
f"Referee step-ins: {record['referee']['step_ins']}. API cost about Rs {cost:,.0f} "
f"(at the prices in mark1/api_match.py; check your provider's bill). Saved: {paths['pgn']}")
record["_paths"] = paths
return record