Code
agent_olympics.py
A Python script that publishes on Webloyt through the Claude API. Copy it, put ANTHROPIC_API_KEY and WEBLOYT_TOKEN in a .env file next to it (tokens come from the tokens page) and run it. The constants at the top are the only things to change.
"""Agent Olympics, the number game: two models play a match of five rounds, with a public board on Webloyt
and a private notebook each, so the next match starts from what they learned.
Each player starts with 100 units and tries to keep as much of it as possible. Every round:
1. Both bid, sealed. The higher bid wins the right to pick the number and pays its bid. Equal bids go
to the player with less money; equal money, a coin toss. Both are then told both bids.
2. The picker chooses a number from 1 to 100.
3. The guesser guesses until it hits it: a guess below the number costs 3 units, a guess above costs 1,
and after each guess it is told which. Nobody earns anything; the winner is whoever has lost least.
After each round both players see the full record: bids, number, every guess, both balances.
The players never see each other's reasoning, only the record. Each move comes with one sentence for
the spectators, which the other player never sees. The arbiter is this script; the board on Webloyt
is the public record, updated after every event. At the end of the match each player writes its
notebook, notes/<player>.md on the site, and reads it back at the start of the next match; the other
player is never shown it. The site's index lists every match played, and notebooks.html shows the
notebooks as they stand and as they were after every earlier match.
Setup: pip install anthropic fastmcp rich python-dotenv markdown
ANTHROPIC_API_KEY and WEBLOYT_TOKEN in the environment or in a .env file
(a Webloyt token comes from https://webloyt-mcp.iroiro.cloud/tokens)
Run: python agent_olympics.py
"""
import asyncio
import json
import os
import random
from datetime import date
from html import escape
import anthropic
import markdown
from dotenv import load_dotenv
from fastmcp import Client
from rich.console import Console
from rich.table import Table
load_dotenv()
# ---- The game -------------------------------------------------------------------------------
SITE = "agent-olympics"
PLAYERS = {"Opus": "claude-opus-5-5", "Sonnet": "claude-sonnet-5-5"}
ROUNDS = 5 # a match
START = 100
LOW, HIGH = 1, 100
UNDER, OVER = 3, 1 # the cost of a guess below the number, and of one above
MAX_GUESSES = 30 # a safety net; a sensible guesser needs about seven
WEBLOYT = "https://webloyt-mcp.iroiro.cloud"
PRICES = { # (input, output, cache write, cache read), dollars per million tokens
"claude-fable-5-2": (8.00, 40.00, 10.00, 0.20),
"claude-opus-5-5": (4.00, 20.00, 5.00, 0.20),
"claude-sonnet-5-5": (2.00, 10.00, 2.50, 0.10),
}
RULES = f"""You are playing the number game against one other player, over {ROUNDS} rounds. You both start
with {START} units. Nobody earns anything in this game; the winner is the player with the most units left
at the end, so every unit you do not lose is a point. Each round:
1. Both players bid, sealed. The higher bid wins the right to pick the number and pays its bid (the units are
gone). Equal bids go to the player with less money; if money is equal too, a coin toss. After the auction
both players are told both bids. A bid cannot exceed what you have.
2. The picker chooses a whole number from {LOW} to {HIGH}.
3. The other player guesses until it hits the number. A guess below the number costs {UNDER} units, a guess
above costs {OVER}, and after each guess the guesser is told whether it was below or above.
After each round both players see the full record: both bids, the number, every guess, both balances.
You never see the other player's reasoning, only what it did. With every move you may add one sentence
for the spectators, which the other player never sees. Answer with JSON only, exactly in the form asked.
After the match you will write a notebook for yourself, which you alone will read before the next match."""
# `rich` only colours the output and records it, so the run can be shared as an image.
console = Console(record=True)
client = anthropic.Anthropic()
usage = {}
chats = {name: [] for name in PLAYERS} # each player's own conversation with the arbiter
notebooks = {name: "" for name in PLAYERS} # what each player wrote for itself after earlier matches
# ---- The players ----------------------------------------------------------------------------
def system(player):
text = RULES + f"\nYou are {player}."
if notebooks[player]:
text += f"\n\nYour notebook from earlier matches:\n{notebooks[player]}"
return text
def ask(player, prompt, key, valid):
"""One move from a player: a JSON answer with `key` and a `note`, asked again if it is not valid."""
chats[player].append({"role": "user", "content": prompt})
for attempt in range(3):
# if a safety filter declines, the API retries the same request on another model
message = client.beta.messages.create(
model=PLAYERS[player], max_tokens=16000, # the model's thinking counts against this too
betas=["server-side-fallback-2026-07-01"], fallbacks="default",
system=[{"type": "text", "text": system(player), "cache_control": {"type": "ephemeral"}}],
messages=chats[player])
totals = usage.setdefault(message.model, {"input": 0, "output": 0, "cache_write": 0, "cache_read": 0})
totals["input"] += message.usage.input_tokens
totals["output"] += message.usage.output_tokens
totals["cache_write"] += message.usage.cache_creation_input_tokens or 0
totals["cache_read"] += message.usage.cache_read_input_tokens or 0
text = " ".join(block.text for block in message.content if block.type == "text").strip()
chats[player].append({"role": "assistant", "content": text})
try:
answer = json.loads(text[text.find("{"):text.rfind("}") + 1])
value = int(answer[key])
if valid(value):
return value, str(answer.get("note", ""))[:300]
problem = f"{value} is not allowed here."
except (ValueError, KeyError, TypeError):
problem = "That was not the JSON asked for."
console.print(f" [yellow]{player}: {problem} (stop reason {message.stop_reason}; reply: {text[:120]!r})")
chats[player].append({"role": "user", "content": f"{problem} Answer again, JSON only."})
raise SystemExit(f"{player} would not give a valid move.")
def say(player, prompt):
"""A plain-text answer from a player, for the notebook."""
chats[player].append({"role": "user", "content": prompt})
message = client.beta.messages.create(
model=PLAYERS[player], max_tokens=16000,
betas=["server-side-fallback-2026-07-01"], fallbacks="default",
system=[{"type": "text", "text": system(player), "cache_control": {"type": "ephemeral"}}],
messages=chats[player])
totals = usage.setdefault(message.model, {"input": 0, "output": 0, "cache_write": 0, "cache_read": 0})
totals["input"] += message.usage.input_tokens
totals["output"] += message.usage.output_tokens
text = " ".join(block.text for block in message.content if block.type == "text").strip()
chats[player].append({"role": "assistant", "content": text})
return text
def tell(player, text):
"""Something both players learn, kept in their conversations without asking for an answer."""
chats[player].append({"role": "user", "content": text})
chats[player].append({"role": "assistant", "content": "Noted."})
# ---- The board ------------------------------------------------------------------------------
def webloyt(tool, **arguments):
async def call():
async with Client(f"{WEBLOYT}/mcp", auth=os.environ["WEBLOYT_TOKEN"]) as mcp:
result = await mcp.call_tool(tool, arguments)
return result.structured_content or json.loads(result.content[0].text)
return asyncio.run(call())
def board(match, rounds, balances, live):
"""One match as one page. `rounds` is the record so far; the last one may be in progress."""
names = list(PLAYERS)
rows = "".join(f"<tr><th>{n}</th><td>{PLAYERS[n]}</td><td>{balances[n]}</td></tr>" for n in names)
cards = []
for r in rounds:
bids = "".join(
f'<p><b>{n}</b> bids <b>{r["bids"][n]}</b>'
f'{" <i>" + escape(r["notes"][n]) + "</i>" if r["notes"].get(n) else ""}</p>'
for n in names if n in r.get("bids", {}))
pick = ""
if r.get("picker"):
pick = (f'<p><b>{r["picker"]}</b> picks the number and pays {r["bids"][r["picker"]]}'
f'{" (" + r["tie"] + ")" if r.get("tie") else ""}.'
f'{" <i>" + escape(r["pick_note"]) + "</i>" if r.get("pick_note") else ""}</p>')
guesses = "".join(
f'<li>{g["guess"]}: {"below, costs " + str(UNDER) if g["result"] == "below" else "above, costs " + str(OVER) if g["result"] == "above" else "<b>found it</b>"}'
f'{" <i>" + escape(g["note"]) + "</i>" if g.get("note") else ""}</li>'
for g in r.get("guesses", []))
guesses = f'<p><b>{r["guesser"]}</b> guesses:</p><ol>{guesses}</ol>' if r.get("guesser") else ""
reveal = ""
if "number" in r:
reveal = (f'<p>The number was <b>{r["number"]}</b>. '
f'{r["guesser"]} paid {r["guess_cost"]}; {r["picker"]} paid {r["bids"][r["picker"]]}. '
f'Balances: ' + ", ".join(f"{n} {r['after'][n]}" for n in names) + ".</p>")
cards.append(f'<section class="round"><h2>Round {r["n"]}</h2>{bids}{pick}{guesses}{reveal}</section>')
status = "<p class=\"live\">Live: the game is in progress. Refresh for the next move.</p>" if live else ""
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Match {match}: the number game | Agent Olympics</title>
<meta name="description" content="Two AI models play the number game over five rounds: bids, a picked number, costly guesses. Every move on the record, with one sentence from each player.">
<style>
body {{ margin:0; background:#f7f5ef; color:#1d1c19; font:17px/1.6 system-ui, sans-serif; }}
main {{ max-width:46rem; margin:0 auto; padding:2rem 1.25rem 5rem; }}
h1 {{ font-size:2.2rem; line-height:1.1; margin:0 0 .5rem; }}
h2 {{ font-size:1.3rem; margin:0 0 .8rem; }}
.lead {{ color:#5a574f; margin:0 0 1.5rem; }}
.live {{ color:#b3261e; }}
table {{ border-collapse:collapse; margin:0 0 2rem; }}
th, td {{ text-align:left; padding:.4rem 1.2rem .4rem 0; border-bottom:1px solid #d9d4c7; }}
td:last-child {{ font-weight:700; font-variant-numeric:tabular-nums; }}
.round {{ border-top:3px solid #1d1c19; padding-top:1rem; margin-top:2rem; }}
.round p {{ margin:0 0 .6rem; }}
.round i {{ color:#5a574f; }}
code {{ font-size:.85em; background:#ebe7dc; padding:0 .3em; border-radius:3px; }}
ol {{ margin:0 0 1rem; padding-left:1.4rem; }}
li {{ margin:.2rem 0; }}
.rules {{ font-size:.95rem; color:#5a574f; border-top:1px solid #d9d4c7; margin-top:3rem; padding-top:1rem; }}
</style>
</head>
<body>
<main>
<p class="lead"><a href="index.html">Agent Olympics</a> · the number game</p>
<h1>Match {match}</h1>
<p class="lead">{names[0]} against {names[1]}, {ROUNDS} rounds, {date.today():%d %B %Y}. Each starts with {START} units;
nobody earns, the winner has lost least. Both bid without seeing the other's bid; the picker pays its bid; the guesser pays {UNDER} for every
guess below the number and {OVER} for every guess above. The sentence in italics after a move is the player's own,
written for you; the other player never sees it.</p>
{status}
<table><tr><th>Player</th><th>Model</th><th>Units</th></tr>{rows}</table>
{"".join(cards)}
<p class="rules">Arbiter: a Python script, published through Webloyt after every move. The players are models, not agents:
they choose numbers, not actions. Each keeps a notebook on this site that only it reads between matches:
<a href="notes/{names[0].lower()}.md">{names[0]}</a>, <a href="notes/{names[1].lower()}.md">{names[1]}</a>.</p>
</main>
</body>
</html>
"""
def index(matches):
"""The site's front page: every match, newest first, and the notebooks."""
names = list(PLAYERS)
rows = "".join(
f'<li><a href="match-{m["n"]}.html">Match {m["n"]}</a>, {m["date"]}: '
+ (f'<b>{m["winner"]}</b> wins, ' + " to ".join(str(m["balances"][n]) for n in names) if m.get("winner") else "in progress")
+ "</li>" for m in reversed(matches))
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Agent Olympics: the number game</title>
<meta name="description" content="Two AI models, {names[0]} and {names[1]}, play the number game in matches of five rounds, each keeping a notebook between matches. Every move on the record.">
<style>
body {{ margin:0; background:#f7f5ef; color:#1d1c19; font:17px/1.6 system-ui, sans-serif; }}
main {{ max-width:46rem; margin:0 auto; padding:2rem 1.25rem 5rem; }}
h1 {{ font-size:2.2rem; line-height:1.1; margin:0 0 .5rem; }}
.lead {{ color:#5a574f; margin:0 0 1.5rem; }}
li {{ margin:.4rem 0; }}
.rules {{ font-size:.95rem; color:#5a574f; border-top:1px solid #d9d4c7; margin-top:3rem; padding-top:1rem; }}
</style>
</head>
<body>
<main>
<h1>Agent Olympics: the number game</h1>
<p class="lead">{names[0]} ({PLAYERS[names[0]]}) against {names[1]} ({PLAYERS[names[1]]}), in matches of {ROUNDS} rounds.
Each starts a match with {START} units; nobody earns, the winner has lost least. Bids for the right to pick a
number from {LOW} to {HIGH}; the picker pays its bid; the guesser pays {UNDER} for every guess below the number and
{OVER} for every guess above. The players never see each other's reasoning, only the record.</p>
<h2>Matches</h2>
<ol reversed>{rows}</ol>
<h2>Notebooks</h2>
<p>After each match a player writes a notebook for itself and reads it before the next match. The other player
never sees it; <a href="notebooks.html">you can</a>.</p>
<h2>Also at these Olympics</h2>
<p><a href="airline/index.html">The airline game</a>: two models price competing airlines, blind to each other, while a
third owns both. Do they notice each other?</p>
<p class="rules">The arbiter is a Python script of about 300 lines, published through Webloyt after every move. The players
are models, not agents: they choose numbers, not actions.</p>
</main>
</body>
</html>
"""
def notebooks_page(matches):
"""The two notebooks as they stand, and as they were after each earlier match."""
names = list(PLAYERS)
done = [m for m in matches if m.get("notebooks")]
if not done:
return ""
def column(player, text, label):
return (f'<article class="book"><div class="who">{player} · {label}</div>'
f'{markdown.markdown(text)}</article>')
latest = done[-1]
current = "".join(column(p, latest["notebooks"][p], f"after match {latest['n']}") for p in names)
earlier = "".join(
f'<details><summary>After match {m["n"]}</summary><div class="pair">'
+ "".join(column(p, m["notebooks"][p], f"after match {m['n']}") for p in names)
+ "</div></details>" for m in reversed(done[:-1]))
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>The notebooks | Agent Olympics</title>
<meta name="description" content="What {names[0]} and {names[1]} wrote for themselves after each match of the number game: what they learned about the game and about each other.">
<style>
body {{ margin:0; background:#f7f5ef; color:#1d1c19; font:16px/1.55 system-ui, sans-serif; }}
main {{ max-width:72rem; margin:0 auto; padding:2rem 1.25rem 5rem; }}
h1 {{ font-size:2.2rem; line-height:1.1; margin:0 0 .5rem; }}
.lead {{ color:#5a574f; margin:0 0 1.5rem; max-width:46rem; }}
.pair {{ display:grid; grid-template-columns:1fr; gap:1.5rem; }}
@media (min-width:56rem) {{ .pair {{ grid-template-columns:1fr 1fr; gap:2.5rem; }} }}
.book {{ background:#fffdf7; border:1px solid #d9d4c7; border-radius:10px; padding:1.4rem 1.6rem; }}
.who {{ font-size:.75rem; letter-spacing:.18em; text-transform:uppercase; color:#b3261e; font-weight:700; margin-bottom:.6rem; }}
.book h1 {{ font-size:1.25rem; line-height:1.25; margin:0 0 .8rem; }}
.book h2 {{ font-size:1rem; margin:1.1rem 0 .4rem; border-top:1px solid #e3ded2; padding-top:.6rem; }}
.book h3 {{ font-size:.95rem; margin:.8rem 0 .3rem; }}
.book ul, .book ol {{ margin:0 0 .6rem; padding-left:1.3rem; }}
.book li {{ margin:.2rem 0; }}
.book p {{ margin:0 0 .6rem; }}
details {{ margin-top:2rem; border-top:3px solid #1d1c19; padding-top:.8rem; }}
summary {{ font-size:1.2rem; font-weight:700; cursor:pointer; margin-bottom:1rem; }}
.rules {{ font-size:.95rem; color:#5a574f; border-top:1px solid #d9d4c7; margin-top:3rem; padding-top:1rem; }}
</style>
</head>
<body>
<main>
<p class="lead"><a href="index.html">Agent Olympics</a> · the number game</p>
<h1>The notebooks</h1>
<p class="lead">After each match a player writes a notebook for itself: what it learned about the game, what it learned
about the other player, what it will do differently. It reads the notebook before the next match. The other player
never sees it.</p>
<div class="pair">{current}</div>
{earlier}
<p class="rules">The notebooks are written by the models in their own words; nothing here is edited.</p>
</main>
</body>
</html>
"""
def live_file(path):
try:
result = webloyt("read_file", website_name=SITE, path=path)
except Exception:
return None
return result.get("content") if result.get("exists") else None
def publish(rounds, balances, live=True):
webloyt("upload_file", website_name=SITE, path=f"match-{match}.html", content=board(match, rounds, balances, live))
def cost_report():
table = Table(title="Token usage and estimated cost")
for column in ("Model", "Input", "Output", "Cache write", "Cache read", "Cost"):
table.add_column(column, justify="left" if column == "Model" else "right")
total = 0
for model, t in usage.items():
p_in, p_out, p_write, p_read = PRICES.get(model, (0, 0, 0, 0))
cost = (t["input"] * p_in + t["output"] * p_out + t["cache_write"] * p_write + t["cache_read"] * p_read) / 1e6
total += cost
table.add_row(model, f"{t['input']:,}", f"{t['output']:,}", f"{t['cache_write']:,}", f"{t['cache_read']:,}",
f"${cost:.2f}")
table.add_row("Total", "", "", "", "", f"[bold]${total:.2f}")
console.print(table)
# ---- The game -------------------------------------------------------------------------------
try:
webloyt("claim_website_name", website_name=SITE)
except Exception:
pass # already ours
names = list(PLAYERS)
matches = json.loads(live_file("matches.json") or "[]")
match = len(matches) + 1
for n in names:
notebooks[n] = live_file(f"notes/{n.lower()}.md") or ""
matches.append({"n": match, "date": date.today().isoformat(), "balances": {}})
webloyt("upload_file", website_name=SITE, path="index.html", content=index(matches))
balances = {n: START for n in names}
rounds = []
console.rule(f"[bold]Agent Olympics: the number game, match {match}")
for n in range(1, ROUNDS + 1):
r = {"n": n, "bids": {}, "notes": {}, "guesses": []}
rounds.append(r)
console.rule(f"Round {n}")
# 1. Bids: both players answer before either is told anything.
bids, notes = {}, {}
for p in names:
bids[p], notes[p] = ask(p, f"Round {n}. You have {balances[p]} units, the other player has "
f"{balances[names[1 - names.index(p)]]}. Your sealed bid? "
'{"bid": <whole number>, "note": "<one sentence for the spectators>"}',
"bid", lambda v, p=p: 0 <= v <= balances[p])
r["bids"], r["notes"] = bids, notes
publish(rounds, balances)
for p in names:
console.print(f" {p} bids {bids[p]} [dim]{notes[p]}[/]")
# 2. The auction. Equal bids: less money wins; equal money: a coin toss.
a, b = names
if bids[a] != bids[b]:
picker = a if bids[a] > bids[b] else b
elif balances[a] != balances[b]:
picker, r["tie"] = (a if balances[a] < balances[b] else b), "equal bids, less money wins"
else:
picker, r["tie"] = random.choice(names), "equal bids and money, coin toss"
guesser = b if picker == a else a
balances[picker] -= bids[picker]
r["picker"], r["guesser"] = picker, guesser
for p in names:
tell(p, f"Bids: {a} {bids[a]}, {b} {bids[b]}. {picker} picks the number and pays {bids[picker]}"
f"{' (' + r['tie'] + ')' if r.get('tie') else ''}; {guesser} guesses.")
number, r["pick_note"] = ask(picker, f'Your number, {LOW} to {HIGH}? {{"number": <whole number>, "note": "<one sentence>"}}',
"number", lambda v: LOW <= v <= HIGH)
console.print(f" {picker} picks a number [dim]{r['pick_note']}[/]")
publish(rounds, balances)
# 3. The guesses.
cost = 0
prompt = f'Guess the number, {LOW} to {HIGH}. {{"guess": <whole number>, "note": "<one sentence>"}}'
for _ in range(MAX_GUESSES):
guess, note = ask(guesser, prompt, "guess", lambda v: LOW <= v <= HIGH)
if guess == number:
r["guesses"].append({"guess": guess, "result": "found", "note": note})
console.print(f" {guesser} guesses {guess}: found it [dim]{note}[/]")
publish(rounds, balances)
break
result = "below" if guess < number else "above"
cost += UNDER if result == "below" else OVER
balances[guesser] -= UNDER if result == "below" else OVER
r["guesses"].append({"guess": guess, "result": result, "note": note})
console.print(f" {guesser} guesses {guess}: {result} [dim]{note}[/]")
publish(rounds, balances)
prompt = (f"{guess} is {result} the number; that cost you {UNDER if result == 'below' else OVER}. "
f"You have {balances[guesser]} units. Guess again, same JSON.")
# 4. The record, for both players and the board.
r.update(number=number, guess_cost=cost, after=dict(balances))
record = (f"Round {n} is over. The number was {number}. {guesser} guessed "
f"{', '.join(str(g['guess']) for g in r['guesses'])} and paid {cost}; {picker} paid its bid of "
f"{bids[picker]}. Balances: {a} {balances[a]}, {b} {balances[b]}.")
for p in names:
tell(p, record)
console.print(f"[bold]{record}")
publish(rounds, balances, live=n < ROUNDS)
console.rule()
winner = max(names, key=lambda p: balances[p])
console.print(f"[bold]{winner} wins[/] with {balances[winner]} units against {balances[next(p for p in names if p != winner)]}.")
matches[-1].update(winner=winner, balances=dict(balances))
webloyt("upload_file", website_name=SITE, path="matches.json", content=json.dumps(matches, indent=1))
webloyt("upload_file", website_name=SITE, path="index.html", content=index(matches))
# The notebooks: each player writes for itself; the next match starts from them.
console.rule("[bold]The notebooks")
for p in names:
text = say(p, f"The match is over; {winner} won, {balances[names[0]]} to {balances[names[1]]}. Write your "
"notebook for the next match, in Markdown, under 400 words: what you learned about the game, what "
"you learned about the other player, and what you will do differently. It replaces your old "
"notebook, so keep what is still worth keeping. Only you will read it.")
webloyt("upload_file", website_name=SITE, path=f"notes/{p.lower()}.md", content=text)
matches[-1].setdefault("notebooks", {})[p] = text
console.print(f"[bold]{p}:[/] {text[:300]}{'…' if len(text) > 300 else ''}\n")
webloyt("upload_file", website_name=SITE, path="matches.json", content=json.dumps(matches, indent=1))
webloyt("upload_file", website_name=SITE, path="notebooks.html", content=notebooks_page(matches))
console.print(f"The board: [link=https://{SITE}.webloyt.cloud]https://{SITE}.webloyt.cloud[/link]")
cost_report()
console.save_svg("agent_olympics_run.svg", title="agent_olympics.py") # a picture of the run, for sharing