Skip to content

Commit bf5b09e

Browse files
committed
Let other tools ask the AI model over the token API
POST /api/v1/ai/complete sends one question to the model set up on the AI page and answers with its reply, so a tool like a security dashboard needs no key of its own. It is off until Share with API tokens is ticked on the AI page, and only an administrator's token with the new ai scope can use it. Both are checked on every call. Prompts and answers are size limited, a per minute limit and at most four at once keep it from crowding out the pages, every question is counted on the AI usage page under api:<purpose>, and a failure says only that the AI did not answer.
1 parent 4e0b522 commit bf5b09e

8 files changed

Lines changed: 273 additions & 0 deletions

File tree

‎app/core/ai.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,15 @@
135135
"Also ask about handlers that look a record up from "
136136
"the request and return it whole, C# and Java "
137137
"included. At most 15 a repository, each once."),
138+
# Off by default for the same reason as the provider. On, an
139+
# administrator's API token with the ai scope can ask the model questions
140+
# from another tool (a security dashboard, say) without its own key.
141+
"ai.api_share": (False, False,
142+
"Let administrators' API tokens with the ai scope ask "
143+
"this model questions."),
144+
"ai.api_per_minute": (20, False,
145+
"Most questions API tokens may send in a minute, all "
146+
"tokens together."),
138147
# What the custom service charges, per million tokens, for the cost page.
139148
# Kept as text so 0.10 stays 0.10. Empty is not counted.
140149
"ai.price_input": ("", False, "Price per million input tokens."),
@@ -221,6 +230,9 @@ def read_form(form, text, number, url, checked) -> dict:
221230
"ai.auto_review_max": number(form.get("ai.auto_review_max") or 200,
222231
"New findings per scan", 0, 100_000),
223232
"ai.code_reasoning": checked("ai.code_reasoning"),
233+
"ai.api_share": checked("ai.api_share"),
234+
"ai.api_per_minute": number(form.get("ai.api_per_minute") or 20,
235+
"API questions per minute", 1, 600),
224236
"ai.code_reasoning_monthly_tokens": number(
225237
form.get("ai.code_reasoning_monthly_tokens") or 0,
226238
"Monthly token limit", 0, 2_000_000_000),

‎app/core/api_reference.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,9 @@ def _finding_filters():
101101
"scans and the repositories behind them. Needs the "
102102
"external scope on an administrator's token, and External "
103103
"sites switched on in Settings."),
104+
("AI", "Ask the model set up on the AI page from another tool, so it needs "
105+
"no key of its own. Needs the ai scope on an administrator's token, "
106+
"and the AI page sharing the model with API tokens."),
104107
]
105108

106109

@@ -414,6 +417,40 @@ def endpoints() -> list:
414417
"example": {"id": 77, "finding": 4182, "status": "revoked",
415418
"decided_by": "admin"},
416419
},
420+
{
421+
"id": "ai_complete", "group": "AI", "method": "POST",
422+
"path": "/ai/complete",
423+
"scope": "ai", "permission": "settings.write",
424+
"summary": "Ask the AI model a question",
425+
"description": "Sends one question to the model set up on the AI "
426+
"page and answers with its reply, so another tool "
427+
"needs no key of its own. Needs the ai scope, which "
428+
"only an administrator's token can carry, and the AI "
429+
"page must share the model with API tokens. Answers "
430+
"409 when it does not, 429 over the per minute limit "
431+
"set there, and 502 when the model did not answer. "
432+
"Every question is counted on the AI usage page under "
433+
"api:<purpose>.",
434+
"params": [],
435+
"body": [{"name": "prompt", "type": "string", "required": True,
436+
"description": "The question, up to 400,000 characters."},
437+
{"name": "system", "type": "string", "required": False,
438+
"description": "Instructions for the model, up to 20,000 "
439+
"characters."},
440+
{"name": "max_tokens", "type": "integer", "required": False,
441+
"description": "The longest answer to accept, 1 to 32000 "
442+
"(never more than the AI page allows). "
443+
"Default 4000."},
444+
{"name": "purpose", "type": "string", "required": False,
445+
"description": "A short lowercase word saying what it is "
446+
"for, kept with the usage."}],
447+
"body_example": {"system": "Reply with JSON only.",
448+
"prompt": "Summarize these alerts: ...",
449+
"max_tokens": 1500, "purpose": "hunt"},
450+
"example": {"text": "{\"summary\": \"...\"}", "provider": "openai",
451+
"model": "the-model-on-the-ai-page", "input_tokens": 812,
452+
"output_tokens": 240, "cut_off": False},
453+
},
417454
{
418455
"id": "approve_exception", "group": "Exceptions", "method": "POST",
419456
"path": "/exceptions/{exception_id}/approve",

‎app/core/api_tokens.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,12 @@
5050
# every call rather than when the token is made.
5151
"external": ("External sites: list sites, record and start dynamic scans "
5252
"(administrators only)"),
53+
# Asking this installation's AI model a question from another tool, so it
54+
# needs no key of its own. Questions cost money and can carry whatever
55+
# the other tool sends, so only an administrator's token can have it, the
56+
# AI page has to share the model too, and both are checked on every call.
57+
"ai": ("AI: ask this installation's AI model questions from another tool "
58+
"(administrators only, when the AI page shares it)"),
5359
}
5460

