Compare commits
3 Commits
af84822641
...
fix/claude
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce9c968301 | ||
| db8b4d0406 | |||
|
|
63a36da2f3 |
10
Dockerfile
10
Dockerfile
@@ -22,6 +22,16 @@ RUN pip install --no-cache-dir -r requirements.txt
|
|||||||
# Install Playwright browsers
|
# Install Playwright browsers
|
||||||
RUN playwright install chromium && playwright install-deps chromium
|
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 . .
|
COPY . .
|
||||||
|
|
||||||
RUN mkdir -p data static templates
|
RUN mkdir -p data static templates
|
||||||
|
|||||||
11
blaaai.nomad
11
blaaai.nomad
@@ -102,11 +102,16 @@ job "blaaai" {
|
|||||||
}
|
}
|
||||||
|
|
||||||
env {
|
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 {
|
template {
|
||||||
data = <<EOT
|
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" }}
|
ANTHROPIC_API_KEY={{ key "blaaai/anthropic_api_key" }}
|
||||||
HARBOR_ROBOT_TOKEN={{ key "blaaai/harbor_robot_token" }}
|
HARBOR_ROBOT_TOKEN={{ key "blaaai/harbor_robot_token" }}
|
||||||
EOT
|
EOT
|
||||||
@@ -115,8 +120,8 @@ EOT
|
|||||||
}
|
}
|
||||||
|
|
||||||
resources {
|
resources {
|
||||||
cpu = 500
|
cpu = 1000
|
||||||
memory = 512
|
memory = 1024 # claude CLI (Node) + chromium need more headroom than the API client
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
133
score.py
133
score.py
@@ -13,20 +13,37 @@ Usage:
|
|||||||
Scores are cached in results_*.json — only new/unscored listings call Claude.
|
Scores are cached in results_*.json — only new/unscored listings call Claude.
|
||||||
Change --prefs to invalidate cache and re-score with new preferences.
|
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:
|
Requires:
|
||||||
ANTHROPIC_API_KEY env var
|
cli backend: `claude` on PATH + CLAUDE_CODE_OAUTH_TOKEN (or an interactive login)
|
||||||
pip install anthropic
|
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 concurrent.futures import ThreadPoolExecutor, as_completed
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import anthropic
|
import anthropic
|
||||||
|
|
||||||
MODEL = "claude-haiku-4-5-20251001" # fast + cheap; swap to sonnet for better ranking
|
MODEL = "claude-haiku-4-5-20251001" # fast + cheap; swap to sonnet for better ranking
|
||||||
API_KEY = "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"
|
|
||||||
MAX_TOKENS = 2048
|
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
|
BASE_DIR = Path(__file__).parent
|
||||||
DATA_DIR = BASE_DIR / "data"
|
DATA_DIR = BASE_DIR / "data"
|
||||||
SCORE_CACHE = BASE_DIR / "data" / "score_cache" # persistent cross-search score cache
|
SCORE_CACHE = BASE_DIR / "data" / "score_cache" # persistent cross-search score cache
|
||||||
@@ -42,9 +59,67 @@ 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)
|
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:
|
def _call_api(client: "anthropic.Anthropic", prompt: str) -> tuple[str, int, int, float]:
|
||||||
"""Save per-search metrics and update global metrics.json."""
|
"""Direct Anthropic API call. Returns (text, input_tokens, output_tokens, cost_usd)."""
|
||||||
cost = calc_cost(input_tokens, output_tokens)
|
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")
|
now = datetime.now().isoformat(timespec="seconds")
|
||||||
|
|
||||||
# Per-search metrics
|
# Per-search metrics
|
||||||
@@ -355,7 +430,7 @@ def score_listings(
|
|||||||
source_file: Path | None = None,
|
source_file: Path | None = None,
|
||||||
) -> list[dict]:
|
) -> list[dict]:
|
||||||
"""Score listings with AI — skips items that are already cached. Runs batches in parallel."""
|
"""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)
|
category = detect_category(items)
|
||||||
phash = prefs_hash(prefs)
|
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)]
|
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)
|
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)
|
prompt = build_prompt(batch, category, criteria, prefs)
|
||||||
response = client.messages.create(
|
try:
|
||||||
model=MODEL,
|
if BACKEND == "api":
|
||||||
max_tokens=MAX_TOKENS,
|
text, inp, out, cost = _call_api(client, prompt)
|
||||||
temperature=0,
|
else:
|
||||||
messages=[{"role": "user", "content": prompt}],
|
text, inp, out, cost = _call_cli(prompt)
|
||||||
)
|
except Exception as e:
|
||||||
inp = response.usage.input_tokens
|
print(f" ⚠ Batch {b_idx + 1} fejlede ({BACKEND}): {str(e)[:200]}", file=sys.stderr)
|
||||||
out = response.usage.output_tokens
|
return {}, 0, 0, 0.0
|
||||||
text = response.content[0].text.strip()
|
|
||||||
json_m = re.search(r"\[.*\]", text, re.DOTALL)
|
json_m = re.search(r"\[.*\]", text, re.DOTALL)
|
||||||
if not json_m:
|
if not json_m:
|
||||||
print(f" ⚠ Kunne ikke parse svar fra batch {b_idx + 1}:\n{text[:300]}", file=sys.stderr)
|
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 = {}
|
result = {}
|
||||||
for s in json.loads(json_m.group(0)):
|
for s in json.loads(json_m.group(0)):
|
||||||
result[str(s["id"])] = s
|
result[str(s["id"])] = s
|
||||||
print(f" ✓ Batch {b_idx + 1}/{len(batches)} færdig ({len(result)} scores, {inp}+{out} tok)", file=sys.stderr)
|
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
|
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)}
|
futures = {pool.submit(score_batch, i, b): i for i, b in enumerate(batches)}
|
||||||
for future in as_completed(futures):
|
for future in as_completed(futures):
|
||||||
scores, inp, out = future.result()
|
scores, inp, out, cost = future.result()
|
||||||
all_scores.update(scores)
|
all_scores.update(scores)
|
||||||
total_input += inp
|
total_input += inp
|
||||||
total_output += out
|
total_output += out
|
||||||
|
total_cost += cost
|
||||||
|
|
||||||
# Write scores + cache metadata back onto items
|
# Write scores + cache metadata back onto items
|
||||||
now = datetime.now().isoformat(timespec="seconds")
|
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))
|
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)
|
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)
|
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 → ${total_cost:.4f} ({BACKEND})", file=sys.stderr)
|
||||||
print(f" 💰 {total_input}+{total_output} tokens → ${cost:.4f}", file=sys.stderr)
|
update_metrics(source_file.parent.name, total_input, total_output, scored_count, cost=total_cost)
|
||||||
update_metrics(source_file.parent.name, total_input, total_output, scored_count)
|
|
||||||
|
|
||||||
# ── Combine, re-sort, re-rank ─────────────────────────────────────────────
|
# ── Combine, re-sort, re-rank ─────────────────────────────────────────────
|
||||||
combined = [i for i in (cached + to_score) if i.get("ai_score") is not None]
|
combined = [i for i in (cached + to_score) if i.get("ai_score") is not None]
|
||||||
@@ -510,8 +585,12 @@ CRITERIA = {
|
|||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
if "ANTHROPIC_API_KEY" not in os.environ and not API_KEY:
|
if BACKEND == "api":
|
||||||
print("Fejl: ANTHROPIC_API_KEY er ikke sat.", file=sys.stderr)
|
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)
|
sys.exit(1)
|
||||||
|
|
||||||
# Parse args properly — handles both --top 3 and --top=3
|
# Parse args properly — handles both --top 3 and --top=3
|
||||||
|
|||||||
Reference in New Issue
Block a user