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.
Files changed (54) hide show
  1. modelsaar/__init__.py +13 -0
  2. modelsaar/adapters/__init__.py +27 -0
  3. modelsaar/adapters/base.py +274 -0
  4. modelsaar/adapters/ollama.py +317 -0
  5. modelsaar/adapters/openai_compat.py +296 -0
  6. modelsaar/catalogue/__init__.py +72 -0
  7. modelsaar/catalogue/starter.yaml +435 -0
  8. modelsaar/cli.py +880 -0
  9. modelsaar/clientconfig/__init__.py +364 -0
  10. modelsaar/config.py +631 -0
  11. modelsaar/doctor.py +233 -0
  12. modelsaar/evaluation/__init__.py +1 -0
  13. modelsaar/evaluation/fixtures/tasks.jsonl +47 -0
  14. modelsaar/evaluation/harness.py +768 -0
  15. modelsaar/evaluation/judge.py +173 -0
  16. modelsaar/evaluation/sandbox.py +341 -0
  17. modelsaar/evaluation/scoring.py +233 -0
  18. modelsaar/learning.py +227 -0
  19. modelsaar/lifecycle.py +208 -0
  20. modelsaar/pipelines.py +439 -0
  21. modelsaar/probes.py +526 -0
  22. modelsaar/protocol/__init__.py +1 -0
  23. modelsaar/protocol/anthropic.py +401 -0
  24. modelsaar/protocol/decisions.py +229 -0
  25. modelsaar/protocol/openai.py +322 -0
  26. modelsaar/protocol/responses.py +560 -0
  27. modelsaar/protocol/sse.py +181 -0
  28. modelsaar/registry.py +229 -0
  29. modelsaar/responses_store.py +117 -0
  30. modelsaar/routing/__init__.py +1 -0
  31. modelsaar/routing/admission.py +359 -0
  32. modelsaar/routing/affinity.py +131 -0
  33. modelsaar/routing/cascade.py +53 -0
  34. modelsaar/routing/classifier.py +298 -0
  35. modelsaar/routing/decision.py +85 -0
  36. modelsaar/routing/eligibility.py +158 -0
  37. modelsaar/routing/requirements.py +290 -0
  38. modelsaar/routing/router.py +1026 -0
  39. modelsaar/routing/scoring.py +179 -0
  40. modelsaar/routing/tokens.py +114 -0
  41. modelsaar/runtime.py +82 -0
  42. modelsaar/security.py +63 -0
  43. modelsaar/server.py +1546 -0
  44. modelsaar/static/status.html +95 -0
  45. modelsaar/store.py +208 -0
  46. modelsaar/testing/__init__.py +1 -0
  47. modelsaar/testing/fakebackend.py +661 -0
  48. modelsaar-0.2.0.dist-info/METADATA +285 -0
  49. modelsaar-0.2.0.dist-info/RECORD +54 -0
  50. modelsaar-0.2.0.dist-info/WHEEL +5 -0
  51. modelsaar-0.2.0.dist-info/entry_points.txt +2 -0
  52. modelsaar-0.2.0.dist-info/licenses/LICENSE +202 -0
  53. modelsaar-0.2.0.dist-info/licenses/NOTICE +18 -0
  54. modelsaar-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,401 @@
