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/probes.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
"""Capability probes: cheap, bounded live checks that turn claims into evidence.
|
|
2
|
+
|
|
3
|
+
Probes are explicit (``modelsaar probe``) because they consume local compute.
|
|
4
|
+
Results are stored per deployment *fingerprint*; a changed model, template,
|
|
5
|
+
quantization or runtime invalidates them automatically.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import time
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from .adapters.base import AdapterError, BaseAdapter, UpstreamResponse, UpstreamStream
|
|
16
|
+
from .protocol.sse import SSEParser, StreamObserver
|
|
17
|
+
from .registry import Deployment, Measurement
|
|
18
|
+
from .store import Store
|
|
19
|
+
|
|
20
|
+
# A 1x1 red PNG (generated with Pillow once; embedded to avoid a dependency).
|
|
21
|
+
# Thinking models spend output tokens on reasoning before the answer; keep probe budgets generous.
|
|
22
|
+
PROBE_MAX_TOKENS = 1024
|
|
23
|
+
PROBE_NAMES = frozenset({"streaming", "tools", "parallel_tools", "json_object", "json_schema", "vision", "continuation", "audio_in", "latency"})
|
|
24
|
+
STREAM_PROBE_MAX_TOKENS = 400
|
|
25
|
+
|
|
26
|
+
_RED_PNG_B64 = (
|
|
27
|
+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class ProbeResult:
|
|
33
|
+
capability: str
|
|
34
|
+
value: str # supported | unsupported | unknown
|
|
35
|
+
note: str = ""
|
|
36
|
+
latency_ms: float = 0.0
|
|
37
|
+
details: dict[str, Any] = field(default_factory=dict)
|
|
38
|
+
# True when the probe's inference timed out: the backend may still be computing, so the
|
|
39
|
+
# runner stops and the caller keeps the slot/memory occupied (uncertain hold).
|
|
40
|
+
uncertain: bool = False
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class ProbeReport:
|
|
45
|
+
deployment_id: str
|
|
46
|
+
fingerprint: str
|
|
47
|
+
results: list[ProbeResult] = field(default_factory=list)
|
|
48
|
+
measurements: list[Measurement] = field(default_factory=list)
|
|
49
|
+
errors: list[str] = field(default_factory=list)
|
|
50
|
+
uncertain: bool = False # a probe timed out; later probes were not run
|
|
51
|
+
skipped: list[str] = field(default_factory=list) # probes not run because of an uncertain timeout
|
|
52
|
+
|
|
53
|
+
def as_dict(self) -> dict[str, Any]:
|
|
54
|
+
return {
|
|
55
|
+
"deployment_id": self.deployment_id,
|
|
56
|
+
"fingerprint": self.fingerprint,
|
|
57
|
+
"results": [r.__dict__ for r in self.results],
|
|
58
|
+
"measurements": [m.__dict__ for m in self.measurements],
|
|
59
|
+
"errors": self.errors,
|
|
60
|
+
"uncertain": self.uncertain,
|
|
61
|
+
"skipped": self.skipped,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _error_result(capability: str, e: AdapterError) -> ProbeResult:
|
|
66
|
+
"""A probe that could not get an answer. A timeout is *uncertain*: the backend may still be
|
|
67
|
+
generating, so it must not be followed by more probe inference on the same reservation."""
|
|
68
|
+
if e.kind == "timeout":
|
|
69
|
+
return ProbeResult(capability, "unknown", f"probe timed out ({e.message[:80]}); backend may still be computing", uncertain=True)
|
|
70
|
+
return ProbeResult(capability, "unknown", f"probe error: {e.message[:100]}")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
_TOOL = {
|
|
74
|
+
"type": "function",
|
|
75
|
+
"function": {
|
|
76
|
+
"name": "get_current_time",
|
|
77
|
+
"description": "Get the current time in a city.",
|
|
78
|
+
"parameters": {
|
|
79
|
+
"type": "object",
|
|
80
|
+
"properties": {"city": {"type": "string", "description": "City name"}},
|
|
81
|
+
"required": ["city"],
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
_TOOL2 = {
|
|
86
|
+
"type": "function",
|
|
87
|
+
"function": {
|
|
88
|
+
"name": "get_weather",
|
|
89
|
+
"description": "Get current weather in a city.",
|
|
90
|
+
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
|
|
91
|
+
},
|
|
92
|
+
}
|
|
93
|
+
_SCHEMA = {
|
|
94
|
+
"type": "object",
|
|
95
|
+
"properties": {"city": {"type": "string"}, "population_millions": {"type": "number"}},
|
|
96
|
+
"required": ["city", "population_millions"],
|
|
97
|
+
"additionalProperties": False,
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
async def _chat(adapter: BaseAdapter, dep: Deployment, body: dict[str, Any], timeout: float) -> UpstreamResponse:
|
|
102
|
+
body = dict(body)
|
|
103
|
+
body.setdefault("temperature", 0)
|
|
104
|
+
body.setdefault("max_tokens", PROBE_MAX_TOKENS)
|
|
105
|
+
return await adapter.chat(dep, body, stream=False, timeout=timeout)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _budget_exhausted(resp: UpstreamResponse) -> bool:
|
|
109
|
+
"""Empty content with finish_reason=length: the model (probably thinking) used the whole budget."""
|
|
110
|
+
try:
|
|
111
|
+
ch = resp.body["choices"][0]
|
|
112
|
+
return ch.get("finish_reason") == "length" and not (ch.get("message") or {}).get("content")
|
|
113
|
+
except (KeyError, IndexError, TypeError):
|
|
114
|
+
return False
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
_EXHAUSTED_NOTE = "output budget exhausted before an answer (thinking model?); increase PROBE_MAX_TOKENS or disable thinking"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _content(resp: UpstreamResponse) -> str:
|
|
121
|
+
try:
|
|
122
|
+
c = resp.body["choices"][0]["message"].get("content")
|
|
123
|
+
if isinstance(c, list):
|
|
124
|
+
return "".join(p.get("text", "") for p in c if isinstance(p, dict))
|
|
125
|
+
return c or ""
|
|
126
|
+
except (KeyError, IndexError, TypeError):
|
|
127
|
+
return ""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _tool_calls(resp: UpstreamResponse) -> list[dict[str, Any]]:
|
|
131
|
+
try:
|
|
132
|
+
return resp.body["choices"][0]["message"].get("tool_calls") or []
|
|
133
|
+
except (KeyError, IndexError, TypeError):
|
|
134
|
+
return []
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
async def probe_tools(adapter: BaseAdapter, dep: Deployment, timeout: float) -> ProbeResult:
|
|
138
|
+
t0 = time.monotonic()
|
|
139
|
+
body = {
|
|
140
|
+
"messages": [{"role": "user", "content": "What time is it in Paris right now? You must call the tool."}],
|
|
141
|
+
"tools": [_TOOL],
|
|
142
|
+
}
|
|
143
|
+
try:
|
|
144
|
+
r = await _chat(adapter, dep, body, timeout)
|
|
145
|
+
except AdapterError as e:
|
|
146
|
+
return _error_result("tools", e)
|
|
147
|
+
ms = (time.monotonic() - t0) * 1000
|
|
148
|
+
if r.status >= 500:
|
|
149
|
+
return ProbeResult("tools", "unknown", f"backend returned {r.status} (transient?) for a tools request", ms)
|
|
150
|
+
if r.status != 200:
|
|
151
|
+
return ProbeResult("tools", "unsupported", f"backend returned {r.status} for a tools request", ms)
|
|
152
|
+
calls = _tool_calls(r)
|
|
153
|
+
for c in calls:
|
|
154
|
+
fn = c.get("function") or {}
|
|
155
|
+
if fn.get("name") == "get_current_time" and c.get("id"):
|
|
156
|
+
try:
|
|
157
|
+
args = json.loads(fn.get("arguments") or "{}")
|
|
158
|
+
except json.JSONDecodeError:
|
|
159
|
+
return ProbeResult("tools", "unsupported", "tool call emitted with non-JSON arguments", ms)
|
|
160
|
+
ok = isinstance(args, dict) and "city" in args
|
|
161
|
+
return ProbeResult("tools", "supported" if ok else "unsupported", "tool call with id and JSON args" if ok else "arguments missing required key", ms)
|
|
162
|
+
return ProbeResult("tools", "unsupported", "no tool_calls returned for an explicit tool request", ms)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
async def probe_parallel_tools(adapter: BaseAdapter, dep: Deployment, timeout: float) -> ProbeResult:
|
|
166
|
+
t0 = time.monotonic()
|
|
167
|
+
body = {
|
|
168
|
+
"messages": [
|
|
169
|
+
{"role": "user", "content": "Call both tools: get the current time in Tokyo AND the weather in Tokyo, in one turn."}
|
|
170
|
+
],
|
|
171
|
+
"tools": [_TOOL, _TOOL2],
|
|
172
|
+
}
|
|
173
|
+
try:
|
|
174
|
+
r = await _chat(adapter, dep, body, timeout)
|
|
175
|
+
except AdapterError as e:
|
|
176
|
+
return _error_result("parallel_tools", e)
|
|
177
|
+
ms = (time.monotonic() - t0) * 1000
|
|
178
|
+
names = {(c.get("function") or {}).get("name") for c in _tool_calls(r)}
|
|
179
|
+
if {"get_current_time", "get_weather"} <= names:
|
|
180
|
+
return ProbeResult("parallel_tools", "supported", "two distinct tool calls in one turn", ms)
|
|
181
|
+
return ProbeResult("parallel_tools", "unsupported", f"got {sorted(n for n in names if n)}", ms)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
async def probe_json_schema(adapter: BaseAdapter, dep: Deployment, timeout: float) -> ProbeResult:
|
|
185
|
+
t0 = time.monotonic()
|
|
186
|
+
body = {
|
|
187
|
+
"messages": [{"role": "user", "content": "Give the city Paris and its population in millions."}],
|
|
188
|
+
"response_format": {"type": "json_schema", "json_schema": {"name": "city", "schema": _SCHEMA, "strict": True}},
|
|
189
|
+
}
|
|
190
|
+
try:
|
|
191
|
+
r = await _chat(adapter, dep, body, timeout)
|
|
192
|
+
except AdapterError as e:
|
|
193
|
+
return _error_result("json_schema", e)
|
|
194
|
+
ms = (time.monotonic() - t0) * 1000
|
|
195
|
+
if r.status >= 500:
|
|
196
|
+
return ProbeResult("json_schema", "unknown", f"backend returned {r.status} (transient?)", ms)
|
|
197
|
+
if r.status != 200:
|
|
198
|
+
return ProbeResult("json_schema", "unsupported", f"backend returned {r.status} for response_format=json_schema", ms)
|
|
199
|
+
if _budget_exhausted(r):
|
|
200
|
+
return ProbeResult("json_schema", "unknown", _EXHAUSTED_NOTE, ms)
|
|
201
|
+
txt = _content(r).strip()
|
|
202
|
+
try:
|
|
203
|
+
obj = json.loads(txt)
|
|
204
|
+
except json.JSONDecodeError:
|
|
205
|
+
return ProbeResult("json_schema", "unsupported", "content is not valid JSON", ms)
|
|
206
|
+
ok = (
|
|
207
|
+
isinstance(obj, dict)
|
|
208
|
+
and isinstance(obj.get("city"), str)
|
|
209
|
+
and isinstance(obj.get("population_millions"), (int, float))
|
|
210
|
+
and set(obj.keys()) <= {"city", "population_millions"}
|
|
211
|
+
)
|
|
212
|
+
return ProbeResult("json_schema", "supported" if ok else "unsupported", "schema-conformant object" if ok else f"non-conformant: keys={sorted(obj) if isinstance(obj, dict) else type(obj).__name__}", ms)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
async def probe_json_object(adapter: BaseAdapter, dep: Deployment, timeout: float) -> ProbeResult:
|
|
216
|
+
t0 = time.monotonic()
|
|
217
|
+
body = {
|
|
218
|
+
"messages": [{"role": "user", "content": "Return a JSON object with a key 'answer' whose value is the number 42."}],
|
|
219
|
+
"response_format": {"type": "json_object"},
|
|
220
|
+
}
|
|
221
|
+
try:
|
|
222
|
+
r = await _chat(adapter, dep, body, timeout)
|
|
223
|
+
except AdapterError as e:
|
|
224
|
+
return _error_result("json_object", e)
|
|
225
|
+
ms = (time.monotonic() - t0) * 1000
|
|
226
|
+
if _budget_exhausted(r):
|
|
227
|
+
return ProbeResult("json_object", "unknown", _EXHAUSTED_NOTE, ms)
|
|
228
|
+
try:
|
|
229
|
+
obj = json.loads(_content(r).strip())
|
|
230
|
+
return ProbeResult("json_object", "supported" if isinstance(obj, dict) else "unsupported", "", ms)
|
|
231
|
+
except json.JSONDecodeError:
|
|
232
|
+
return ProbeResult("json_object", "unsupported", "content is not valid JSON", ms)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
async def probe_vision(adapter: BaseAdapter, dep: Deployment, timeout: float) -> ProbeResult:
|
|
236
|
+
t0 = time.monotonic()
|
|
237
|
+
body = {
|
|
238
|
+
"messages": [
|
|
239
|
+
{
|
|
240
|
+
"role": "user",
|
|
241
|
+
"content": [
|
|
242
|
+
{"type": "text", "text": "What single colour is this image? Answer with one word."},
|
|
243
|
+
{"type": "image_url", "image_url": {"url": "data:image/png;base64," + _RED_PNG_B64}},
|
|
244
|
+
],
|
|
245
|
+
}
|
|
246
|
+
]
|
|
247
|
+
}
|
|
248
|
+
try:
|
|
249
|
+
r = await _chat(adapter, dep, body, timeout)
|
|
250
|
+
except AdapterError as e:
|
|
251
|
+
return _error_result("vision", e)
|
|
252
|
+
ms = (time.monotonic() - t0) * 1000
|
|
253
|
+
if r.status >= 500:
|
|
254
|
+
return ProbeResult("vision", "unknown", f"backend returned {r.status} (transient?)", ms)
|
|
255
|
+
if r.status != 200:
|
|
256
|
+
return ProbeResult("vision", "unsupported", f"backend returned {r.status} for an image request", ms)
|
|
257
|
+
if _budget_exhausted(r):
|
|
258
|
+
return ProbeResult("vision", "unknown", _EXHAUSTED_NOTE, ms)
|
|
259
|
+
txt = _content(r).lower()
|
|
260
|
+
if "red" in txt:
|
|
261
|
+
return ProbeResult("vision", "supported", "accepted a base64 image and identified its colour", ms)
|
|
262
|
+
return ProbeResult("vision", "unsupported", f"image accepted but answer did not identify the colour ({txt[:40]!r})", ms)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
# The exact shape agentic clients (e.g. Odysseus) send on a follow-up turn: the previous assistant message
|
|
266
|
+
# is replayed with both its ``content`` and its ``reasoning_content``. Routing marks such requests
|
|
267
|
+
# ``needs_continuation``; this probe sends that shape through the adapter unchanged (adapters forward
|
|
268
|
+
# ``messages`` as received), so the backend's acceptance of ``reasoning_content`` in history is what is tested.
|
|
269
|
+
_CONTINUATION_HISTORY: list[dict[str, Any]] = [
|
|
270
|
+
{"role": "user", "content": "What is 2 + 2? Reply with the number only."},
|
|
271
|
+
{"role": "assistant", "content": "4", "reasoning_content": "The user asks for a simple sum. 2 + 2 = 4."},
|
|
272
|
+
{"role": "user", "content": "Add 3 to your previous answer. Reply with the number only."},
|
|
273
|
+
]
|
|
274
|
+
_CONTINUATION_NOTE = (
|
|
275
|
+
"accepted an assistant history carrying reasoning_content and answered (protocol acceptance; whether the "
|
|
276
|
+
"model semantically uses the replayed reasoning is not verifiable through the OpenAI-compatible API)"
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
async def probe_continuation(adapter: BaseAdapter, dep: Deployment, timeout: float) -> ProbeResult:
|
|
281
|
+
"""Can this deployment take a follow-up turn whose assistant history carries ``reasoning_content``?
|
|
282
|
+
|
|
283
|
+
``supported``: HTTP 200 with a well-formed assistant answer to *this* request (the one carrying the
|
|
284
|
+
reasoning history) — not inferred from any other request. ``unsupported``: the backend explicitly
|
|
285
|
+
rejected the request (4xx) or answered without an assistant message. ``unknown``: 5xx, transport
|
|
286
|
+
error, timeout (uncertain hold), malformed body, or output budget exhausted before an answer.
|
|
287
|
+
"""
|
|
288
|
+
t0 = time.monotonic()
|
|
289
|
+
body = {"messages": [dict(m) for m in _CONTINUATION_HISTORY]}
|
|
290
|
+
try:
|
|
291
|
+
r = await _chat(adapter, dep, body, timeout)
|
|
292
|
+
except AdapterError as e:
|
|
293
|
+
return _error_result("continuation", e)
|
|
294
|
+
ms = (time.monotonic() - t0) * 1000
|
|
295
|
+
if r.status >= 500:
|
|
296
|
+
return ProbeResult("continuation", "unknown", f"backend returned {r.status} (transient?) for a history with reasoning_content", ms)
|
|
297
|
+
if r.status != 200:
|
|
298
|
+
msg = ""
|
|
299
|
+
try:
|
|
300
|
+
err = r.body.get("error") if isinstance(r.body, dict) else None
|
|
301
|
+
msg = (err.get("message") if isinstance(err, dict) else err) or ""
|
|
302
|
+
except Exception: # noqa: BLE001
|
|
303
|
+
msg = ""
|
|
304
|
+
return ProbeResult(
|
|
305
|
+
"continuation", "unsupported",
|
|
306
|
+
f"backend rejected an assistant history carrying reasoning_content (HTTP {r.status}{': ' + str(msg)[:80] if msg else ''})", ms,
|
|
307
|
+
)
|
|
308
|
+
if not isinstance(r.body, dict) or not isinstance(r.body.get("choices"), list) or not r.body["choices"]:
|
|
309
|
+
return ProbeResult("continuation", "unknown", "HTTP 200 without a choices array (malformed response)", ms)
|
|
310
|
+
if _budget_exhausted(r):
|
|
311
|
+
return ProbeResult("continuation", "unknown", _EXHAUSTED_NOTE, ms)
|
|
312
|
+
msg_obj = (r.body["choices"][0] or {}).get("message")
|
|
313
|
+
if not isinstance(msg_obj, dict) or msg_obj.get("role") not in (None, "assistant"):
|
|
314
|
+
return ProbeResult("continuation", "unsupported", "HTTP 200 but no assistant message in the first choice", ms)
|
|
315
|
+
answered = bool(_content(r).strip()) or bool(_tool_calls(r))
|
|
316
|
+
if not answered:
|
|
317
|
+
return ProbeResult("continuation", "unsupported", "HTTP 200 but the assistant message carried neither content nor tool_calls", ms)
|
|
318
|
+
return ProbeResult("continuation", "supported", _CONTINUATION_NOTE, ms, details={"answer_mentions_7": "7" in _content(r)})
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
_AUDIO_NOTE = (
|
|
322
|
+
"an inline input_audio part (0.25 s generated WAV tone) was accepted and answered with a well-formed assistant "
|
|
323
|
+
"message: protocol acceptance of audio input on this path, not transcription or audio-understanding quality"
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _probe_wav() -> str:
|
|
328
|
+
"""A 0.25 s, 16 kHz mono 16-bit PCM 440 Hz tone, generated (no bundled media), base64-encoded."""
|
|
329
|
+
import base64
|
|
330
|
+
import io
|
|
331
|
+
import math
|
|
332
|
+
import struct
|
|
333
|
+
import wave
|
|
334
|
+
|
|
335
|
+
buf = io.BytesIO()
|
|
336
|
+
with wave.open(buf, "wb") as w:
|
|
337
|
+
w.setnchannels(1)
|
|
338
|
+
w.setsampwidth(2)
|
|
339
|
+
w.setframerate(16000)
|
|
340
|
+
w.writeframes(b"".join(struct.pack("<h", int(12000 * math.sin(2 * math.pi * 440 * i / 16000))) for i in range(4000)))
|
|
341
|
+
return base64.b64encode(buf.getvalue()).decode()
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
async def probe_audio_in(adapter: BaseAdapter, dep: Deployment, timeout: float) -> ProbeResult:
|
|
345
|
+
"""Does this backend path accept an inline ``input_audio`` content part for this model? ``supported`` only
|
|
346
|
+
on HTTP 200 with a well-formed assistant message; ``unsupported`` on an explicit 4xx or an answer without
|
|
347
|
+
content; ``unknown`` (capability untouched) on 5xx, transport errors or an exhausted output budget."""
|
|
348
|
+
body = {
|
|
349
|
+
"model": dep.model,
|
|
350
|
+
"messages": [{"role": "user", "content": [{"type": "text", "text": "Reply with the single word: ok"}, {"type": "input_audio", "input_audio": {"data": _probe_wav(), "format": "wav"}}]}],
|
|
351
|
+
"max_tokens": 512,
|
|
352
|
+
"temperature": 0,
|
|
353
|
+
}
|
|
354
|
+
t0 = time.monotonic()
|
|
355
|
+
try:
|
|
356
|
+
r = await _chat(adapter, dep, body, timeout)
|
|
357
|
+
except AdapterError as e:
|
|
358
|
+
return _error_result("audio_in", e)
|
|
359
|
+
ms = (time.monotonic() - t0) * 1000
|
|
360
|
+
if r.status >= 500:
|
|
361
|
+
return ProbeResult("audio_in", "unknown", f"backend returned {r.status} (transient?) for an input_audio part", ms)
|
|
362
|
+
if r.status != 200:
|
|
363
|
+
return ProbeResult("audio_in", "unsupported", f"backend rejected the input_audio part with HTTP {r.status}", ms)
|
|
364
|
+
if _budget_exhausted(r):
|
|
365
|
+
return ProbeResult("audio_in", "unknown", _EXHAUSTED_NOTE, ms)
|
|
366
|
+
if not _content(r):
|
|
367
|
+
return ProbeResult("audio_in", "unsupported", "HTTP 200 but no assistant content for a request with an input_audio part", ms)
|
|
368
|
+
return ProbeResult("audio_in", "supported", _AUDIO_NOTE, ms)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
async def probe_streaming(adapter: BaseAdapter, dep: Deployment, timeout: float) -> tuple[ProbeResult, float | None]:
|
|
372
|
+
t0 = time.monotonic()
|
|
373
|
+
body = {"messages": [{"role": "user", "content": "Count from 1 to 5, separated by spaces."}], "max_tokens": STREAM_PROBE_MAX_TOKENS, "temperature": 0}
|
|
374
|
+
try:
|
|
375
|
+
s: UpstreamStream = await adapter.chat(dep, body, stream=True, timeout=timeout)
|
|
376
|
+
except AdapterError as e:
|
|
377
|
+
return _error_result("streaming", e), None
|
|
378
|
+
if s.status != 200:
|
|
379
|
+
await s.close()
|
|
380
|
+
return ProbeResult("streaming", "unknown" if s.status >= 500 else "unsupported", f"backend returned {s.status}"), None
|
|
381
|
+
parser = SSEParser()
|
|
382
|
+
obs = StreamObserver()
|
|
383
|
+
ttft: float | None = None
|
|
384
|
+
try:
|
|
385
|
+
async for chunk in s.aiter_bytes():
|
|
386
|
+
if ttft is None:
|
|
387
|
+
ttft = (time.monotonic() - t0) * 1000
|
|
388
|
+
for ev in parser.feed(chunk):
|
|
389
|
+
obs.observe(ev)
|
|
390
|
+
except AdapterError as e:
|
|
391
|
+
await s.close()
|
|
392
|
+
return _error_result("streaming", e), ttft
|
|
393
|
+
finally:
|
|
394
|
+
await s.close()
|
|
395
|
+
ms = (time.monotonic() - t0) * 1000
|
|
396
|
+
delivered = obs.content_chunks >= 1 or obs.reasoning_chunks >= 1
|
|
397
|
+
ok = obs.events >= 2 and delivered and obs.saw_done
|
|
398
|
+
value = "supported" if ok else ("unknown" if (obs.events >= 2 and obs.saw_done and obs.finish_reason == "length") else "unsupported")
|
|
399
|
+
note = (
|
|
400
|
+
f"events={obs.events} content_chunks={obs.content_chunks} reasoning_chunks={obs.reasoning_chunks} "
|
|
401
|
+
f"done={obs.saw_done} finish={obs.finish_reason} usage={'yes' if obs.usage else 'no'}"
|
|
402
|
+
)
|
|
403
|
+
if value == "unknown":
|
|
404
|
+
note += "; " + _EXHAUSTED_NOTE
|
|
405
|
+
return ProbeResult("streaming", value, note, ms), ttft
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
async def measure_latency(adapter: BaseAdapter, dep: Deployment, timeout: float) -> tuple[Measurement, bool]:
|
|
409
|
+
"""Two short requests: the first may include model loading, the second is warm. The second
|
|
410
|
+
value is True when a request timed out (the backend may still be computing)."""
|
|
411
|
+
body = {"messages": [{"role": "user", "content": "Reply with the single word: ready"}], "max_tokens": 256, "temperature": 0}
|
|
412
|
+
times: list[float] = []
|
|
413
|
+
uncertain = False
|
|
414
|
+
for _ in range(2):
|
|
415
|
+
t0 = time.monotonic()
|
|
416
|
+
try:
|
|
417
|
+
r = await _chat(adapter, dep, body, timeout)
|
|
418
|
+
except AdapterError as e:
|
|
419
|
+
if e.kind == "timeout":
|
|
420
|
+
uncertain = True
|
|
421
|
+
break
|
|
422
|
+
if r.status != 200:
|
|
423
|
+
break
|
|
424
|
+
times.append((time.monotonic() - t0) * 1000)
|
|
425
|
+
m = Measurement(
|
|
426
|
+
task="latency_probe",
|
|
427
|
+
samples=len(times),
|
|
428
|
+
source="probe",
|
|
429
|
+
measured_at=time.time(),
|
|
430
|
+
conditions={
|
|
431
|
+
"workload": "single short prompt, max_tokens=256, temperature=0",
|
|
432
|
+
"effective_context": dep.context_length,
|
|
433
|
+
"runtime": f"{dep.runtime} {dep.runtime_version}".strip(),
|
|
434
|
+
"endpoint": dep.endpoint,
|
|
435
|
+
"resident_before": dep.loaded,
|
|
436
|
+
},
|
|
437
|
+
)
|
|
438
|
+
if len(times) == 2:
|
|
439
|
+
m.p50_ms = times[1]
|
|
440
|
+
m.p95_ms = max(times)
|
|
441
|
+
m.load_ms = max(0.0, times[0] - times[1]) if not dep.loaded else 0.0
|
|
442
|
+
elif times:
|
|
443
|
+
m.p50_ms = times[0]
|
|
444
|
+
return m, uncertain
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
async def run_probes(
|
|
448
|
+
adapter: BaseAdapter,
|
|
449
|
+
dep: Deployment,
|
|
450
|
+
store: Store | None,
|
|
451
|
+
which: list[str] | None = None,
|
|
452
|
+
timeout: float = 120.0,
|
|
453
|
+
) -> ProbeReport:
|
|
454
|
+
if not which:
|
|
455
|
+
which = ["streaming", "tools", "parallel_tools", "json_object", "json_schema", "vision", "continuation", "latency"]
|
|
456
|
+
# The audio probe joins the default set only where the runtime does not already say "no audio"
|
|
457
|
+
# (Ollama /api/show lists no audio capability for most models): no pointless inference.
|
|
458
|
+
if dep.cap("audio_in") != "unsupported":
|
|
459
|
+
which.insert(-1, "audio_in")
|
|
460
|
+
rep = ProbeReport(dep.id, dep.fingerprint)
|
|
461
|
+
if dep.role != "generative":
|
|
462
|
+
rep.errors.append(f"deployment role is {dep.role}; chat probes apply only to generative deployments")
|
|
463
|
+
return rep
|
|
464
|
+
|
|
465
|
+
async def _save(r: ProbeResult) -> None:
|
|
466
|
+
rep.results.append(r)
|
|
467
|
+
if r.value != "unknown":
|
|
468
|
+
dep.set_cap(r.capability, r.value, "probe", r.note) # type: ignore[arg-type]
|
|
469
|
+
if store:
|
|
470
|
+
store.save_probe(dep.id, dep.fingerprint, r.capability, r.value, r.note)
|
|
471
|
+
if r.uncertain:
|
|
472
|
+
rep.uncertain = True
|
|
473
|
+
|
|
474
|
+
def _stop(after: str) -> None:
|
|
475
|
+
# One reservation covers this run. After a timeout the backend may still be computing, so
|
|
476
|
+
# no further inference is started on it; the caller holds the reservation as uncertain.
|
|
477
|
+
rep.errors.append(
|
|
478
|
+
f"probe {after!r} timed out; the backend may still be computing, so the remaining probes were "
|
|
479
|
+
"not run and the slot is held as uncertain (re-run `modelsaar probe` later)"
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
order = ["streaming", "tools", "parallel_tools", "json_object", "json_schema", "vision", "continuation", "audio_in", "latency"]
|
|
483
|
+
ttft: float | None = None
|
|
484
|
+
for name in order:
|
|
485
|
+
if name not in which:
|
|
486
|
+
continue
|
|
487
|
+
if rep.uncertain:
|
|
488
|
+
rep.skipped.append(name)
|
|
489
|
+
continue
|
|
490
|
+
if name == "streaming":
|
|
491
|
+
r, ttft = await probe_streaming(adapter, dep, timeout)
|
|
492
|
+
await _save(r)
|
|
493
|
+
elif name == "tools":
|
|
494
|
+
if dep.cap("tools") == "unsupported" and dep.capabilities["tools"].provenance == "source_claim":
|
|
495
|
+
rep.results.append(ProbeResult("tools", "unsupported", "skipped: backend metadata says tools unsupported"))
|
|
496
|
+
else:
|
|
497
|
+
await _save(await probe_tools(adapter, dep, timeout))
|
|
498
|
+
elif name == "parallel_tools":
|
|
499
|
+
if dep.cap("tools") == "supported":
|
|
500
|
+
await _save(await probe_parallel_tools(adapter, dep, timeout))
|
|
501
|
+
elif name == "json_object":
|
|
502
|
+
await _save(await probe_json_object(adapter, dep, timeout))
|
|
503
|
+
elif name == "json_schema":
|
|
504
|
+
await _save(await probe_json_schema(adapter, dep, timeout))
|
|
505
|
+
elif name == "vision":
|
|
506
|
+
if dep.cap("vision") == "unsupported" and dep.capabilities["vision"].provenance == "source_claim":
|
|
507
|
+
rep.results.append(ProbeResult("vision", "unsupported", "skipped: backend metadata says vision unsupported"))
|
|
508
|
+
else:
|
|
509
|
+
await _save(await probe_vision(adapter, dep, timeout))
|
|
510
|
+
elif name == "continuation":
|
|
511
|
+
await _save(await probe_continuation(adapter, dep, timeout))
|
|
512
|
+
elif name == "audio_in":
|
|
513
|
+
await _save(await probe_audio_in(adapter, dep, timeout))
|
|
514
|
+
elif name == "latency":
|
|
515
|
+
m, timed_out = await measure_latency(adapter, dep, timeout)
|
|
516
|
+
if timed_out:
|
|
517
|
+
rep.uncertain = True
|
|
518
|
+
if ttft is not None:
|
|
519
|
+
m.ttft_ms = ttft
|
|
520
|
+
rep.measurements.append(m)
|
|
521
|
+
dep.measurements[m.task] = m
|
|
522
|
+
if store and m.samples:
|
|
523
|
+
store.save_measurement(dep.id, dep.fingerprint, m.__dict__)
|
|
524
|
+
if rep.uncertain and name not in rep.skipped:
|
|
525
|
+
_stop(name)
|
|
526
|
+
return rep
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""OpenAI-compatible protocol models and helpers."""
|