"""Protocol v2 LLM baseline: VAI DeepSeek through an OpenAI-compatible endpoint, with usage log and token budget.""" from __future__ import annotations import hashlib import json import os import sqlite3 import threading import time import httpx import yaml from . import m2, m34, paths PROTOCOL_V2 = paths.REPO_ROOT / "configs" / "protocol_v2.yaml" CALL_COLUMNS = ("mode", "modality", "item", "attempt", "ok", "error", "model_returned", "request_id", "finish_reason", "input_tokens", "output_tokens", "elapsed_s") class ModelAccessError(RuntimeError): """The key, endpoint or model is not usable. The run stops and does not substitute a model.""" class BudgetExceeded(RuntimeError): pass def configuration_v2(): """Verify both locked protocols and return (v1 protocol, v1 baseline config, v2 protocol).""" protocol, cfg = m34.configuration() expected = PROTOCOL_V2.with_suffix(".yaml.sha256").read_text().split()[0] if m2.digest(PROTOCOL_V2) != expected: raise ValueError("The protocol v2 checksum did not match.") v2 = yaml.safe_load(PROTOCOL_V2.read_text()) if v2["status"] != "locked" or v2["extends"]["sha256"] != m2.digest(m2.PROTOCOL): raise ValueError("Protocol v2 does not extend the locked v1 protocol.") return protocol, cfg, v2 def model_spec(v2, model_id, task): for spec in v2["baselines"]["api"]: if spec["id"] == model_id: if task not in spec["tasks"]: raise ValueError(f"{model_id} is not a v2 baseline for {task}.") return spec raise ValueError(f"{model_id} is not the v2 API baseline.") def endpoint(): """Base URL and key come from the environment or the untracked .env, never from a command line or a log.""" base, key = os.environ.get("VOLVE_DIA_M34_API_BASE"), os.environ.get("VOLVE_DIA_M34_API_KEY") if not base or not key: raise ModelAccessError("Set VOLVE_DIA_M34_API_BASE and VOLVE_DIA_M34_API_KEY (environment or .env).") return base.rstrip("/") + "/", key def validate(body, schema): """Local shape checks, identical in effect to the v1 `chat` validation.""" if not isinstance(body, dict) or not set(schema["required"]) <= body.keys(): raise ValueError("Invalid response shape.") if "citations" in body: c = body["citations"] if not isinstance(c, list) or not all(isinstance(x, str) for x in c) or len(c) > 8: raise ValueError("Invalid citation shape.") if "answer" in body: if body["answer"] is not None and not isinstance(body["answer"], (str, list, int, float, bool)): raise ValueError("Invalid answer.") if not isinstance(body["unit"], str): raise ValueError("Invalid unit.") if "tool" in body and (body["tool"] not in ("query", "search", "finish") or not isinstance(body["arguments"], dict)): raise ValueError("Invalid tool call.") json.dumps(body, allow_nan=False) return body class ApiCaller: """Thread-safe adapter with the v1 call signature `call(messages, schema)`, plus a per-call usage log.""" def __init__(self, client, spec, v2, store, budget_tokens, seed): self.client, self.spec, self.params, self.store = client, spec, v2["inference"], store self.budget, self.seed = budget_tokens, seed self.lock, self.local = threading.Lock(), threading.local() self.spent = int(store.execute("SELECT COALESCE(SUM(input_tokens + output_tokens), 0) FROM calls").fetchone()[0]) def bind(self, mode, modality, item): self.local.key = (mode, modality, item) def _log(self, attempt, ok, error, data, started): usage = (data or {}).get("usage") or {} choice = ((data or {}).get("choices") or [{}])[0] i, o = int(usage.get("prompt_tokens") or 0), int(usage.get("completion_tokens") or 0) row = (*self.local.key, attempt, int(ok), error, (data or {}).get("model"), (data or {}).get("id"), choice.get("finish_reason"), i, o, round(time.monotonic() - started, 3)) with self.lock: self.spent += i + o with self.store: self.store.execute(f"INSERT INTO calls VALUES ({','.join('?' * len(CALL_COLUMNS))})", row) if self.budget is not None and self.spent >= self.budget: raise BudgetExceeded(f"Logged tokens {self.spent} reached the approved budget.") def __call__(self, messages, schema): p = self.params request = {"model": self.spec["api_model"], "messages": messages, "temperature": p["temperature"], "max_tokens": p["max_tokens"], "seed": self.seed, "response_format": {"type": "json_object"}} request["chat_template_kwargs"] = p["chat_template_kwargs"] last = None for attempt in range(1, p["attempts_per_call"] + 1): started, data = time.monotonic(), None try: res = self.client.post("chat/completions", json=request) if res.status_code in (401, 403, 404): raise ModelAccessError(f"API service returned HTTP {res.status_code}.") if res.status_code == 400: raise ModelAccessError("API service rejected the request (HTTP 400).") res.raise_for_status() data = res.json() choice = data["choices"][0] if choice.get("finish_reason") == "length": raise ValueError("Output truncated.") body = validate(json.loads(choice["message"]["content"]), schema) self._log(attempt, True, None, data, started) return body except (ModelAccessError, BudgetExceeded): raise except (httpx.HTTPError, ValueError, KeyError, IndexError, TypeError) as error: last = type(error).__name__ # Exception text may contain the provider URL. self._log(attempt, False, last, data, started) time.sleep(attempt) raise ValueError(f"Completion failed: {last}") def make_client(timeout=120.0): base, key = endpoint() return httpx.Client(base_url=base, headers={"Authorization": f"Bearer {key}"}, timeout=timeout, trust_env=False) def open_store(path, provenance): store = sqlite3.connect(path, check_same_thread=False, timeout=60) store.execute("PRAGMA journal_mode=WAL") store.execute("CREATE TABLE IF NOT EXISTS metadata (provenance TEXT)") store.execute(f"CREATE TABLE IF NOT EXISTS calls ({', '.join(CALL_COLUMNS)})") text = json.dumps(provenance, sort_keys=True, default=str, allow_nan=False) prior = store.execute("SELECT provenance FROM metadata").fetchone() if prior and prior[0] != text: raise ValueError("API checkpoint provenance differs.") if not prior: store.execute("INSERT INTO metadata VALUES (?)", [text]) store.commit() return store def code_fingerprint(): digest = hashlib.sha256() for name in ("scripts/15_m34_v2.py", "volve_dia/m34_v2.py", "scripts/12_m34_qa.py", "volve_dia/m34_qa.py", "scripts/14_m34_t2_llm.py"): digest.update(name.encode()) digest.update((paths.REPO_ROOT / name).read_bytes()) return digest.hexdigest()