1
+ """Anthropic Messages API — a fail-closed translation onto the chat path.
2
+
3
+ ``POST /v1/messages`` requests are translated into the gateway's chat-completions request, routed and
4
+ dispatched under exactly the same rules, and the answer is translated back. Fail-closed means:
5
+ anything that would change what the model is asked, or that depends on Anthropic-hosted state or
6
+ tools, is refused with a typed Anthropic error (HTTP 400) before any backend is contacted — server
7
+ tools (web search, code execution, computer use, bash, text editor), ``thinking`` budgets,
8
+ ``top_k``, ``redacted_thinking`` blocks, document/file blocks, images inside tool results, MCP
9
+ servers, containers and unknown fields.
10
+
11
+ Two things have no chat-completions equivalent and are *recorded*, never silently dropped (they
12
+ appear as translation notes on the routing decision): ``cache_control`` markers (an advisory
13
+ performance hint; the backend manages its own cache) and ``tool_result.is_error`` (the result text
14
+ is forwarded unchanged; the flag itself is not representable).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import time
21
+ import uuid
22
+ from typing import Any
23
+
24
+ from .openai import ProtocolError
25
+
26
+ _TOP_LEVEL = frozenset(
27
+ {
28
+ "model", "max_tokens", "messages", "system", "tools", "tool_choice", "temperature", "top_p", "top_k",
29
+ "stop_sequences", "stream", "metadata", "thinking", "service_tier", "mcp_servers", "container",
30
+ "context_management", "output_config", "modelsaar",
31
+ }
32
+ ) # fmt: skip
33
+ _STOP = {"stop": "end_turn", "length": "max_tokens", "tool_calls": "tool_use", "function_call": "tool_use", "content_filter": "refusal"}
34
+
35
+
36
+ def _bad(msg: str, param: str | None = None, code: str = "unsupported_messages_feature") -> ProtocolError:
37
+ return ProtocolError(msg, status=400, code=code, param=param)
38
+
39
+
40
+ def _mid(prefix: str = "msg") -> str:
41
+ return f"{prefix}_{uuid.uuid4().hex[:24]}"
42
+
43
+
44
+ def _cache_note(block: dict[str, Any], where: str, notes: list[str]) -> None:
45
+ if block.get("cache_control") is not None:
46
+ n = "cache_control is advisory; prompt caching is managed by the backend (not forwarded, no cache hit promised)"
47
+ if n not in notes:
48
+ notes.append(n)
49
+
50
+
51
+ def _text_blocks(content: Any, where: str, notes: list[str]) -> str:
52
+ """A string or a list of text blocks -> one string. Anything else is refused."""
53
+ if isinstance(content, str):
54
+ return content
55
+ if not isinstance(content, list):
56
+ raise _bad(f"{where} must be a string or a list of text blocks", where, "invalid_request_error")
57
+ out = []
58
+ for i, b in enumerate(content):
59
+ if not isinstance(b, dict) or b.get("type") != "text" or not isinstance(b.get("text"), str):
60
+ t = b.get("type") if isinstance(b, dict) else type(b).__name__
61
+ raise _bad(f"{where}[{i}]: only text blocks are supported here (got {t!r})", f"{where}[{i}]")
62
+ if set(b) - {"type", "text", "cache_control"}:
63
+ raise _bad(f"{where}[{i}]: unsupported keys {sorted(set(b) - {'type', 'text', 'cache_control'})} (citations are not translated)", f"{where}[{i}]")
64
+ _cache_note(b, where, notes)
65
+ out.append(b["text"])
66
+ return "\n\n".join(out)
67
+
68
+
69
+ def _image(block: dict[str, Any], loc: str) -> dict[str, Any]:
70
+ src = block.get("source")
71
+ if not isinstance(src, dict):
72
+ raise _bad(f"{loc}: image block requires a source", loc, "invalid_request_error")
73
+ if src.get("type") == "base64" and isinstance(src.get("data"), str) and isinstance(src.get("media_type"), str):
74
+ return {"type": "image_url", "image_url": {"url": f"data:{src['media_type']};base64,{src['data']}"}}
75
+ if src.get("type") == "url" and isinstance(src.get("url"), str):
76
+ # Passed on as an external URL: the routing layer refuses to fetch it and excludes backends that would.
77
+ return {"type": "image_url", "image_url": {"url": src["url"]}}
78
+ raise _bad(f"{loc}: image source type {src.get('type')!r} is not supported (file ids need Anthropic's file store)", loc)
79
+
80
+
81
+ def messages_to_chat(body: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
82
+ unknown = set(body) - _TOP_LEVEL
83
+ if unknown:
84
+ raise _bad(f"unsupported request field(s): {sorted(unknown)}", sorted(unknown)[0])
85
+ if not isinstance(body.get("model"), str) or not body["model"]:
86
+ raise _bad("model is required", "model", "invalid_request_error")
87
+ mt = body.get("max_tokens")
88
+ if not isinstance(mt, int) or isinstance(mt, bool) or mt < 1:
89
+ raise _bad("max_tokens is required and must be a positive integer", "max_tokens", "invalid_request_error")
90
+ if body.get("top_k") is not None:
91
+ raise _bad("top_k has no chat-completions equivalent on this gateway and is not silently dropped", "top_k")
92
+ th = body.get("thinking")
93
+ if th is not None and not (isinstance(th, dict) and th.get("type") == "disabled"):
94
+ raise _bad(
95
+ "thinking budgets are an Anthropic-model contract and are not translated; omit `thinking` (a local "
96
+ "deployment decides its own reasoning) or send {\"type\": \"disabled\"}",
97
+ "thinking",
98
+ )
99
+ for k in ("mcp_servers", "container", "context_management", "output_config", "service_tier"):
100
+ if body.get(k):
101
+ raise _bad(f"{k} needs Anthropic-hosted functionality and is not supported", k)
102
+ notes: list[str] = []
103
+ messages: list[dict[str, Any]] = []
104
+ if body.get("system") is not None:
105
+ messages.append({"role": "system", "content": _text_blocks(body["system"], "system", notes)})
106
+ raw = body.get("messages")
107
+ if not isinstance(raw, list) or not raw:
108
+ raise _bad("messages must be a non-empty list", "messages", "invalid_request_error")
109
+ for i, m in enumerate(raw):
110
+ loc = f"messages[{i}]"
111
+ if not isinstance(m, dict) or m.get("role") not in ("user", "assistant"):
112
+ raise _bad(f"{loc}: role must be user or assistant", loc, "invalid_request_error")
113
+ role, content = m["role"], m.get("content")
114
+ if isinstance(content, str):
115
+ messages.append({"role": role, "content": content})
116
+ continue
117
+ if not isinstance(content, list) or not content:
118
+ raise _bad(f"{loc}: content must be a string or a non-empty list of blocks", loc, "invalid_request_error")
119
+ parts: list[dict[str, Any]] = []
120
+ tool_calls: list[dict[str, Any]] = []
121
+ tool_results: list[dict[str, Any]] = []
122
+ reasoning: list[str] = []
123
+ for j, b in enumerate(content):
124
+ bloc = f"{loc}.content[{j}]"
125
+ if not isinstance(b, dict):
126
+ raise _bad(f"{bloc}: content block must be an object", bloc, "invalid_request_error")
127
+ t = b.get("type")
128
+ _cache_note(b, bloc, notes)
129
+ if t == "text":
130
+ if not isinstance(b.get("text"), str):
131
+ raise _bad(f"{bloc}: text block requires a string 'text'", bloc, "invalid_request_error")
132
+ if b.get("citations"):
133
+ raise _bad(f"{bloc}: citations are not translated", bloc)
134
+ parts.append({"type": "text", "text": b["text"]})
135
+ elif t == "image" and role == "user":
136
+ parts.append(_image(b, bloc))
137
+ elif t == "tool_use" and role == "assistant":
138
+ if not (isinstance(b.get("id"), str) and isinstance(b.get("name"), str) and isinstance(b.get("input"), dict)):
139
+ raise _bad(f"{bloc}: tool_use requires id, name and input (object)", bloc, "invalid_request_error")
140
+ tool_calls.append({"id": b["id"], "type": "function", "function": {"name": b["name"], "arguments": json.dumps(b["input"], separators=(",", ":"), ensure_ascii=False)}})
141
+ elif t == "tool_result" and role == "user":
142
+ if not isinstance(b.get("tool_use_id"), str) or not b["tool_use_id"]:
143
+ raise _bad(f"{bloc}: tool_result requires tool_use_id", bloc, "invalid_request_error")
144
+ c = b.get("content", "")
145
+ text = _text_blocks(c if c is not None else "", f"{bloc}.content", notes)
146
+ if b.get("is_error"):
147
+ notes.append("tool_result.is_error is not representable in chat completions; the result text is forwarded unchanged")
148
+ tool_results.append({"role": "tool", "tool_call_id": b["tool_use_id"], "content": text})
149
+ elif t == "thinking" and role == "assistant":
150
+ if not isinstance(b.get("thinking"), str):
151
+ raise _bad(f"{bloc}: thinking block requires 'thinking' text", bloc, "invalid_request_error")
152
+ reasoning.append(b["thinking"])
153
+ if b.get("signature"):
154
+ n = "thinking.signature is Anthropic-specific verification state; a local deployment cannot verify it (not forwarded)"
155
+ if n not in notes:
156
+ notes.append(n)
157
+ elif t == "redacted_thinking":
158
+ raise _bad(f"{bloc}: redacted_thinking is opaque provider state and cannot be consumed by another deployment", bloc, "unsupported_stateful_feature")
159
+ else:
160
+ raise _bad(
161
+ f"{bloc}: unsupported content block type {t!r} for role {role} (supported: text, image, tool_use, "
162
+ "tool_result, thinking; documents, files and server-tool blocks are not forwarded)",
163
+ bloc,
164
+ "unsupported_content_type",
165
+ )
166
+ if role == "user":
167
+ # Tool results first (they answer the previous assistant turn), then any accompanying user text.
168
+ messages.extend(tool_results)
169
+ if parts:
170
+ only_text = all(p["type"] == "text" for p in parts)
171
+ messages.append({"role": "user", "content": "\n\n".join(p["text"] for p in parts) if only_text else parts})
172
+ else:
173
+ msg: dict[str, Any] = {"role": "assistant", "content": "".join(p["text"] for p in parts) if parts else None}
174
+ if tool_calls:
175
+ msg["tool_calls"] = tool_calls
176
+ if reasoning:
177
+ msg["reasoning_content"] = "".join(reasoning)
178
+ messages.append(msg)
179
+
180
+ chat: dict[str, Any] = {"model": body["model"], "messages": messages, "max_tokens": mt}
181
+ tools = body.get("tools")
182
+ if tools:
183
+ if not isinstance(tools, list):
184
+ raise _bad("tools must be a list", "tools", "invalid_request_error")
185
+ out_tools = []
186
+ for i, t in enumerate(tools):
187
+ loc = f"tools[{i}]"
188
+ if not isinstance(t, dict):
189
+ raise _bad(f"{loc}: tool must be an object", loc, "invalid_request_error")
190
+ if t.get("type") not in (None, "custom"):
191
+ raise _bad(
192
+ f"{loc}: tool type {t.get('type')!r} is an Anthropic server/client-defined tool; the gateway executes "
193
+ "no tools and supports only custom tools with an input_schema",
194
+ loc,
195
+ )
196
+ if not isinstance(t.get("name"), str) or not isinstance(t.get("input_schema"), dict):
197
+ raise _bad(f"{loc}: custom tool requires name and input_schema", loc, "invalid_request_error")
198
+ extra = set(t) - {"type", "name", "description", "input_schema", "cache_control"}
199
+ if extra:
200
+ raise _bad(f"{loc}: unsupported keys {sorted(extra)}", loc)
201
+ _cache_note(t, loc, notes)
202
+ fn: dict[str, Any] = {"name": t["name"], "parameters": t["input_schema"]}
203
+ if t.get("description") is not None:
204
+ fn["description"] = t["description"]
205
+ out_tools.append({"type": "function", "function": fn})
206
+ chat["tools"] = out_tools
207
+ tc = body.get("tool_choice")
208
+ if tc is not None:
209
+ if not isinstance(tc, dict) or tc.get("type") not in ("auto", "any", "tool", "none"):
210
+ raise _bad("tool_choice.type must be auto, any, tool or none", "tool_choice", "invalid_request_error")
211
+ if tc["type"] == "tool":
212
+ if not isinstance(tc.get("name"), str):
213
+ raise _bad("tool_choice type tool requires a name", "tool_choice", "invalid_request_error")
214
+ chat["tool_choice"] = {"type": "function", "function": {"name": tc["name"]}}
215
+ else:
216
+ chat["tool_choice"] = {"auto": "auto", "any": "required", "none": "none"}[tc["type"]]
217
+ if tc.get("disable_parallel_tool_use") is not None:
218
+ chat["parallel_tool_calls"] = not bool(tc["disable_parallel_tool_use"])
219
+ for src, dst in (("temperature", "temperature"), ("top_p", "top_p"), ("modelsaar", "modelsaar")):
220
+ if body.get(src) is not None:
221
+ chat[dst] = body[src]
222
+ ss = body.get("stop_sequences")
223
+ if ss:
224
+ if not isinstance(ss, list) or not all(isinstance(s, str) for s in ss):
225
+ raise _bad("stop_sequences must be a list of strings", "stop_sequences", "invalid_request_error")
226
+ chat["stop"] = ss
227
+ md = body.get("metadata")
228
+ if md is not None:
229
+ if not isinstance(md, dict) or set(md) - {"user_id"}:
230
+ raise _bad("metadata supports only user_id", "metadata")
231
+ if md.get("user_id") is not None:
232
+ chat["user"] = str(md["user_id"])
233
+ if body.get("stream"):
234
+ chat["stream"] = True
235
+ return chat, {"model": body["model"], "notes": notes, "stop_sequences": list(ss or [])}
236
+
237
+
238
+ # --------------------------------------------------------------------------- #
239
+ def _usage(u: Any) -> dict[str, int]:
240
+ u = u if isinstance(u, dict) else {}
241
+ return {"input_tokens": int(u.get("prompt_tokens") or 0), "output_tokens": int(u.get("completion_tokens") or 0)}
242
+
243
+
244
+ def chat_to_message(chat: dict[str, Any], ctx: dict[str, Any]) -> dict[str, Any]:
245
+ """Non-streaming chat completion -> Anthropic message. Raises ValueError when a tool call's
246
+ arguments are not a JSON object (``tool_use.input`` must be one; nothing is invented)."""
247
+ choice = (chat.get("choices") or [{}])[0]
248
+ msg = choice.get("message") or {}
249
+ content: list[dict[str, Any]] = []
250
+ rc = msg.get("reasoning_content") or msg.get("reasoning")
251
+ if isinstance(rc, str) and rc:
252
+ content.append({"type": "thinking", "thinking": rc, "signature": ""})
253
+ text = msg.get("content")
254
+ if isinstance(text, list):
255
+ text = "".join(p.get("text", "") for p in text if isinstance(p, dict) and p.get("type") == "text")
256
+ if isinstance(text, str) and text:
257
+ content.append({"type": "text", "text": text})
258
+ for tc in msg.get("tool_calls") or []:
259
+ fn = tc.get("function") if isinstance(tc, dict) else None
260
+ if not isinstance(fn, dict) or not tc.get("id") or not isinstance(fn.get("name"), str):
261
+ raise ValueError("upstream tool call without id/name cannot be represented as a tool_use block")
262
+ args = fn.get("arguments")
263
+ try:
264
+ parsed = json.loads(args) if isinstance(args, str) else args
265
+ except json.JSONDecodeError as e:
266
+ raise ValueError(f"upstream tool-call arguments are not valid JSON ({e.msg})") from e
267
+ if parsed is None or parsed == "":
268
+ parsed = {}
269
+ if not isinstance(parsed, dict):
270
+ raise ValueError("upstream tool-call arguments are not a JSON object")
271
+ content.append({"type": "tool_use", "id": str(tc["id"]), "name": fn["name"], "input": parsed})
272
+ fr = choice.get("finish_reason")
273
+ return {
274
+ "id": _mid(),
275
+ "type": "message",
276
+ "role": "assistant",
277
+ "model": ctx["model"],
278
+ "content": content,
279
+ "stop_reason": _STOP.get(fr or "stop", "end_turn"),
280
+ "stop_sequence": None,
281
+ "usage": _usage(chat.get("usage")),
282
+ }
283
+
284
+
285
+ _ERR_TYPES = {400: "invalid_request_error", 401: "authentication_error", 403: "permission_error", 404: "not_found_error", 413: "request_too_large", 429: "rate_limit_error", 503: "overloaded_error"}
286
+
287
+
288
+ def error_to_anthropic(status: int, body: Any) -> dict[str, Any]:
289
+ """OpenAI-style error envelope -> Anthropic error envelope. The gateway's own code and diagnostic
290
+ block (``modelsaar``: request id, blockers, remedies) are preserved."""
291
+ e = body.get("error") if isinstance(body, dict) and isinstance(body.get("error"), dict) else {}
292
+ err: dict[str, Any] = {"type": _ERR_TYPES.get(status, "invalid_request_error" if status < 500 else "api_error"), "message": e.get("message") or "error"}
293
+ if e.get("code"):
294
+ err["code"] = e["code"]
295
+ if e.get("param"):
296
+ err["param"] = e["param"]
297
+ if isinstance(e.get("modelsaar"), dict):
298
+ err["modelsaar"] = e["modelsaar"]
299
+ return {"type": "error", "error": err}
300
+
301
+
302
+ class MessagesStreamTranslator:
303
+ """Chat-completion chunks -> Anthropic streaming events. Content blocks are opened and closed
304
+ strictly in order (thinking, text, one block per tool call); a post-commit upstream failure
305
+ becomes an ``error`` event and no ``message_stop`` — never a fabricated ending."""
306
+
307
+ def __init__(self, ctx: dict[str, Any]) -> None:
308
+ self.ctx = ctx
309
+ self.id = _mid()
310
+ self.started = False
311
+ self.index = -1
312
+ self.open: str | None = None # "thinking" | "text" | "tool"
313
+ self.tools: dict[int, dict[str, str]] = {} # chat tool index -> buffered {id, name, args}
314
+ self.finish_reason: str | None = None
315
+ self.usage = {"input_tokens": 0, "output_tokens": 0}
316
+ self.closed = False
317
+ self.created = int(time.time())
318
+
319
+ @staticmethod
320
+ def _ev(name: str, data: dict[str, Any]) -> bytes:
321
+ return f"event: {name}\ndata: {json.dumps(data, separators=(',', ':'), ensure_ascii=False)}\n\n".encode()
322
+
323
+ def _start(self) -> list[bytes]:
324
+ if self.started:
325
+ return []
326
+ self.started = True
327
+ m = {"id": self.id, "type": "message", "role": "assistant", "model": self.ctx["model"], "content": [], "stop_reason": None, "stop_sequence": None, "usage": {"input_tokens": 0, "output_tokens": 0}}
328
+ return [self._ev("message_start", {"type": "message_start", "message": m})]
329
+
330
+ def _close_open(self) -> list[bytes]:
331
+ if self.open is None:
332
+ return []
333
+ self.open = None
334
+ return [self._ev("content_block_stop", {"type": "content_block_stop", "index": self.index})]
335
+
336
+ def _open(self, kind: str, block: dict[str, Any]) -> list[bytes]:
337
+ out = self._close_open()
338
+ self.index += 1
339
+ self.open = kind
340
+ out.append(self._ev("content_block_start", {"type": "content_block_start", "index": self.index, "content_block": block}))
341
+ return out
342
+
343
+ def feed(self, chunk: dict[str, Any]) -> list[bytes]:
344
+ out = self._start()
345
+ if isinstance(chunk.get("usage"), dict):
346
+ self.usage = _usage(chunk["usage"])
347
+ for ch in chunk.get("choices") or []:
348
+ delta = ch.get("delta") or {}
349
+ rc = delta.get("reasoning_content") or delta.get("reasoning")
350
+ if isinstance(rc, str) and rc:
351
+ if self.open != "thinking":
352
+ out += self._open("thinking", {"type": "thinking", "thinking": "", "signature": ""})
353
+ out.append(self._ev("content_block_delta", {"type": "content_block_delta", "index": self.index, "delta": {"type": "thinking_delta", "thinking": rc}}))
354
+ text = delta.get("content")
355
+ if isinstance(text, str) and text:
356
+ if self.open != "text":
357
+ out += self._open("text", {"type": "text", "text": ""})
358
+ out.append(self._ev("content_block_delta", {"type": "content_block_delta", "index": self.index, "delta": {"type": "text_delta", "text": text}}))
359
+ for tc in delta.get("tool_calls") or []:
360
+ if not isinstance(tc, dict):
361
+ continue
362
+ # Chat tool-call deltas may interleave across indexes; Anthropic content blocks are strictly
363
+ # sequential. Arguments are therefore buffered per call and each tool_use block is emitted
364
+ # whole (start, one input_json_delta, stop) at the end of the turn, in index order.
365
+ fn = tc.get("function") or {}
366
+ st = self.tools.setdefault(tc.get("index", 0), {"id": "", "name": "", "args": ""})
367
+ if tc.get("id") and not st["id"]:
368
+ st["id"] = str(tc["id"])
369
+ if fn.get("name") and not st["name"]:
370
+ st["name"] = fn["name"]
371
+ if isinstance(fn.get("arguments"), str):
372
+ st["args"] += fn["arguments"]
373
+ if ch.get("finish_reason"):
374
+ self.finish_reason = ch["finish_reason"]
375
+ return out
376
+
377
+ def error(self, err: dict[str, Any]) -> list[bytes]:
378
+ out = self._start()
379
+ self.closed = True
380
+ out.append(self._ev("error", error_to_anthropic(502, err)))
381
+ return out
382
+
383
+ def finish(self) -> list[bytes]:
384
+ if self.closed:
385
+ return []
386
+ self.closed = True
387
+ out = self._start() + self._close_open()
388
+ for idx in sorted(self.tools):
389
+ st = self.tools[idx]
390
+ out += self._open("tool", {"type": "tool_use", "id": st["id"] or _mid("toolu"), "name": st["name"], "input": {}})
391
+ if st["args"]:
392
+ out.append(self._ev("content_block_delta", {"type": "content_block_delta", "index": self.index, "delta": {"type": "input_json_delta", "partial_json": st["args"]}}))
393
+ out += self._close_open()
394
+ out.append(
395
+ self._ev(
396
+ "message_delta",
397
+ {"type": "message_delta", "delta": {"stop_reason": _STOP.get(self.finish_reason or "stop", "end_turn"), "stop_sequence": None}, "usage": {"output_tokens": self.usage["output_tokens"], "input_tokens": self.usage["input_tokens"]}},
398
+ )
399
+ )
400
+ out.append(self._ev("message_stop", {"type": "message_stop"}))
401
+ return out
@@ -0,0 +1,229 @@
1
+ """`POST /v1/decisions` — the gateway's decision-model endpoint.
2
+
3
+ The wire contract is Ollama's System One request and answer (docs.ollama.com/api/systemone), carried
4
+ through the gateway with its usual authentication, model resolution, admission, locality policy and
5
+ decision records:
6
+
7
+ request ``{"model": <deployment id | "auto">, "state": <non-empty string | object | array>,
8
+ "questions": {<name>: {"type": "choice"|"noul"|"score", "instructions": ..., "criteria": ...}},
9
+ "images": [<base64>, ...] (optional; needs a vision-capable decision model)}``
10
+ response ``{"model": ..., "answers": {<name>: <answer>}, "usage": {"input_tokens": n, "output_tokens": n}}``
11
+
12
+ Question limits are the documented ones (1..64 questions; ``choice`` 2..255 options; ``score`` 2..10
13
+ levels; text and schema at most 64 KiB; the whole request the backend receives — JSON including base64
14
+ images — at most 32 MiB, checked before dispatch). Before any of that, the gateway reads at most
15
+ ``server.max_request_bytes`` (default 32 MiB) of the client's body — a larger declared ``Content-Length``
16
+ is refused before reading and a streamed body is cut off at the limit — so no request is buffered beyond
17
+ that bound. ``keep_alive`` and any other field are refused: model lifecycle
18
+ is managed by the gateway, not per request. Answers are validated against the questions before they are
19
+ returned (type match, options from the criteria, probabilities and confidence in [0, 1]); a backend answer
20
+ that violates the contract is reported as ``decision_contract_violation`` instead of being passed on.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import base64
26
+ import json
27
+ import math
28
+ import re
29
+ from typing import Any, Literal
30
+
31
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
32
+
33
+ from .openai import ProtocolError
34
+
35
+ MAX_QUESTIONS = 64
36
+ MAX_TEXT_BYTES = 64 * 1024 # documented local limit for state + questions (excluding images)
37
+ MAX_REQUEST_BYTES = 32 * 1024 * 1024 # documented local limit for the whole request Ollama receives (JSON incl. base64 images)
38
+ _NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,100}$")
39
+ Instructions = str | dict[str, Any] | list[Any]
40
+
41
+
42
+ def _non_empty_text(v: Any, what: str) -> Any:
43
+ if isinstance(v, str):
44
+ if not v.strip():
45
+ raise ValueError(f"{what} must contain a non-whitespace character")
46
+ return v
47
+ if isinstance(v, (dict, list)):
48
+ return v
49
+ raise ValueError(f"{what} must be a non-empty string, an object or an array")
50
+
51
+
52
+ class ChoiceQuestion(BaseModel):
53
+ model_config = ConfigDict(extra="forbid")
54
+ type: Literal["choice"]
55
+ instructions: Instructions
56
+ criteria: dict[str, str | None] = Field(min_length=2, max_length=255)
57
+
58
+ @field_validator("instructions")
59
+ @classmethod
60
+ def _instr(cls, v: Any) -> Any:
61
+ return _non_empty_text(v, "instructions")
62
+
63
+
64
+ class NoulQuestion(BaseModel):
65
+ model_config = ConfigDict(extra="forbid")
66
+ type: Literal["noul"]
67
+ instructions: Instructions
68
+ criteria: dict[Literal["true", "false"], str] | None = None
69
+
70
+ @field_validator("instructions")
71
+ @classmethod
72
+ def _instr(cls, v: Any) -> Any:
73
+ return _non_empty_text(v, "instructions")
74
+
75
+
76
+ class ScoreQuestion(BaseModel):
77
+ model_config = ConfigDict(extra="forbid")
78
+ type: Literal["score"]
79
+ instructions: Instructions
80
+ criteria: list[str] = Field(min_length=2, max_length=10)
81
+
82
+ @field_validator("instructions")
83
+ @classmethod
84
+ def _instr(cls, v: Any) -> Any:
85
+ return _non_empty_text(v, "instructions")
86
+
87
+
88
+ Question = ChoiceQuestion | NoulQuestion | ScoreQuestion
89
+
90
+
91
+ class DecisionsRequest(BaseModel):
92
+ model_config = ConfigDict(extra="forbid")
93
+ model: str = Field(min_length=1)
94
+ state: Any
95
+ questions: dict[str, Question] = Field(min_length=1, max_length=MAX_QUESTIONS)
96
+ images: list[str] | None = None
97
+
98
+ @field_validator("state")
99
+ @classmethod
100
+ def _state(cls, v: Any) -> Any:
101
+ return _non_empty_text(v, "state")
102
+
103
+ @field_validator("questions")
104
+ @classmethod
105
+ def _names(cls, v: dict[str, Question]) -> dict[str, Question]:
106
+ for name in v:
107
+ if not _NAME_RE.match(name):
108
+ raise ValueError(f"question name {name!r} must be 1-100 characters of letters, digits, '_', '.' or '-'")
109
+ return v
110
+
111
+ @field_validator("images")
112
+ @classmethod
113
+ def _images(cls, v: list[str] | None) -> list[str] | None:
114
+ if v is None:
115
+ return None
116
+ if not v:
117
+ raise ValueError("images must not be empty when present")
118
+ for i, img in enumerate(v):
119
+ if not isinstance(img, str) or not img:
120
+ raise ValueError(f"images[{i}] must be a base64 string")
121
+ if img.startswith(("data:", "http://", "https://")):
122
+ raise ValueError(f"images[{i}]: URLs and data URLs are not accepted; send raw base64")
123
+ try:
124
+ base64.b64decode(img, validate=True)
125
+ except Exception as e: # noqa: BLE001
126
+ raise ValueError(f"images[{i}] is not valid base64") from e
127
+ return v
128
+
129
+ @model_validator(mode="after")
130
+ def _size(self) -> DecisionsRequest:
131
+ text = json.dumps({"state": self.state, "questions": {k: q.model_dump() for k, q in self.questions.items()}}, ensure_ascii=False)
132
+ if len(text.encode("utf-8")) > MAX_TEXT_BYTES:
133
+ raise ValueError(f"state and questions exceed {MAX_TEXT_BYTES // 1024} KiB")
134
+ return self
135
+
136
+ def upstream_questions(self) -> dict[str, Any]:
137
+ return {k: q.model_dump(exclude_none=True) for k, q in self.questions.items()}
138
+
139
+ def upstream_bytes(self) -> int:
140
+ """Size of the JSON the backend will receive (model, state, questions, images), as the adapter
141
+ serialises it; checked against the documented 32 MiB whole-request limit before dispatch."""
142
+ body: dict[str, Any] = {"model": self.model, "state": self.state, "questions": self.upstream_questions()}
143
+ if self.images:
144
+ body["images"] = self.images
145
+ return len(json.dumps(body).encode("utf-8"))
146
+
147
+
148
+ def parse_decisions_request(body: dict[str, Any]) -> DecisionsRequest:
149
+ """Validate the body. Field errors are ``400`` naming the field; a request whose upstream form would
150
+ exceed the documented whole-request limit is ``413`` (the gateway's own ``server.max_request_bytes``
151
+ bounds the bytes read from the client before this point)."""
152
+ try:
153
+ req = DecisionsRequest.model_validate(body)
154
+ except ValidationError as e:
155
+ first = e.errors()[0]
156
+ loc = ".".join(str(p) for p in first.get("loc", ()))
157
+ msg = first.get("msg", "invalid request")
158
+ raise ProtocolError(
159
+ f"invalid decisions request: {loc + ': ' if loc else ''}{msg}", param=loc.split(".")[0] if loc else None
160
+ ) from e
161
+ size = req.upstream_bytes()
162
+ if size > MAX_REQUEST_BYTES:
163
+ raise ProtocolError(
164
+ f"decisions request too large: {size} bytes including base64 images and JSON overhead exceed the "
165
+ f"{MAX_REQUEST_BYTES // (1024 * 1024)} MiB limit of the decision backend",
166
+ status=413,
167
+ param="images" if req.images else "state",
168
+ )
169
+ return req
170
+
171
+
172
+ # --------------------------------------------------------------------------- #
173
+ # Answer validation (the backend's answer is untrusted data)
174
+ # --------------------------------------------------------------------------- #
175
+ def _unit(v: Any) -> bool:
176
+ return not isinstance(v, bool) and isinstance(v, (int, float)) and math.isfinite(v) and 0.0 <= v <= 1.0
177
+
178
+
179
+ def decision_answers_problem(req: DecisionsRequest, body: Any) -> str | None:
180
+ """Return a description of the first contract violation in an upstream answer body, or ``None``."""
181
+ if not isinstance(body, dict):
182
+ return "response is not a JSON object"
183
+ answers = body.get("answers")
184
+ if not isinstance(answers, dict):
185
+ return "response has no 'answers' object"
186
+ missing = sorted(set(req.questions) - set(answers))
187
+ if missing:
188
+ return f"no answer for question(s) {missing}"
189
+ extra = sorted(set(answers) - set(req.questions))
190
+ if extra:
191
+ return f"answers for unknown question(s) {extra}"
192
+ for name, q in req.questions.items():
193
+ a = answers[name]
194
+ if not isinstance(a, dict):
195
+ return f"answer {name!r} is not an object"
196
+ if a.get("type") != q.type:
197
+ return f"answer {name!r} has type {a.get('type')!r}, question type is {q.type!r}"
198
+ if q.type == "choice":
199
+ probs = a.get("probabilities")
200
+ if not isinstance(probs, dict) or set(probs) != set(q.criteria):
201
+ return f"answer {name!r}: probabilities do not cover exactly the {len(q.criteria)} options"
202
+ if not all(_unit(p) for p in probs.values()):
203
+ return f"answer {name!r}: a probability is not a finite number in [0, 1]"
204
+ choice = a.get("choice")
205
+ if not isinstance(choice, str) or choice not in q.criteria:
206
+ return f"answer {name!r}: choice is not one of the options"
207
+ if any(p > probs[choice] for p in probs.values()):
208
+ return f"answer {name!r}: choice is not the highest-probability option"
209
+ if not _unit(a.get("confidence")):
210
+ return f"answer {name!r}: confidence is not a finite number in [0, 1]"
211
+ elif q.type == "noul":
212
+ if not _unit(a.get("noul")):
213
+ return f"answer {name!r}: noul is not a finite number in [0, 1]"
214
+ else: # score
215
+ n = len(q.criteria)
216
+ score = a.get("score")
217
+ if isinstance(score, bool) or not isinstance(score, (int, float)) or not math.isfinite(score) or not 0 <= score <= n - 1:
218
+ return f"answer {name!r}: score is not a finite number in [0, {n - 1}]"
219
+ probs = a.get("probabilities")
220
+ if not isinstance(probs, dict) or set(probs) != {str(i) for i in range(n)}:
221
+ return f"answer {name!r}: probabilities do not cover exactly the {n} levels"
222
+ if not all(_unit(p) for p in probs.values()):
223
+ return f"answer {name!r}: a probability is not a finite number in [0, 1]"
224
+ if not _unit(a.get("confidence")):
225
+ return f"answer {name!r}: confidence is not a finite number in [0, 1]"
226
+ usage = body.get("usage")
227
+ if usage is not None and not isinstance(usage, dict):
228
+ return "usage is not an object"
229
+ return None