ed-donner commited on
Commit
9cfaeb6
Β·
1 Parent(s): 5880d30

Updated CLAUDE.md

Browse files
Files changed (1) hide show
  1. CLAUDE.md +24 -9
CLAUDE.md CHANGED
@@ -9,9 +9,13 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
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
  ## Required env (.env at project root)
13
 
14
- - Provider keys: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENROUTER_API_KEY` (for anything routed via OpenRouter, e.g. `moonshotai/kimi-k2.6`).
15
  - `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`.
16
  - `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.
17
 
@@ -21,15 +25,17 @@ Single-process Gradio app where two LLMs play Connect 4 against each other. The
21
 
22
  - `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`.
23
  - `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`.
24
- - `arena/board.py::Board` is pure game logic plus multiple render formats (`__repr__`, `html`, `svg` via `board_view.py`, `json`, `alternative`). The JSON and `alternative` ASCII forms are both sent to the LLM in the same prompt so the model sees the position two ways.
25
  - `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.
26
- - `arena/llm.py::LLM` wraps **LiteLLM** (`litellm.completion`). One code path for OpenAI, Anthropic, and OpenRouter, selected by the model-name prefix each subclass attaches (`anthropic/claude-...`, `openrouter/moonshotai/...`, or plain `gpt-...`). Returns parsed Pydantic instances.
27
 
28
  ### LLM layer (LiteLLM)
29
 
30
  - `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.
31
  - **OpenAI path** (`LLM._send`, inherited by `GPT`): non-streaming, no `max_tokens`, just `response_format=schema_cls`.
32
- - **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 has no Anthropic-style timeout, so streaming is unnecessary even though kimi calls can take a couple of minutes.
 
 
33
  - **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`).
34
  - **Opus-4.7-only kwargs** (`Claude._is_opus_4_7()` gate):
35
  - `thinking={"type": "adaptive"}` β€” adaptive extended reasoning.
@@ -39,11 +45,20 @@ Single-process Gradio app where two LLMs play Connect 4 against each other. The
39
 
40
  ### Adding a model
41
 
42
- 1. Add the display name to the appropriate `model_names` list on `GPT`, `Claude`, 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.
43
- 2. `Claude.api_model_name()` auto-prefixes with `anthropic/`; `OpenRouter.api_model_name()` auto-prefixes with `openrouter/`; `GPT` needs no prefix. For a brand-new provider, add a subclass with its own prefix override.
44
- 3. 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.
45
- 4. No other registration step β€” `ALL_MODEL_NAMES` in `c4.py` is computed at import time from `LLM.all_model_names()`.
 
46
 
47
  ### Leaderboard / ELO
48
 
49
- `arena/record.py` computes ELO on the fly from the full game history every time the Leaderboard tab is selected (K=32, default 1000, self-play excluded). There is no cached ratings table. `Game.get_ratings()` then filters to models currently registered in `LLM.all_supported_model_names()`, so retired model names disappear from the leaderboard even though their games remain in the DB.
 
 
 
 
 
 
 
 
 
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
 
 
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.
 
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.