#!/usr/bin/env python3 """Run Task A (extraction) or Task C (polishing) on one model. Same prompts for every model, one request at a time. run.py [--local] writes results/_.jsonl and results/_.meta.json Local models go through the OpenAI-compatible LocalAI endpoint; others through the Anthropic SDK. For local runs the CPU package energy (Intel RAPL) is read before and after. """ import json, os, re, sys, time, urllib.request task, model = sys.argv[1], sys.argv[2] local = "--local" in sys.argv S = os.environ["BENCH_SECRETS"] # directory holding lai.key / claude.key (never committed) LAI = os.environ.get("LAI_URL", "http://127.0.0.1:18180") RAPL = "/sys/class/powercap/intel-rapl:0/energy_uj" SYSTEM_A = """You extract order details from customer support messages. Return ONLY a JSON object, no other text, with exactly these keys: customer_name (string), order_id (string), product (string, as written, lowercase), quantity (integer), amount (number: total order amount, no currency symbols or thousands separators), currency (one of INR, USD, EUR; "Rs", "₹" and "rupees" mean INR, "$" means USD, "€" means EUR), date (order date as YYYY-MM-DD; numeric dates are day/month/year; if the year is missing assume 2026), category (one of billing, shipping, refund, technical, account), urgency (one of low, normal, high). Ignore other order ids, ticket numbers, phone numbers and amounts that are not about this order.""" SYSTEM_C = """You polish rough blog drafts written by an engineer. Fix grammar, spelling and clarity, and make it read naturally, while keeping the author's voice and meaning. Keep every number, unit, name, command and technical identifier exactly as written. Do not add new facts. Return only the polished paragraph.""" items = [json.loads(l) for l in open(f"task_{task}.jsonl")] system = SYSTEM_A if task == "a" else SYSTEM_C if model.startswith("qwen3-1.7b"): # Qwen3 hybrid models think by default; /no_think is Qwen's documented switch for plain answers. system += "\n/no_think" def call_local(text): key = open(f"{S}/lai.key").read().strip() body = {"model": model, "temperature": 0, "max_tokens": 600, "messages": [{"role": "system", "content": system}, {"role": "user", "content": text}]} req = urllib.request.Request(f"{LAI}/v1/chat/completions", data=json.dumps(body).encode(), headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}) d = json.load(urllib.request.urlopen(req, timeout=1800)) u = d.get("usage", {}) content = d["choices"][0]["message"].get("content") or "" content = re.sub(r".*?", "", content, flags=re.S).strip() # drop empty or leftover think blocks return content, u.get("prompt_tokens", 0), u.get("completion_tokens", 0) client = None if not local: import anthropic client = anthropic.Anthropic(api_key=open(f"{S}/claude.key").read().strip()) def call_claude(text): r = client.messages.create(model=model, max_tokens=2000, system=system, output_config={"effort": "low"}, messages=[{"role": "user", "content": text}]) out = "".join(b.text for b in r.content if b.type == "text") return out, r.usage.input_tokens, r.usage.output_tokens def energy(): try: return int(open(RAPL).read()) except OSError: return None os.makedirs("results", exist_ok=True) name = model.replace("/", "_") out_path = f"results/{task}_{name}.jsonl" if local: # warm up so model loading is not counted t = time.time(); call_local("Say ok."); warm = time.time() - t else: warm = None e0, t0 = energy(), time.time() with open(out_path, "w") as f: for it in items: t = time.time() try: out, pin, pout = (call_local if local else call_claude)(it["text"]) err = None except Exception as e: out, pin, pout, err = "", 0, 0, str(e)[:200] f.write(json.dumps({"id": it["id"], "output": out, "seconds": round(time.time() - t, 2), "input_tokens": pin, "output_tokens": pout, "error": err}, ensure_ascii=False) + "\n") f.flush() print(it["id"], f"{time.time() - t:.1f}s", "ERR " + err if err else "", flush=True) e1, t1 = energy(), time.time() meta = {"task": task, "model": model, "local": local, "items": len(items), "wall_s": round(t1 - t0, 1), "warmup_s": round(warm, 1) if warm else None, "package_joules": round((e1 - e0) / 1e6, 1) if (local and e0 is not None and e1 is not None and e1 >= e0) else None} json.dump(meta, open(f"results/{task}_{name}.meta.json", "w"), indent=1) print(json.dumps(meta))