modelsaar 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- modelsaar/__init__.py +13 -0
- modelsaar/adapters/__init__.py +27 -0
- modelsaar/adapters/base.py +274 -0
- modelsaar/adapters/ollama.py +317 -0
- modelsaar/adapters/openai_compat.py +296 -0
- modelsaar/catalogue/__init__.py +72 -0
- modelsaar/catalogue/starter.yaml +435 -0
- modelsaar/cli.py +880 -0
- modelsaar/clientconfig/__init__.py +364 -0
- modelsaar/config.py +631 -0
- modelsaar/doctor.py +233 -0
- modelsaar/evaluation/__init__.py +1 -0
- modelsaar/evaluation/fixtures/tasks.jsonl +47 -0
- modelsaar/evaluation/harness.py +768 -0
- modelsaar/evaluation/judge.py +173 -0
- modelsaar/evaluation/sandbox.py +341 -0
- modelsaar/evaluation/scoring.py +233 -0
- modelsaar/learning.py +227 -0
- modelsaar/lifecycle.py +208 -0
- modelsaar/pipelines.py +439 -0
- modelsaar/probes.py +526 -0
- modelsaar/protocol/__init__.py +1 -0
- modelsaar/protocol/anthropic.py +401 -0
- modelsaar/protocol/decisions.py +229 -0
- modelsaar/protocol/openai.py +322 -0
- modelsaar/protocol/responses.py +560 -0
- modelsaar/protocol/sse.py +181 -0
- modelsaar/registry.py +229 -0
- modelsaar/responses_store.py +117 -0
- modelsaar/routing/__init__.py +1 -0
- modelsaar/routing/admission.py +359 -0
- modelsaar/routing/affinity.py +131 -0
- modelsaar/routing/cascade.py +53 -0
- modelsaar/routing/classifier.py +298 -0
- modelsaar/routing/decision.py +85 -0
- modelsaar/routing/eligibility.py +158 -0
- modelsaar/routing/requirements.py +290 -0
- modelsaar/routing/router.py +1026 -0
- modelsaar/routing/scoring.py +179 -0
- modelsaar/routing/tokens.py +114 -0
- modelsaar/runtime.py +82 -0
- modelsaar/security.py +63 -0
- modelsaar/server.py +1546 -0
- modelsaar/static/status.html +95 -0
- modelsaar/store.py +208 -0
- modelsaar/testing/__init__.py +1 -0
- modelsaar/testing/fakebackend.py +661 -0
- modelsaar-0.2.0.dist-info/METADATA +285 -0
- modelsaar-0.2.0.dist-info/RECORD +54 -0
- modelsaar-0.2.0.dist-info/WHEEL +5 -0
- modelsaar-0.2.0.dist-info/entry_points.txt +2 -0
- modelsaar-0.2.0.dist-info/licenses/LICENSE +202 -0
- modelsaar-0.2.0.dist-info/licenses/NOTICE +18 -0
- modelsaar-0.2.0.dist-info/top_level.txt +1 -0
modelsaar/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""ModelSaar - intelligent routing for local AI models.
|
|
2
|
+
|
|
3
|
+
One OpenAI-compatible endpoint that selects the most suitable *eligible* local
|
|
4
|
+
deployment per request, explains the decision, and preserves the client's
|
|
5
|
+
semantics (tools, media, schemas, streaming).
|
|
6
|
+
|
|
7
|
+
Created by Gopala Subramanium.
|
|
8
|
+
https://me.sgopala.com
|
|
9
|
+
See LICENSE and NOTICE for project and third-party attribution.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
__version__ = "0.2.0"
|
|
13
|
+
CONFIG_VERSION = 1
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Backend adapters. Add a runtime by subclassing BaseAdapter and registering it."""
|
|
2
|
+
|
|
3
|
+
from .base import AdapterError, BaseAdapter, UpstreamResponse, UpstreamStream
|
|
4
|
+
from .ollama import OllamaAdapter
|
|
5
|
+
from .openai_compat import OpenAICompatAdapter
|
|
6
|
+
|
|
7
|
+
ADAPTER_TYPES = {
|
|
8
|
+
"ollama": OllamaAdapter,
|
|
9
|
+
"openai_compatible": OpenAICompatAdapter,
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def register_adapter(type_name: str, cls: type[BaseAdapter]) -> None:
|
|
14
|
+
"""Plugin hook: register an additional adapter type without touching the router."""
|
|
15
|
+
ADAPTER_TYPES[type_name] = cls
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ADAPTER_TYPES",
|
|
20
|
+
"AdapterError",
|
|
21
|
+
"BaseAdapter",
|
|
22
|
+
"OllamaAdapter",
|
|
23
|
+
"OpenAICompatAdapter",
|
|
24
|
+
"UpstreamResponse",
|
|
25
|
+
"UpstreamStream",
|
|
26
|
+
"register_adapter",
|
|
27
|
+
]
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Adapter base: a backend is contacted only at its configured host (allow-list)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import AsyncIterator
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any
|
|
10
|
+
from urllib.parse import urlsplit
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
from ..config import BackendConfig
|
|
15
|
+
from ..registry import Deployment
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AdapterError(Exception):
|
|
19
|
+
"""Transport-level or backend-level failure. ``retryable`` is only True when
|
|
20
|
+
the failure happened before any response bytes were received and the
|
|
21
|
+
operation is safe to repeat."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, message: str, status: int = 502, retryable: bool = False, kind: str = "upstream_error"):
|
|
24
|
+
super().__init__(message)
|
|
25
|
+
self.message = message
|
|
26
|
+
self.status = status
|
|
27
|
+
self.retryable = retryable
|
|
28
|
+
self.kind = kind
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class UpstreamResponse:
|
|
33
|
+
status: int
|
|
34
|
+
body: dict[str, Any]
|
|
35
|
+
headers: dict[str, str]
|
|
36
|
+
elapsed_ms: float
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class UpstreamStream:
|
|
41
|
+
"""An open streaming response. ``aiter_bytes`` yields raw bytes; ``close``
|
|
42
|
+
must be awaited exactly once."""
|
|
43
|
+
|
|
44
|
+
status: int
|
|
45
|
+
headers: dict[str, str]
|
|
46
|
+
_response: httpx.Response
|
|
47
|
+
_stream_ctx: Any
|
|
48
|
+
started_at: float = field(default_factory=time.monotonic)
|
|
49
|
+
|
|
50
|
+
async def aiter_bytes(self) -> AsyncIterator[bytes]:
|
|
51
|
+
"""Yield raw bytes. A read timeout while the stream is open is typed as an
|
|
52
|
+
``AdapterError(kind="timeout")`` so callers can hold occupancy as uncertain: the backend may
|
|
53
|
+
still be generating after the gateway stops waiting."""
|
|
54
|
+
try:
|
|
55
|
+
async for chunk in self._response.aiter_bytes():
|
|
56
|
+
yield chunk
|
|
57
|
+
except httpx.ReadTimeout as e:
|
|
58
|
+
raise AdapterError("read timeout while streaming", status=504, retryable=False, kind="timeout") from e
|
|
59
|
+
except httpx.HTTPError as e:
|
|
60
|
+
raise AdapterError(f"{e.__class__.__name__}: {e}", status=502, retryable=False, kind="transport") from e
|
|
61
|
+
|
|
62
|
+
async def aread(self) -> bytes:
|
|
63
|
+
return await self._response.aread()
|
|
64
|
+
|
|
65
|
+
async def close(self) -> None:
|
|
66
|
+
try:
|
|
67
|
+
await self._stream_ctx.__aexit__(None, None, None)
|
|
68
|
+
except Exception: # pragma: no cover - best effort
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class BaseAdapter:
|
|
73
|
+
type_name = "base"
|
|
74
|
+
# Capabilities the *adapter path* itself cannot provide regardless of model.
|
|
75
|
+
adapter_capabilities: dict[str, str] = {}
|
|
76
|
+
|
|
77
|
+
def __init__(self, cfg: BackendConfig, allowed_hosts: set[str]) -> None:
|
|
78
|
+
self.cfg = cfg
|
|
79
|
+
self.base_url = cfg.base_url
|
|
80
|
+
parts = urlsplit(self.base_url)
|
|
81
|
+
self.host = parts.netloc
|
|
82
|
+
if self.host not in allowed_hosts and parts.hostname not in allowed_hosts:
|
|
83
|
+
raise ValueError(f"backend {cfg.id}: host {self.host} is not in security.allowed_backend_hosts")
|
|
84
|
+
api_key = cfg.api_key or (os.environ.get(cfg.api_key_env) if cfg.api_key_env else None)
|
|
85
|
+
headers = {"User-Agent": "modelsaar/0.2"}
|
|
86
|
+
if api_key:
|
|
87
|
+
headers["Authorization"] = f"Bearer {api_key}"
|
|
88
|
+
self._client = httpx.AsyncClient(
|
|
89
|
+
base_url=self.base_url,
|
|
90
|
+
headers=headers,
|
|
91
|
+
timeout=httpx.Timeout(cfg.timeout_s, connect=cfg.connect_timeout_s),
|
|
92
|
+
follow_redirects=False, # never follow redirects to other hosts
|
|
93
|
+
limits=httpx.Limits(max_connections=cfg.max_concurrent + 4),
|
|
94
|
+
)
|
|
95
|
+
self.runtime_version: str = ""
|
|
96
|
+
# Execution endpoint identity used in deployment fingerprints (no credentials).
|
|
97
|
+
self.endpoint = f"{parts.scheme}://{parts.netloc}{parts.path.rstrip('/')}"
|
|
98
|
+
# Server root on the SAME host (base_url without a trailing /v1): some runtimes serve native
|
|
99
|
+
# operations (vLLM /tokenize, llama.cpp /props, /tokenize, /apply-template) outside /v1.
|
|
100
|
+
root_path = parts.path.rstrip("/")
|
|
101
|
+
if root_path.endswith("/v1"):
|
|
102
|
+
root_path = root_path[: -len("/v1")]
|
|
103
|
+
self._root = f"{parts.scheme}://{parts.netloc}{root_path}"
|
|
104
|
+
|
|
105
|
+
def _root_url(self, path: str) -> str:
|
|
106
|
+
"""Absolute URL of a native (non-/v1) path on this backend's own host. The path must be relative;
|
|
107
|
+
the host is fixed at construction and cannot be influenced by a request."""
|
|
108
|
+
if "://" in path or path.startswith("//") or not path.startswith("/"):
|
|
109
|
+
raise AdapterError("adapter paths must be relative", status=500, kind="internal")
|
|
110
|
+
return self._root + path
|
|
111
|
+
|
|
112
|
+
async def aclose(self) -> None:
|
|
113
|
+
await self._client.aclose()
|
|
114
|
+
|
|
115
|
+
# ----------------------------------------------------------------- #
|
|
116
|
+
def _url(self, path: str) -> str:
|
|
117
|
+
# Defensive: a path must be relative; it can never change the host.
|
|
118
|
+
if "://" in path or path.startswith("//"):
|
|
119
|
+
raise AdapterError("adapter paths must be relative", status=500, kind="internal")
|
|
120
|
+
return path
|
|
121
|
+
|
|
122
|
+
async def _get_json(self, path: str, **kw: Any) -> dict[str, Any]:
|
|
123
|
+
try:
|
|
124
|
+
r = await self._client.get(self._url(path), **kw)
|
|
125
|
+
except httpx.HTTPError as e:
|
|
126
|
+
raise AdapterError(f"{self.cfg.id}: {e.__class__.__name__}: {e}", retryable=True, kind="connect") from e
|
|
127
|
+
if r.status_code >= 400:
|
|
128
|
+
raise AdapterError(f"{self.cfg.id}: GET {path} -> {r.status_code}", status=502)
|
|
129
|
+
try:
|
|
130
|
+
return r.json()
|
|
131
|
+
except ValueError as e:
|
|
132
|
+
raise AdapterError(f"{self.cfg.id}: non-JSON response from {path}", status=502) from e
|
|
133
|
+
|
|
134
|
+
def _deadline(self, timeout: float | None) -> httpx.Timeout:
|
|
135
|
+
"""The effective deadline for one upstream call: the backend's configured ``timeout_s`` or the
|
|
136
|
+
caller's (server) deadline, whichever is tighter. A caller passing ``None`` gets the backend
|
|
137
|
+
deadline, never "no timeout" (an explicit ``None`` would disable the client timeout in httpx)."""
|
|
138
|
+
read = self.cfg.timeout_s if timeout is None else min(float(timeout), self.cfg.timeout_s)
|
|
139
|
+
return httpx.Timeout(read, connect=min(self.cfg.connect_timeout_s, read))
|
|
140
|
+
|
|
141
|
+
async def _post_json(self, path: str, body: dict[str, Any], timeout: float | None = None) -> UpstreamResponse:
|
|
142
|
+
t0 = time.monotonic()
|
|
143
|
+
try:
|
|
144
|
+
r = await self._client.post(self._url(path), json=body, timeout=self._deadline(timeout))
|
|
145
|
+
except (httpx.ConnectError, httpx.ConnectTimeout) as e:
|
|
146
|
+
raise AdapterError(f"{self.cfg.id}: connection failed: {e}", retryable=True, kind="connect") from e
|
|
147
|
+
except httpx.ReadTimeout as e:
|
|
148
|
+
raise AdapterError(f"{self.cfg.id}: read timeout", status=504, retryable=False, kind="timeout") from e
|
|
149
|
+
except httpx.HTTPError as e:
|
|
150
|
+
raise AdapterError(f"{self.cfg.id}: {e.__class__.__name__}: {e}", retryable=False, kind="transport") from e
|
|
151
|
+
elapsed = (time.monotonic() - t0) * 1000
|
|
152
|
+
try:
|
|
153
|
+
data = r.json()
|
|
154
|
+
except ValueError:
|
|
155
|
+
data = {"error": {"message": r.text[:500], "type": "upstream_non_json"}}
|
|
156
|
+
return UpstreamResponse(status=r.status_code, body=data, headers=dict(r.headers), elapsed_ms=elapsed)
|
|
157
|
+
|
|
158
|
+
async def _post_stream(self, path: str, body: dict[str, Any], timeout: float | None = None) -> UpstreamStream:
|
|
159
|
+
req = self._client.build_request("POST", self._url(path), json=body, timeout=self._deadline(timeout))
|
|
160
|
+
try:
|
|
161
|
+
resp = await self._client.send(req, stream=True)
|
|
162
|
+
except (httpx.ConnectError, httpx.ConnectTimeout) as e:
|
|
163
|
+
raise AdapterError(f"{self.cfg.id}: connection failed: {e}", retryable=True, kind="connect") from e
|
|
164
|
+
except httpx.ReadTimeout as e:
|
|
165
|
+
raise AdapterError(f"{self.cfg.id}: read timeout", status=504, retryable=False, kind="timeout") from e
|
|
166
|
+
except httpx.HTTPError as e:
|
|
167
|
+
raise AdapterError(f"{self.cfg.id}: {e.__class__.__name__}: {e}", retryable=False, kind="transport") from e
|
|
168
|
+
|
|
169
|
+
class _Ctx:
|
|
170
|
+
async def __aexit__(self_inner, *a: object) -> None:
|
|
171
|
+
await resp.aclose()
|
|
172
|
+
|
|
173
|
+
return UpstreamStream(status=resp.status_code, headers=dict(resp.headers), _response=resp, _stream_ctx=_Ctx())
|
|
174
|
+
|
|
175
|
+
# ----------------------------------------------------------------- #
|
|
176
|
+
# Interface
|
|
177
|
+
async def health(self) -> tuple[bool, str]:
|
|
178
|
+
raise NotImplementedError
|
|
179
|
+
|
|
180
|
+
async def discover(self) -> list[Deployment]:
|
|
181
|
+
raise NotImplementedError
|
|
182
|
+
|
|
183
|
+
# True when ``loaded_models`` is a real observation of the runtime (e.g. Ollama /api/ps). Pools
|
|
184
|
+
# keep assumed residency for deployments of a backend that cannot report it.
|
|
185
|
+
reports_residency: bool = False
|
|
186
|
+
# Outcome of the most recent residency query: True = observed, False = the query failed (the
|
|
187
|
+
# runtime is up but did not answer /api/ps), None = never asked / not a reporting runtime.
|
|
188
|
+
# A failed query is NOT an empty resident set; callers keep known/assumed occupancy.
|
|
189
|
+
last_residency_observation_ok: bool | None = None
|
|
190
|
+
|
|
191
|
+
async def loaded_models(self) -> dict[str, dict[str, Any]] | None:
|
|
192
|
+
"""Return {model_name: info} for models currently resident in memory when the runtime exposes
|
|
193
|
+
it, ``{}`` when it does not report residency, and ``None`` when the query failed."""
|
|
194
|
+
return {}
|
|
195
|
+
|
|
196
|
+
async def chat(self, dep: Deployment, body: dict[str, Any], stream: bool, timeout: float | None = None):
|
|
197
|
+
raise NotImplementedError
|
|
198
|
+
|
|
199
|
+
async def embeddings(self, dep: Deployment, body: dict[str, Any], timeout: float | None = None) -> UpstreamResponse:
|
|
200
|
+
raise NotImplementedError
|
|
201
|
+
|
|
202
|
+
async def embed_media(self, dep: Deployment, part: dict[str, Any], timeout: float | None = None) -> UpstreamResponse:
|
|
203
|
+
"""Embed ONE inline image or audio content part. Backends without a verified wire contract refuse."""
|
|
204
|
+
raise AdapterError(
|
|
205
|
+
f"the {self.type_name} backend path has no verified wire contract for image/audio embeddings",
|
|
206
|
+
status=501,
|
|
207
|
+
kind="unsupported",
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
async def decide(
|
|
211
|
+
self,
|
|
212
|
+
dep: Deployment,
|
|
213
|
+
state: Any,
|
|
214
|
+
questions: dict[str, Any],
|
|
215
|
+
timeout: float | None = None,
|
|
216
|
+
images: list[str] | None = None,
|
|
217
|
+
) -> UpstreamResponse:
|
|
218
|
+
"""Ask a decision model (``role == "decision"``) one or more typed questions about ``state`` (a
|
|
219
|
+
non-empty string, or an object/array) and return its native answer (per-option probabilities, no
|
|
220
|
+
generated text). ``images`` are base64 strings shared by all questions (vision decision models
|
|
221
|
+
only). Backends without a decision endpoint raise ``AdapterError(kind="unsupported")`` so callers
|
|
222
|
+
fail closed."""
|
|
223
|
+
raise AdapterError(
|
|
224
|
+
f"{self.cfg.id}: backend type {getattr(self.cfg, 'type', 'backend')!r} has no decision-model endpoint",
|
|
225
|
+
status=501,
|
|
226
|
+
kind="unsupported",
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
async def tokenize(self, dep: Deployment, text: str) -> int | None:
|
|
230
|
+
"""Exact token count if the runtime supports it; None otherwise."""
|
|
231
|
+
return None
|
|
232
|
+
|
|
233
|
+
# ---- managed lifecycle (only ever called for a backend with lifecycle.managed: true) ----
|
|
234
|
+
def lifecycle_operations(self) -> frozenset[str]:
|
|
235
|
+
"""Which of {"load", "unload"} this backend path can perform."""
|
|
236
|
+
return frozenset()
|
|
237
|
+
|
|
238
|
+
async def load_model(self, dep: Deployment, keep_alive_s: int | None, timeout: float) -> None:
|
|
239
|
+
raise AdapterError(f"{self.type_name} cannot load models", status=501, kind="unsupported")
|
|
240
|
+
|
|
241
|
+
async def unload_model(self, dep: Deployment, timeout: float) -> None:
|
|
242
|
+
raise AdapterError(f"{self.type_name} cannot unload models", status=501, kind="unsupported")
|
|
243
|
+
|
|
244
|
+
async def tokenize_chat(self, dep: Deployment, body: dict[str, Any]) -> tuple[int, str] | None:
|
|
245
|
+
"""Exact input-token count of the whole chat request as the runtime itself would render it (chat
|
|
246
|
+
template applied, tool definitions included), with a label naming how it was obtained; None when
|
|
247
|
+
the runtime offers no such operation. Media tokens are not included (the caller keeps its
|
|
248
|
+
per-image allowance)."""
|
|
249
|
+
return None
|
|
250
|
+
|
|
251
|
+
def forwardable_fields(self) -> frozenset[str]:
|
|
252
|
+
from ..protocol.openai import FORWARDABLE_CHAT_FIELDS
|
|
253
|
+
|
|
254
|
+
return FORWARDABLE_CHAT_FIELDS
|
|
255
|
+
|
|
256
|
+
def unsupported_fields(self) -> frozenset[str]:
|
|
257
|
+
"""Fields that this backend path cannot honour; the router rejects requests using them."""
|
|
258
|
+
return frozenset()
|
|
259
|
+
|
|
260
|
+
def cache_prompt_policy(self, value: bool) -> tuple[bool, str]:
|
|
261
|
+
"""Disposition of the client-compatibility hint ``cache_prompt`` for this backend path.
|
|
262
|
+
|
|
263
|
+
Returns (accepted, note). No shipped backend path offers per-request cache control through the
|
|
264
|
+
OpenAI-compatible surface the gateway uses: the backend manages its own prompt cache. ``true`` is
|
|
265
|
+
therefore an advisory no-op (nothing is forwarded, no cache hit is promised); ``false`` asks for a
|
|
266
|
+
guaranteed bypass that cannot be honoured, so it is refused with a precise explanation rather than
|
|
267
|
+
silently accepted."""
|
|
268
|
+
kind = getattr(self.cfg, "type", "backend")
|
|
269
|
+
if value:
|
|
270
|
+
return True, f"advisory; prompt caching is managed by the {kind} backend itself (not forwarded, no cache hit promised)"
|
|
271
|
+
return False, (
|
|
272
|
+
f"cache_prompt=false asks for a guaranteed prompt-cache bypass, which the {kind} backend path cannot honour "
|
|
273
|
+
"per request (its cache is backend-managed); omit the field or send cache_prompt=true"
|
|
274
|
+
)
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""Ollama adapter.
|
|
2
|
+
|
|
3
|
+
Discovery uses Ollama's native API for truthful metadata (``/api/tags``,
|
|
4
|
+
``/api/show``, ``/api/ps``, ``/api/version``); inference is forwarded through
|
|
5
|
+
Ollama's OpenAI-compatible endpoints so tool semantics are preserved exactly
|
|
6
|
+
as Ollama implements them.
|
|
7
|
+
|
|
8
|
+
Documented limits of Ollama's OpenAI layer that this adapter enforces
|
|
9
|
+
(source: https://docs.ollama.com/api/openai-compatibility, checked 2026-10-11):
|
|
10
|
+
``tool_choice``, ``logit_bias``, ``n``, ``logprobs`` are not supported, and
|
|
11
|
+
image inputs must be base64 data URLs (remote image URLs are not fetched).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import re
|
|
18
|
+
import time
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
|
|
23
|
+
from ..registry import CAPABILITY_KEYS, Deployment, merge_capabilities
|
|
24
|
+
from .base import AdapterError, BaseAdapter, UpstreamResponse
|
|
25
|
+
|
|
26
|
+
_CLOUD_NAME = re.compile(r"(:cloud$|-cloud$|-cloud:)")
|
|
27
|
+
|
|
28
|
+
# Ollama does not expose the server's default context length through the
|
|
29
|
+
# API for unloaded models. This is Ollama's documented default when neither
|
|
30
|
+
# the Modelfile nor OLLAMA_CONTEXT_LENGTH sets one (assumption; see docs/).
|
|
31
|
+
OLLAMA_ASSUMED_DEFAULT_NUM_CTX = 4096
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class OllamaAdapter(BaseAdapter):
|
|
35
|
+
type_name = "ollama"
|
|
36
|
+
reports_residency = True # /api/ps is a real observation of resident models
|
|
37
|
+
adapter_capabilities = {
|
|
38
|
+
# Ollama's OpenAI-compatible layer documents no video content parts (checked 2026-12-05).
|
|
39
|
+
"video_in": "unsupported",
|
|
40
|
+
"tool_choice_required": "unsupported", # OpenAI layer ignores tool_choice
|
|
41
|
+
"json_object": "supported",
|
|
42
|
+
"streaming": "supported",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async def health(self) -> tuple[bool, str]:
|
|
46
|
+
try:
|
|
47
|
+
v = await self._get_json("/api/version")
|
|
48
|
+
self.runtime_version = str(v.get("version", ""))
|
|
49
|
+
return True, f"ollama {self.runtime_version}"
|
|
50
|
+
except AdapterError as e:
|
|
51
|
+
return False, e.message
|
|
52
|
+
|
|
53
|
+
async def loaded_models(self) -> dict[str, dict[str, Any]] | None:
|
|
54
|
+
try:
|
|
55
|
+
ps = await self._get_json("/api/ps")
|
|
56
|
+
except AdapterError:
|
|
57
|
+
self.last_residency_observation_ok = False
|
|
58
|
+
return None # failed query: not an observation, never "nothing is resident"
|
|
59
|
+
self.last_residency_observation_ok = True
|
|
60
|
+
out: dict[str, dict[str, Any]] = {}
|
|
61
|
+
for m in ps.get("models", []) or []:
|
|
62
|
+
name = m.get("name") or m.get("model")
|
|
63
|
+
if name:
|
|
64
|
+
out[name] = {
|
|
65
|
+
"size_vram": m.get("size_vram"),
|
|
66
|
+
"size": m.get("size"),
|
|
67
|
+
"expires_at": m.get("expires_at"),
|
|
68
|
+
"context_length": m.get("context_length"),
|
|
69
|
+
}
|
|
70
|
+
return out
|
|
71
|
+
|
|
72
|
+
async def discover(self) -> list[Deployment]:
|
|
73
|
+
tags = await self._get_json("/api/tags")
|
|
74
|
+
ok, _ = await self.health()
|
|
75
|
+
loaded = (await self.loaded_models() if ok else None) or {}
|
|
76
|
+
deps: list[Deployment] = []
|
|
77
|
+
for m in tags.get("models", []) or []:
|
|
78
|
+
name = m.get("name") or m.get("model")
|
|
79
|
+
if not name:
|
|
80
|
+
continue
|
|
81
|
+
details = m.get("details") or {}
|
|
82
|
+
dep = Deployment(
|
|
83
|
+
id=f"{self.cfg.id}/{name}",
|
|
84
|
+
backend_id=self.cfg.id,
|
|
85
|
+
backend_type="ollama",
|
|
86
|
+
model=name,
|
|
87
|
+
family=str(details.get("family", "")),
|
|
88
|
+
parameter_size=str(details.get("parameter_size", "")),
|
|
89
|
+
quantization=str(details.get("quantization_level", "")),
|
|
90
|
+
digest=str(m.get("digest", "")),
|
|
91
|
+
identity=str(m.get("digest", "")),
|
|
92
|
+
identity_source="ollama digest" if m.get("digest") else "",
|
|
93
|
+
runtime="ollama",
|
|
94
|
+
runtime_version=self.runtime_version,
|
|
95
|
+
endpoint=self.endpoint,
|
|
96
|
+
resource_pool=self.cfg.resource_pool,
|
|
97
|
+
discovered=True,
|
|
98
|
+
available_on_disk=True,
|
|
99
|
+
discovered_at=time.time(),
|
|
100
|
+
)
|
|
101
|
+
# Locality: a locally addressed Ollama can forward to Ollama Cloud.
|
|
102
|
+
remote = bool(m.get("remote_model") or m.get("remote_host")) or bool(_CLOUD_NAME.search(name))
|
|
103
|
+
if remote:
|
|
104
|
+
dep.locality = "remote"
|
|
105
|
+
dep.locality_evidence = (
|
|
106
|
+
f"ollama /api/tags reports remote_model/remote_host or cloud-suffixed name "
|
|
107
|
+
f"({m.get('remote_host') or 'cloud'}): inference does not run on this host"
|
|
108
|
+
)
|
|
109
|
+
else:
|
|
110
|
+
dep.locality = self.cfg.locality
|
|
111
|
+
dep.locality_evidence = (
|
|
112
|
+
f"operator declared backend locality={self.cfg.locality}; /api/tags shows no remote_model "
|
|
113
|
+
"(trust assumption: the gateway cannot inspect the runtime's internals)"
|
|
114
|
+
)
|
|
115
|
+
size = m.get("size")
|
|
116
|
+
if isinstance(size, (int, float)) and size > 0:
|
|
117
|
+
dep.memory_gb_estimate = round(size / 1e9 * 1.15, 2)
|
|
118
|
+
dep.memory_estimate_provenance = (
|
|
119
|
+
"weights file size x1.15 runtime overhead; KV cache for the served context is NOT included"
|
|
120
|
+
)
|
|
121
|
+
await self._enrich(dep)
|
|
122
|
+
if name in loaded:
|
|
123
|
+
dep.loaded = True
|
|
124
|
+
dep.loaded_observed_at = time.time()
|
|
125
|
+
lc = loaded[name].get("context_length")
|
|
126
|
+
if isinstance(lc, int) and lc > 0:
|
|
127
|
+
dep.raw_metadata["observed_served_context"] = lc
|
|
128
|
+
if isinstance(lc, int) and lc > 0 and dep.raw_metadata.get("num_ctx_source") != "modelfile":
|
|
129
|
+
dep.context_length = lc
|
|
130
|
+
dep.raw_metadata["num_ctx_source"] = "ollama /api/ps (currently loaded)"
|
|
131
|
+
dep.healthy = ok
|
|
132
|
+
dep.health_checked_at = time.time()
|
|
133
|
+
dep.compute_fingerprint()
|
|
134
|
+
deps.append(dep)
|
|
135
|
+
return deps
|
|
136
|
+
|
|
137
|
+
async def _enrich(self, dep: Deployment) -> None:
|
|
138
|
+
try:
|
|
139
|
+
show = await self._client.post(self._url("/api/show"), json={"model": dep.model})
|
|
140
|
+
info = show.json() if show.status_code == 200 else {}
|
|
141
|
+
except Exception:
|
|
142
|
+
info = {}
|
|
143
|
+
caps_list = info.get("capabilities") or []
|
|
144
|
+
model_info = info.get("model_info") or {}
|
|
145
|
+
details = info.get("details") or {}
|
|
146
|
+
arch = str(model_info.get("general.architecture", "")) or str(details.get("family", ""))
|
|
147
|
+
dep.family = dep.family or arch
|
|
148
|
+
if not dep.publisher:
|
|
149
|
+
dep.publisher = str(model_info.get("general.basename", "")) or ""
|
|
150
|
+
# Trained context length (model-card value) vs served context (num_ctx).
|
|
151
|
+
trained_ctx = None
|
|
152
|
+
for k, v in model_info.items():
|
|
153
|
+
if k.endswith(".context_length") and isinstance(v, int):
|
|
154
|
+
trained_ctx = v
|
|
155
|
+
break
|
|
156
|
+
dep.raw_metadata["trained_context_length"] = trained_ctx
|
|
157
|
+
params_text = str(info.get("parameters", "") or "")
|
|
158
|
+
m = re.search(r"num_ctx\s+(\d+)", params_text)
|
|
159
|
+
if m:
|
|
160
|
+
dep.context_length = int(m.group(1))
|
|
161
|
+
dep.raw_metadata["num_ctx_source"] = "modelfile"
|
|
162
|
+
elif self.cfg.default_context_length:
|
|
163
|
+
declared = self.cfg.default_context_length
|
|
164
|
+
dep.context_length = min(trained_ctx, declared) if trained_ctx else declared
|
|
165
|
+
dep.raw_metadata["num_ctx_source"] = (
|
|
166
|
+
f"operator declaration backends[].default_context_length={declared} (the runtime's server-wide default, "
|
|
167
|
+
"e.g. OLLAMA_CONTEXT_LENGTH; capped at the trained context)"
|
|
168
|
+
)
|
|
169
|
+
else:
|
|
170
|
+
dep.context_length = min(trained_ctx, OLLAMA_ASSUMED_DEFAULT_NUM_CTX) if trained_ctx else OLLAMA_ASSUMED_DEFAULT_NUM_CTX
|
|
171
|
+
dep.raw_metadata["num_ctx_source"] = (
|
|
172
|
+
f"assumed Ollama default ({OLLAMA_ASSUMED_DEFAULT_NUM_CTX}); set num_ctx in the Modelfile, "
|
|
173
|
+
"OLLAMA_CONTEXT_LENGTH, or an operator override to change"
|
|
174
|
+
)
|
|
175
|
+
for k, v in model_info.items():
|
|
176
|
+
if k.endswith(".embedding_length") and isinstance(v, int) and "embedding" in caps_list:
|
|
177
|
+
dep.embedding_dimensions = v
|
|
178
|
+
template = str(info.get("template", "") or "")
|
|
179
|
+
dep.template_hash = hashlib.sha256(template.encode()).hexdigest()[:12] if template else ""
|
|
180
|
+
dep.raw_metadata["license_excerpt"] = str(info.get("license", "") or "")[:200]
|
|
181
|
+
# Role from capabilities. A model that declares "decision" and not "completion" is a System One
|
|
182
|
+
# decision model (Ollama /v1/systemone: per-option probabilities, no generation) and is never
|
|
183
|
+
# offered as a chat model; the catalogue may still refine the role afterwards.
|
|
184
|
+
if "embedding" in caps_list and "completion" not in caps_list:
|
|
185
|
+
dep.role = "embedding"
|
|
186
|
+
elif "decision" in caps_list and "completion" not in caps_list:
|
|
187
|
+
dep.role = "decision"
|
|
188
|
+
else:
|
|
189
|
+
dep.role = "generative"
|
|
190
|
+
claims: dict[str, str] = {}
|
|
191
|
+
claims["tools"] = "supported" if "tools" in caps_list else ("unsupported" if caps_list else "unknown")
|
|
192
|
+
claims["vision"] = "supported" if ("vision" in caps_list or "image" in caps_list) else (
|
|
193
|
+
"unsupported" if caps_list else "unknown"
|
|
194
|
+
)
|
|
195
|
+
claims["audio_in"] = "supported" if "audio" in caps_list else ("unsupported" if caps_list else "unknown")
|
|
196
|
+
claims["thinking"] = "supported" if "thinking" in caps_list else ("unsupported" if caps_list else "unknown")
|
|
197
|
+
merge_capabilities(dep, claims, "source_claim", note="ollama /api/show capabilities") # type: ignore[arg-type]
|
|
198
|
+
merge_capabilities(dep, dict(self.adapter_capabilities), "adapter", note="ollama OpenAI-compatible layer") # type: ignore[arg-type]
|
|
199
|
+
# Parallel tools / json_schema / continuation remain unknown until probed.
|
|
200
|
+
for k in CAPABILITY_KEYS:
|
|
201
|
+
dep.capabilities.setdefault(k, dep.capabilities.get(k)) # keep unknowns explicit
|
|
202
|
+
dep.raw_metadata["capabilities_list"] = caps_list
|
|
203
|
+
|
|
204
|
+
# --------------------------------------------------------------- #
|
|
205
|
+
def lifecycle_operations(self) -> frozenset[str]:
|
|
206
|
+
return frozenset({"load", "unload"})
|
|
207
|
+
|
|
208
|
+
async def _lifecycle_call(self, dep: Deployment, payload: dict[str, Any], timeout: float) -> dict[str, Any]:
|
|
209
|
+
"""Ollama's documented load/unload: a generate request without a prompt (docs.ollama.com/faq,
|
|
210
|
+
"preload"/"unload"; keep_alive 0 unloads). No prompt text is involved."""
|
|
211
|
+
try:
|
|
212
|
+
r = await self._client.post(self._url("/api/generate"), json={"model": dep.model, "stream": False, **payload}, timeout=self._deadline(timeout))
|
|
213
|
+
except httpx.TimeoutException as e:
|
|
214
|
+
raise AdapterError(f"ollama did not answer the lifecycle request within {timeout:g}s", kind="timeout") from e
|
|
215
|
+
except httpx.ConnectError as e:
|
|
216
|
+
raise AdapterError(f"cannot connect to ollama: {e}", kind="connect") from e
|
|
217
|
+
except httpx.HTTPError as e:
|
|
218
|
+
raise AdapterError(f"ollama lifecycle request failed: {e}") from e
|
|
219
|
+
if r.status_code != 200:
|
|
220
|
+
raise AdapterError(f"ollama answered {r.status_code} to the lifecycle request: {r.text[:200]}")
|
|
221
|
+
try:
|
|
222
|
+
return r.json()
|
|
223
|
+
except ValueError:
|
|
224
|
+
return {}
|
|
225
|
+
|
|
226
|
+
async def load_model(self, dep: Deployment, keep_alive_s: int | None, timeout: float) -> None:
|
|
227
|
+
if dep.role != "generative":
|
|
228
|
+
raise AdapterError(f"only generative models are loaded through /api/generate (role {dep.role})", status=422, kind="unsupported")
|
|
229
|
+
await self._lifecycle_call(dep, {} if keep_alive_s is None else {"keep_alive": f"{int(keep_alive_s)}s"}, timeout)
|
|
230
|
+
|
|
231
|
+
async def unload_model(self, dep: Deployment, timeout: float) -> None:
|
|
232
|
+
await self._lifecycle_call(dep, {"keep_alive": 0}, timeout)
|
|
233
|
+
|
|
234
|
+
def unsupported_fields(self) -> frozenset[str]:
|
|
235
|
+
return frozenset({"logit_bias", "logprobs", "top_logprobs", "n"})
|
|
236
|
+
|
|
237
|
+
def translate_chat_body(self, body: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
|
|
238
|
+
"""Typed, allow-listed translation. Returns (body, notes)."""
|
|
239
|
+
out = dict(body)
|
|
240
|
+
notes: list[str] = []
|
|
241
|
+
tc = out.get("tool_choice")
|
|
242
|
+
if tc is not None:
|
|
243
|
+
if tc == "auto":
|
|
244
|
+
out.pop("tool_choice")
|
|
245
|
+
notes.append("tool_choice=auto is Ollama's default; field omitted")
|
|
246
|
+
elif tc == "none":
|
|
247
|
+
out.pop("tool_choice")
|
|
248
|
+
if out.get("tools"):
|
|
249
|
+
out.pop("tools")
|
|
250
|
+
notes.append("tool_choice=none translated by omitting tool definitions (faithful semantics)")
|
|
251
|
+
else:
|
|
252
|
+
raise AdapterError(
|
|
253
|
+
"Ollama's OpenAI-compatible layer does not support tool_choice=required/named",
|
|
254
|
+
status=400,
|
|
255
|
+
kind="unsupported_semantics",
|
|
256
|
+
)
|
|
257
|
+
for k in ("user", "metadata", "store", "prompt_cache_key", "service_tier", "modelsaar"):
|
|
258
|
+
if k in out:
|
|
259
|
+
out.pop(k)
|
|
260
|
+
notes.append(f"non-semantic field {k} not forwarded")
|
|
261
|
+
for k in ("session_id", "cache_prompt"):
|
|
262
|
+
if k in out:
|
|
263
|
+
out.pop(k)
|
|
264
|
+
notes.append(f"client-compatibility field {k} consumed by the gateway; not forwarded")
|
|
265
|
+
return out, notes
|
|
266
|
+
|
|
267
|
+
async def chat(self, dep: Deployment, body: dict[str, Any], stream: bool, timeout: float | None = None):
|
|
268
|
+
fwd, _ = self.translate_chat_body(body)
|
|
269
|
+
fwd["model"] = dep.model
|
|
270
|
+
fwd["stream"] = stream
|
|
271
|
+
if stream:
|
|
272
|
+
so = dict(fwd.get("stream_options") or {})
|
|
273
|
+
so.setdefault("include_usage", True)
|
|
274
|
+
fwd["stream_options"] = so
|
|
275
|
+
return await self._post_stream("/v1/chat/completions", fwd, timeout=timeout)
|
|
276
|
+
return await self._post_json("/v1/chat/completions", fwd, timeout=timeout)
|
|
277
|
+
|
|
278
|
+
async def embeddings(self, dep: Deployment, body: dict[str, Any], timeout: float | None = None) -> UpstreamResponse:
|
|
279
|
+
fwd = {k: v for k, v in body.items() if k in ("input", "encoding_format", "dimensions")}
|
|
280
|
+
fwd["model"] = dep.model
|
|
281
|
+
return await self._post_json("/v1/embeddings", fwd, timeout=timeout)
|
|
282
|
+
|
|
283
|
+
async def embed_media(self, dep: Deployment, part: dict[str, Any], timeout: float | None = None) -> UpstreamResponse:
|
|
284
|
+
raise AdapterError(
|
|
285
|
+
"Ollama's documented embedding API (/api/embed, and its OpenAI-compatible /v1/embeddings) accepts text "
|
|
286
|
+
"input only (docs.ollama.com/openapi.yaml, checked 2026-12-05); image/audio embeddings are not forwarded "
|
|
287
|
+
"through an Ollama backend. Serve the model with a runtime that documents multimodal embedding input "
|
|
288
|
+
"(e.g. vLLM) and declare it as an openai_compatible backend",
|
|
289
|
+
status=501,
|
|
290
|
+
kind="unsupported",
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
async def decide(
|
|
294
|
+
self,
|
|
295
|
+
dep: Deployment,
|
|
296
|
+
state: Any,
|
|
297
|
+
questions: dict[str, Any],
|
|
298
|
+
timeout: float | None = None,
|
|
299
|
+
images: list[str] | None = None,
|
|
300
|
+
) -> UpstreamResponse:
|
|
301
|
+
"""Ollama's System One endpoint (``POST /v1/systemone``, Ollama >= 0.35.0): ``state`` is the
|
|
302
|
+
text to judge (a non-empty string, or an object/array; never chat messages), ``questions`` maps
|
|
303
|
+
1..64 names to typed questions (``choice`` with 2..255 criteria, ``noul``, ``score``), ``images``
|
|
304
|
+
are base64 strings shared by all questions; the answer carries per-option probabilities and a
|
|
305
|
+
concentration ``confidence``. No streaming, tools or generation controls exist on this endpoint,
|
|
306
|
+
and model lifecycle (``keep_alive``) is not forwarded."""
|
|
307
|
+
if isinstance(state, str):
|
|
308
|
+
if not state.strip():
|
|
309
|
+
raise AdapterError(f"{self.cfg.id}: decision state must be a non-empty string", status=400, kind="internal")
|
|
310
|
+
elif not isinstance(state, (dict, list)):
|
|
311
|
+
raise AdapterError(f"{self.cfg.id}: decision state must be a string, object or array", status=400, kind="internal")
|
|
312
|
+
if not isinstance(questions, dict) or not 1 <= len(questions) <= 64:
|
|
313
|
+
raise AdapterError(f"{self.cfg.id}: decision requests take 1..64 questions", status=400, kind="internal")
|
|
314
|
+
body: dict[str, Any] = {"model": dep.model, "state": state, "questions": questions}
|
|
315
|
+
if images:
|
|
316
|
+
body["images"] = list(images)
|
|
317
|
+
return await self._post_json("/v1/systemone", body, timeout=timeout)
|