FarmHouse: run Python-only on a local LLM; simulator plays real games

Starts from upstream 54cc5e9. Cards reach the simulator with type and text (filled from the Scryfall bulk DB) and the right quantities; the LLM engine asks several questions per turn and with reasoning off; Moxfield and Archidekt deck links work in every import and card names resolve locally; deck builds are fitted to the commander's colour identity; Scryfall format/User-Agent/429 handling fixed; coach init fixed. See FARMHOUSE-CHANGES.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016Er49soaMyG7Yburq57PeB
This commit is contained in:
fez5587andClaude Sonnet 5.5 committed 2026-10-26 16:42:58 -05:00
1 parent 54cc5e9b2e
commit fee8ded52d
26 files changed
+866 -28

No files matched your search

@@ -23,8 +23,9 @@ from openai import OpenAI
logger = logging.getLogger(__name__)
# Ollama exposes an OpenAI-compatible endpoint
DEFAULT_BASE_URL = "http://localhost:11434/v1"
DEFAULT_MODEL = "qwen2.5:7b"
import os as _farmhouse_os # FARMHOUSE_LLM_ENV_V1
DEFAULT_BASE_URL = _farmhouse_os.environ.get("LLM_URL", "http://localhost:11434/v1")
DEFAULT_MODEL = _farmhouse_os.environ.get("LLM_MODEL", "qwen2.5:7b")
def _get_client(base_url: str = DEFAULT_BASE_URL) -> OpenAI:
@@ -118,6 +119,13 @@ def chat(
if json_mode:
kwargs["response_format"] = {"type": "json_object"}
# FARMHOUSE_LLM_KNOBS_V1
_fh_effort = _farmhouse_os.environ.get("LLM_REASONING", "").strip()
if _fh_effort:
kwargs["extra_body"] = {"reasoning_effort": _fh_effort}
_fh_cap = int(_farmhouse_os.environ.get("LLM_MAX_TOKENS", "0") or 0)
if _fh_cap:
kwargs["max_tokens"] = min(kwargs["max_tokens"], _fh_cap)
response = client.chat.completions.create(**kwargs)
return response.choices[0].message.content or ""
@@ -16,8 +16,26 @@ import requests
from ..core.models import CardEntry
BASE_URL = "https://api.scryfall.com"
_SF_HEADERS = {"User-Agent": "CommanderAILab/3.0 (self-hosted)", "Accept": "application/json"} # FARMHOUSE_SCRYFALL_HEADERS_V1
def _fh_request(method, url, **kw):
"""requests.<method> that backs off on Scryfall's 429 / 5xx, honouring Retry-After (a build makes hundreds of
calls; upstream had no retry, so one 429 anywhere ended it). Gives up after 5 tries and returns the last response."""
import time as _t
resp = None
for attempt in range(5):
resp = getattr(requests, method)(url, **kw)
if resp.status_code not in (429, 500, 502, 503, 504):
return resp
try:
wait = float(resp.headers.get("Retry-After", "") or 0)
except ValueError:
wait = 0.0
_t.sleep(max(wait, 2.0) + attempt * 2.0)
return resp
_last_request_time: float = 0.0
REQUEST_DELAY = 0.1 # 100ms between requests (Scryfall asks for 50-100ms)
REQUEST_DELAY = 0.25 # 250ms: upstream used 100ms (10/s, Scryfall's ceiling) and drew 429s when builds ran back to back
def _throttle() -> None:
@@ -32,7 +50,7 @@ def _throttle() -> None:
def _get(endpoint: str, params: Optional[Dict] = None) -> Dict:
"""Make a throttled GET request to Scryfall."""
_throttle()
resp = requests.get(f"{BASE_URL}{endpoint}", params=params, timeout=15)
resp = _fh_request("get", f"{BASE_URL}{endpoint}", params=params, headers=_SF_HEADERS, timeout=15)
resp.raise_for_status()
return resp.json()
@@ -113,7 +131,7 @@ def search_cards_by_identity(
if not next_url:
break
_throttle()
resp = requests.get(next_url, timeout=15)
resp = _fh_request("get", next_url, headers=_SF_HEADERS, timeout=15)
resp.raise_for_status()
data = resp.json()
@@ -168,9 +186,9 @@ def get_cards_by_names(names: List[str]) -> List[CardEntry]:
batch = names[i : i + 75]
identifiers = [{"name": n} for n in batch]
_throttle()
resp = requests.post(
f"{BASE_URL}/cards/collection",
json={"identifiers": identifiers},
resp = _fh_request(
"post", f"{BASE_URL}/cards/collection",
json={"identifiers": identifiers}, headers=_SF_HEADERS,
timeout=30,
)
resp.raise_for_status()
@@ -119,6 +119,9 @@ def validate_card_names(
# ---------------------------------------------------------------------------
from .farmhouse_fit import fit_deck as _farmhouse_fit_deck # FARMHOUSE_FIT_V1
def build_deck(request: BuildRequest) -> BuildResult:
"""
Execute the full 7-step deck build pipeline.
@@ -306,6 +309,7 @@ def build_deck(request: BuildRequest) -> BuildResult:
logger.warning(f"Ratio enforcement returned {total} cards")
# ── Step 7: Assemble final deck ────────────────────────────────────────
adjusted = _farmhouse_fit_deck(adjusted, target_ratios, commander_ci, warnings) # FARMHOUSE_FIT_V1b
logger.info("Step 7: Assembling final deck")
# Build a globally-deduplicated name list. enforce_deck_ratios can
@@ -0,0 +1,67 @@
"""Deterministic guards for the deck build, copied into the app by the Dockerfile (pipeline/farmhouse_fit.py).
Upstream's step 6 asks the LLM to trim the candidate pool to 99 cards by category and step 5 promises a colour-identity filter that
is not in the code. With a small local model that gave decks with an off-colour card (a red card in a four-colour deck) and, with
a larger one, 359 cards instead of 99; either made the app reject its own result ("Value error ... outside commander identity" /
"Deck must contain exactly 99 cards"). This does both jobs in plain code, using the Scryfall card database the app already keeps
(services.scryfall_bulk, 100,000+ cards): drop every card outside the commander's colour identity, drop duplicates, keep each
category to its target count (candidates arrive best-first: EDHREC, then Scryfall, then the model), and never exceed 99.
Anything the database does not know is kept, not dropped. The existing back-fill adds basic lands if the total is short.
"""
import json
import logging
logger = logging.getLogger(__name__)
def _identity_checker(allowed):
try:
from services.scryfall_bulk import get_bulk_db
conn = get_bulk_db()
except Exception as exc: # no database: do not guess, keep everything
logger.warning("farmhouse_fit: Scryfall card database unavailable (%s); colour identity not checked", exc)
return lambda name: True
def ok(name):
try:
row = conn.execute("SELECT color_identity FROM cards WHERE name = ? OR name LIKE ? LIMIT 1",
(name, name + " // %")).fetchone()
if not row:
return True
return set(json.loads(row[0] or "[]")) <= allowed
except Exception:
return True
return ok
def fit_deck(adjusted, target_ratios, commander_ci, warnings, total=99):
"""Return {category: [names]} that is colour-legal, duplicate-free, within each category's target, and at most `total` cards."""
allowed = set(commander_ci or [])
ok = _identity_checker(allowed)
out, seen, off_colour = {}, set(), []
for cat, names in adjusted.items():
keep = []
for name in names:
if name in seen:
continue
if not ok(name):
off_colour.append(name)
continue
seen.add(name)
keep.append(name)
limit = target_ratios.get(cat)
out[cat] = keep[:limit] if isinstance(limit, int) and limit >= 0 else keep
if off_colour:
warnings.append("Dropped %d card(s) outside the commander's colour identity: %s" % (len(off_colour), ", ".join(off_colour[:8])))
count = sum(len(v) for v in out.values())
if count > total:
# Over: trim from the tail of the largest category (the model's late picks), one card at a time.
excess = count - total
while excess > 0:
cat = max(out, key=lambda c: len(out[c]))
if not out[cat]:
break
out[cat].pop()
excess -= 1
warnings.append("Trimmed the candidate list from %d to %d cards." % (count, total))
return out
@@ -632,6 +632,8 @@ class DeepSeekBrain:
"top_p": self.config.top_p,
"stream": False,
}
if os.environ.get("LLM_REASONING"): # FARMHOUSE_BRAIN_REASONING
payload["reasoning_effort"] = os.environ["LLM_REASONING"]
url = self.config.api_base.rstrip("/") + "/v1/chat/completions"
req_data = json.dumps(payload).encode("utf-8")
+10 -1
View File
@@ -247,7 +247,16 @@ class DeepSeekGameEngine:
# DeepSeek-powered turn
# ──────────────────────────────────────────────────────────
def _play_turn_deepseek(
def _play_turn_deepseek( # FARMHOUSE_MULTISTEP
self, sim: SimState, pi: int, turn: int, events: list[str],
deck_context: dict | None = None,
) -> str:
from commander_ai_lab.sim import farmhouse_turns as _ft
if _ft.steps() <= 1:
return self._play_turn_deepseek_single(sim, pi, turn, events, deck_context)
return _ft.play_turn(self, sim, pi, turn, events, deck_context)
def _play_turn_deepseek_single(
self, sim: SimState, pi: int, turn: int, events: list[str],
deck_context: dict | None = None,
) -> str:
@@ -0,0 +1,66 @@
"""A DeepSeek-engine turn that asks the model more than once (copied to commander_ai_lab/sim/farmhouse_turns.py by the Dockerfile).
Upstream asked the model ONE question per turn and applied the answer as a single action, then filled in with a heuristic. That is
one model call per turn for a turn that really has several decisions (land, a spell, another spell, attack). This keeps asking, up
to BRAIN_STEPS times (default 4), re-reading the board after each action, and stops when the model attacks or holds, when an action
changes nothing (so it cannot loop), or at the limit. Whatever is left uses the engine's own heuristic exactly as before.
Everything it touches is an existing engine method, so the rules enforcement (one land a turn, mana, the two-spell cap per call) is
the engine's own.
"""
import os
CAST = ("cast_creature", "cast_removal", "cast_board_wipe", "cast_ramp", "cast_spell")
ATTACK = ("attack_all", "attack_safe")
def steps():
try:
return max(1, min(int(os.environ.get("BRAIN_STEPS", "4")), 8))
except ValueError:
return 4
def play_turn(engine, sim, pi, turn, events, deck_context=None):
"""Same contract as DeepSeekGameEngine._play_turn_deepseek: plays the turn, returns the ML action type of the first decision."""
p = sim.players[pi]
first_action = None
first_mana = engine._count_untapped_lands(sim, pi)
combat_done = False
for step in range(steps()):
mana = engine._count_untapped_lands(sim, pi)
decision = engine.brain.choose_action(sim, pi, turn, mana, deck_context=deck_context)
action = decision.get("action", "hold")
target = decision.get("target_card", "") or ""
if first_action is None:
first_action = action
if engine.record_log:
events.append("[AI Brain: %s] Step %d: %s%s (%s)" % (decision.get("source", "?"), step + 1, action,
(" → " + target) if target else "", decision.get("reasoning", "")))
if step == 0: # the land drop, as upstream always does
engine._play_land(sim, pi, target if action == "play_land" else None, events)
mana = engine._count_untapped_lands(sim, pi)
if action in CAST:
before = (len(p.hand), engine._count_untapped_lands(sim, pi))
engine._play_spells_targeted(sim, pi, mana, action, target, events)
if (len(p.hand), engine._count_untapped_lands(sim, pi)) == before:
break # nothing castable: stop asking, fall through to combat
continue
if action in ATTACK:
engine._resolve_combat_deepseek(sim, pi, turn, action, events)
combat_done = True
break
if action == "hold":
if engine.record_log:
events.append("Holds — no attack")
combat_done = True
break
# play_land or anything unknown: try a heuristic spell once, then combat
engine._play_spells_heuristic(sim, pi, engine._count_untapped_lands(sim, pi), events)
break
if not combat_done:
engine._resolve_combat_heuristic(sim, pi, turn, events)
return engine._map_action_to_ml_type(first_action or "hold", first_mana)