280 lines
15 KiB
Python
280 lines
15 KiB
Python
"""Speaking to a model server on a provider row: the OpenAI chat protocol, and LM Studio's loading.
|
|
|
|
The address and key are ARGUMENTS, taken by the caller from `model_provider` through core's
|
|
`offering()` and `api_key()` — never from settings and never from a request, so nothing a caller
|
|
sends can point this process somewhere else.
|
|
|
|
**One model at a time on LM Studio.** The card this targets holds one model; a second load next to
|
|
the first ends in LM Studio's `HTTP 400 {"error":"terminated"}`. So every load goes through
|
|
`LOAD_LOCK`, unloads whatever is in memory first, and re-reads the listing once it holds the lock
|
|
(somebody ahead in the queue may have loaded the same model already). Asks are not serialised: LM
|
|
Studio queues requests to the one loaded model on its own. Other servers (Ollama, vLLM, a cloud API)
|
|
load on their own; `loaded_models` answers `None` for them and nothing is loaded by hand.
|
|
|
|
**Only an administrator switches the model.** Everybody shares the one card, so anyone else asking
|
|
for another model is refused (`ModelBusy`) and nothing is loaded or evicted; with nothing in memory
|
|
anyone may load the first. The router refuses up front with a 409, and `ensure_loaded` decides again
|
|
under the lock, because the answer read before the queue can be stale by the time it gets its turn.
|
|
|
|
**"Whatever is in memory" means chat models.** An embedding model is not what a switch replaces and
|
|
stays loaded. `/api/v1/models` is the listing with instance ids, the ones an unload takes;
|
|
`/api/v0/models` is the one whose `type` we rely on. So `ensure_loaded` reads both, and an instance
|
|
with no chat type in `/api/v0` is left alone.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import re
|
|
from collections.abc import AsyncIterator
|
|
|
|
import httpx
|
|
|
|
from app.errors import ValidationError
|
|
|
|
#: Loading an 11B model from disk took about a minute on the reference machine.
|
|
LOAD_TIMEOUT = httpx.Timeout(connect=5.0, read=300.0, write=30.0, pool=10.0)
|
|
LIST_TIMEOUT = httpx.Timeout(5.0)
|
|
#: The window Atrium loads a model with when nothing is in memory.
|
|
DEFAULT_CONTEXT = 65536 # history, up to 8 rounds of tool results (~6k chars each) and a thinking model's answer
|
|
#: LM Studio model types that answer a chat. `embeddings` models only turn text into vectors.
|
|
CHAT_TYPES = frozenset({"llm", "vlm"})
|
|
|
|
LOAD_LOCK = asyncio.Lock()
|
|
|
|
|
|
class GatewayError(Exception):
|
|
"""The model server is unreachable or refused; the message is a sentence for a person."""
|
|
|
|
|
|
class ModelBusy(GatewayError):
|
|
"""Another model is running and this asker may not switch it."""
|
|
|
|
code = "model_busy"
|
|
|
|
def __init__(self, running: str) -> None:
|
|
super().__init__(f"Teraz działa model {running}. Zmienić go może tylko administrator.")
|
|
self.running = running
|
|
self.en = f"The model running now is {running}. Only an administrator can switch it."
|
|
|
|
|
|
def server_root(base_url: str) -> str:
|
|
"""`http://host:1234` and `http://host:1234/v1` name the same server — the same reading as
|
|
Compass's `agents/client.server_root`, so one provider row means one thing in both."""
|
|
base = base_url.rstrip("/")
|
|
return base[:-3].rstrip("/") if base.endswith("/v1") else base
|
|
|
|
|
|
def _headers(key: str | None) -> dict[str, str]:
|
|
return {"Authorization": f"Bearer {key}"} if key else {}
|
|
|
|
|
|
async def _json(client: httpx.AsyncClient, method: str, url: str, key: str | None,
|
|
body: dict | None = None):
|
|
try:
|
|
resp = await client.request(method, url, headers=_headers(key), json=body)
|
|
except httpx.HTTPError as exc:
|
|
raise GatewayError(f"Serwer modeli nie odpowiada ({type(exc).__name__}).") from exc
|
|
if resp.status_code != 200:
|
|
raise GatewayError(f"Serwer modeli odpowiedział HTTP {resp.status_code}.")
|
|
return resp.json()
|
|
|
|
|
|
async def loaded_models(root: str, key: str | None) -> dict[str, bool] | None:
|
|
"""`{model id: in memory}` from LM Studio's own listing, or `None` when this server has no such
|
|
listing (it is not LM Studio, or it does not answer): then nothing is loaded by hand."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=LIST_TIMEOUT) as client:
|
|
listing = await _json(client, "GET", f"{root}/api/v0/models", key)
|
|
except GatewayError:
|
|
return None
|
|
return {m["id"]: m.get("state") == "loaded"
|
|
for m in listing.get("data", []) if m.get("type") in CHAT_TYPES and m.get("id")}
|
|
|
|
|
|
def refuse_switch(loaded: dict[str, bool], model: str) -> None:
|
|
"""`ModelBusy` when a chat model other than `model` is in memory; nothing loaded passes."""
|
|
running = [m for m, in_memory in loaded.items() if in_memory]
|
|
if running and model not in running:
|
|
raise ModelBusy(running[0])
|
|
|
|
|
|
async def ensure_loaded(root: str, key: str | None, model: str, *, may_switch: bool) -> None:
|
|
"""Put `model` in memory on LM Studio, unloading the chat model there first. Without `may_switch`
|
|
a different chat model in memory is `ModelBusy`, and nothing is touched."""
|
|
async with LOAD_LOCK, httpx.AsyncClient(timeout=LOAD_TIMEOUT) as client:
|
|
typed = await _json(client, "GET", f"{root}/api/v0/models", key)
|
|
chat = {m.get("id") for m in typed.get("data", []) if m.get("type") in CHAT_TYPES}
|
|
listing = await _json(client, "GET", f"{root}/api/v1/models", key)
|
|
instances = [(entry.get("key"), inst["id"])
|
|
for entry in listing.get("models", []) for inst in entry.get("loaded_instances", ())
|
|
if entry.get("key") in chat or inst["id"] in chat]
|
|
if any(model in pair for pair in instances):
|
|
return # loaded by whoever held the lock before us
|
|
if instances and not may_switch:
|
|
raise ModelBusy(instances[0][0] or instances[0][1])
|
|
for _, instance_id in instances:
|
|
await _json(client, "POST", f"{root}/api/v1/models/unload", key, {"instance_id": instance_id})
|
|
# Never more than the model was trained on: Bielik 11B v3.x stops at 32 768, and asking for
|
|
# DEFAULT_CONTEXT stretched it past what it reads well. LM Studio says so in `max_context_length`.
|
|
trained = next((m.get("max_context_length") for m in typed.get("data", []) if m.get("id") == model), None)
|
|
context = min(DEFAULT_CONTEXT, trained) if isinstance(trained, int) and trained > 0 else DEFAULT_CONTEXT
|
|
await _json(client, "POST", f"{root}/api/v1/models/load", key,
|
|
{"model": model, "context_length": context})
|
|
|
|
|
|
async def stream_chat(root: str, key: str | None, model: str, messages: list[dict],
|
|
max_tokens: int, **extra) -> AsyncIterator[bytes]:
|
|
"""The server's own server-sent events for one answer, passed through unchanged. `extra` carries
|
|
the OpenAI `tools` / `tool_choice` when the caller offers tools, and the sampling and reasoning
|
|
fields the person set (`temperature`, `top_p`, `top_k`, `presence_penalty`, `reasoning_effort`)."""
|
|
body = {"model": model, "messages": messages, "max_tokens": max_tokens, "stream": True, **extra}
|
|
async with httpx.AsyncClient(timeout=LOAD_TIMEOUT) as client:
|
|
try:
|
|
# Identity: the raw bytes pass through to the browser with no Content-Encoding of ours, and a
|
|
# cloud API gzips by default (api.anthropic.com did, 2026-11-06) — the chat read garbage.
|
|
async with client.stream("POST", f"{root}/v1/chat/completions",
|
|
headers={**_headers(key), "Accept-Encoding": "identity"},
|
|
json=body) as resp:
|
|
if resp.status_code != 200:
|
|
# The server's own reason (OpenAI-shaped `error.message`), capped: a bare "HTTP 400"
|
|
# left a refused parameter invisible. The key travels in a header, never echoed here.
|
|
raw = b""
|
|
async for chunk in resp.aiter_raw():
|
|
raw += chunk
|
|
if len(raw) > 4096:
|
|
break
|
|
try:
|
|
why = json.loads(raw)["error"]["message"]
|
|
except (ValueError, KeyError, TypeError):
|
|
why = ""
|
|
why = f": {str(why)[:300]}" if why else ""
|
|
raise GatewayError(f"Serwer modeli odpowiedział HTTP {resp.status_code}{why}")
|
|
async for chunk in resp.aiter_raw():
|
|
yield chunk
|
|
except httpx.HTTPError as exc:
|
|
raise GatewayError(f"Serwer modeli nie odpowiada ({type(exc).__name__}).") from exc
|
|
|
|
|
|
# ── listing what a provider offers (the administrator's "discover" / "refresh") ──────────────────
|
|
# An administrator-steered outbound call, SSRF-shaped like the module probe: no redirects, one
|
|
# deadline for the whole exchange, and a capped body. The key travels only in a header and never
|
|
# appears in an error.
|
|
|
|
LIST_DEADLINE = 10.0
|
|
LIST_MAX_BYTES = 2 * 1024 * 1024
|
|
#: Vendors whose address is a cloud API, not somebody's own server: no LM Studio listing to ask.
|
|
CLOUD_VENDORS = frozenset({"openai", "openrouter", "anthropic"})
|
|
# ponytail: a pattern, not a catalogue of model ids — extend it when a non-chat model leaks through.
|
|
NON_CHAT = re.compile(r"embed|tts|whisper|dall-e|image|moderation|audio|transcribe|realtime|rerank", re.I)
|
|
|
|
|
|
def _refusal(code: str, pl: str, en: str) -> ValidationError:
|
|
return ValidationError(pl, {"code": code, "en": en})
|
|
|
|
|
|
def _unreachable(why_pl: str, why_en: str) -> ValidationError:
|
|
return _refusal("provider_unreachable", f"Serwer modeli nie odpowiada: {why_pl}.",
|
|
f"The model server does not answer: {why_en}.")
|
|
|
|
|
|
class _NotFound(Exception):
|
|
"""A non-200 answer that is not a refusal of the key — for an optional listing, just absent."""
|
|
|
|
|
|
async def _capped_json(client: httpx.AsyncClient, url: str, headers: dict[str, str]):
|
|
# Raw bytes, identity only: a decoded read is a decompression bomb (one gzip chunk → many MB).
|
|
async with client.stream("GET", url, headers={**headers, "Accept-Encoding": "identity"}) as resp:
|
|
if resp.is_redirect:
|
|
raise _unreachable("przekierowanie odrzucone", "redirect refused")
|
|
if resp.status_code in (401, 403):
|
|
raise _refusal("provider_key_refused", "Serwer modeli odrzucił klucz.",
|
|
"The model server refused the key.")
|
|
if resp.status_code != 200:
|
|
raise _NotFound(resp.status_code)
|
|
if resp.headers.get("content-encoding", "identity").lower() != "identity":
|
|
raise _unreachable("odpowiedź jest skompresowana", "the answer is compressed")
|
|
body = bytearray()
|
|
async for chunk in resp.aiter_raw():
|
|
body += chunk
|
|
if len(body) > LIST_MAX_BYTES:
|
|
raise _unreachable("odpowiedź jest za duża", "the answer is too large")
|
|
try:
|
|
return json.loads(body)
|
|
except (ValueError, RecursionError): # 2 MB of `[` nests deeper than the decoder recurses
|
|
raise _unreachable("odpowiedź nie jest JSON-em", "the answer is not JSON") from None
|
|
|
|
|
|
def _data(listing) -> list:
|
|
"""`listing["data"]` when somebody else's server answered the documented shape; anything else
|
|
is a 422, never an AttributeError (a 500) on untrusted input."""
|
|
data = listing.get("data") if isinstance(listing, dict) else None
|
|
if not isinstance(data, list):
|
|
raise _unreachable("nieoczekiwany kształt odpowiedzi", "unexpected answer shape")
|
|
return data
|
|
|
|
|
|
async def _openai_models(client: httpx.AsyncClient, base_url: str, key: str | None,
|
|
vendor: str | None) -> list[dict]:
|
|
root, headers = server_root(base_url), _headers(key)
|
|
try:
|
|
listing = await _capped_json(client, f"{root}/v1/models", headers)
|
|
except _NotFound as exc:
|
|
raise _unreachable(f"HTTP {exc.args[0]}", f"HTTP {exc.args[0]}") from None
|
|
models = [{"id": m["id"], "dialect": "openai",
|
|
**({"context_window": m["max_model_len"]}
|
|
if isinstance(m.get("max_model_len"), int) and m["max_model_len"] > 0 else {})}
|
|
for m in _data(listing) if isinstance(m, dict) and isinstance(m.get("id"), str)]
|
|
if vendor not in CLOUD_VENDORS:
|
|
# LM Studio's own listing says which models chat; `/v1/models` lists embeddings too. Same
|
|
# reading as `loaded_models`, but through the capped reader. Not LM Studio → no listing.
|
|
# Optional: a server behind a login page answers this path with a 302, HTML or a 401, and
|
|
# that says nothing about `/v1/models`, which already answered — any refusal = no listing.
|
|
try:
|
|
lm_data = _data(await _capped_json(client, f"{root}/api/v0/models", headers))
|
|
except (_NotFound, ValidationError):
|
|
lm_data = []
|
|
types = {m.get("id"): m.get("type") for m in lm_data if isinstance(m, dict)}
|
|
models = [m for m in models if types.get(m["id"], "llm") in CHAT_TYPES]
|
|
return models
|
|
|
|
|
|
#: https://platform.claude.com/docs/en/api/versioning (latest on 2026-11-06); the listing itself is
|
|
#: https://platform.claude.com/docs/en/api/models-list — `lifecycle`, `max_input_tokens`.
|
|
ANTHROPIC_VERSION = "2026-10-21"
|
|
|
|
|
|
async def _anthropic_models(client: httpx.AsyncClient, base_url: str, key: str | None) -> list[dict]:
|
|
headers = {"anthropic-version": ANTHROPIC_VERSION, **({"x-api-key": key} if key else {})}
|
|
# ponytail: one page of 1000 (the maximum), no `after_id` paging — the catalogue is far smaller.
|
|
try:
|
|
listing = await _capped_json(client, f"{base_url.rstrip('/')}/models?limit=1000", headers)
|
|
except _NotFound as exc:
|
|
raise _unreachable(f"HTTP {exc.args[0]}", f"HTTP {exc.args[0]}") from None
|
|
# The default listing includes `deprecated` models, closed to new adopters: offer active only.
|
|
return [{"id": m["id"], "dialect": "openai",
|
|
**({"context_window": m["max_input_tokens"]}
|
|
if isinstance(m.get("max_input_tokens"), int) and m["max_input_tokens"] > 0 else {})}
|
|
for m in _data(listing)
|
|
if isinstance(m, dict) and isinstance(m.get("id"), str) and m.get("lifecycle") == "active"]
|
|
|
|
|
|
async def list_models(base_url: str, key: str | None, vendor: str | None, *,
|
|
transport: httpx.AsyncBaseTransport | None = None) -> list[dict]:
|
|
"""The chat models a provider offers under this key, as `{id, context_window?, dialect}`.
|
|
Refusals are 422 Problem Details with `code` `provider_key_refused` / `provider_unreachable` /
|
|
`provider_no_models`. `transport` exists for tests."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=LIST_DEADLINE, follow_redirects=False,
|
|
transport=transport) as client:
|
|
listing = (_anthropic_models(client, base_url, key) if vendor == "anthropic"
|
|
else _openai_models(client, base_url, key, vendor))
|
|
models = await asyncio.wait_for(listing, LIST_DEADLINE)
|
|
except (httpx.HTTPError, TimeoutError) as exc:
|
|
raise _unreachable(type(exc).__name__, type(exc).__name__) from None
|
|
models = [m for m in models if not NON_CHAT.search(m["id"])]
|
|
if not models:
|
|
raise _refusal("provider_no_models", "Pod tym kluczem/adresem nie ma żadnego modelu czatu.",
|
|
"There is no chat model under this key/address.")
|
|
return models
|