|
| 1 | +"""Asking this installation's AI model from another tool, over the token API. |
| 2 | +
|
| 3 | +Another tool (a security dashboard, say) can use the model set up on the AI |
| 4 | +page instead of needing a key of its own. It is off until an administrator |
| 5 | +ticks "Share with API tokens" on the AI page, and only an administrator's |
| 6 | +token with the ai scope can use it. Both are checked on every call, because |
| 7 | +a token outlives the setting it was made under. |
| 8 | +
|
| 9 | +The question goes to the model as it came and the answer comes straight back. |
| 10 | +Nothing is stored except the usage row every question writes, under |
| 11 | +api:<purpose>, so the AI usage page shows what other tools spent. A request |
| 12 | +that fails says so in one plain sentence; the reason the provider gave stays |
| 13 | +in the log, since it can name how the provider is reached. |
| 14 | +
|
| 15 | +Mounted under /api/v1 by routes_api_v1, so it shares that router's token |
| 16 | +handling and its place in the API reference. |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import collections |
| 22 | +import logging |
| 23 | +import re |
| 24 | +import threading |
| 25 | +import time |
| 26 | + |
| 27 | +from fastapi import APIRouter, Depends, HTTPException, Request |
| 28 | +from starlette.concurrency import run_in_threadpool |
| 29 | + |
| 30 | +from app.core.db import session_scope |
| 31 | + |
| 32 | +log = logging.getLogger("gcr.api.ai") |
| 33 | + |
| 34 | +api = APIRouter() |
| 35 | + |
| 36 | +MAX_PROMPT_CHARS = 400_000 # a few hundred kilobytes: a big context, not a file dump |
| 37 | +MAX_SYSTEM_CHARS = 20_000 |
| 38 | +MAX_ANSWER_TOKENS = 32_000 |
| 39 | +# At most this many API questions wait on the model at once. Each holds a |
| 40 | +# thread from the pool every page shares, for as long as the provider takes, |
| 41 | +# so without this a slow provider could leave the pages with none. |
| 42 | +MAX_AT_ONCE = 4 |
| 43 | +API_TIMEOUT = 180 # seconds; a caller has long given up by then |
| 44 | +_PURPOSE = re.compile(r"^[a-z][a-z0-9_]{0,27}$") |
| 45 | + |
| 46 | +# In memory on purpose, like the page rate limiter: one process, and a limiter |
| 47 | +# that needs the database fails open when the database is the problem. |
| 48 | +_sent: collections.deque = collections.deque() |
| 49 | +_lock = threading.Lock() |
| 50 | +_busy = threading.BoundedSemaphore(MAX_AT_ONCE) |
| 51 | +_CONTROL = re.compile(r"[\x00-\x1f\x7f]") |
| 52 | + |
| 53 | + |
| 54 | +def _plain(text) -> str: |
| 55 | + """For the log: no line breaks or other control characters from outside.""" |
| 56 | + return _CONTROL.sub(" ", str(text or ""))[:200] |
| 57 | + |
| 58 | + |
| 59 | +def _slot(per_minute: int) -> bool: |
| 60 | + """True when one more question fits in the last minute, and counts it.""" |
| 61 | + now = time.monotonic() |
| 62 | + with _lock: |
| 63 | + while _sent and now - _sent[0] > 60: |
| 64 | + _sent.popleft() |
| 65 | + if len(_sent) >= max(1, per_minute): |
| 66 | + return False |
| 67 | + _sent.append(now) |
| 68 | + return True |
| 69 | + |
| 70 | + |
| 71 | +def _caller(): |
| 72 | + from app.web.routes_api_v1 import caller_for |
| 73 | + |
| 74 | + return caller_for("ai") |
| 75 | + |
| 76 | + |
| 77 | +async def _body(request: Request) -> dict: |
| 78 | + try: |
| 79 | + body = await request.json() |
| 80 | + except Exception: |
| 81 | + raise HTTPException(status_code=400, detail="Send a JSON body.") |
| 82 | + if not isinstance(body, dict): |
| 83 | + raise HTTPException(status_code=400, detail="Send a JSON object.") |
| 84 | + extra = set(body) - {"prompt", "system", "max_tokens", "purpose"} |
| 85 | + if extra: |
| 86 | + raise HTTPException(status_code=400, |
| 87 | + detail=f"Unknown field: {sorted(extra)[0][:40]}.") |
| 88 | + prompt, system = body.get("prompt"), body.get("system", "") |
| 89 | + if not isinstance(prompt, str) or not prompt.strip(): |
| 90 | + raise HTTPException(status_code=400, detail="Send the question as prompt.") |
| 91 | + if len(prompt) > MAX_PROMPT_CHARS: |
| 92 | + raise HTTPException(status_code=413, |
| 93 | + detail=f"The prompt is over {MAX_PROMPT_CHARS} characters.") |
| 94 | + if not isinstance(system, str) or len(system) > MAX_SYSTEM_CHARS: |
| 95 | + raise HTTPException(status_code=400, |
| 96 | + detail=f"system is text up to {MAX_SYSTEM_CHARS} characters.") |
| 97 | + raw = body.get("max_tokens") |
| 98 | + if raw is not None and type(raw) is not int: # not true, 3.9 or a number too big for an int |
| 99 | + raise HTTPException(status_code=400, detail="max_tokens is a whole number.") |
| 100 | + max_tokens = 4000 if raw is None else raw |
| 101 | + if not 1 <= max_tokens <= MAX_ANSWER_TOKENS: |
| 102 | + raise HTTPException(status_code=400, |
| 103 | + detail=f"max_tokens is 1 to {MAX_ANSWER_TOKENS}.") |
| 104 | + purpose = str(body.get("purpose") or "other") |
| 105 | + if not _PURPOSE.match(purpose): |
| 106 | + raise HTTPException(status_code=400, |
| 107 | + detail="purpose is a short lowercase word, like hunt.") |
| 108 | + return {"prompt": prompt, "system": system, "max_tokens": max_tokens, |
| 109 | + "purpose": purpose} |
| 110 | + |
| 111 | + |
| 112 | +@api.post("/ai/complete") |
| 113 | +async def ai_complete(request: Request, caller=Depends(_caller())): |
| 114 | + """One question to the model on the AI page, one answer back.""" |
| 115 | + from app.core import ai, rbac |
| 116 | + from app.web.routes_api_v1 import _me |
| 117 | + |
| 118 | + asked = await _body(request) |
| 119 | + with session_scope() as db: |
| 120 | + me = _me(db, caller) |
| 121 | + if not rbac.can(me, "settings.write"): |
| 122 | + raise HTTPException(status_code=403, |
| 123 | + detail="Only an administrator's token can ask the AI.") |
| 124 | + username = me.username |
| 125 | + cfg = ai.config(db) |
| 126 | + if not ai.enabled(cfg) or not cfg.get("ai.api_share"): |
| 127 | + raise HTTPException(status_code=409, |
| 128 | + detail=("This installation's AI is not shared with API " |
| 129 | + "tokens. An administrator can share it on the " |
| 130 | + "AI page.")) |
| 131 | + if not _slot(int(cfg.get("ai.api_per_minute") or 20)): |
| 132 | + raise HTTPException(status_code=429, |
| 133 | + detail="Too many questions this minute. Try again shortly.", |
| 134 | + headers={"Retry-After": "60"}) |
| 135 | + if not _busy.acquire(blocking=False): |
| 136 | + raise HTTPException(status_code=429, |
| 137 | + detail="Too many questions waiting on the AI. Try again shortly.", |
| 138 | + headers={"Retry-After": "30"}) |
| 139 | + try: |
| 140 | + max_tokens = min(asked["max_tokens"], int(cfg.get("ai.max_tokens") or 16000)) |
| 141 | + timeout = min(float(cfg.get("ai.timeout") or API_TIMEOUT), API_TIMEOUT) |
| 142 | + out = await run_in_threadpool( |
| 143 | + ai.complete, cfg, asked["system"], asked["prompt"], max_tokens=max_tokens, |
| 144 | + timeout=timeout, purpose=f"api:{asked['purpose']}") |
| 145 | + finally: |
| 146 | + _busy.release() |
| 147 | + log.info("api ai %s for %s (token %s): ok=%s in=%s out=%s %sms", |
| 148 | + asked["purpose"], _plain(username), _plain(getattr(caller.token, "name", "?")), |
| 149 | + out.get("ok"), out.get("input_tokens"), out.get("output_tokens"), |
| 150 | + out.get("duration_ms")) |
| 151 | + if not out.get("ok"): |
| 152 | + log.warning("api ai %s failed: %s", asked["purpose"], _plain(out.get("error"))) |
| 153 | + raise HTTPException(status_code=502, |
| 154 | + detail=("The AI did not answer. An administrator can " |
| 155 | + "see why on the AI usage page and in the log.")) |
| 156 | + return {"text": out["text"], "provider": out.get("provider"), |
| 157 | + "model": out.get("model"), "input_tokens": out.get("input_tokens"), |
| 158 | + "output_tokens": out.get("output_tokens"), "cut_off": bool(out.get("cut_off"))} |
0 commit comments