"""Run every item through one model under each condition. Resumable; exits nonzero on any failure. Usage: python3 run_model.py --model gemma4:31b # local Ollama (default route) python3 run_model.py --route openrouter --model reflection/beam-1.0-501b-a23b add condition names to run a subset, e.g. ... plain_nothink guarded_nothink The Ollama route mirrors the LifeOS voice pipeline's extraction call (voice-to-obsidian main.py): a JSON schema passed as `format`, num_ctx 8192, num_predict 2400, the model's default sampling. Credentials, where a route needs one, are read from the environment (OPENROUTER_API_KEY) and never written anywhere. """ import argparse, concurrent.futures as cf, json, os, re, sys, threading, time, urllib.error, urllib.request SCHEMA_TEXT = """Return a single JSON object with exactly these keys: "has_deadline": true or false "deadline_date": "YYYY-MM-DD" or null "deadline_time": "HH:MM" (24-hour) or null "timezone": an IANA timezone name such as "America/New_York", or null "should_set_alarm": true or false Return only the JSON object.""" JSON_SCHEMA = { "type": "object", "properties": { "has_deadline": {"type": "boolean"}, "deadline_date": {"type": ["string", "null"]}, "deadline_time": {"type": ["string", "null"]}, "timezone": {"type": ["string", "null"]}, "should_set_alarm": {"type": "boolean"}, }, "required": ["has_deadline", "deadline_date", "deadline_time", "timezone", "should_set_alarm"], } PLAIN = "Extract the deadline from this personal capture.\n\n" + SCHEMA_TEXT GUARDED = ( "You are the deadline extractor for a personal assistant. Every deadline you return is mirrored " "into a phone alarm, so an invented or wrong date is worse than returning none. " "Set has_deadline to true only when the capture states a firm deadline that can be put on a calendar today; " "placeholders, guesses, 'TBD', and deadlines that depend on an event that has not happened yet are not firm. " "Resolve relative dates against the recording time. Give a clock time and timezone only if the capture states them. " "should_set_alarm is true only for a firm deadline on or after the recording date.\n\n" + SCHEMA_TEXT ) # name: (system prompt, think). "nothink" is the pipeline's own setting. CONDITIONS = { "plain_nothink": (PLAIN, False), "plain_nothink_rep": (PLAIN, False), "plain_think": (PLAIN, True), "guarded_nothink": (GUARDED, False), "guarded_think": (GUARDED, True), } def parse(text): m = re.search(r"\{.*\}", text or "", re.S) if not m: return None try: return json.loads(m.group(0)) except json.JSONDecodeError: return None def openrouter_key(): key = os.environ.get("OPENROUTER_API_KEY", "").strip() if not key: sys.exit("FAIL: OPENROUTER_API_KEY is not set") return key def request(args, item, cond): system, think = CONDITIONS[cond] msgs = [{"role": "system", "content": system}, {"role": "user", "content": f"Recorded at: {item['recorded_at']}\n\n{item['text']}"}] if args.route == "ollama": body = {"model": args.model, "messages": msgs, "stream": False, "format": JSON_SCHEMA, "think": think, "options": {"num_ctx": args.num_ctx, "num_predict": 2400 if not think else 8000}, "keep_alive": "30m"} return urllib.request.Request(args.ollama_url + "/api/chat", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) body = {"model": args.model, "messages": msgs, "max_tokens": 6000, "usage": {"include": True}, "reasoning": {"effort": "high" if think else "low"}} if args.provider: body["provider"] = {"order": [args.provider], "allow_fallbacks": False} return urllib.request.Request("https://openrouter.ai/api/v1/chat/completions", data=json.dumps(body).encode(), headers={"Authorization": "Bearer " + args.key, "Content-Type": "application/json"}) def call(args, item, cond): last = None for attempt in range(5): try: t0 = time.time() resp = json.load(urllib.request.urlopen(request(args, item, cond), timeout=900)) if args.route == "ollama": msg = resp["message"] usage = {"prompt_tokens": resp.get("prompt_eval_count"), "completion_tokens": resp.get("eval_count")} provider = "ollama@" + args.ollama_url else: msg = resp["choices"][0]["message"] usage, provider = resp.get("usage"), resp.get("provider") return {"id": item["id"], "model": args.model, "route": args.route, "provider": provider, "condition": cond, "family": item["family"], "capture_kind": item["capture_kind"], "content": msg.get("content"), "reasoning": msg.get("thinking") or msg.get("reasoning"), "pred": parse(msg.get("content")), "gold": item["gold"], "usage": usage, "latency_s": round(time.time() - t0, 2)} except urllib.error.HTTPError as e: last = f"HTTP {e.code}: {e.read()[:300]!r}" if e.code in (400, 401, 403, 404): break except Exception as e: # network, timeout, malformed response last = repr(e) time.sleep(2 ** attempt) raise RuntimeError(f"{item['id']}/{cond}: {last}") def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--route", choices=["ollama", "openrouter"], default="ollama") ap.add_argument("--provider", help="OpenRouter host to pin, e.g. baseten") ap.add_argument("--workers", type=int, default=2) ap.add_argument("--num-ctx", type=int, default=8192, help="8192 = the voice pipeline's setting") ap.add_argument("--ollama-url", default="http://127.0.0.1:11434", help="e.g. an SSH tunnel to another Mac") ap.add_argument("--out") ap.add_argument("--limit", type=int, help="first N items only (smoke test)") ap.add_argument("conditions", nargs="*") args = ap.parse_args() args.key = openrouter_key() if args.route == "openrouter" else None out = args.out or "results/" + re.sub(r"[^A-Za-z0-9.]+", "_", args.model) + ".jsonl" os.makedirs(os.path.dirname(out) or ".", exist_ok=True) conds = args.conditions or list(CONDITIONS) items = [json.loads(l) for l in open("items.jsonl")][: args.limit] done = {(r["id"], r["condition"]) for r in map(json.loads, open(out))} if os.path.exists(out) else set() todo = [(it, c) for c in conds for it in items if (it["id"], c) not in done] print(f"{args.model}: {len(todo)} calls to make ({len(done)} already done) -> {out}", flush=True) lock, failures, n = threading.Lock(), [], 0 with cf.ThreadPoolExecutor(args.workers) as ex, open(out, "a") as f: futs = [ex.submit(call, args, it, c) for it, c in todo] for fut in cf.as_completed(futs): try: row = fut.result() with lock: f.write(json.dumps(row) + "\n"); f.flush() except Exception as e: failures.append(str(e)); print("FAIL", e, flush=True) n += 1 if n % 25 == 0: print(f"{n}/{len(todo)} done, {len(failures)} failed", flush=True) if failures: sys.exit(f"FAIL: {len(failures)} calls failed; rerun to resume. First: {failures[0]}") print(f"OK all {len(todo)} calls succeeded") if __name__ == "__main__": main()