Before making harder
Browse files- .claude/scheduled_tasks.lock +0 -1
- AGENTS.md +64 -0
- CLAUDE.md +1 -64
- arena/llm.py +58 -16
- arena/player.py +6 -1
.claude/scheduled_tasks.lock
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
{"sessionId":"1ffc7076-1a4f-4a7e-bc52-a4306e3f7848","pid":26765,"acquiredAt":1776890608934}
|
|
|
|
|
|
AGENTS.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Connect Four Arena
|
| 2 |
+
|
| 3 |
+
This file provides guidance to Coding Agents when working with code in this repository.
|
| 4 |
+
|
| 5 |
+
## Commands
|
| 6 |
+
|
| 7 |
+
- Run the Gradio app locally: `python app.py` (entry point loads `.env`, builds the UI from `arena/c4.py`).
|
| 8 |
+
- Install deps: `pip install -r requirements.txt` (HuggingFace Spaces target; no `uv` / `pyproject.toml` here).
|
| 9 |
+
- No test suite or lint config is wired up. `black` is listed in requirements for manual formatting.
|
| 10 |
+
- `prototype.ipynb` is an exploratory notebook kept alongside the app; it is not part of the runtime path.
|
| 11 |
+
|
| 12 |
+
### Gradio version (pinned — do not "upgrade")
|
| 13 |
+
|
| 14 |
+
`requirements.txt` pins `gradio==5.15.0` deliberately, matching `sdk_version` in `README.md` (HF Spaces uses that value at deploy time). Gradio **6.x regresses the Leaderboard**: switching to the tab freezes the browser's main thread indefinitely after the SSE payload arrives — the `js=` parameter on `Blocks` also stops auto-calling the named function there. Pinning is the fix; do not bump it without a matching HF `sdk_version` bump *and* a live re-test of the Leaderboard tab.
|
| 15 |
+
|
| 16 |
+
## Required env (.env at project root)
|
| 17 |
+
|
| 18 |
+
- Provider keys: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENROUTER_API_KEY`, `GEMINI_API_KEY`, `XAI_API_KEY`. Only the keys corresponding to enabled models need to be present.
|
| 19 |
+
- `MONGO_URI` — optional. Without it, `arena/record.py` silently returns no history and does not persist games (the Leaderboard tab just shows empty tables). The DB name is `outsmart`, collection `connect`.
|
| 20 |
+
- `MODELS` — optional comma-separated allowlist. `LLM.all_model_names()` intersects this with the registered models to populate the dropdowns; useful for Spaces deployments that should expose a subset.
|
| 21 |
+
|
| 22 |
+
## Architecture
|
| 23 |
+
|
| 24 |
+
Single-process Gradio app where two LLMs play Connect 4 against each other. The layering is deliberate:
|
| 25 |
+
|
| 26 |
+
- `app.py` → `arena/c4.py::make_display` builds the Gradio `Blocks` and wires callbacks. All UI state is held in a single `gr.State` containing a `Game`.
|
| 27 |
+
- `arena/game.py::Game` owns a `Board` and two `Player`s keyed by color constant (`RED=1`, `YELLOW=-1`, see `arena/board.py`). `Game.record()` writes results via `arena/record.py`.
|
| 28 |
+
- `arena/board.py::Board` is pure game logic plus multiple render formats (`__repr__`, `html`, `svg` via `board_view.py`, `display`, `next_drops`). `display()` is a labelled ASCII grid with row numbers and an explicit "bottom (pieces stack upward)" marker; `next_drops()` is a single line listing which row each legal column's next piece lands on. These two are what's sent to the LLM — the older `json()`/`alternative()` dual representation was removed once per-token cost and diagonal blindness on small models drove a redesign.
|
| 29 |
+
- `arena/player.py::Player` owns the prompt templates. Builds a dynamic Pydantic `MoveSchema` per turn (`move_column: Literal[*legal_moves]`) so the structured output layer makes illegal columns unrepresentable. `process_move` receives a parsed schema instance; the only forfeit path is an exhausted-retry API failure.
|
| 30 |
+
- `arena/llm.py::LLM` wraps **LiteLLM** (`litellm.completion`). One code path for OpenAI, Anthropic, Gemini, xAI (Grok), and OpenRouter, selected by the model-name prefix each subclass attaches (`anthropic/claude-...`, `gemini/gemini-...`, `xai/grok-...`, `openrouter/moonshotai/...`, or plain `gpt-...`). Returns parsed Pydantic instances.
|
| 31 |
+
|
| 32 |
+
### LLM layer (LiteLLM)
|
| 33 |
+
|
| 34 |
+
- `send(system, user, schema_cls) -> BaseModel | None` is the single entry point. Internally calls `litellm.completion(..., response_format=schema_cls)` and retries up to 3 times; returns `None` only when retries are exhausted (the forfeit signal). The old JSON-substring extraction hack is gone — structured outputs either return valid JSON or raise.
|
| 35 |
+
- **OpenAI path** (`LLM._send`, inherited by `GPT`): non-streaming, no `max_tokens`, just `response_format=schema_cls`.
|
| 36 |
+
- **OpenRouter path** (`OpenRouter._send`): same as OpenAI shape plus `reasoning={"effort": "high"}` so reasoning models like `moonshotai/kimi-k2.6` run at max effort, not OpenRouter's default. Verified on the wire. Valid OpenRouter effort levels are `"low"`, `"medium"`, `"high"` — LiteLLM's param validator rejects `"xhigh"`/`"max"`, so do not reintroduce those. OpenRouter also rejects LiteLLM's unified `reasoning_effort=` param, which is why we use the `reasoning={...}` dict form instead. OpenRouter has no Anthropic-style timeout, so streaming is unnecessary even though some calls can take a couple of minutes.
|
| 37 |
+
- **Gemini path** (`Gemini._send`): uses LiteLLM's unified `reasoning_effort="high"` (which maps to Gemini 3+'s `thinking_level`), but *only* for non-Lite variants. Flash-Lite variants are non-reasoning by design and LiteLLM raises `UnsupportedParamsError` if `reasoning_effort` is passed — the class skips the kwarg when `"lite"` is in the model name. Temperature is left at Gemini's default (1.0); values < 1.0 can cause infinite loops per LiteLLM provider docs.
|
| 38 |
+
- **xAI Grok path** (`Grok._send`): inherits the default OpenAI-style `_send` with *no* reasoning param. Grok 4.20 rejects `reasoningEffort` on every variant including the `-reasoning` one (xAI's error message: "Model ... does not support parameter reasoningEffort."). The `-reasoning` variant reasons at its built-in level; the `-non-reasoning` variant doesn't.
|
| 39 |
+
- **Anthropic path** (`Claude._send`): always streams with `max_tokens=64_000` to avoid Anthropic's 10-min non-streaming timeout at high token ceilings. Chunks are rebuilt via `litellm.stream_chunk_builder`, then parsed by `_parse_message`, which handles both delivery shapes LiteLLM may use (`message.content` JSON or `message.tool_calls[0].function.arguments`).
|
| 40 |
+
- **Opus-4.7-only kwargs** (`Claude._is_opus_4_7()` gate):
|
| 41 |
+
- `thinking={"type": "adaptive"}` — adaptive extended reasoning.
|
| 42 |
+
- `output_config={"effort": "max"}` — **must-have** for Opus. Without this it runs at a weaker reasoning level and is unfairly disadvantaged on the leaderboard.
|
| 43 |
+
- These are Opus-4.7-only because on older Claude models (Opus 4.1, Sonnet 4.5, Haiku 4.5) LiteLLM falls back to forced tool-use to implement `response_format`, and Anthropic rejects any `thinking` combined with forced tool-use ("Thinking may not be enabled when tool_choice forces tool use"). Opus 4.7 uses a different internal path in LiteLLM (no `tool_choice` on the wire — confirmed via packet capture) and accepts the combination. Don't try to re-enable thinking on the older models without changing the structured-output path.
|
| 44 |
+
- **LiteLLM `output_config` monkey-patch** (top of `arena/llm.py`): LiteLLM's `AnthropicConfig._apply_output_config` hardcodes `effort='max'` as "Opus 4.6 only" (see `litellm/llms/anthropic/chat/transformation.py:1539`) and raises before the request leaves the process. We replace that method with a minimal version that forwards `output_config` as-is and lets the Anthropic API be the source of truth. This patch is load-bearing — if LiteLLM is upgraded, re-check that the method name, signature, and validation logic haven't changed, and that our patch still attaches correctly. Verify by capturing the outbound HTTPS body and confirming `output_config` is at the top level.
|
| 45 |
+
|
| 46 |
+
### Adding a model
|
| 47 |
+
|
| 48 |
+
1. Add the display name to the appropriate `model_names` list on `GPT`, `Claude`, `Gemini`, `Grok`, or `OpenRouter` in `arena/llm.py`. Display names may include a trailing space suffix for UI friendliness; `api_model_name()` strips it before the call.
|
| 49 |
+
2. Each subclass's `api_model_name()` auto-prefixes for LiteLLM: `anthropic/`, `gemini/`, `xai/`, `openrouter/`. `GPT` needs no prefix. For a brand-new provider, add a subclass with its own prefix override.
|
| 50 |
+
3. Use the provider's own model-listing endpoint to verify the exact model string rather than guessing — `https://generativelanguage.googleapis.com/v1beta/models` for Gemini, `https://api.x.ai/v1/models` for xAI. LiteLLM's provider docs lag behind; the provider's live model list is authoritative.
|
| 51 |
+
4. If adding another Opus-4.7-class model that also supports `thinking`+`output_config`, widen the `_is_opus_4_7()` check — but first re-verify with packet capture that LiteLLM doesn't inject `tool_choice` for that model, otherwise the thinking-vs-forced-tool-use conflict reappears.
|
| 52 |
+
5. No other registration step — `ALL_MODEL_NAMES` in `c4.py` is computed at import time from `LLM.all_model_names()`.
|
| 53 |
+
|
| 54 |
+
### Leaderboard / ELO
|
| 55 |
+
|
| 56 |
+
`arena/record.py` exposes three query helpers, all going through `_fetch_games(query, sort_direction, limit)`:
|
| 57 |
+
|
| 58 |
+
- `get_games(limit=20)` — used by the Recent games table. Sort-desc + limit + reverse so Python gets the newest-first window in chronological order. Capped because the Gradio Dataframe payload was large enough to cause visible client-side lag.
|
| 59 |
+
- `count_games()` — `collection.count_documents({})`, used to show the "Most recent 20 of N games played" label on the Recent games table. Server-side count, no row transfer.
|
| 60 |
+
- `get_supported_games(supported_models)` — `$in` filter pushed into the Mongo query so ELO only pulls games where *both* players are currently registered in `LLM.all_supported_model_names()`. Retired-model games stay in the DB for history but don't influence ratings.
|
| 61 |
+
|
| 62 |
+
ELO computation (K=32, default 1000, self-play excluded via `calculate_elo_ratings`'s `exclude_self_play=True`) runs on the filtered set only, which keeps the tab responsive even as total game history grows large (currently 9k+ rows, of which only ~100 involve current models).
|
| 63 |
+
|
| 64 |
+
If the query ever feels slow at the DB layer, a compound index on `(red_player, yellow_player)` would make the `$in` filter near-instant — that's a one-time `createIndex` against the `outsmart.connect` collection.
|
CLAUDE.md
CHANGED
|
@@ -1,64 +1 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
| 4 |
-
|
| 5 |
-
## Commands
|
| 6 |
-
|
| 7 |
-
- Run the Gradio app locally: `python app.py` (entry point loads `.env`, builds the UI from `arena/c4.py`).
|
| 8 |
-
- Install deps: `pip install -r requirements.txt` (HuggingFace Spaces target; no `uv` / `pyproject.toml` here).
|
| 9 |
-
- No test suite or lint config is wired up. `black` is listed in requirements for manual formatting.
|
| 10 |
-
- `prototype.ipynb` is an exploratory notebook kept alongside the app; it is not part of the runtime path.
|
| 11 |
-
|
| 12 |
-
### Gradio version (pinned — do not "upgrade")
|
| 13 |
-
|
| 14 |
-
`requirements.txt` pins `gradio==5.15.0` deliberately, matching `sdk_version` in `README.md` (HF Spaces uses that value at deploy time). Gradio **6.x regresses the Leaderboard**: switching to the tab freezes the browser's main thread indefinitely after the SSE payload arrives — the `js=` parameter on `Blocks` also stops auto-calling the named function there. Pinning is the fix; do not bump it without a matching HF `sdk_version` bump *and* a live re-test of the Leaderboard tab.
|
| 15 |
-
|
| 16 |
-
## Required env (.env at project root)
|
| 17 |
-
|
| 18 |
-
- Provider keys: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENROUTER_API_KEY`, `GEMINI_API_KEY`, `XAI_API_KEY`. Only the keys corresponding to enabled models need to be present.
|
| 19 |
-
- `MONGO_URI` — optional. Without it, `arena/record.py` silently returns no history and does not persist games (the Leaderboard tab just shows empty tables). The DB name is `outsmart`, collection `connect`.
|
| 20 |
-
- `MODELS` — optional comma-separated allowlist. `LLM.all_model_names()` intersects this with the registered models to populate the dropdowns; useful for Spaces deployments that should expose a subset.
|
| 21 |
-
|
| 22 |
-
## Architecture
|
| 23 |
-
|
| 24 |
-
Single-process Gradio app where two LLMs play Connect 4 against each other. The layering is deliberate:
|
| 25 |
-
|
| 26 |
-
- `app.py` → `arena/c4.py::make_display` builds the Gradio `Blocks` and wires callbacks. All UI state is held in a single `gr.State` containing a `Game`.
|
| 27 |
-
- `arena/game.py::Game` owns a `Board` and two `Player`s keyed by color constant (`RED=1`, `YELLOW=-1`, see `arena/board.py`). `Game.record()` writes results via `arena/record.py`.
|
| 28 |
-
- `arena/board.py::Board` is pure game logic plus multiple render formats (`__repr__`, `html`, `svg` via `board_view.py`, `display`, `next_drops`). `display()` is a labelled ASCII grid with row numbers and an explicit "bottom (pieces stack upward)" marker; `next_drops()` is a single line listing which row each legal column's next piece lands on. These two are what's sent to the LLM — the older `json()`/`alternative()` dual representation was removed once per-token cost and diagonal blindness on small models drove a redesign.
|
| 29 |
-
- `arena/player.py::Player` owns the prompt templates. Builds a dynamic Pydantic `MoveSchema` per turn (`move_column: Literal[*legal_moves]`) so the structured output layer makes illegal columns unrepresentable. `process_move` receives a parsed schema instance; the only forfeit path is an exhausted-retry API failure.
|
| 30 |
-
- `arena/llm.py::LLM` wraps **LiteLLM** (`litellm.completion`). One code path for OpenAI, Anthropic, Gemini, xAI (Grok), and OpenRouter, selected by the model-name prefix each subclass attaches (`anthropic/claude-...`, `gemini/gemini-...`, `xai/grok-...`, `openrouter/moonshotai/...`, or plain `gpt-...`). Returns parsed Pydantic instances.
|
| 31 |
-
|
| 32 |
-
### LLM layer (LiteLLM)
|
| 33 |
-
|
| 34 |
-
- `send(system, user, schema_cls) -> BaseModel | None` is the single entry point. Internally calls `litellm.completion(..., response_format=schema_cls)` and retries up to 3 times; returns `None` only when retries are exhausted (the forfeit signal). The old JSON-substring extraction hack is gone — structured outputs either return valid JSON or raise.
|
| 35 |
-
- **OpenAI path** (`LLM._send`, inherited by `GPT`): non-streaming, no `max_tokens`, just `response_format=schema_cls`.
|
| 36 |
-
- **OpenRouter path** (`OpenRouter._send`): same as OpenAI shape plus `reasoning={"effort": "high"}` so reasoning models like `moonshotai/kimi-k2.6` run at max effort, not OpenRouter's default. Verified on the wire. Valid OpenRouter effort levels are `"low"`, `"medium"`, `"high"` — LiteLLM's param validator rejects `"xhigh"`/`"max"`, so do not reintroduce those. OpenRouter also rejects LiteLLM's unified `reasoning_effort=` param, which is why we use the `reasoning={...}` dict form instead. OpenRouter has no Anthropic-style timeout, so streaming is unnecessary even though some calls can take a couple of minutes.
|
| 37 |
-
- **Gemini path** (`Gemini._send`): uses LiteLLM's unified `reasoning_effort="high"` (which maps to Gemini 3+'s `thinking_level`), but *only* for non-Lite variants. Flash-Lite variants are non-reasoning by design and LiteLLM raises `UnsupportedParamsError` if `reasoning_effort` is passed — the class skips the kwarg when `"lite"` is in the model name. Temperature is left at Gemini's default (1.0); values < 1.0 can cause infinite loops per LiteLLM provider docs.
|
| 38 |
-
- **xAI Grok path** (`Grok._send`): inherits the default OpenAI-style `_send` with *no* reasoning param. Grok 4.20 rejects `reasoningEffort` on every variant including the `-reasoning` one (xAI's error message: "Model ... does not support parameter reasoningEffort."). The `-reasoning` variant reasons at its built-in level; the `-non-reasoning` variant doesn't.
|
| 39 |
-
- **Anthropic path** (`Claude._send`): always streams with `max_tokens=64_000` to avoid Anthropic's 10-min non-streaming timeout at high token ceilings. Chunks are rebuilt via `litellm.stream_chunk_builder`, then parsed by `_parse_message`, which handles both delivery shapes LiteLLM may use (`message.content` JSON or `message.tool_calls[0].function.arguments`).
|
| 40 |
-
- **Opus-4.7-only kwargs** (`Claude._is_opus_4_7()` gate):
|
| 41 |
-
- `thinking={"type": "adaptive"}` — adaptive extended reasoning.
|
| 42 |
-
- `output_config={"effort": "max"}` — **must-have** for Opus. Without this it runs at a weaker reasoning level and is unfairly disadvantaged on the leaderboard.
|
| 43 |
-
- These are Opus-4.7-only because on older Claude models (Opus 4.1, Sonnet 4.5, Haiku 4.5) LiteLLM falls back to forced tool-use to implement `response_format`, and Anthropic rejects any `thinking` combined with forced tool-use ("Thinking may not be enabled when tool_choice forces tool use"). Opus 4.7 uses a different internal path in LiteLLM (no `tool_choice` on the wire — confirmed via packet capture) and accepts the combination. Don't try to re-enable thinking on the older models without changing the structured-output path.
|
| 44 |
-
- **LiteLLM `output_config` monkey-patch** (top of `arena/llm.py`): LiteLLM's `AnthropicConfig._apply_output_config` hardcodes `effort='max'` as "Opus 4.6 only" (see `litellm/llms/anthropic/chat/transformation.py:1539`) and raises before the request leaves the process. We replace that method with a minimal version that forwards `output_config` as-is and lets the Anthropic API be the source of truth. This patch is load-bearing — if LiteLLM is upgraded, re-check that the method name, signature, and validation logic haven't changed, and that our patch still attaches correctly. Verify by capturing the outbound HTTPS body and confirming `output_config` is at the top level.
|
| 45 |
-
|
| 46 |
-
### Adding a model
|
| 47 |
-
|
| 48 |
-
1. Add the display name to the appropriate `model_names` list on `GPT`, `Claude`, `Gemini`, `Grok`, or `OpenRouter` in `arena/llm.py`. Display names may include a trailing space suffix for UI friendliness; `api_model_name()` strips it before the call.
|
| 49 |
-
2. Each subclass's `api_model_name()` auto-prefixes for LiteLLM: `anthropic/`, `gemini/`, `xai/`, `openrouter/`. `GPT` needs no prefix. For a brand-new provider, add a subclass with its own prefix override.
|
| 50 |
-
3. Use the provider's own model-listing endpoint to verify the exact model string rather than guessing — `https://generativelanguage.googleapis.com/v1beta/models` for Gemini, `https://api.x.ai/v1/models` for xAI. LiteLLM's provider docs lag behind; the provider's live model list is authoritative.
|
| 51 |
-
4. If adding another Opus-4.7-class model that also supports `thinking`+`output_config`, widen the `_is_opus_4_7()` check — but first re-verify with packet capture that LiteLLM doesn't inject `tool_choice` for that model, otherwise the thinking-vs-forced-tool-use conflict reappears.
|
| 52 |
-
5. No other registration step — `ALL_MODEL_NAMES` in `c4.py` is computed at import time from `LLM.all_model_names()`.
|
| 53 |
-
|
| 54 |
-
### Leaderboard / ELO
|
| 55 |
-
|
| 56 |
-
`arena/record.py` exposes three query helpers, all going through `_fetch_games(query, sort_direction, limit)`:
|
| 57 |
-
|
| 58 |
-
- `get_games(limit=20)` — used by the Recent games table. Sort-desc + limit + reverse so Python gets the newest-first window in chronological order. Capped because the Gradio Dataframe payload was large enough to cause visible client-side lag.
|
| 59 |
-
- `count_games()` — `collection.count_documents({})`, used to show the "Most recent 20 of N games played" label on the Recent games table. Server-side count, no row transfer.
|
| 60 |
-
- `get_supported_games(supported_models)` — `$in` filter pushed into the Mongo query so ELO only pulls games where *both* players are currently registered in `LLM.all_supported_model_names()`. Retired-model games stay in the DB for history but don't influence ratings.
|
| 61 |
-
|
| 62 |
-
ELO computation (K=32, default 1000, self-play excluded via `calculate_elo_ratings`'s `exclude_self_play=True`) runs on the filtered set only, which keeps the tab responsive even as total game history grows large (currently 9k+ rows, of which only ~100 involve current models).
|
| 63 |
-
|
| 64 |
-
If the query ever feels slow at the DB layer, a compound index on `(red_player, yellow_player)` would make the `$in` filter near-instant — that's a one-time `createIndex` against the `outsmart.connect` collection.
|
|
|
|
| 1 |
+
@AGENTS.md
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
arena/llm.py
CHANGED
|
@@ -5,8 +5,9 @@ Single code path for OpenAI, Anthropic, Google (Gemini), xAI (Grok), and
|
|
| 5 |
OpenRouter. Structured outputs via a Pydantic schema passed through
|
| 6 |
`response_format`; LiteLLM implements this as tool-use under the hood for
|
| 7 |
providers that lack native JSON-schema support. Anthropic calls stream (to
|
| 8 |
-
dodge the 10-min non-streaming timeout at high max_tokens)
|
| 9 |
-
`thinking` + `output_config`
|
|
|
|
| 10 |
Gemini and Grok use LiteLLM's unified `reasoning_effort="high"` knob so they
|
| 11 |
also play at maximum reasoning.
|
| 12 |
"""
|
|
@@ -20,6 +21,7 @@ from typing import Dict, List, Self, Type
|
|
| 20 |
import litellm
|
| 21 |
from dotenv import load_dotenv
|
| 22 |
from litellm.llms.anthropic.chat.transformation import AnthropicConfig
|
|
|
|
| 23 |
from pydantic import BaseModel
|
| 24 |
|
| 25 |
load_dotenv(override=True)
|
|
@@ -40,7 +42,8 @@ AnthropicConfig._apply_output_config = _apply_output_config
|
|
| 40 |
|
| 41 |
logger = logging.getLogger(__name__)
|
| 42 |
|
| 43 |
-
ANTHROPIC_MAX_TOKENS =
|
|
|
|
| 44 |
RETRIES = 3
|
| 45 |
RETRY_DELAY_SECONDS = 2
|
| 46 |
|
|
@@ -118,23 +121,49 @@ class LLM(ABC):
|
|
| 118 |
|
| 119 |
|
| 120 |
class GPT(LLM):
|
| 121 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
-
model_names = ["gpt-5.4", "gpt-5.4-mini", "gpt-5.4-nano"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
|
| 126 |
class Claude(LLM):
|
| 127 |
"""
|
| 128 |
Anthropic models. Streams the response so we can set max_tokens high without
|
| 129 |
-
hitting the 10-min non-streaming timeout.
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
"""
|
| 136 |
|
| 137 |
model_names = [
|
|
|
|
| 138 |
"claude-opus-4-7",
|
| 139 |
"claude-sonnet-4-6",
|
| 140 |
"claude-haiku-4-5",
|
|
@@ -143,9 +172,15 @@ class Claude(LLM):
|
|
| 143 |
def api_model_name(self) -> str:
|
| 144 |
return f"anthropic/{super().api_model_name()}"
|
| 145 |
|
|
|
|
|
|
|
|
|
|
| 146 |
def _is_opus_4_7(self) -> bool:
|
| 147 |
return "opus-4-7" in self.api_model_name().lower()
|
| 148 |
|
|
|
|
|
|
|
|
|
|
| 149 |
def _send(self, system: str, user: str, schema_cls: Type[BaseModel]) -> BaseModel:
|
| 150 |
kwargs = dict(
|
| 151 |
model=self.api_model_name(),
|
|
@@ -153,13 +188,20 @@ class Claude(LLM):
|
|
| 153 |
{"role": "system", "content": system},
|
| 154 |
{"role": "user", "content": user},
|
| 155 |
],
|
| 156 |
-
|
| 157 |
-
max_tokens=ANTHROPIC_MAX_TOKENS,
|
| 158 |
stream=True,
|
| 159 |
)
|
| 160 |
-
if self.
|
| 161 |
-
|
| 162 |
-
kwargs["
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
stream = litellm.completion(**kwargs)
|
| 164 |
rebuilt = litellm.stream_chunk_builder(list(stream))
|
| 165 |
return _parse_message(rebuilt.choices[0].message, schema_cls)
|
|
|
|
| 5 |
OpenRouter. Structured outputs via a Pydantic schema passed through
|
| 6 |
`response_format`; LiteLLM implements this as tool-use under the hood for
|
| 7 |
providers that lack native JSON-schema support. Anthropic calls stream (to
|
| 8 |
+
dodge the 10-min non-streaming timeout at high max_tokens); Opus 4.7 carries
|
| 9 |
+
`thinking` + `output_config` and Fable 5 carries `output_format` +
|
| 10 |
+
`output_config` so both run at full reasoning strength (see Claude docstring).
|
| 11 |
Gemini and Grok use LiteLLM's unified `reasoning_effort="high"` knob so they
|
| 12 |
also play at maximum reasoning.
|
| 13 |
"""
|
|
|
|
| 21 |
import litellm
|
| 22 |
from dotenv import load_dotenv
|
| 23 |
from litellm.llms.anthropic.chat.transformation import AnthropicConfig
|
| 24 |
+
from litellm.utils import type_to_response_format_param
|
| 25 |
from pydantic import BaseModel
|
| 26 |
|
| 27 |
load_dotenv(override=True)
|
|
|
|
| 42 |
|
| 43 |
logger = logging.getLogger(__name__)
|
| 44 |
|
| 45 |
+
ANTHROPIC_MAX_TOKENS = 128_000
|
| 46 |
+
HAIKU_MAX_TOKENS = 64_000 # Haiku 4.5's output ceiling; the API rejects anything higher
|
| 47 |
RETRIES = 3
|
| 48 |
RETRY_DELAY_SECONDS = 2
|
| 49 |
|
|
|
|
| 121 |
|
| 122 |
|
| 123 |
class GPT(LLM):
|
| 124 |
+
"""
|
| 125 |
+
OpenAI gpt-5.x models. Sends `reasoning_effort="xhigh"` so models reason
|
| 126 |
+
at maximum strength rather than OpenAI's default level. The base `_send`
|
| 127 |
+
doesn't pass reasoning controls, so we override here.
|
| 128 |
+
"""
|
| 129 |
|
| 130 |
+
model_names = ["gpt-5.6-sol", "gpt-5.5", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-nano"]
|
| 131 |
+
|
| 132 |
+
def _send(self, system: str, user: str, schema_cls: Type[BaseModel]) -> BaseModel:
|
| 133 |
+
response = litellm.completion(
|
| 134 |
+
model=self.api_model_name(),
|
| 135 |
+
messages=[
|
| 136 |
+
{"role": "system", "content": system},
|
| 137 |
+
{"role": "user", "content": user},
|
| 138 |
+
],
|
| 139 |
+
response_format=schema_cls,
|
| 140 |
+
reasoning_effort="xhigh",
|
| 141 |
+
)
|
| 142 |
+
return _parse_message(response.choices[0].message, schema_cls)
|
| 143 |
|
| 144 |
|
| 145 |
class Claude(LLM):
|
| 146 |
"""
|
| 147 |
Anthropic models. Streams the response so we can set max_tokens high without
|
| 148 |
+
hitting the 10-min non-streaming timeout. Reasoning is controlled per model:
|
| 149 |
+
|
| 150 |
+
- Fable 5: thinking is always on and cannot be configured; effort is set via
|
| 151 |
+
`output_config={"effort": "xhigh"}`. LiteLLM's `reasoning_effort` param is
|
| 152 |
+
unusable here (its Anthropic mapping only knows models up to Opus 4.7), and
|
| 153 |
+
its `response_format` mapping falls back to forced tool use for models not
|
| 154 |
+
in its hardcoded allowlist — which Anthropic rejects when thinking is on.
|
| 155 |
+
So we bypass both: we build the native `output_format` json_schema payload
|
| 156 |
+
with LiteLLM's own mapper and pass it through directly (verified on the
|
| 157 |
+
wire: no tools/tool_choice, structured-outputs beta header auto-added).
|
| 158 |
+
- Opus 4.7: adaptive thinking + `output_config={"effort": "xhigh"}`. Its
|
| 159 |
+
`response_format` takes LiteLLM's native output_format path already.
|
| 160 |
+
- Sonnet 4.6, Haiku 4.5: no reasoning kwargs. LiteLLM implements their
|
| 161 |
+
`response_format` via forced tool use, and Anthropic rejects thinking
|
| 162 |
+
combined with forced tool_choice.
|
| 163 |
"""
|
| 164 |
|
| 165 |
model_names = [
|
| 166 |
+
"claude-fable-5",
|
| 167 |
"claude-opus-4-7",
|
| 168 |
"claude-sonnet-4-6",
|
| 169 |
"claude-haiku-4-5",
|
|
|
|
| 172 |
def api_model_name(self) -> str:
|
| 173 |
return f"anthropic/{super().api_model_name()}"
|
| 174 |
|
| 175 |
+
def _is_fable(self) -> bool:
|
| 176 |
+
return "fable" in self.api_model_name().lower()
|
| 177 |
+
|
| 178 |
def _is_opus_4_7(self) -> bool:
|
| 179 |
return "opus-4-7" in self.api_model_name().lower()
|
| 180 |
|
| 181 |
+
def _max_tokens(self) -> int:
|
| 182 |
+
return HAIKU_MAX_TOKENS if "haiku" in self.api_model_name().lower() else ANTHROPIC_MAX_TOKENS
|
| 183 |
+
|
| 184 |
def _send(self, system: str, user: str, schema_cls: Type[BaseModel]) -> BaseModel:
|
| 185 |
kwargs = dict(
|
| 186 |
model=self.api_model_name(),
|
|
|
|
| 188 |
{"role": "system", "content": system},
|
| 189 |
{"role": "user", "content": user},
|
| 190 |
],
|
| 191 |
+
max_tokens=self._max_tokens(),
|
|
|
|
| 192 |
stream=True,
|
| 193 |
)
|
| 194 |
+
if self._is_fable():
|
| 195 |
+
response_format = type_to_response_format_param(response_format=schema_cls)
|
| 196 |
+
kwargs["output_format"] = AnthropicConfig().map_response_format_to_anthropic_output_format(
|
| 197 |
+
response_format
|
| 198 |
+
)
|
| 199 |
+
kwargs["output_config"] = {"effort": "xhigh"}
|
| 200 |
+
else:
|
| 201 |
+
kwargs["response_format"] = schema_cls
|
| 202 |
+
if self._is_opus_4_7():
|
| 203 |
+
kwargs["thinking"] = {"type": "adaptive"}
|
| 204 |
+
kwargs["output_config"] = {"effort": "xhigh"}
|
| 205 |
stream = litellm.completion(**kwargs)
|
| 206 |
rebuilt = litellm.stream_chunk_builder(list(stream))
|
| 207 |
return _parse_message(rebuilt.choices[0].message, schema_cls)
|
arena/player.py
CHANGED
|
@@ -26,7 +26,12 @@ class Player:
|
|
| 26 |
Players take turns to drop counters into one of 7 columns A, B, C, D, E, F, G.
|
| 27 |
The winner is the first player to get 4 counters in a row in any direction (horizontal, vertical, or diagonal).
|
| 28 |
You are {pieces[self.color]} and your opponent is {pieces[self.color * -1]}.
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
def user(self, board) -> str:
|
| 32 |
return f"""It is your turn to make a move as {pieces[self.color]}.
|
|
|
|
| 26 |
Players take turns to drop counters into one of 7 columns A, B, C, D, E, F, G.
|
| 27 |
The winner is the first player to get 4 counters in a row in any direction (horizontal, vertical, or diagonal).
|
| 28 |
You are {pieces[self.color]} and your opponent is {pieces[self.color * -1]}.
|
| 29 |
+
|
| 30 |
+
Look first for a move that wins immediately, then for one that blocks an opponent's win next move; avoid any move that hands your opponent an immediate winning reply.
|
| 31 |
+
Beyond those, prefer moves that create double threats — two winning paths the opponent cannot block in a single turn.
|
| 32 |
+
Otherwise build central control and develop connections. When the right move is evident, commit; the strongest play is often the obvious one.
|
| 33 |
+
Avoid over-thinking. Do not reconsider moves multiple times. After considering opportunities, threats, and the overall position, pick your best move and stick to it.
|
| 34 |
+
"""
|
| 35 |
|
| 36 |
def user(self, board) -> str:
|
| 37 |
return f"""It is your turn to make a move as {pieces[self.color]}.
|