From 63a36da2f3720c4a59b5c9dbdfec72f2a8f53b1f Mon Sep 17 00:00:00 2001 From: Henrik Jess Nielsen Date: Thu, 29 Oct 2026 21:54:01 +0100 Subject: [PATCH] feat(score): add Claude CLI backend via subscription token Replace the direct Anthropic API call in score.py with a pluggable backend (BLAAAI_BACKEND=cli|api, default cli). The CLI path shells out to `claude -p` authed by CLAUDE_CODE_OAUTH_TOKEN, so scoring counts against the Claude subscription instead of API billing. - _call_cli forces a tool-free, JSON-only role (--append-system-prompt, --disallowed-tools) and retries the intermittently-failing `claude -p` - lower default concurrency (3) since each call spawns a heavy Node process - metrics use the CLI's reported total_cost_usd and full token load - batch failures no longer crash the whole scoring run - remove the hardcoded live ANTHROPIC_API_KEY fallback (rotate it in console) - Dockerfile installs Node + @anthropic-ai/claude-code - Nomad injects CLAUDE_CODE_OAUTH_TOKEN via Consul, bumps memory for Node --- Dockerfile | 10 ++++ blaaai.nomad | 11 +++-- score.py | 133 ++++++++++++++++++++++++++++++++++++++++----------- 3 files changed, 124 insertions(+), 30 deletions(-) diff --git a/Dockerfile b/Dockerfile index 3c3800a..2bf6a19 100644 --- a/Dockerfile +++ b/Dockerfile @@ -22,6 +22,16 @@ RUN pip install --no-cache-dir -r requirements.txt # Install Playwright browsers RUN playwright install chromium && playwright install-deps chromium +# Install Node + the Claude CLI (used by the default BLAAAI_BACKEND=cli scoring path) +RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \ + && apt-get install -y --no-install-recommends nodejs \ + && npm install -g @anthropic-ai/claude-code \ + && npm cache clean --force \ + && rm -rf /var/lib/apt/lists/* + +# Claude CLI needs a writable config dir; keep it on the mounted data volume +ENV CLAUDE_CONFIG_DIR=/app/data/.claude + COPY . . RUN mkdir -p data static templates diff --git a/blaaai.nomad b/blaaai.nomad index 229c9b6..d415717 100644 --- a/blaaai.nomad +++ b/blaaai.nomad @@ -102,11 +102,16 @@ job "blaaai" { } env { - PORT = "${NOMAD_PORT_http}" + PORT = "${NOMAD_PORT_http}" + BLAAAI_BACKEND = "cli" # score via the claude CLI (subscription), not API billing + BLAAAI_MAX_WORKERS = "2" # heavy Node procs — keep low within the memory budget } template { data = < float: return round(input_tokens * _PRICE_INPUT_PER_TOKEN + output_tokens * _PRICE_OUTPUT_PER_TOKEN, 6) -def update_metrics(search_id: str, input_tokens: int, output_tokens: int, listings_scored: int) -> None: - """Save per-search metrics and update global metrics.json.""" - cost = calc_cost(input_tokens, output_tokens) +def _call_api(client: "anthropic.Anthropic", prompt: str) -> tuple[str, int, int, float]: + """Direct Anthropic API call. Returns (text, input_tokens, output_tokens, cost_usd).""" + response = client.messages.create( + model=MODEL, + max_tokens=MAX_TOKENS, + temperature=0, + messages=[{"role": "user", "content": prompt}], + ) + inp = response.usage.input_tokens + out = response.usage.output_tokens + text = response.content[0].text.strip() + return text, inp, out, calc_cost(inp, out) + + +def _call_cli(prompt: str) -> tuple[str, int, int, float]: + """Call the `claude` CLI in print mode. Returns (text, input_tokens, output_tokens, cost_usd). + + Prompt is piped via stdin (no argv length limit). The CLI is forced into a + tool-free, JSON-only role so it behaves like an inference endpoint. `claude -p` + fails intermittently (empty exit-1), so retry a few times — batches are idempotent. + """ + cmd = [ + "claude", "-p", + "--output-format", "json", + "--model", MODEL, + "--append-system-prompt", CLI_SYSTEM, + "--max-turns", str(CLI_MAX_TURNS), + "--disallowed-tools", "Bash,Edit,Write,Read,WebSearch,WebFetch", + ] + last_err = "" + for attempt in range(CLI_RETRIES): + proc = subprocess.run(cmd, input=prompt, capture_output=True, text=True, timeout=CLI_TIMEOUT) + if proc.returncode != 0 or not proc.stdout.strip(): + last_err = f"exit {proc.returncode}: {(proc.stderr or proc.stdout)[:300]}" + continue + data = json.loads(proc.stdout) + if data.get("is_error"): + last_err = f"is_error: {str(data.get('result'))[:300]}" + continue + break + else: + raise RuntimeError(f"claude cli failed after {CLI_RETRIES} attempts — {last_err}") + u = data.get("usage", {}) or {} + # Cache tokens dominate the CLI's load — count them so metrics reflect reality. + inp = (u.get("input_tokens", 0) + + u.get("cache_creation_input_tokens", 0) + + u.get("cache_read_input_tokens", 0)) + out = u.get("output_tokens", 0) + cost = data.get("total_cost_usd") or 0.0 + return str(data.get("result", "")).strip(), inp, out, cost + + +def update_metrics(search_id: str, input_tokens: int, output_tokens: int, + listings_scored: int, cost: float | None = None) -> None: + """Save per-search metrics and update global metrics.json. + + `cost` lets the caller pass the backend's real cost (the CLI reports + total_cost_usd); when None we fall back to API pricing via calc_cost(). + """ + if cost is None: + cost = calc_cost(input_tokens, output_tokens) now = datetime.now().isoformat(timespec="seconds") # Per-search metrics @@ -355,7 +430,7 @@ def score_listings( source_file: Path | None = None, ) -> list[dict]: """Score listings with AI — skips items that are already cached. Runs batches in parallel.""" - client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY", API_KEY)) + client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) if BACKEND == "api" else None category = detect_category(items) phash = prefs_hash(prefs) @@ -399,35 +474,36 @@ def score_listings( batches = [to_score[i:i + batch_size] for i in range(0, len(to_score), batch_size)] print(f" ({len(batches)} parallelle batches à max {batch_size})", file=sys.stderr) - def score_batch(b_idx: int, batch: list[dict]) -> tuple[dict[str, dict], int, int]: + def score_batch(b_idx: int, batch: list[dict]) -> tuple[dict[str, dict], int, int, float]: prompt = build_prompt(batch, category, criteria, prefs) - response = client.messages.create( - model=MODEL, - max_tokens=MAX_TOKENS, - temperature=0, - messages=[{"role": "user", "content": prompt}], - ) - inp = response.usage.input_tokens - out = response.usage.output_tokens - text = response.content[0].text.strip() + try: + if BACKEND == "api": + text, inp, out, cost = _call_api(client, prompt) + else: + text, inp, out, cost = _call_cli(prompt) + except Exception as e: + print(f" ⚠ Batch {b_idx + 1} fejlede ({BACKEND}): {str(e)[:200]}", file=sys.stderr) + return {}, 0, 0, 0.0 json_m = re.search(r"\[.*\]", text, re.DOTALL) if not json_m: print(f" ⚠ Kunne ikke parse svar fra batch {b_idx + 1}:\n{text[:300]}", file=sys.stderr) - return {}, inp, out + return {}, inp, out, cost result = {} for s in json.loads(json_m.group(0)): result[str(s["id"])] = s print(f" ✓ Batch {b_idx + 1}/{len(batches)} færdig ({len(result)} scores, {inp}+{out} tok)", file=sys.stderr) - return result, inp, out + return result, inp, out, cost total_input = total_output = 0 - with ThreadPoolExecutor(max_workers=min(len(batches), 8)) as pool: + total_cost = 0.0 + with ThreadPoolExecutor(max_workers=min(len(batches), MAX_WORKERS)) as pool: futures = {pool.submit(score_batch, i, b): i for i, b in enumerate(batches)} for future in as_completed(futures): - scores, inp, out = future.result() + scores, inp, out, cost = future.result() all_scores.update(scores) total_input += inp total_output += out + total_cost += cost # Write scores + cache metadata back onto items now = datetime.now().isoformat(timespec="seconds") @@ -455,9 +531,8 @@ def score_listings( source_file.write_text(json.dumps(list(all_items_map.values()), ensure_ascii=False, indent=2)) scored_count = sum(1 for i in to_score if i.get("ai_score") is not None) print(f" 💾 {scored_count} nye scores gemt → {source_file}", file=sys.stderr) - cost = calc_cost(total_input, total_output) - print(f" 💰 {total_input}+{total_output} tokens → ${cost:.4f}", file=sys.stderr) - update_metrics(source_file.parent.name, total_input, total_output, scored_count) + print(f" 💰 {total_input}+{total_output} tokens → ${total_cost:.4f} ({BACKEND})", file=sys.stderr) + update_metrics(source_file.parent.name, total_input, total_output, scored_count, cost=total_cost) # ── Combine, re-sort, re-rank ───────────────────────────────────────────── combined = [i for i in (cached + to_score) if i.get("ai_score") is not None] @@ -510,8 +585,12 @@ CRITERIA = { def main() -> None: - if "ANTHROPIC_API_KEY" not in os.environ and not API_KEY: - print("Fejl: ANTHROPIC_API_KEY er ikke sat.", file=sys.stderr) + if BACKEND == "api": + if "ANTHROPIC_API_KEY" not in os.environ: + print("Fejl: ANTHROPIC_API_KEY er ikke sat (BLAAAI_BACKEND=api).", file=sys.stderr) + sys.exit(1) + elif shutil.which("claude") is None: + print("Fejl: `claude` CLI blev ikke fundet på PATH (BLAAAI_BACKEND=cli).", file=sys.stderr) sys.exit(1) # Parse args properly — handles both --top 3 and --top=3