seldon-runtime 0.1.1.dev0__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.
- seldon_runtime/__init__.py +3 -0
- seldon_runtime/attempt_bound.py +35 -0
- seldon_runtime/components.py +316 -0
- seldon_runtime/conditional.py +277 -0
- seldon_runtime/contract_versions.py +15 -0
- seldon_runtime/contracts.py +859 -0
- seldon_runtime/deadline.py +51 -0
- seldon_runtime/executor.py +852 -0
- seldon_runtime/gliner_normalize.py +274 -0
- seldon_runtime/instruction_envelope.py +57 -0
- seldon_runtime/json_pointer.py +26 -0
- seldon_runtime/local.py +173 -0
- seldon_runtime/local_models.py +27 -0
- seldon_runtime/local_telemetry.py +108 -0
- seldon_runtime/native_schema.py +33 -0
- seldon_runtime/output_budget.py +166 -0
- seldon_runtime/program_validation.py +137 -0
- seldon_runtime/provider_error.py +42 -0
- seldon_runtime/research_kernels.py +77 -0
- seldon_runtime/runner.py +544 -0
- seldon_runtime/semantic.py +684 -0
- seldon_runtime/telemetry.py +197 -0
- seldon_runtime/templates.py +109 -0
- seldon_runtime/tool_wire.py +116 -0
- seldon_runtime-0.1.1.dev0.dist-info/METADATA +178 -0
- seldon_runtime-0.1.1.dev0.dist-info/RECORD +30 -0
- seldon_runtime-0.1.1.dev0.dist-info/WHEEL +5 -0
- seldon_runtime-0.1.1.dev0.dist-info/licenses/LICENSE +202 -0
- seldon_runtime-0.1.1.dev0.dist-info/licenses/NOTICE +9 -0
- seldon_runtime-0.1.1.dev0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Best-effort bounded aggregate reports, outside the inference path."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import time
|
|
7
|
+
from uuid import uuid4
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .local_telemetry import (
|
|
11
|
+
LATENCY_BOUNDS_MS,
|
|
12
|
+
LocalStatusReport,
|
|
13
|
+
LocalUsageBatch,
|
|
14
|
+
bounded_reason,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
REPORT_SECONDS = 60
|
|
19
|
+
MAX_PENDING = 32
|
|
20
|
+
MAX_SEND = 4
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Telemetry:
|
|
24
|
+
def __init__(self, runner, enabled):
|
|
25
|
+
self.runner = runner
|
|
26
|
+
self.enabled = enabled
|
|
27
|
+
self.counts = {}
|
|
28
|
+
self.pending = []
|
|
29
|
+
self.dropped = 0
|
|
30
|
+
self.task = None
|
|
31
|
+
self.reporting_id = str(uuid4())
|
|
32
|
+
self.flushing = False
|
|
33
|
+
|
|
34
|
+
def start(self):
|
|
35
|
+
if self.enabled and (self.task is None or self.task.done()):
|
|
36
|
+
self.task = asyncio.create_task(self.loop())
|
|
37
|
+
|
|
38
|
+
def record(self, bundle, elapsed_ms, *, fallback=None, failed=False):
|
|
39
|
+
if not self.enabled:
|
|
40
|
+
return
|
|
41
|
+
self.start()
|
|
42
|
+
revision = bundle["revision_id"]
|
|
43
|
+
if revision not in self.counts:
|
|
44
|
+
if len(self.counts) >= MAX_PENDING:
|
|
45
|
+
self.dropped += 1
|
|
46
|
+
return # bounded best-effort telemetry, never billing authority
|
|
47
|
+
self.counts[revision] = {
|
|
48
|
+
"batch_id": str(uuid4()),
|
|
49
|
+
"revision_id": revision,
|
|
50
|
+
"runtime_version": __version__,
|
|
51
|
+
"model_versions": {k: v["hf_revision"] for k, v in bundle["local_models"].items()},
|
|
52
|
+
"requests": 0,
|
|
53
|
+
"failures": 0,
|
|
54
|
+
"fallbacks": {},
|
|
55
|
+
"latency_histogram": [0] * 6,
|
|
56
|
+
}
|
|
57
|
+
row = self.counts[revision]
|
|
58
|
+
if row["requests"] >= 1_000_000:
|
|
59
|
+
self.dropped += 1
|
|
60
|
+
return
|
|
61
|
+
row["requests"] += 1
|
|
62
|
+
row["failures"] += bool(failed)
|
|
63
|
+
row["latency_histogram"][sum(elapsed_ms > b for b in LATENCY_BOUNDS_MS)] += 1
|
|
64
|
+
if fallback:
|
|
65
|
+
reason = bounded_reason(fallback)
|
|
66
|
+
row["fallbacks"][reason] = row["fallbacks"].get(reason, 0) + 1
|
|
67
|
+
|
|
68
|
+
async def loop(self):
|
|
69
|
+
while True:
|
|
70
|
+
await asyncio.sleep(REPORT_SECONDS)
|
|
71
|
+
await self.flush()
|
|
72
|
+
|
|
73
|
+
async def send(self, path, report):
|
|
74
|
+
runner = self.runner
|
|
75
|
+
headers = {
|
|
76
|
+
"Authorization": f"Bearer {runner._api_key}",
|
|
77
|
+
"Content-Type": "application/json",
|
|
78
|
+
}
|
|
79
|
+
started = time.monotonic()
|
|
80
|
+
context = {"entity_id": runner._function_id, "correlation_id": self.reporting_id}
|
|
81
|
+
logger.info(
|
|
82
|
+
"function_local_report_started",
|
|
83
|
+
extra={
|
|
84
|
+
**context,
|
|
85
|
+
"operation": "function_local_report_started",
|
|
86
|
+
"endpoint": path,
|
|
87
|
+
"method": "POST",
|
|
88
|
+
},
|
|
89
|
+
)
|
|
90
|
+
try:
|
|
91
|
+
status, _, response = await asyncio.wait_for(
|
|
92
|
+
runner._http(
|
|
93
|
+
"POST",
|
|
94
|
+
f"{runner._base_url}/v1/seldon/functions/{runner._function_id}/{path}",
|
|
95
|
+
headers,
|
|
96
|
+
json.dumps(report).encode(),
|
|
97
|
+
),
|
|
98
|
+
timeout=10,
|
|
99
|
+
)
|
|
100
|
+
if status in (200, 201, 202, 204):
|
|
101
|
+
logger.info(
|
|
102
|
+
"function_local_report_completed",
|
|
103
|
+
extra={
|
|
104
|
+
**context,
|
|
105
|
+
"operation": "function_local_report_completed",
|
|
106
|
+
"duration_ms": round((time.monotonic() - started) * 1000),
|
|
107
|
+
"response_bytes": len(response),
|
|
108
|
+
},
|
|
109
|
+
)
|
|
110
|
+
return True
|
|
111
|
+
logger.warning(
|
|
112
|
+
"function_local_report_rejected",
|
|
113
|
+
extra={
|
|
114
|
+
"operation": "function_local_report_rejected",
|
|
115
|
+
"entity_id": runner._function_id,
|
|
116
|
+
"correlation_id": self.reporting_id,
|
|
117
|
+
"status": status,
|
|
118
|
+
},
|
|
119
|
+
)
|
|
120
|
+
return False
|
|
121
|
+
except Exception as exc:
|
|
122
|
+
logger.warning(
|
|
123
|
+
"function_local_report_unavailable",
|
|
124
|
+
extra={
|
|
125
|
+
"operation": "function_local_report_unavailable",
|
|
126
|
+
"entity_id": runner._function_id,
|
|
127
|
+
"correlation_id": self.reporting_id,
|
|
128
|
+
"error_type": type(exc).__name__,
|
|
129
|
+
},
|
|
130
|
+
)
|
|
131
|
+
return False
|
|
132
|
+
|
|
133
|
+
async def flush(self):
|
|
134
|
+
if not self.enabled or self.flushing:
|
|
135
|
+
return
|
|
136
|
+
self.flushing = True
|
|
137
|
+
try:
|
|
138
|
+
for row in self.counts.values():
|
|
139
|
+
if len(self.pending) >= MAX_PENDING:
|
|
140
|
+
self.dropped += row["requests"]
|
|
141
|
+
else:
|
|
142
|
+
self.pending.append([row, 0])
|
|
143
|
+
self.counts.clear()
|
|
144
|
+
# Bound a manual/background flush to five HTTP budgets including status.
|
|
145
|
+
for entry in list(self.pending)[:MAX_SEND]:
|
|
146
|
+
row, attempts = entry
|
|
147
|
+
try:
|
|
148
|
+
body = LocalUsageBatch.model_validate(row).model_dump(mode="json")
|
|
149
|
+
except ValueError:
|
|
150
|
+
self.dropped += row["requests"]
|
|
151
|
+
self.pending.remove(entry)
|
|
152
|
+
continue
|
|
153
|
+
delivered = await self.send("local-usage", body)
|
|
154
|
+
entry[1] = attempts + 1
|
|
155
|
+
if delivered or entry[1] >= 3:
|
|
156
|
+
if not delivered:
|
|
157
|
+
self.dropped += row["requests"]
|
|
158
|
+
self.pending.remove(entry)
|
|
159
|
+
try:
|
|
160
|
+
status = LocalStatusReport.model_validate(self.runner.status()).model_dump(
|
|
161
|
+
mode="json"
|
|
162
|
+
)
|
|
163
|
+
except ValueError:
|
|
164
|
+
return
|
|
165
|
+
await self.send("local-status", status)
|
|
166
|
+
finally:
|
|
167
|
+
self.flushing = False
|
|
168
|
+
if self.dropped:
|
|
169
|
+
logger.warning(
|
|
170
|
+
"function_local_report_dropped",
|
|
171
|
+
extra={
|
|
172
|
+
"operation": "function_local_report_dropped",
|
|
173
|
+
"entity_id": self.runner._function_id,
|
|
174
|
+
"correlation_id": self.reporting_id,
|
|
175
|
+
"count": self.dropped,
|
|
176
|
+
},
|
|
177
|
+
)
|
|
178
|
+
self.dropped = 0
|
|
179
|
+
|
|
180
|
+
async def close(self):
|
|
181
|
+
if self.task:
|
|
182
|
+
try:
|
|
183
|
+
self.task.cancel()
|
|
184
|
+
await self.task
|
|
185
|
+
except (asyncio.CancelledError, RuntimeError):
|
|
186
|
+
pass
|
|
187
|
+
try:
|
|
188
|
+
await asyncio.wait_for(self.flush(), timeout=10)
|
|
189
|
+
except TimeoutError:
|
|
190
|
+
logger.warning(
|
|
191
|
+
"function_local_report_shutdown_timeout",
|
|
192
|
+
extra={
|
|
193
|
+
"operation": "function_local_report_shutdown_timeout",
|
|
194
|
+
"entity_id": self.runner._function_id,
|
|
195
|
+
"correlation_id": self.reporting_id,
|
|
196
|
+
},
|
|
197
|
+
)
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Bounded literal-anchor templates; no regex backtracking or expression evaluation."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from functools import lru_cache
|
|
5
|
+
from string import Formatter
|
|
6
|
+
from typing import NamedTuple
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TemplateError(ValueError):
|
|
10
|
+
def __init__(self, reason, segment=0, *, repeated=False):
|
|
11
|
+
super().__init__(reason)
|
|
12
|
+
self.segment = segment
|
|
13
|
+
self.repeated = repeated
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Template(NamedTuple):
|
|
17
|
+
literals: tuple[str, ...]
|
|
18
|
+
names: tuple[str, ...]
|
|
19
|
+
placeholders: tuple[str, ...]
|
|
20
|
+
|
|
21
|
+
def render(self, values):
|
|
22
|
+
return "".join(
|
|
23
|
+
literal + (values[self.names[index]] if index < len(self.names) else "")
|
|
24
|
+
for index, literal in enumerate(self.literals)
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
def match(self, text):
|
|
28
|
+
literals, names, _ = self
|
|
29
|
+
if not names:
|
|
30
|
+
if text != literals[0]:
|
|
31
|
+
raise TemplateError("template_mismatch")
|
|
32
|
+
return {}
|
|
33
|
+
start, end = len(literals[0]), len(text) - len(literals[-1])
|
|
34
|
+
if not text.startswith(literals[0]) or not text.endswith(literals[-1]) or end < start:
|
|
35
|
+
raise TemplateError("template_mismatch")
|
|
36
|
+
first, pos = [], start
|
|
37
|
+
for index in range(len(names)):
|
|
38
|
+
boundary = end if index == len(names) - 1 else text.find(literals[index + 1], pos, end)
|
|
39
|
+
if boundary < pos:
|
|
40
|
+
raise TemplateError("template_mismatch", index + 1)
|
|
41
|
+
first.append(text[pos:boundary])
|
|
42
|
+
pos = boundary + len(literals[index + 1])
|
|
43
|
+
last, pos = [], end
|
|
44
|
+
for index in range(len(names) - 1, -1, -1):
|
|
45
|
+
boundary = start if index == 0 else text.rfind(literals[index], start, pos)
|
|
46
|
+
if boundary < start:
|
|
47
|
+
raise TemplateError("template_mismatch", index)
|
|
48
|
+
last.append(text[boundary + (len(literals[index]) if index else 0) : pos])
|
|
49
|
+
pos = boundary
|
|
50
|
+
if first != last[::-1]:
|
|
51
|
+
raise TemplateError("ambiguous_template_match")
|
|
52
|
+
values = {}
|
|
53
|
+
for name, value in zip(names, first):
|
|
54
|
+
if name in values and values[name] != value:
|
|
55
|
+
raise TemplateError("template_mismatch", repeated=True)
|
|
56
|
+
values[name] = value
|
|
57
|
+
return values
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@lru_cache(maxsize=1024)
|
|
61
|
+
def parse_template(text: str, syntax: str) -> Template:
|
|
62
|
+
literals, names, placeholders = [], [], []
|
|
63
|
+
pending = ""
|
|
64
|
+
try:
|
|
65
|
+
if syntax == "python_format":
|
|
66
|
+
for token in re.findall(r"\{\{|\}\}|\{[^{}]*\}|[{}]", text):
|
|
67
|
+
if token not in {"{{", "}}"} and not re.fullmatch(
|
|
68
|
+
r"\{[a-zA-Z_][a-zA-Z0-9_]{0,63}\}", token
|
|
69
|
+
):
|
|
70
|
+
raise ValueError
|
|
71
|
+
parts = Formatter().parse(text)
|
|
72
|
+
elif syntax == "jinja_variables":
|
|
73
|
+
parts = []
|
|
74
|
+
end = 0
|
|
75
|
+
for match in re.finditer(r"\{\{\s*([a-zA-Z_][a-zA-Z0-9_]{0,63})\s*\}\}", text):
|
|
76
|
+
parts.append((text[end : match.start()], match[1], "", None, match[0]))
|
|
77
|
+
end = match.end()
|
|
78
|
+
parts.append((text[end:], None, "", None, None))
|
|
79
|
+
else:
|
|
80
|
+
raise ValueError
|
|
81
|
+
for part in parts:
|
|
82
|
+
literal, name, format_spec, conversion = part[:4]
|
|
83
|
+
if syntax == "jinja_variables" and any(
|
|
84
|
+
token in literal for token in ("{{", "}}", "{%", "{#")
|
|
85
|
+
):
|
|
86
|
+
raise ValueError
|
|
87
|
+
pending += literal
|
|
88
|
+
if name is None:
|
|
89
|
+
continue
|
|
90
|
+
if format_spec or conversion or not re.fullmatch(r"[a-zA-Z_][a-zA-Z0-9_]{0,63}", name):
|
|
91
|
+
raise ValueError
|
|
92
|
+
if names and not pending:
|
|
93
|
+
raise TemplateError("adjacent_placeholders")
|
|
94
|
+
literals.append(pending)
|
|
95
|
+
names.append(name)
|
|
96
|
+
placeholders.append("{" + name + "}" if syntax == "python_format" else part[4])
|
|
97
|
+
pending = ""
|
|
98
|
+
literals.append(pending)
|
|
99
|
+
except TemplateError:
|
|
100
|
+
raise
|
|
101
|
+
except (ValueError, TypeError):
|
|
102
|
+
raise TemplateError("template_syntax_unsupported") from None
|
|
103
|
+
return Template(tuple(literals), tuple(names), tuple(placeholders))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@lru_cache(maxsize=256)
|
|
107
|
+
def compile_templates(spec_digest: str, syntax: str, messages: tuple[str, ...]):
|
|
108
|
+
"""The digest makes the cache follow immutable contract identity."""
|
|
109
|
+
return tuple(parse_template(text, syntax) for text in messages)
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""A single forced function tool is an output format, never an executable action."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from jsonschema import Draft202012Validator
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def output_tool(request):
|
|
10
|
+
"""Validate the bounded tool wire contract and return its function definition."""
|
|
11
|
+
tools = request.get("tools")
|
|
12
|
+
if tools is None:
|
|
13
|
+
if request.get("tool_choice") is not None or request.get("parallel_tool_calls") is not None:
|
|
14
|
+
raise ValueError("output_tool_required")
|
|
15
|
+
return None
|
|
16
|
+
if request.get("response_format") is not None:
|
|
17
|
+
raise ValueError("conflicting_output_formats")
|
|
18
|
+
if not isinstance(tools, list) or len(tools) != 1:
|
|
19
|
+
raise ValueError("single_output_tool_required")
|
|
20
|
+
tool = tools[0]
|
|
21
|
+
if (
|
|
22
|
+
not isinstance(tool, dict)
|
|
23
|
+
or set(tool) != {"type", "function"}
|
|
24
|
+
or tool["type"] != "function"
|
|
25
|
+
):
|
|
26
|
+
raise ValueError("invalid_output_tool")
|
|
27
|
+
function = tool["function"]
|
|
28
|
+
if (
|
|
29
|
+
not isinstance(function, dict)
|
|
30
|
+
or set(function) - {"name", "description", "parameters", "strict"}
|
|
31
|
+
or not isinstance(function.get("name"), str)
|
|
32
|
+
or not re.fullmatch(r"[a-zA-Z0-9_-]{1,64}", function["name"])
|
|
33
|
+
or ("description" in function and not isinstance(function["description"], str))
|
|
34
|
+
or ("strict" in function and type(function["strict"]) is not bool)
|
|
35
|
+
or not isinstance(function.get("parameters"), dict)
|
|
36
|
+
or function["parameters"].get("type") != "object"
|
|
37
|
+
):
|
|
38
|
+
raise ValueError("invalid_output_tool")
|
|
39
|
+
choice = request.get("tool_choice")
|
|
40
|
+
named = {"type": "function", "function": {"name": function["name"]}}
|
|
41
|
+
if choice != "required" and choice != named:
|
|
42
|
+
raise ValueError("forced_output_tool_required")
|
|
43
|
+
if "parallel_tool_calls" in request and request["parallel_tool_calls"] is not False:
|
|
44
|
+
raise ValueError("parallel_output_tools_unsupported")
|
|
45
|
+
return function
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def request_schema(request):
|
|
49
|
+
tool = output_tool(request)
|
|
50
|
+
return (
|
|
51
|
+
tool["parameters"]
|
|
52
|
+
if tool
|
|
53
|
+
else (request.get("response_format") or {}).get("json_schema", {}).get("schema")
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def decode_output(raw, request):
|
|
58
|
+
"""Keep legacy content decoding; tool results must match the registered name/schema."""
|
|
59
|
+
from .contracts import canonical
|
|
60
|
+
|
|
61
|
+
tool = output_tool(request)
|
|
62
|
+
choice = raw["choices"][0]
|
|
63
|
+
message = choice["message"]
|
|
64
|
+
if tool is None:
|
|
65
|
+
output = json.loads(message["content"])
|
|
66
|
+
else:
|
|
67
|
+
calls = message.get("tool_calls")
|
|
68
|
+
if (
|
|
69
|
+
len(raw["choices"]) != 1
|
|
70
|
+
or choice.get("finish_reason") != "tool_calls"
|
|
71
|
+
or message.get("content") not in (None, "")
|
|
72
|
+
or not isinstance(calls, list)
|
|
73
|
+
or len(calls) != 1
|
|
74
|
+
or not isinstance(calls[0], dict)
|
|
75
|
+
or calls[0].get("type") != "function"
|
|
76
|
+
or not isinstance(calls[0].get("function"), dict)
|
|
77
|
+
or calls[0]["function"].get("name") != tool["name"]
|
|
78
|
+
or not isinstance(calls[0]["function"].get("arguments"), str)
|
|
79
|
+
):
|
|
80
|
+
raise ValueError("invalid_provider_output")
|
|
81
|
+
output = json.loads(calls[0]["function"]["arguments"])
|
|
82
|
+
if not Draft202012Validator(tool["parameters"]).is_valid(output):
|
|
83
|
+
raise ValueError("invalid_provider_output")
|
|
84
|
+
canonical(output)
|
|
85
|
+
return output
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def completion_choice(request, output, *, call_id):
|
|
89
|
+
"""Wrap validated execution output in the original Function response format."""
|
|
90
|
+
from .contracts import canonical
|
|
91
|
+
|
|
92
|
+
tool = output_tool(request)
|
|
93
|
+
content = canonical(output)
|
|
94
|
+
if tool is None:
|
|
95
|
+
return {
|
|
96
|
+
"index": 0,
|
|
97
|
+
"finish_reason": "stop",
|
|
98
|
+
"message": {"role": "assistant", "content": content},
|
|
99
|
+
}
|
|
100
|
+
if not Draft202012Validator(tool["parameters"]).is_valid(output):
|
|
101
|
+
raise ValueError("output_schema")
|
|
102
|
+
return {
|
|
103
|
+
"index": 0,
|
|
104
|
+
"finish_reason": "tool_calls",
|
|
105
|
+
"message": {
|
|
106
|
+
"role": "assistant",
|
|
107
|
+
"content": None,
|
|
108
|
+
"tool_calls": [
|
|
109
|
+
{
|
|
110
|
+
"id": call_id,
|
|
111
|
+
"type": "function",
|
|
112
|
+
"function": {"name": tool["name"], "arguments": content},
|
|
113
|
+
}
|
|
114
|
+
],
|
|
115
|
+
},
|
|
116
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: seldon-runtime
|
|
3
|
+
Version: 0.1.1.dev0
|
|
4
|
+
Summary: Standalone Seldon Functions interpreter and local execution client
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Source, https://github.com/Deep-Insight-Labs/seldon-runtime
|
|
7
|
+
Project-URL: Issues, https://github.com/Deep-Insight-Labs/seldon-runtime/issues
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
License-File: NOTICE
|
|
12
|
+
Requires-Dist: pydantic>=2.2
|
|
13
|
+
Requires-Dist: jsonschema>=4.21
|
|
14
|
+
Requires-Dist: tiktoken>=0.7
|
|
15
|
+
Provides-Extra: gliner
|
|
16
|
+
Requires-Dist: gliner2[local]~=2.1.0; extra == "gliner"
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
19
|
+
Requires-Dist: ruff==0.16.4; extra == "dev"
|
|
20
|
+
Requires-Dist: build>=1; extra == "dev"
|
|
21
|
+
Requires-Dist: twine>=6; extra == "dev"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# Seldon Runtime
|
|
25
|
+
|
|
26
|
+
`seldon-runtime` is the standalone Python interpreter and local execution client
|
|
27
|
+
for eligible Seldon Functions. The package name is **`seldon-runtime`**, and the
|
|
28
|
+
Python import is `seldon_runtime`. This project is separate from SeldonIO.
|
|
29
|
+
|
|
30
|
+
A single generic runtime executes authorized Function bundles on your hardware.
|
|
31
|
+
Optimization and hosted comparison happen on Seldon. The runtime contains no
|
|
32
|
+
optimizer, billing service, dashboard or server infrastructure. Its first local
|
|
33
|
+
model adapter uses pinned GLiNER2 open weights for extraction and classification.
|
|
34
|
+
|
|
35
|
+
This is a source preview. A source checkout or successful build does not establish
|
|
36
|
+
PyPI publication, production feature activation, or quality on your own inputs.
|
|
37
|
+
|
|
38
|
+
## Install
|
|
39
|
+
|
|
40
|
+
Python 3.11 or later is required. The base interpreter uses Pydantic, jsonschema
|
|
41
|
+
and tiktoken. Local GLiNER inference additionally needs PyTorch and the model extra.
|
|
42
|
+
Before publication, replace the package name below with a locally built wheel.
|
|
43
|
+
|
|
44
|
+
On Linux, install CPU PyTorch explicitly to avoid downloading CUDA dependencies:
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
python -m pip install torch --index-url https://download.pytorch.org/whl/cpu
|
|
48
|
+
python -m pip install 'seldon-runtime[gliner]'
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
On macOS:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
python -m pip install torch
|
|
55
|
+
python -m pip install 'seldon-runtime[gliner]'
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
In a uv environment, use `uv pip install` for the same commands. In a Linux uv
|
|
59
|
+
project, persist the dedicated torch index:
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
uv add torch --index pytorch=https://download.pytorch.org/whl/cpu
|
|
63
|
+
uv add 'seldon-runtime[gliner]'
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The model weights and tokenizer files download on first use. Cache the pinned
|
|
67
|
+
snapshot in advance for restricted networks. Token-chunked plans also need the
|
|
68
|
+
tiktoken BPE cache (`TIKTOKEN_CACHE_DIR`). Model weights are not bundled in the wheel.
|
|
69
|
+
|
|
70
|
+
## Run a Function locally
|
|
71
|
+
|
|
72
|
+
Only activated, locally eligible v3/v4 revisions can be loaded. Hosted-only models,
|
|
73
|
+
reference-bound Functions and v5 plans are ineligible. Authorization uses your
|
|
74
|
+
workspace API key; it does not grant management access.
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
import asyncio
|
|
78
|
+
import os
|
|
79
|
+
|
|
80
|
+
from seldon_runtime.runner import Runner
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
async def main():
|
|
84
|
+
runner = await Runner.load(
|
|
85
|
+
"FUNCTION_UUID",
|
|
86
|
+
os.environ["SELDON_API_KEY"],
|
|
87
|
+
fallback="raise",
|
|
88
|
+
telemetry=False,
|
|
89
|
+
)
|
|
90
|
+
try:
|
|
91
|
+
result = await runner({"document": "Ada works at Acme"})
|
|
92
|
+
print(result["output"])
|
|
93
|
+
print(runner.status())
|
|
94
|
+
finally:
|
|
95
|
+
await runner.aclose()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
asyncio.run(main())
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Use the input names from your Function contract. Each result also reports
|
|
102
|
+
`fallback_used` and `fallback_reason`. `LocalExecutionError.reason` is a bounded
|
|
103
|
+
machine-readable code; errors do not expose credentials or internal paths.
|
|
104
|
+
|
|
105
|
+
`fallback="raise"` prevents hosted inference fallback. `fallback="seldon"` sends
|
|
106
|
+
failed calls to Seldon and incurs ordinary hosted usage charges. An explicit
|
|
107
|
+
`{"endpoint": "...", "api_key": "..."}` uses your own OpenAI-compatible endpoint.
|
|
108
|
+
A failed initial verification raises before installing the bundle.
|
|
109
|
+
|
|
110
|
+
The [Seldon Python SDK](https://github.com/Deep-Insight-Labs/seldon-python) provides
|
|
111
|
+
optional typed declarations and `seldon function pull`, `verify` and `run` commands
|
|
112
|
+
using this runtime. It is not required for direct `Runner` use.
|
|
113
|
+
|
|
114
|
+
## Verification and refresh
|
|
115
|
+
|
|
116
|
+
`Runner.load()` checks at least 95% exact agreement against the revision's held-out
|
|
117
|
+
conformance set before installing a new revision/model/runtime combination.
|
|
118
|
+
`await runner.verify()` reruns up to 200 local inputs and reports agreement,
|
|
119
|
+
sample count and p50/p95 latency. This measures agreement on that set, not business
|
|
120
|
+
correctness or coverage of all inputs. `allow_unverified=True` explicitly skips
|
|
121
|
+
verification and is not parity evidence.
|
|
122
|
+
|
|
123
|
+
Bundles are cached without API keys, revalidated at load and every 15 minutes on
|
|
124
|
+
a long-lived event loop. A failed refresh keeps the last validated revision for
|
|
125
|
+
at most 24 hours from its last successful check; expiry applies your fallback
|
|
126
|
+
policy. A disabled, deleted or unauthorized Function stops serving when observed.
|
|
127
|
+
Short-lived loops may not finish background refresh, so the 24-hour expiry is the
|
|
128
|
+
upper bound. Local execution still needs these control-plane calls.
|
|
129
|
+
|
|
130
|
+
`runner.status()` reads current local state without network or inference. Optional
|
|
131
|
+
reporting sends bounded counts, latency histograms and status outside inference;
|
|
132
|
+
it never sends inputs, outputs or payload hashes. `telemetry=False` disables both
|
|
133
|
+
usage and status reporting. Reports are best effort and are not billing authority.
|
|
134
|
+
Always close the runner to stop background tasks and attempt a bounded flush.
|
|
135
|
+
|
|
136
|
+
## Development
|
|
137
|
+
|
|
138
|
+
```sh
|
|
139
|
+
python -m pip install -e '.[dev]'
|
|
140
|
+
python -m ruff check .
|
|
141
|
+
python -m ruff format --check .
|
|
142
|
+
python -m pytest -q
|
|
143
|
+
python -m build
|
|
144
|
+
python -m twine check dist/*
|
|
145
|
+
python scripts/verify_artifacts.py dist/*
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Default tests replace model weights and HTTP at explicit runtime seams. They
|
|
149
|
+
exercise execution, output normalization, authorization refusals, conformance,
|
|
150
|
+
refresh, cache handling, fallback and reporting. Synthetic frozen plan/spec
|
|
151
|
+
fixtures check serialization and digest stability. No private repository or
|
|
152
|
+
server package is required. Run `pytest -m local_model` only after installing the
|
|
153
|
+
GLiNER extra; it downloads or reuses the pinned model weights.
|
|
154
|
+
|
|
155
|
+
`tests/installed_local_probe.py` verifies a real installed GLiNER runtime in a
|
|
156
|
+
server-free environment. Base-wheel installation alone does not qualify native
|
|
157
|
+
model dependencies or performance. Existing model probes cover macOS ARM64 and
|
|
158
|
+
Linux ARM64 CPU; other hardware and Windows are not claimed as qualified.
|
|
159
|
+
|
|
160
|
+
## Releases
|
|
161
|
+
|
|
162
|
+
The publishing workflow is `.github/workflows/runtime-publish.yml` in
|
|
163
|
+
`Deep-Insight-Labs/seldon-runtime`. Register project `seldon-runtime` as a trusted
|
|
164
|
+
publisher on TestPyPI with environment `testpypi`, and on PyPI with environment
|
|
165
|
+
`pypi`. A `runtime-v<version>` tag must match `pyproject.toml` and `__version__`.
|
|
166
|
+
|
|
167
|
+
Publication is disabled unless `SELDON_RUNTIME_TESTPYPI_PUBLISH_ENABLED` and
|
|
168
|
+
`SELDON_RUNTIME_PUBLISH_ENABLED` are enabled separately. The workflow checks the
|
|
169
|
+
standalone project, builds wheel and sdist, publishes to TestPyPI, downloads and
|
|
170
|
+
installs that exact wheel with normal dependencies from PyPI, then publishes the
|
|
171
|
+
original checked artifacts to PyPI. A manual branch dispatch only builds artifacts.
|
|
172
|
+
No stored registry token is required. Registry versions are immutable.
|
|
173
|
+
|
|
174
|
+
## License
|
|
175
|
+
|
|
176
|
+
Apache-2.0; see [LICENSE](LICENSE) and [NOTICE](NOTICE). Optional GLiNER2 code and
|
|
177
|
+
downloaded weights retain their own upstream licenses. The release is scoped to
|
|
178
|
+
this repository; it does not license the separately operated Seldon service.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
seldon_runtime/__init__.py,sha256=_2FjrY_GAv9Vz09Kg604JEmCtUxK2yijkL61JxaBJHk,102
|
|
2
|
+
seldon_runtime/attempt_bound.py,sha256=uXGBUBg09Uie75EfSTs_QfSn52tntoJDb8YQ6V_w9GY,1258
|
|
3
|
+
seldon_runtime/components.py,sha256=y9l9MuYXNT3yuEWWlDDBec7Vb88Z0_5cKEZTuqyOpQE,12215
|
|
4
|
+
seldon_runtime/conditional.py,sha256=x0Yg0l8T_KlhKvKLVYutbpNGow2vqZRnN9qfcu5jORQ,10867
|
|
5
|
+
seldon_runtime/contract_versions.py,sha256=nzZ2LwZht0v_kyiBIwkj6b58L8MWY3uISvxGxyC_9FM,980
|
|
6
|
+
seldon_runtime/contracts.py,sha256=ZF3qPLTPlM-_fDjkZ8FFmVuny85jDFU8_8w5Br1ZB00,34729
|
|
7
|
+
seldon_runtime/deadline.py,sha256=L8xBebhoLM2vlI0C5EhLbELflCaag_AgBD-AptKJDws,1879
|
|
8
|
+
seldon_runtime/executor.py,sha256=3PcVNXp-nOo1QkLLnJOst4rDbHYreXMbf3-Ds7q8rzU,34896
|
|
9
|
+
seldon_runtime/gliner_normalize.py,sha256=V-29aGos27Ay6Eczz3AJ9yroEaZ7BSNw-v20ZqKsjs8,11384
|
|
10
|
+
seldon_runtime/instruction_envelope.py,sha256=S-riu21kqicDyPnZgKPlpWH_J7IpNo_AGRJ4Jnn1zq4,2719
|
|
11
|
+
seldon_runtime/json_pointer.py,sha256=r__ji3JyTNDn-bGfc9oVIoA1FAq2UBvbQ-05UBi6_8g,849
|
|
12
|
+
seldon_runtime/local.py,sha256=I9sKUsSZsTjEn4fDrjCzfzscPjb0xXBijhWXjIR6hbM,6873
|
|
13
|
+
seldon_runtime/local_models.py,sha256=ubqPSabFaXr7E9_1TmMRjl09M20SHqCZmxNqbr_Fo_0,1210
|
|
14
|
+
seldon_runtime/local_telemetry.py,sha256=fd2u7d7Fr6OOPS50CkmS5tSAXT0DfWrGE-X-Izwa0mw,3405
|
|
15
|
+
seldon_runtime/native_schema.py,sha256=M2V3FdlGRxeBJ6RjGTb8iLcqmmMhclK6Auh1nh8ic1M,1515
|
|
16
|
+
seldon_runtime/output_budget.py,sha256=kmP9mZlawRT7sQUrgdnTOPGjcNoTNjb9fmYlVlhwx-s,7442
|
|
17
|
+
seldon_runtime/program_validation.py,sha256=s9gF1foKC8j6TVxMfVGdw-u5m4qlPKZ20PS1PDscKVc,6044
|
|
18
|
+
seldon_runtime/provider_error.py,sha256=IM9H1rDFN-obkDlzDr0f-CXbf5RsYu5jXsj3chTNX3Y,1689
|
|
19
|
+
seldon_runtime/research_kernels.py,sha256=cMOSYJQD67ngbhcCvkq6pNxrHrgAluBgcMxICo9n-Xw,2162
|
|
20
|
+
seldon_runtime/runner.py,sha256=AAcZoFr4caUT6BEtjCelc58zvul2wT2hZOAigE2_g9k,20911
|
|
21
|
+
seldon_runtime/semantic.py,sha256=F7_ZYEL2t1_2RxfyMIj-Ged6jl8nC3Xb39SWfaMmTbg,27277
|
|
22
|
+
seldon_runtime/telemetry.py,sha256=2ik9i1vTnTx5U42tPMhsmDC_EcernSov_dxgzAF04uE,6984
|
|
23
|
+
seldon_runtime/templates.py,sha256=zp48gE-ZEsvd3aU-bH8W7d8-MtS35AqzmSQtpuz7W-4,4379
|
|
24
|
+
seldon_runtime/tool_wire.py,sha256=s2x3TgbjP26hwe_twAS-ArlbLhEXUQUpohK4VoeXgwE,4279
|
|
25
|
+
seldon_runtime-0.1.1.dev0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
26
|
+
seldon_runtime-0.1.1.dev0.dist-info/licenses/NOTICE,sha256=d6FAH8kHaW9m59M6DJFVNLp1y1CkiSmZs3FiYzoWtMk,428
|
|
27
|
+
seldon_runtime-0.1.1.dev0.dist-info/METADATA,sha256=2JRIAKwcuOOH2oHPbN7rZ2el6OwFaRyWzyULHUMNpGY,7471
|
|
28
|
+
seldon_runtime-0.1.1.dev0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
29
|
+
seldon_runtime-0.1.1.dev0.dist-info/top_level.txt,sha256=OIOoWE_VYJXj3yVmPF3EeSqNJ5DNWZbmSEWB5JMLcTU,15
|
|
30
|
+
seldon_runtime-0.1.1.dev0.dist-info/RECORD,,
|