5561
PREFIX = "gcr_"
@@ -74,6 +80,8 @@ def allowed_scopes(owner, scopes) -> list:
7480
wanted = sorted({s.strip() for s in scopes if s.strip() in SCOPES})
7581
if "external" in wanted and not rbac.can(owner, "external.manage"):
7682
raise ValueError("Only an administrator's token can work with external sites.")
83+
if "ai" in wanted and not rbac.can(owner, "settings.write"):
84+
raise ValueError("Only an administrator's token can ask the AI.")
7785
if "approve" in wanted and not (rbac.can(owner, "waiver.approve")
7886
and rbac.can(owner, "exclusion.write")):
7987
raise ValueError("Only an administrator's token can approve exceptions.")

‎app/web/routes_api_ai.py‎

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
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"))}

‎app/web/routes_api_v1.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2290,3 +2290,11 @@ def deploy_check(request: Request,
22902290
for _route in _external_api.routes:
22912291
router.add_api_route(_route.path, _route.endpoint, methods=list(_route.methods),
22922292
name=_route.name)
2293+
2294+
2295+
# Asking the AI model on the AI page from another tool, the same way.
2296+
from app.web.routes_api_ai import api as _ai_api # noqa: E402
2297+
2298+
for _route in _ai_api.routes:
2299+
router.add_api_route(_route.path, _route.endpoint, methods=list(_route.methods),
2300+
name=_route.name)

‎app/web/templates/ai.html‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,30 @@
261261
</div>
262262
</div>
263263

264+
<div class="card">
265+
<div class="card-head">Share with API tokens</div>
266+
<div class="card-body">
267+
<label class="check">
268+
<input type="checkbox" name="ai.api_share" value="1"
269+
{{ 'checked' if values['ai.api_share'] }}>
270+
Let administrators' API tokens with the ai scope ask this model questions
271+
</label>
272+
<p class="faint small">Another tool, like a security dashboard, can then
273+
use this model through <span class="mono">POST /api/v1/ai/complete</span>
274+
instead of needing its own key. Only a token an administrator made, with
275+
the ai scope, can use it. What it sends goes to the provider above as it
276+
came, so share it only with tools you trust with that. Every question is
277+
counted on the AI usage page under <span class="mono">api:</span> and the
278+
purpose the tool gives. Nothing goes out while the provider above is off.</p>
279+
<label>Questions per minute
280+
<input type="number" name="ai.api_per_minute" min="1" max="600"
281+
value="{{ values['ai.api_per_minute'] }}">
282+
</label>
283+
<p class="faint small">All API tokens together. Over it, a tool is told to
284+
wait a minute.</p>
285+
</div>
286+
</div>
287+
264288
<div class="card">
265289
<div class="card-head">Code reasoning</div>
266290
<div class="card-body">

‎documentation/CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,19 @@ Newest first. Written for somebody deciding whether to upgrade, so every entry
44
says what is different for a person using the product rather than which files
55
moved.
66

7+
## 2026-12-01
8+
9+
**Other tools can use the AI model set up here.** Tick Share with API tokens
10+
on the AI page, and an administrator's API token with the new ai scope can ask
11+
the model a question with POST /api/v1/ai/complete, so a tool like a security
12+
dashboard needs no AI key of its own. It is off until an administrator shares
13+
it, only an administrator's token can carry the ai scope, and both are checked
14+
on every call, so a token stops working the moment its owner is no longer an
15+
administrator or the sharing is turned off. A per minute limit on the same
16+
page covers all tokens together. Every question is counted on the AI usage
17+
page under api: and the purpose the tool gives. A failed question says only
18+
that the AI did not answer; the reason stays in the log for an administrator.
19+
720
## 2026-11-12
821

922
**Let a team see its own external sites.** External sites groups, a new kind

‎documentation/ai-validation.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,3 +222,16 @@ grades from the learned rules and the AI grades already given, and with no
222222
provider set up the bulk button on the findings list becomes **Apply learned
223223
rules**, which answers from the rules alone and sends nothing anywhere. Every validation, bulk run,
224224
save, test and rule decision is in the audit log.
225+
226+
## Sharing the model with other tools
227+
228+
Another tool, like a security dashboard, can ask the model set up here instead
229+
of needing an AI key of its own. Tick Share with API tokens on the AI page,
230+
then make an API token with the ai scope on IDE tokens. Only an administrator
231+
can make one, and it stops working if its owner stops being an administrator
232+
or the sharing is turned off. The tool sends POST /api/v1/ai/complete with a
233+
prompt, optionally a system text, max_tokens and a one word purpose, and gets
234+
the model's answer back. What it sends goes to the provider as it came, so
235+
share it only with tools you trust with that. The per minute limit on the
236+
same card covers all tokens together, and every question shows on the AI usage
237+
page under api: and its purpose.

0 commit comments

Comments
 (0)