"""Play Qwen3.8-27B (thinking off) against a running server to measure per-task solve rates. The HF token is read inside this process via huggingface_hub (HF_TOKEN_PATH selects the file); it is never printed or written anywhere. Usage: HF_TOKEN_PATH=... python scripts/calibrate.py --url http://localhost:8000 --episodes 4 --out reports/calibration/run1 """ import argparse import json import random import re import sys import threading import time import urllib.error import urllib.request from concurrent.futures import ThreadPoolExecutor from pathlib import Path from statistics import mean sys.path.insert(0, str(Path(__file__).resolve().parents[1])) sys.path.insert(0, str(Path(__file__).resolve().parent)) from huggingface_hub import get_token # noqa: E402 from pydantic import ValidationError # noqa: E402 from five_desks.models import DeskAction # noqa: E402 from five_desks.tasks import TASK_IDS # noqa: E402 from wsclient import Session # noqa: E402 ROUTER = "https://router.huggingface.co/v1/chat/completions" FINISH_ACTION = {"tool": "submit", "answer": {}} _decoder = json.JSONDecoder(strict=False) def system_prompt(action_schema: dict) -> str: return ( "You are an agent acting in an environment. Reply to every message with exactly one JSON object and " "nothing else: an action that matches the action schema below, or {\"finish\": true} to end the episode.\n" f"Action schema: {json.dumps(action_schema)}" ) def first_json_object(text: str): text = re.sub(r".*?", "", text or "", flags=re.S) for match in re.finditer(r"\{", text): try: obj, _ = _decoder.raw_decode(text[match.start():]) if isinstance(obj, dict): return obj except json.JSONDecodeError: continue return None class Model: def __init__(self, model: str, max_tokens: int, temperature: float, thinking: bool = False): self.model, self.max_tokens, self.temperature, self.thinking = model, max_tokens, temperature, thinking self._token = get_token() if not self._token: raise SystemExit("No Hugging Face token found (set HF_TOKEN_PATH).") self.usage = {"prompt_tokens": 0, "completion_tokens": 0, "calls": 0} self._lock = threading.Lock() self.empty_examples = [] def chat(self, messages): # Some provider responses come back with no content at all; retry those rather than score them. for _ in range(3): content, used, finish = self._chat_once(messages) if content.strip() or finish == "length": break return content, used, finish def _chat_once(self, messages): body = {"model": self.model, "messages": messages, "max_tokens": self.max_tokens, "temperature": self.temperature, "chat_template_kwargs": {"enable_thinking": self.thinking}} for attempt in range(5): req = urllib.request.Request(ROUTER, data=json.dumps(body).encode(), headers={ "Authorization": f"Bearer {self._token}", "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=180) as response: data = json.load(response) break except urllib.error.HTTPError as exc: if exc.code in (429, 500, 502, 503, 504) and attempt < 4: time.sleep(2 ** attempt * 3) continue raise RuntimeError(f"inference HTTP {exc.code}: {exc.read().decode()[:200]}") from None except (urllib.error.URLError, TimeoutError): # DNS hiccups and slow responses are retried too if attempt < 4: time.sleep(2 ** attempt * 3) continue raise usage = data.get("usage") or {} with self._lock: self.usage["prompt_tokens"] += usage.get("prompt_tokens", 0) self.usage["completion_tokens"] += usage.get("completion_tokens", 0) self.usage["calls"] += 1 choice = data["choices"][0] message = choice["message"] content = message.get("content") or "" if not content.strip(): with self._lock: self.usage["empty_content"] = self.usage.get("empty_content", 0) + 1 self.empty_examples.append({k: v for k, v in message.items() if v}) return content, usage.get("completion_tokens", 0), choice.get("finish_reason") def play(url, model, schema, task_id, completion_budget, context_budget): messages = [{"role": "system", "content": system_prompt(schema)}] episode = {"task_id": task_id, "turns": [], "end": None, "reward": 0.0} completion_used = 0 with Session(url) as session: episode["seed"] = random.SystemRandom().randrange(2**48) data = session.reset(task_id=task_id, seed=episode["seed"]) obs = data["observation"] while True: obs_text = json.dumps({k: v for k, v in obs.items() if k != "metadata" or v}) messages.append({"role": "user", "content": obs_text}) if len(messages) > 2: completion_used += len(obs_text) // 3 # later observations count against the budget if completion_used >= completion_budget or sum(len(m["content"]) for m in messages) // 3 >= context_budget: episode["end"] = "budget" data = session.step(FINISH_ACTION) break reply, used, finish_reason = model.chat(messages) completion_used += used messages.append({"role": "assistant", "content": reply}) episode["turns"].append({"obs": obs_text[:4000], "reply": reply[:2000], "finish_reason": finish_reason, "tokens": used}) if finish_reason == "length": episode["end"] = "truncated" data = session.step(FINISH_ACTION) break action = first_json_object(reply) if isinstance(action, dict) and set(action) == {"action"} and isinstance(action["action"], dict): action = action["action"] if action is None: episode["end"] = "empty_reply" if not reply.strip() else "invalid_json" data = session.step(FINISH_ACTION) break if action.get("finish") is True: episode["end"] = "finish" data = session.step(FINISH_ACTION) break try: DeskAction.model_validate(action) except ValidationError: episode["end"] = "schema_invalid" data = session.step(FINISH_ACTION) break data = session.step(action) obs = data["observation"] if data["done"]: episode["end"] = "submitted" if action.get("tool") == "submit" else "out_of_steps" episode["final"] = obs.get("output") break episode["reward"] = data.get("reward") or 0.0 episode["n_turns"] = len(episode["turns"]) episode["completion_tokens_est"] = completion_used return episode def main(): parser = argparse.ArgumentParser() parser.add_argument("--url", default="http://localhost:8000") parser.add_argument("--model", default="Qwen/Qwen3.8-27B:deepinfra") parser.add_argument("--episodes", type=int, default=4) parser.add_argument("--tasks", default="", help="comma-separated task ids or prefixes (default: all)") parser.add_argument("--workers", type=int, default=8) parser.add_argument("--max-tokens", type=int, default=1024) parser.add_argument("--temperature", type=float, default=1.0) parser.add_argument("--completion-budget", type=int, default=8192) parser.add_argument("--context-budget", type=int, default=16384) parser.add_argument("--out", required=True) args = parser.parse_args() tasks = TASK_IDS if args.tasks: wanted = args.tasks.split(",") tasks = [t for t in TASK_IDS if any(t.startswith(w) for w in wanted)] with urllib.request.urlopen(f"{args.url}/schema", timeout=15) as response: schema = json.load(response)["action"] model = Model(args.model, args.max_tokens, args.temperature) out = Path(args.out) out.mkdir(parents=True, exist_ok=True) jobs = [t for t in tasks for _ in range(args.episodes)] started = time.monotonic() results = [] with ThreadPoolExecutor(args.workers) as pool, open(out / "episodes.jsonl", "w") as log: futures = [pool.submit(play, args.url, model, schema, t, args.completion_budget, args.context_budget) for t in jobs] for fut in futures: try: ep = fut.result() except Exception as exc: # infrastructure errors are excluded, not scored as 0 print("episode error:", exc, file=sys.stderr) continue results.append(ep) log.write(json.dumps(ep) + "\n") summary = {} for task_id in tasks: eps = [e for e in results if e["task_id"] == task_id] if not eps: continue rewards = [e["reward"] for e in eps] ends = {} for e in eps: ends[e["end"]] = ends.get(e["end"], 0) + 1 summary[task_id] = {"n": len(eps), "mean": round(mean(rewards), 3), "rewards": rewards, "mixed": len(set(rewards)) > 1, "ends": ends, "turns": round(mean(e["n_turns"] for e in eps), 1)} report = {"model": args.model, "episodes": len(results), "seconds": round(time.monotonic() - started), "usage": model.usage, "tasks": summary} (out / "summary.json").write_text(json.dumps(report, indent=2) + "\n") (out / "empty_examples.json").write_text(json.dumps(model.empty_examples[:20], indent=2) + "\n") print(f"{'task':24s} {'mean':>5s} rewards ends") for task_id, s in summary.items(): print(f"{task_id:24s} {s['mean']:5.2f} {str(s['rewards']):30s} {s['ends']}") print("usage:", model.usage, "seconds:", report["seconds"]) if __name__ == "__main__": main()