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,290 @@
1
+ """Derive structural requirements and a cheap deterministic task classification.
2
+
3
+ Nothing here reads model outputs or follows instructions found in prompts; the
4
+ analysis is purely structural/lexical and its result is data for the router.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+ from ..config import TokenEstimateConfig
14
+ from .tokens import TokenBudget, _text_of, estimate_chat_tokens
15
+
16
+ TASKS = (
17
+ "conversation",
18
+ "coding",
19
+ "agent",
20
+ "math",
21
+ "extraction",
22
+ "document_vision",
23
+ "translation",
24
+ "summarization",
25
+ "rag",
26
+ "decision",
27
+ )
28
+
29
+
30
+ @dataclass
31
+ class Requirements:
32
+ role: str = "generative"
33
+ needs_tools: bool = False
34
+ tool_choice_mode: str = "none" # none | auto | required | named
35
+ needs_parallel_tools: bool = False
36
+ needs_json_schema: bool = False
37
+ needs_json_object: bool = False
38
+ needs_streaming: bool = False
39
+ needs_vision: bool = False
40
+ needs_audio: bool = False
41
+ needs_video: bool = False
42
+ has_remote_image_url: bool = False
43
+ needs_continuation: bool = False # reasoning_content present in history
44
+ outstanding_tool_call_ids: list[str] = field(default_factory=list)
45
+ is_tool_result_turn: bool = False
46
+ tokens: TokenBudget | None = None
47
+ tasks: dict[str, float] = field(default_factory=dict) # label -> confidence 0..1
48
+ primary_task: str = "conversation"
49
+ ambiguous: bool = False
50
+ multilingual: bool = False
51
+ languages: list[str] = field(default_factory=list)
52
+ signals: list[str] = field(default_factory=list)
53
+ unsupported_fields_used: list[str] = field(default_factory=list)
54
+
55
+ def as_dict(self) -> dict[str, Any]:
56
+ d = {
57
+ "role": self.role,
58
+ "needs_tools": self.needs_tools,
59
+ "tool_choice_mode": self.tool_choice_mode,
60
+ "needs_parallel_tools": self.needs_parallel_tools,
61
+ "needs_json_schema": self.needs_json_schema,
62
+ "needs_json_object": self.needs_json_object,
63
+ "needs_streaming": self.needs_streaming,
64
+ "needs_vision": self.needs_vision,
65
+ "needs_audio": self.needs_audio,
66
+ "needs_video": self.needs_video,
67
+ "has_remote_image_url": self.has_remote_image_url,
68
+ "needs_continuation": self.needs_continuation,
69
+ "outstanding_tool_call_ids": self.outstanding_tool_call_ids,
70
+ "is_tool_result_turn": self.is_tool_result_turn,
71
+ "tasks": self.tasks,
72
+ "primary_task": self.primary_task,
73
+ "ambiguous": self.ambiguous,
74
+ "multilingual": self.multilingual,
75
+ "languages": self.languages,
76
+ "signals": self.signals,
77
+ }
78
+ if self.tokens:
79
+ d["tokens"] = {
80
+ "input_estimate": self.tokens.input_estimate,
81
+ "output_allowance": self.tokens.output_allowance,
82
+ "reasoning_allowance": self.tokens.reasoning_allowance,
83
+ "images": self.tokens.images,
84
+ "method": self.tokens.method,
85
+ "total": self.tokens.total,
86
+ }
87
+ return d
88
+
89
+
90
+ # --------------------------------------------------------------------------- #
91
+ # Lexical signals (deterministic). Short lists on purpose: clear cases only.
92
+ # --------------------------------------------------------------------------- #
93
+ _CODE_FENCE = re.compile(r"```")
94
+ _CODE_WORDS = re.compile(
95
+ r"\b(def |class |import |#include|function\s*\(|=>|console\.log|print\(|SELECT .* FROM|"
96
+ r"traceback|stack ?trace|exception|compile|refactor|unit test|pytest|npm|pip install|git |"
97
+ r"regex|typescript|python|javascript|rust|golang|\bjava\b|c\+\+|bash script|shell script|sql|undefined is not|"
98
+ r"null pointer|segfault|syntax error|TypeError|ValueError|NameError|npm ERR|ModuleNotFound)\b",
99
+ re.IGNORECASE,
100
+ )
101
+ _AGENT_TOOLS = re.compile(
102
+ r"\b(bash|shell|execute_command|run_command|read_file|write_file|edit_file|list_dir|grep|glob|search_files|"
103
+ r"apply_patch|str_replace|terminal|repo|repository)\b",
104
+ re.IGNORECASE,
105
+ )
106
+ _AGENT_SYS = re.compile(r"\b(coding agent|software engineer|repository|codebase|workspace|terminal)\b", re.IGNORECASE)
107
+ _MATH = re.compile(
108
+ r"(\\frac|\\int|\\sum|\^\d|\b\d+\s*[\+\-\*/×÷]\s*\d+\b|\bsolve\b|\bequation|\bintegral|\bderivative|\btheorem|"
109
+ r"\bprove\b|\bprobability\b|\bcalculate\b|\bcompute\b|\bsum of\b|\bproduct of\b|\bprime\b|\barea\b|"
110
+ r"\bperimeter\b|\bpercent|\baverage\b|\bhow many\b|\bsolve for\b|\d+\s*[×÷])",
111
+ re.IGNORECASE,
112
+ )
113
+ _TRANSLATE = re.compile(r"\b(translate|translation|traduis|traducir|übersetze|翻译|翻訳)\b", re.IGNORECASE)
114
+ _SUMMARIZE = re.compile(r"\b(summari[sz]e|summary|tl;dr|tldr|condense|key points|abstract)\b", re.IGNORECASE)
115
+ _EXTRACT = re.compile(r"\b(extract|parse|structured|json|fields?|schema|csv|table of)\b", re.IGNORECASE)
116
+ _RAG = re.compile(r"(\bcontext:|\bdocument:|<context>|<document>|according to the (provided|following)|based on the (text|passage|document))", re.IGNORECASE)
117
+ _DECISION = re.compile(r"\b(classify|categori[sz]e|which of the following|yes or no|choose (one|between)|label)\b", re.IGNORECASE)
118
+ def _is_inline_data_url(url: str) -> bool:
119
+ """Only base64 data: URLs are inline media; every other reference (http, HTTP, //, file, ftp, ...)
120
+ is external and must not be fetched by the gateway or the backend on our behalf."""
121
+ u = url.strip()
122
+ return u[:5].lower() == "data:" and ";base64," in u[:120]
123
+
124
+
125
+ _GREETING = re.compile(r"\b(hi|hello|hey|thanks|thank you|good (morning|evening|afternoon)|bye|ok|okay|yes|no|sure)\b", re.IGNORECASE)
126
+ _NON_LATIN = re.compile(r"[Ѐ-ӿ֐-׿؀-ۿऀ-ॿ஀-௿぀-ヿ一-鿿가-힯]")
127
+ _LATIN_HINTS = {
128
+ "fr": re.compile(r"\b(le|la|les|des|est|avec|pour|vous|nous)\b", re.IGNORECASE),
129
+ "es": re.compile(r"\b(el|los|las|está|para|usted|nosotros|gracias)\b", re.IGNORECASE),
130
+ "de": re.compile(r"\b(der|die|das|und|nicht|ist|mit|für|Sie)\b"),
131
+ }
132
+
133
+
134
+ def _detect_languages(text: str) -> list[str]:
135
+ langs: list[str] = []
136
+ if _NON_LATIN.search(text):
137
+ if re.search(r"[一-鿿]", text):
138
+ langs.append("zh/ja")
139
+ if re.search(r"[぀-ヿ]", text):
140
+ langs.append("ja")
141
+ if re.search(r"[가-힯]", text):
142
+ langs.append("ko")
143
+ if re.search(r"[Ѐ-ӿ]", text):
144
+ langs.append("ru")
145
+ if re.search(r"[؀-ۿ]", text):
146
+ langs.append("ar")
147
+ if re.search(r"[ऀ-ॿ]", text):
148
+ langs.append("hi")
149
+ if re.search(r"[஀-௿]", text):
150
+ langs.append("ta")
151
+ if re.search(r"[֐-׿]", text):
152
+ langs.append("he")
153
+ for code, rx in _LATIN_HINTS.items():
154
+ if len(rx.findall(text)) >= 4:
155
+ langs.append(code)
156
+ if re.search(r"\b(the|and|is|are|you|please|what|how)\b", text, re.IGNORECASE):
157
+ langs.append("en")
158
+ return list(dict.fromkeys(langs))
159
+
160
+
161
+ def analyze_chat(body: dict[str, Any], cfg: TokenEstimateConfig, thinking_possible: bool = True) -> Requirements:
162
+ req = Requirements()
163
+ msgs = body.get("messages") or []
164
+ tools = body.get("tools") or []
165
+ req.needs_streaming = bool(body.get("stream"))
166
+ req.needs_tools = bool(tools)
167
+ tc = body.get("tool_choice")
168
+ if tools:
169
+ if tc is None or tc == "auto":
170
+ req.tool_choice_mode = "auto"
171
+ elif tc == "none":
172
+ req.tool_choice_mode = "none"
173
+ elif tc == "required":
174
+ req.tool_choice_mode = "required"
175
+ elif isinstance(tc, dict):
176
+ req.tool_choice_mode = "named"
177
+ if body.get("parallel_tool_calls") is True:
178
+ req.needs_parallel_tools = True
179
+ rf = body.get("response_format")
180
+ if isinstance(rf, dict):
181
+ if rf.get("type") == "json_schema":
182
+ req.needs_json_schema = True
183
+ elif rf.get("type") == "json_object":
184
+ req.needs_json_object = True
185
+
186
+ # Walk the history: modalities, tool continuity, continuation data.
187
+ user_text_parts: list[str] = []
188
+ system_text = ""
189
+ last_user_text = ""
190
+ for m in msgs:
191
+ if not isinstance(m, dict):
192
+ continue
193
+ role = m.get("role")
194
+ content = m.get("content")
195
+ text, _ = _text_of(content)
196
+ if isinstance(content, list):
197
+ for p in content:
198
+ if not isinstance(p, dict):
199
+ continue
200
+ t = p.get("type")
201
+ if t in ("image_url", "input_image", "image"):
202
+ req.needs_vision = True
203
+ url = ""
204
+ iu = p.get("image_url")
205
+ if isinstance(iu, dict):
206
+ url = str(iu.get("url", ""))
207
+ elif isinstance(iu, str):
208
+ url = iu
209
+ if not _is_inline_data_url(url):
210
+ req.has_remote_image_url = True
211
+ elif t in ("input_audio", "audio"):
212
+ req.needs_audio = True
213
+ elif t == "video_url":
214
+ req.needs_video = True
215
+ if role in ("system", "developer"):
216
+ system_text += text + "\n"
217
+ elif role == "user":
218
+ user_text_parts.append(text)
219
+ last_user_text = text
220
+ if role == "assistant":
221
+ if m.get("reasoning_content"):
222
+ req.needs_continuation = True
223
+ last = msgs[-1] if msgs and isinstance(msgs[-1], dict) else {}
224
+ req.is_tool_result_turn = last.get("role") == "tool"
225
+ # The current round trip = tool messages at the tail answering the tool_calls of the assistant
226
+ # message immediately before them. Older, already-answered calls do not pin anything.
227
+ tail_ids: list[str] = []
228
+ i = len(msgs) - 1
229
+ while i >= 0 and isinstance(msgs[i], dict) and msgs[i].get("role") == "tool":
230
+ if msgs[i].get("tool_call_id"):
231
+ tail_ids.append(str(msgs[i]["tool_call_id"]))
232
+ i -= 1
233
+ issued: list[str] = []
234
+ if i >= 0 and isinstance(msgs[i], dict) and msgs[i].get("role") == "assistant":
235
+ issued = [str(c["id"]) for c in msgs[i].get("tool_calls") or [] if isinstance(c, dict) and c.get("id")]
236
+ req.outstanding_tool_call_ids = [cid for cid in issued if cid in set(tail_ids)] if req.is_tool_result_turn else []
237
+
238
+ # Task classification uses the *original* user intent, not just the last tool result.
239
+ full_user = "\n".join(user_text_parts)
240
+ scores: dict[str, float] = {t: 0.0 for t in TASKS}
241
+ sig = req.signals
242
+
243
+ def add(task: str, w: float, why: str) -> None:
244
+ scores[task] = min(1.0, scores[task] + w)
245
+ sig.append(f"{task}:{why}")
246
+
247
+ if req.needs_tools:
248
+ tool_names = " ".join(str((t.get("function") or {}).get("name", "")) for t in tools if isinstance(t, dict))
249
+ if _AGENT_TOOLS.search(tool_names) or _AGENT_SYS.search(system_text):
250
+ add("agent", 0.8, "agent-style tools/system prompt")
251
+ add("coding", 0.5, "agent tools imply code work")
252
+ else:
253
+ add("agent", 0.4, "tools present")
254
+ if _CODE_FENCE.search(full_user) or len(_CODE_WORDS.findall(full_user)) >= 2:
255
+ add("coding", 0.7, "code fences or >=2 code keywords")
256
+ elif _CODE_WORDS.search(full_user):
257
+ add("coding", 0.35, "one code keyword")
258
+ if _MATH.search(last_user_text or full_user):
259
+ add("math", 0.5, "math symbols/keywords")
260
+ if req.needs_json_schema or req.needs_json_object:
261
+ add("extraction", 0.8, "structured output requested")
262
+ elif _EXTRACT.search(last_user_text):
263
+ add("extraction", 0.35, "extraction keywords")
264
+ if req.needs_vision:
265
+ add("document_vision", 0.9, "image input present")
266
+ if _TRANSLATE.search(last_user_text):
267
+ add("translation", 0.7, "translate keyword")
268
+ if _SUMMARIZE.search(last_user_text):
269
+ add("summarization", 0.6, "summarize keyword")
270
+ if _RAG.search(full_user) or _RAG.search(system_text):
271
+ add("rag", 0.6, "context/document framing")
272
+ if _DECISION.search(last_user_text):
273
+ add("decision", 0.4, "classification phrasing")
274
+ langs = _detect_languages(full_user)
275
+ req.languages = langs
276
+ req.multilingual = len([lang for lang in langs if lang != "en"]) >= 1
277
+ if req.multilingual:
278
+ sig.append("multilingual:" + ",".join(langs))
279
+ if max(scores.values()) == 0.0:
280
+ words = last_user_text.split()
281
+ vague = len(words) <= 3 and not _GREETING.search(last_user_text) and not req.needs_tools
282
+ scores["conversation"] = 0.4 if vague else 0.6
283
+ sig.append("conversation:default (no structural signals" + ("; very short/vague" if vague else "") + ")")
284
+ req.tasks = {k: round(v, 2) for k, v in scores.items() if v > 0}
285
+ req.primary_task = max(req.tasks.items(), key=lambda kv: kv[1])[0]
286
+ top = sorted(req.tasks.values(), reverse=True)
287
+ # Ambiguous when the best label is weak or two labels compete.
288
+ req.ambiguous = top[0] < 0.5 or (len(top) > 1 and top[0] - top[1] < 0.2 and top[0] < 0.8)
289
+ req.tokens = estimate_chat_tokens(body, cfg, thinking_possible)
290
+ return req