Files
Atrium/backend/app/routers/models.py
T
tobayah 0520eacd77 Pokazówka: merge #33 (dostawcy: wklej klucz) na main + #39
Konflikty: stałe kluczy osobistych zostają obok KEY_UNREADABLE przeniesionego przez #33; tabela i formularz dostawcy z #33 z kolumną i wyborem „Czyj klucz” z main.
2026-11-17 21:17:17 +01:00

202 lines
10 KiB
Python

"""Home's "ask the model": the models a person may use, and one streamed answer.
The address and key come only from `model_provider` (dredd-core, written by the hub's administrator
through `admin_providers`), resolved by `services/providers.call_target` from a model id — never from
settings, never from the request. Roman's conditions (Atrium #6) hold: session checked on the server,
a rate limit and caps on the question and the answer, an audit row per ask (who, which model, which
provider, whose key — never the question), and a refusal when nobody offers the model.
Only an administrator's ask may switch the model loaded on a local provider: anyone else asking for
another one gets a 409 naming the running model, before anything is loaded, evicted or audited.
There is no door for modules here: a module that calls a model itself reads the provider, and with
the key opt-in its key, from the shared tables (core's design).
"""
from __future__ import annotations
import json
import time
import uuid
from collections import defaultdict, deque
from datetime import date
from fastapi import APIRouter, Depends, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..errors import ConflictError, ValidationError
from ..integrations import model_server
from ..models import AppUser
from ..schemas import MyModelKeyIn
from ..services import audit, providers
router = APIRouter(tags=["models"])
MAX_ANSWER_TOKENS = 8192 # thinking models spend most of it reasoning; 1024 cut Qwen off before a word
#: The whole question as sent: history, tool calls, tool results AND the tool definitions. Counting
#: only `content` left `tools` / `tool_calls` unbounded (review on #27).
MAX_PROMPT_CHARS = 160_000 # history plus up to 8 rounds of tool results (up to 30k chars each); context is 64k tokens
#: Model rounds per person per minute: one question is several (each tool call costs a round).
#: ponytail: in-process, per worker; the image runs one worker.
ASKS_PER_MINUTE = 40
_asks: dict[uuid.UUID, deque] = defaultdict(deque)
#: The browser sends the sources (Home reads the modules with the asker's session); the model only reads them.
SYSTEM = """Jesteś asystentem kancelarii. Dziś jest {today}. Odpowiadasz WYŁĄCZNIE na podstawie ponumerowanych źródeł z pytania.
Zasady:
1. Każde zdanie z faktem kończ numerem źródła w nawiasie kwadratowym, np. [2].
2. Sumy, liczby i rankingi przepisuj ze źródeł typu „zestawienie” albo „ranking”. Nie licz sam.
3. Jeśli źródła nie zawierają odpowiedzi, napisz: „W danych, do których masz dostęp, nie znalazłem odpowiedzi.” i nic nie dopowiadaj. Nie twierdź, że czegoś nie ma w ogóle.
4. Pisz krótko, po polsku (po angielsku, jeśli pytanie jest po angielsku), bez identyfikatorów technicznych.
5. Pytanie niezwiązane z pracą kancelarii: odpowiedz jednym zdaniem, że pomagasz w danych kancelarii.
6. Dwie pierwsze wymiany w tej rozmowie to PRZYKŁADY formatu z fikcyjnymi danymi. Nigdy nie cytuj z nich nazw ani liczb.
7. Wcześniejsze odpowiedzi w tej rozmowie mogą być błędne. Każde nowe twierdzenie opieraj na aktualnych źródłach. Gdy użytkownik poprawia odpowiedź, sprawdź to w źródłach i albo przyznaj mu rację, albo wskaż źródło, które mówi inaczej."""
@router.get("/models")
def list_models(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
"""`configured` is false when this person may use no model at all, and Home stays the plain search.
ponytail: `choices` / `modules` stay empty for the console in #29 until its Models page goes."""
models = providers.usable_models(db, user)
return {"configured": bool(models), "models": models, "choices": {}, "modules": []}
# ── a person's own keys (dredd-core 0.18.0, key_mode = "user") ───────────────
# Write-only like the firm's key: in through `set_user_key`, out only as `key_prefix`.
@router.get("/me/model-keys")
def my_model_keys(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
return providers.my_keys(db, user)
@router.put("/me/model-keys/{provider_id}")
def set_my_model_key(provider_id: uuid.UUID, body: MyModelKeyIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
out = providers.set_my_key(db, user, provider_id, body.api_key, ip=client_ip(request))
db.commit()
return out
@router.delete("/me/model-keys/{provider_id}")
def clear_my_model_key(provider_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
out = providers.clear_my_key(db, user, provider_id, ip=client_ip(request))
db.commit()
return out
class Message(BaseModel):
role: str = Field(pattern="^(user|assistant|tool)$")
content: str | None = Field(default=None, max_length=MAX_PROMPT_CHARS)
tool_calls: list[dict] | None = Field(default=None, max_length=10)
tool_call_id: str | None = Field(default=None, max_length=200)
class AskIn(BaseModel):
"""The tools are the browser's: it runs each call against the modules with the asker's own
session, so what the model may read is decided by the modules, never here."""
model: str = Field(min_length=1, max_length=200)
messages: list[Message] = Field(min_length=1, max_length=80)
tools: list[dict] | None = Field(default=None, max_length=10)
tool_choice: str | None = Field(default=None, pattern="^(auto|required|none)$")
temperature: float | None = Field(default=None, ge=0, le=2)
top_p: float | None = Field(default=None, ge=0, le=1)
top_k: int | None = Field(default=None, ge=1, le=200)
presence_penalty: float | None = Field(default=None, ge=-2, le=2)
max_tokens: int | None = Field(default=None, ge=64, le=16384)
thinking: bool | None = None
def prompt_size(body: AskIn) -> int:
"""Characters of everything the model is sent besides the system prompt."""
return len(json.dumps(body.model_dump(include={"messages", "tools"}, exclude_none=True),
ensure_ascii=False))
def _sampling(body: AskIn, vendor: str | None = None) -> dict:
"""The person's sampling knobs, only those they set; the model's defaults otherwise.
`thinking=False` is `reasoning_effort: "none"`: against LM Studio with qwen/qwen3.5-9b (2026-10-29)
it alone stopped the reasoning (4 completion tokens, 0.4 s, no reasoning_content, against 316-863
tokens and 3-27 s by default). `chat_template_kwargs {"enable_thinking": false}`, `reasoning: "off"`
and a trailing `/no_think` were ignored or only shortened it, so they are not sent.
Do not swap this for the `chat_template_kwargs` form the Qwen3.5 model card recommends: re-measured
2026-11-03 (LM Studio, llama.cpp CUDA 2.41.0) the model still reasoned, spent the whole max_tokens
on it and returned an EMPTY answer, on /v1 and /api/v0 alike."""
out = body.model_dump(include={"temperature", "top_p", "top_k", "presence_penalty"},
exclude_none=True)
if body.thinking is False:
out["reasoning_effort"] = "none"
if vendor == "anthropic":
# Newer Claude models refuse `temperature` outright (400 "deprecated for this model",
# claude-opus-5-5, 2026-11-06); the knobs were tuned for small local models anyway.
for k in ("temperature", "top_p", "top_k"):
out.pop(k, None)
return out
def _rate_limit(user_id: uuid.UUID) -> None:
now = time.monotonic()
seen = _asks[user_id]
while seen and now - seen[0] > 60:
seen.popleft()
if len(seen) >= ASKS_PER_MINUTE:
raise ConflictError(f"Za dużo pytań naraz: najwyżej {ASKS_PER_MINUTE} na minutę.")
seen.append(now)
def _busy(exc: model_server.ModelBusy) -> dict:
"""The Problem Details extras of a refusal, also carried by the stream's `error` event."""
return {"code": exc.code, "en": exc.en, "running": exc.running}
def _event(payload: dict) -> bytes:
return f"event: atrium\ndata: {json.dumps(payload, ensure_ascii=False)}\n\n".encode()
@router.post("/models/ask")
async def ask(body: AskIn, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> StreamingResponse:
"""Server-sent events: the model server's own chunks, plus `event: atrium` for loading and errors."""
if prompt_size(body) > MAX_PROMPT_CHARS:
raise ValidationError("Pytanie z historią rozmowy jest za długie.")
target = providers.call_target(db, user, body.model)
_rate_limit(user.id)
root, key = model_server.server_root(target["base_url"]), target["key"]
may_switch = bool(user.is_admin)
loaded = await model_server.loaded_models(root, key) if target["kind"] == "local" else None
if loaded is not None and not may_switch:
try:
model_server.refuse_switch(loaded, body.model)
except model_server.ModelBusy as exc:
raise ConflictError(str(exc), _busy(exc)) from exc
audit.record(db, action="model.ask", entity_type="model", actor_id=user.id,
detail=body.model, ip=client_ip(request),
diff={"model": body.model, "provider": target["provider"],
"key_source": target["key_source"]})
db.commit()
messages = [{"role": "system", "content": SYSTEM.format(today=date.today())},
*(m.model_dump(exclude_none=True) for m in body.messages)]
tools = {"tools": body.tools, "tool_choice": body.tool_choice} if body.tools else {}
extra = {**tools, **_sampling(body, providers.vendor_of(target["base_url"]))}
max_tokens = body.max_tokens or MAX_ANSWER_TOKENS
async def events():
try:
if loaded is not None and not loaded.get(body.model):
yield _event({"loading": body.model})
await model_server.ensure_loaded(root, key, body.model, may_switch=may_switch)
yield _event({"loaded": body.model})
async for chunk in model_server.stream_chat(root, key, body.model, messages, max_tokens, **extra):
yield chunk
except model_server.ModelBusy as exc: # lost the race for the lock: same refusal, mid-stream
yield _event({"error": str(exc), **_busy(exc)})
except model_server.GatewayError as exc:
yield _event({"error": str(exc)})
return StreamingResponse(events(), media_type="text/event-stream",
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"})