7 Commits

Author SHA1 Message Date
Henrik Jess Nielsen
afa1c03d5a fix(deploy): lower CPU reservation back to 500 to fit autobox
autobox has ~580 MHz free; cpu=1000 could not be placed during rolling
replacement. CPU reservation is a scheduling floor (procs still burst on idle
cores), so 500 is enough for the batch scoring work. Memory stays at 1024.
2026-10-29 22:23:19 +01:00
d6806f386f Merge pull request 'fix(score): strip ANTHROPIC_API_KEY from CLI subprocess env' (#3) from fix/cli-oauth-env into main
Some checks failed
Build and Deploy BlaaAi / build-and-deploy (push) Has been cancelled
Reviewed-on: #3
2026-10-29 22:15:21 +01:00
Henrik Jess Nielsen
1171d965e8 fix(score): strip ANTHROPIC_API_KEY from CLI subprocess env
With ANTHROPIC_API_KEY also present in the environment, the claude CLI does
API-key auth and ignores CLAUDE_CODE_OAUTH_TOKEN, failing with 401 Invalid API
key when that key is invalid/out of credit. Strip it from the subprocess env so
the subscription token is used; the api backend still reads it from os.environ.
2026-10-29 22:12:24 +01:00
2925d86447 Merge pull request 'fix(deploy): match Consul key name for Claude auth token' (#2) from fix/claude-auth-consul-key into main
All checks were successful
Build and Deploy BlaaAi / build-and-deploy (push) Successful in 5m21s
Reviewed-on: #2
2026-10-29 22:01:47 +01:00
Henrik Jess Nielsen
ce9c968301 fix(deploy): match Consul key name for Claude auth token
The Nomad template read blaaai/claude_oauth_token but the token was stored
at blaaai/claude_auth_token, so CLAUDE_CODE_OAUTH_TOKEN rendered empty and
CLI auth failed in prod.
2026-10-29 22:00:43 +01:00
db8b4d0406 Merge pull request 'feat(score): add Claude CLI backend via subscription token' (#1) from feat/claude-cli-backend into main
Some checks failed
Build and Deploy BlaaAi / build-and-deploy (push) Has been cancelled
Reviewed-on: #1
2026-10-29 21:59:35 +01:00
Henrik Jess Nielsen
63a36da2f3 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
2026-10-29 21:54:01 +01:00
3 changed files with 130 additions and 30 deletions

View File

@@ -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

View File

@@ -103,10 +103,15 @@ job "blaaai" {
env {
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 = <<EOT
# Subscription auth for the claude CLI (generate with `claude setup-token`)
CLAUDE_CODE_OAUTH_TOKEN={{ key "blaaai/claude_auth_token" }}
# Kept for BLAAAI_BACKEND=api fallback
ANTHROPIC_API_KEY={{ key "blaaai/anthropic_api_key" }}
HARBOR_ROBOT_TOKEN={{ key "blaaai/harbor_robot_token" }}
EOT
@@ -115,8 +120,8 @@ EOT
}
resources {
cpu = 500
memory = 512
cpu = 500 # autobox CPU is nearly full; reservation is a floor, procs still burst
memory = 1024 # claude CLI (Node) + chromium need more headroom than the API client
}
}
}

137
score.py
View File

@@ -13,20 +13,37 @@ Usage:
Scores are cached in results_*.json — only new/unscored listings call Claude.
Change --prefs to invalidate cache and re-score with new preferences.
Backends (BLAAAI_BACKEND):
cli (default) — calls the `claude` CLI, authed via a subscription token
(CLAUDE_CODE_OAUTH_TOKEN / `claude setup-token`). Usage counts
against the Claude subscription, not API billing.
api — calls the Anthropic API directly (needs ANTHROPIC_API_KEY).
Requires:
ANTHROPIC_API_KEY env var
pip install anthropic
cli backend: `claude` on PATH + CLAUDE_CODE_OAUTH_TOKEN (or an interactive login)
api backend: ANTHROPIC_API_KEY env var + `pip install anthropic`
"""
import hashlib, json, os, re, sys, uuid as _uuid
import hashlib, json, os, re, shutil, subprocess, sys, uuid as _uuid
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from pathlib import Path
import anthropic
MODEL = "claude-haiku-4-5-20251001" # fast + cheap; swap to sonnet for better ranking
API_KEY = "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"
MAX_TOKENS = 2048
BACKEND = os.environ.get("BLAAAI_BACKEND", "cli").lower() # "cli" | "api"
MAX_WORKERS = int(os.environ.get("BLAAAI_MAX_WORKERS", "3")) # CLI spawns heavy Node procs — keep low
CLI_TIMEOUT = int(os.environ.get("BLAAAI_CLI_TIMEOUT", "180")) # seconds per claude call
CLI_MAX_TURNS = int(os.environ.get("BLAAAI_CLI_MAX_TURNS", "6")) # headroom; agent may take an internal turn
CLI_RETRIES = int(os.environ.get("BLAAAI_CLI_RETRIES", "3")) # claude -p fails intermittently
# The claude CLI is a coding agent; force it into a plain JSON-only endpoint role.
CLI_SYSTEM = (
"Du er et JSON-only endpoint. Svar UDELUKKENDE med det JSON-array der bedes om i "
"brugerbeskeden. Ingen forklaring, ingen markdown, ingen kodeblokke, ingen "
"spørgsmål, ingen værktøjer. Kun rå JSON."
)
BASE_DIR = Path(__file__).parent
DATA_DIR = BASE_DIR / "data"
SCORE_CACHE = BASE_DIR / "data" / "score_cache" # persistent cross-search score cache
@@ -42,8 +59,72 @@ def calc_cost(input_tokens: int, output_tokens: int) -> 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."""
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",
]
# ANTHROPIC_API_KEY in the env takes precedence over the OAuth token and makes
# the CLI do API-key auth (401 "Invalid API key"). Strip it so the subscription
# token is used; the api backend still sees it via os.environ.
cli_env = {k: v for k, v in os.environ.items() if k != "ANTHROPIC_API_KEY"}
last_err = ""
for attempt in range(CLI_RETRIES):
proc = subprocess.run(cmd, input=prompt, capture_output=True, text=True,
timeout=CLI_TIMEOUT, env=cli_env)
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")
@@ -355,7 +436,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 +480,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 +537,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 +591,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