The hub's own small model calls (action badges, short header titles, Send-later titles) leave the core for a plugin, on any model: - sidecar POST /complete (host only): one short answer, no transcript — a harness driver's optional complete() (claude / agy / opencode / pi), or the EVOX2 / OpenRouter over HTTP; wakeLocal:false never wakes the box or loads a model (asleep → fallback at once); fallback model/harness/account; usage returned in Anthropic's shape. - complete.run bridge (hub/complete): calls /complete, books the spend in the side-call ledger. conversations.label bridge: hub/labels/pending (look_pending.py), hub/labels/look (meta.lookAuto), hub/labels/short-title. - provides conversation.title (scheduled/title.py, short_title.py — no plugin: first words / no short title) and conversation.look. - removed: sidecar/title.py, sidecar/look.py, conversations/look_labeler.py and its thread; /api/look/pending rebuilt on look_pending. - docs/plugins.md, CLAUDE.md, sidecar README updated; tests: test_hubcomplete, test_complete, test_look, test_short_title. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
133 lines
5.3 KiB
Python
Executable File
133 lines
5.3 KiB
Python
Executable File
#!/usr/bin/env -S uv run --script
|
|
# /// script
|
|
# requires-python = ">=3.11"
|
|
# dependencies = ["anthropic"]
|
|
# ///
|
|
"""look-backfill — label past conversations' action badge through the
|
|
Message Batches API (Claude Haiku 5.5, half price), once.
|
|
|
|
New conversations are labelled live by the ``conversation-labels`` plugin
|
|
(any model through the host sidecar's ``/complete``, a work conversation on
|
|
its own seat). This is the one-off for the ones from before it
|
|
ran: it asks the hub what's still unlabelled (``GET /api/look/pending`` —
|
|
the user turns are built there, with the same system prompt), sends them as
|
|
one batch, waits, and records the answers (``POST /api/look/auto``).
|
|
|
|
Work conversations are left out by default (``--exclude work``): they are
|
|
labelled on the work seat by the plugin itself, so work prompts never go
|
|
through this (personal) API key.
|
|
|
|
ANTHROPIC_API_KEY=… scripts/look-backfill.py # last 7 days
|
|
scripts/look-backfill.py --days 30 --dry-run # just count
|
|
scripts/look-backfill.py --batch msgbatch_… # resume a batch
|
|
|
|
``AI_AGENT_URL`` (default http://127.0.0.1:8096) is the hub.
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import sys
|
|
import time
|
|
import urllib.request
|
|
|
|
import anthropic
|
|
|
|
MODEL = "claude-haiku-5-5"
|
|
HUB = os.environ.get("AI_AGENT_URL", "http://127.0.0.1:8096").rstrip("/")
|
|
# Batch price: half of Haiku 5.5's $0.10 / $0.50 per MTok.
|
|
PRICE_IN, PRICE_OUT = 0.05 / 1e6, 0.25 / 1e6
|
|
|
|
|
|
def hub(path: str, body: dict | None = None) -> dict:
|
|
req = urllib.request.Request(
|
|
HUB + path, method="POST" if body is not None else "GET",
|
|
data=json.dumps(body).encode() if body is not None else None,
|
|
headers={"Content-Type": "application/json", "Accept": "application/json"})
|
|
with urllib.request.urlopen(req, timeout=300) as r:
|
|
return json.loads(r.read())
|
|
|
|
|
|
def requests_for(pending: dict) -> tuple[list[dict], dict[str, str]]:
|
|
schema = {"type": "object",
|
|
"properties": {"action": {"type": "string", "enum": pending["actions"]}},
|
|
"required": ["action"], "additionalProperties": False}
|
|
ids, reqs = {}, []
|
|
for i, it in enumerate(pending["items"]):
|
|
cid = f"c{i}" # custom_id: [a-zA-Z0-9_-]{1,64}
|
|
ids[cid] = it["id"]
|
|
reqs.append({"custom_id": cid, "params": {
|
|
"model": MODEL,
|
|
# Haiku 5.5 thinks by default and thinking counts toward max_tokens.
|
|
"max_tokens": 1024,
|
|
"system": pending["system"],
|
|
"messages": [{"role": "user", "content": it["text"]}],
|
|
"output_config": {"effort": "low", "format": {"type": "json_schema",
|
|
"schema": schema}},
|
|
}})
|
|
return reqs, ids
|
|
|
|
|
|
def main() -> int:
|
|
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
ap.add_argument("--days", type=float, default=7)
|
|
ap.add_argument("--exclude", default="work", help="accounts left to the labeller")
|
|
ap.add_argument("--batch", help="resume: an existing batch id (needs --ids)")
|
|
ap.add_argument("--ids", help="the custom_id → session map a previous run saved")
|
|
ap.add_argument("--dry-run", action="store_true")
|
|
a = ap.parse_args()
|
|
|
|
client = anthropic.Anthropic()
|
|
if a.batch:
|
|
if not a.ids:
|
|
sys.exit("--batch needs --ids (printed when the batch was created)")
|
|
ids = json.load(open(a.ids))
|
|
batch_id = a.batch
|
|
else:
|
|
pending = hub(f"/api/look/pending?days={a.days}&exclude={a.exclude}")
|
|
reqs, ids = requests_for(pending)
|
|
print(f"{len(reqs)} conversations to label (last {a.days:g} days, "
|
|
f"excluding {a.exclude or 'nothing'})")
|
|
if a.dry_run or not reqs:
|
|
return 0
|
|
batch = client.messages.batches.create(requests=reqs)
|
|
batch_id = batch.id
|
|
ids_path = f"/tmp/look-backfill-{batch_id}.json"
|
|
json.dump(ids, open(ids_path, "w"))
|
|
print(f"batch {batch_id} (ids saved to {ids_path})")
|
|
|
|
while True:
|
|
b = client.messages.batches.retrieve(batch_id)
|
|
if b.processing_status == "ended":
|
|
break
|
|
print(f" {b.processing_status}: {b.request_counts.processing} processing, "
|
|
f"{b.request_counts.succeeded} done", flush=True)
|
|
time.sleep(20)
|
|
|
|
items, tin, tout, failed = [], 0, 0, 0
|
|
for r in client.messages.batches.results(batch_id):
|
|
sid = ids.get(r.custom_id)
|
|
if not sid:
|
|
continue
|
|
if r.result.type != "succeeded":
|
|
failed += 1 # left unlabelled: the next run (or the labeller) retries
|
|
continue
|
|
msg = r.result.message
|
|
tin += msg.usage.input_tokens
|
|
tout += msg.usage.output_tokens
|
|
text = next((blk.text for blk in msg.content if blk.type == "text"), "")
|
|
try:
|
|
action = json.loads(text).get("action")
|
|
except ValueError:
|
|
action = None
|
|
items.append({"id": sid, "action": action, "model": msg.model})
|
|
if items:
|
|
out = hub("/api/look/auto", {"items": items, "source": "batch"})
|
|
print(f"recorded {out.get('recorded')} labels, {failed} failed")
|
|
print(f"tokens {tin} in / {tout} out ≈ ${tin * PRICE_IN + tout * PRICE_OUT:.4f}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|