| 84 | |
| 85 | |
| 86 | def call(key, model, state, questions, retries=5): |
| 87 | body = json.dumps({"model": model, "state": state, "questions": questions}).encode() |
| 88 | req = urllib.request.Request(API, data=body, method="POST", headers={ |
| 89 | "Authorization": f"Bearer {key}", "Content-Type": "application/json"}) |
| 90 | delay = 1.0 |
| 91 | for attempt in range(retries): |
| 92 | t0 = time.time() |
| 93 | try: |
| 94 | with urllib.request.urlopen(req, timeout=60) as r: |
| 95 | data = json.load(r) |
| 96 | data["_latency_ms"] = int((time.time() - t0) * 1000) |
| 97 | return data |
| 98 | except urllib.error.HTTPError as e: |
| 99 | if e.code in (429, 529) and attempt < retries - 1: |
| 100 | time.sleep(delay); delay *= 2; continue |
| 101 | detail = e.read().decode(errors="replace")[:300] |
| 102 | raise RuntimeError(f"HTTP {e.code}: {detail}") |
| 103 | raise RuntimeError("retries exhausted") |
| 104 | |
| 105 | |
| 106 | def choice_q(instructions, criteria): |