279 lines
12 KiB
Python
279 lines
12 KiB
Python
"""
|
|
``POST /complete`` — one short answer from **any** model the lab can reach,
|
|
with nothing a real run loads: no transcript, no tools, no hooks, no MCP.
|
|
|
|
What the hub's side calls use (the ``conversation-labels`` plugin's short
|
|
titles, scheduled titles and action badges, through the ``complete.run`` hub
|
|
bridge — backend ``plugins/hubcomplete.py``). Replaces the Haiku-only
|
|
``/title`` and ``/look`` endpoints (2026-11-26).
|
|
|
|
Body::
|
|
|
|
{system, prompt, model, harness?, account?,
|
|
fallbackModel?, fallbackHarness?, fallbackAccount?,
|
|
wakeLocal?: false, timeout?: 30}
|
|
|
|
Where it goes (``route``):
|
|
|
|
* ``harness: "evox2"`` (or a model the EVOX2 serves, under ``pi``,
|
|
``opencode`` or no harness) — the
|
|
llama-server's ``/v1/chat/completions`` directly. ``wakeLocal: false`` (the
|
|
default) only looks: an asleep box, or a router whose model isn't loaded,
|
|
fails at once — so the fallback answers within the second instead of a
|
|
minute's Wake-on-LAN and a model load that would push a live run's model
|
|
out of VRAM. ``wakeLocal: true`` wakes and loads it (``local_ready``).
|
|
* ``harness: "openrouter"`` (or a ``vendor/model`` id that isn't local) —
|
|
OpenRouter's chat API on the key pi's runs use (``OPENROUTER_API_KEY``, else
|
|
``RUNNER_ENV_FILE``).
|
|
* any other harness — its driver's optional ``complete(system, prompt, model,
|
|
account, timeout)`` (``harness_base``): ``claude -p
|
|
--no-session-persistence``, ``agy --print``, ``opencode run`` on a
|
|
throwaway database. A harness without one is a 409.
|
|
|
|
A primary that fails (an error, a timeout, a box asleep) goes to the
|
|
fallback when one is named. Answers ``{text, model, harness, account, usage?,
|
|
costUsd?, fallbackUsed, primaryError?}`` — ``usage`` in Anthropic's shape
|
|
(``input_tokens``, ``output_tokens``, ``cache_read_input_tokens``,
|
|
``cache_creation_input_tokens``) so the hub prices it with the book it
|
|
prices transcripts with.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
from fastapi import APIRouter, Header, HTTPException
|
|
from pydantic import BaseModel
|
|
|
|
from validate import _auth
|
|
|
|
router = APIRouter()
|
|
|
|
DIRECT = ("evox2", "openrouter")
|
|
OPENROUTER_URL = os.environ.get("OPENROUTER_CHAT_URL",
|
|
"https://openrouter.ai/api/v1/chat/completions")
|
|
MAX_SYSTEM = 12_000
|
|
MAX_PROMPT = 30_000
|
|
MAX_TOKENS = 1024
|
|
LOOK_TIMEOUT_S = 3 # the asleep check: the box answers in ms when awake
|
|
|
|
|
|
class CompleteError(Exception):
|
|
def __init__(self, status: int, message: str, kind: str = "complete"):
|
|
super().__init__(message)
|
|
self.status, self.message, self.kind = status, message, kind
|
|
|
|
|
|
class CompleteBody(BaseModel):
|
|
system: str = ""
|
|
prompt: str
|
|
model: str | None = None
|
|
harness: str | None = None
|
|
account: str | None = None
|
|
fallbackModel: str | None = None
|
|
fallbackHarness: str | None = None
|
|
fallbackAccount: str | None = None
|
|
wakeLocal: bool = False
|
|
timeout: int = 30
|
|
|
|
|
|
# ── usage, one shape ─────────────────────────────────────────────────────────
|
|
def openai_usage(u: dict | None) -> dict | None:
|
|
"""An OpenAI-style ``usage`` (prompt / completion / cached) → Anthropic's."""
|
|
if not isinstance(u, dict):
|
|
return None
|
|
cached = int(((u.get("prompt_tokens_details") or {}).get("cached_tokens")) or 0)
|
|
return {"input_tokens": max(0, int(u.get("prompt_tokens") or 0) - cached),
|
|
"output_tokens": int(u.get("completion_tokens") or 0),
|
|
"cache_read_input_tokens": cached, "cache_creation_input_tokens": 0}
|
|
|
|
|
|
# ── direct HTTP: an OpenAI-compatible chat endpoint ─────────────────────────
|
|
def chat(url: str, key: str | None, model: str, system: str, prompt: str,
|
|
timeout: float, extra: dict | None = None) -> dict:
|
|
"""``{text, usage, costUsd}`` from one ``chat/completions`` call."""
|
|
msgs = ([{"role": "system", "content": system}] if system else []) + \
|
|
[{"role": "user", "content": prompt}]
|
|
body = {"model": model, "messages": msgs, "max_tokens": MAX_TOKENS,
|
|
"temperature": 0.2, "stream": False, **(extra or {})}
|
|
headers = {"Content-Type": "application/json"}
|
|
if key:
|
|
headers["Authorization"] = f"Bearer {key}"
|
|
req = urllib.request.Request(url, json.dumps(body).encode(), headers)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
out = json.loads(r.read().decode() or "{}")
|
|
except urllib.error.HTTPError as e:
|
|
detail = e.read().decode(errors="replace")[:300]
|
|
raise CompleteError(502, f"HTTP {e.code}: {detail}", "upstream") from None
|
|
except (OSError, ValueError) as e:
|
|
raise CompleteError(503, f"unreachable: {e}", "unreachable") from None
|
|
choice = (out.get("choices") or [{}])[0] or {}
|
|
text = ((choice.get("message") or {}).get("content") or "").strip()
|
|
if not text:
|
|
raise CompleteError(502, "empty answer", "empty")
|
|
u = out.get("usage") if isinstance(out.get("usage"), dict) else None
|
|
cost = u.get("cost") if u else None
|
|
return {"text": text, "usage": openai_usage(u),
|
|
"costUsd": float(cost) if isinstance(cost, (int, float)) else None,
|
|
"model": out.get("model") or model}
|
|
|
|
|
|
def local_target(model: str | None) -> dict | None:
|
|
"""``{root, key, model}`` of the EVOX2 server ``model`` is on, or None.
|
|
Takes pi's spelling (a bare id) and opencode's (``evox2…/<id>``)."""
|
|
import usage_loader
|
|
m = (model or "").strip()
|
|
if not m:
|
|
return None
|
|
if m.split("/", 1)[0].startswith("evox2"):
|
|
return usage_loader.local_target("opencode", m)
|
|
return usage_loader.local_target("pi", m)
|
|
|
|
|
|
def _loaded(t: dict) -> str | None:
|
|
"""None when the server is up with ``t``'s model loaded, else why not.
|
|
Never loads anything (``/models`` lists, it doesn't autoload)."""
|
|
headers = {"Authorization": f"Bearer {t['key']}"} if t.get("key") else {}
|
|
req = urllib.request.Request(f"{t['root']}/models", headers=headers)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=LOOK_TIMEOUT_S) as r:
|
|
body = json.loads(r.read().decode() or "{}")
|
|
except urllib.error.HTTPError:
|
|
return None # not a router: one model, always loaded
|
|
except (OSError, ValueError):
|
|
return "the EVOX2 is asleep or unreachable"
|
|
rows = body.get("data") if isinstance(body, dict) else None
|
|
if not isinstance(rows, list):
|
|
return None
|
|
for row in rows:
|
|
if isinstance(row, dict) and row.get("id") == t["model"]:
|
|
st = (row.get("status") or {}).get("value") or "loaded"
|
|
return None if st == "loaded" else f"{t['model']} is {st} on the EVOX2"
|
|
return None
|
|
|
|
|
|
def evox2(model: str, system: str, prompt: str, timeout: float, wake: bool) -> dict:
|
|
t = local_target(model)
|
|
if t is None:
|
|
raise CompleteError(400, f"{model!r} is not an EVOX2 model", "bad_model")
|
|
why = _loaded(t)
|
|
if why and wake:
|
|
import usage_loader
|
|
r = usage_loader.local_ready("pi", t["model"], int(max(10, timeout)))
|
|
why = None if r.get("ready") else (r.get("reason") or why)
|
|
if why:
|
|
raise CompleteError(503, why, "asleep")
|
|
out = chat(f"{t['root']}/v1/chat/completions", t.get("key"), t["model"], system,
|
|
prompt, timeout, {"chat_template_kwargs": {"enable_thinking": False}})
|
|
return {**out, "model": t["model"], "harness": "evox2", "account": "evox2",
|
|
"costUsd": 0.0}
|
|
|
|
|
|
def openrouter_key() -> str:
|
|
key = os.environ.get("OPENROUTER_API_KEY", "")
|
|
if key:
|
|
return key
|
|
p = pathlib.Path(os.path.expanduser(os.environ.get("RUNNER_ENV_FILE",
|
|
"~/homelab/.env.claude")))
|
|
try:
|
|
for line in p.read_text(encoding="utf-8").splitlines():
|
|
if line.startswith("OPENROUTER_API_KEY="):
|
|
return line.split("=", 1)[1].strip().strip("'\"")
|
|
except OSError:
|
|
pass
|
|
return ""
|
|
|
|
|
|
def openrouter(model: str, system: str, prompt: str, timeout: float) -> dict:
|
|
key = openrouter_key()
|
|
if not key:
|
|
raise CompleteError(409, "no OpenRouter key on this machine", "auth")
|
|
out = chat(OPENROUTER_URL, key, model, system, prompt, timeout,
|
|
{"usage": {"include": True}})
|
|
return {**out, "harness": "openrouter", "account": "openrouter"}
|
|
|
|
|
|
# ── routing ─────────────────────────────────────────────────────────────────
|
|
def route(harness: str | None, model: str | None) -> str:
|
|
"""Which engine answers: ``evox2`` / ``openrouter`` (direct HTTP) or a
|
|
harness id."""
|
|
h = (harness or "").strip().lower()
|
|
m = (model or "").strip()
|
|
if h in DIRECT:
|
|
return h
|
|
# A local model goes straight to its llama-server, whichever harness was
|
|
# named for it — same server, same answer, no CLI to start.
|
|
if h in ("", "pi", "opencode") and m and local_target(m):
|
|
return "evox2"
|
|
if h in ("", "pi") and "/" in m:
|
|
return "openrouter"
|
|
return h or "claude"
|
|
|
|
|
|
def run_one(harness: str | None, model: str | None, account: str | None,
|
|
system: str, prompt: str, timeout: float, wake: bool) -> dict:
|
|
eng = route(harness, model)
|
|
if eng == "evox2":
|
|
return evox2(model or "", system, prompt, timeout, wake)
|
|
if eng == "openrouter":
|
|
if not model:
|
|
raise CompleteError(400, "an OpenRouter model is required", "bad_model")
|
|
return openrouter(model, system, prompt, timeout)
|
|
import harness_base
|
|
import harness_loader
|
|
d = harness_loader.get(eng)
|
|
if d is None:
|
|
raise CompleteError(409, f"harness {eng!r} isn't on this machine", "no_harness")
|
|
if not harness_base.implements(d, "complete"):
|
|
raise CompleteError(409, f"harness {eng!r} has no one-shot completion", "unsupported")
|
|
try:
|
|
out = d.complete(system, prompt, model, account, timeout)
|
|
except HTTPException as e:
|
|
det = e.detail if isinstance(e.detail, dict) else {"message": str(e.detail)}
|
|
raise CompleteError(e.status_code if e.status_code >= 400 else 502,
|
|
str(det.get("message") or det)[-300:],
|
|
str(det.get("kind") or eng)) from None
|
|
if not isinstance(out, dict) or not (out.get("text") or "").strip():
|
|
raise CompleteError(502, f"{eng}: empty answer", "empty")
|
|
return {"usage": None, "costUsd": None, **out, "harness": eng}
|
|
|
|
|
|
def complete(body: CompleteBody) -> dict:
|
|
system = (body.system or "")[:MAX_SYSTEM]
|
|
prompt = (body.prompt or "").strip()[:MAX_PROMPT]
|
|
if not prompt:
|
|
raise CompleteError(400, "empty prompt", "bad_request")
|
|
timeout = float(max(5, min(int(body.timeout or 30), 180)))
|
|
t0 = time.monotonic()
|
|
try:
|
|
out = run_one(body.harness, body.model, body.account, system, prompt,
|
|
timeout, body.wakeLocal)
|
|
return {**out, "fallbackUsed": False, "seconds": round(time.monotonic() - t0, 2)}
|
|
except CompleteError as e:
|
|
if not (body.fallbackModel or body.fallbackHarness):
|
|
raise
|
|
primary = f"{e.kind}: {e.message}"
|
|
# The primary's account only carries over to the same engine (a work
|
|
# Claude seat means nothing to agy).
|
|
same = route(body.fallbackHarness, body.fallbackModel) == route(body.harness, body.model)
|
|
out = run_one(body.fallbackHarness, body.fallbackModel,
|
|
body.fallbackAccount or (body.account if same else None),
|
|
system, prompt, timeout, False)
|
|
return {**out, "fallbackUsed": True, "primaryError": primary[:300],
|
|
"seconds": round(time.monotonic() - t0, 2)}
|
|
|
|
|
|
@router.post("/complete")
|
|
def complete_route(body: CompleteBody, authorization: str | None = Header(default=None)) -> dict:
|
|
_auth(authorization)
|
|
try:
|
|
return complete(body)
|
|
except CompleteError as e:
|
|
raise HTTPException(e.status, {"message": e.message, "kind": e.kind}) from None
|