@techis/ai-runtime 0.4.1 → 0.6.0

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 (58) hide show
  1. package/API.md +2 -2
  2. package/NATIVE-IMAGES.md +52 -0
  3. package/PYTHON.md +46 -0
  4. package/README.md +9 -4
  5. package/dist/adapters/image.d.ts +5 -0
  6. package/dist/adapters/image.d.ts.map +1 -0
  7. package/dist/adapters/image.js +105 -0
  8. package/dist/adapters/image.js.map +1 -0
  9. package/dist/adapters/registry.d.ts.map +1 -1
  10. package/dist/adapters/registry.js +8 -2
  11. package/dist/adapters/registry.js.map +1 -1
  12. package/dist/adapters/types.d.ts +6 -0
  13. package/dist/adapters/types.d.ts.map +1 -1
  14. package/dist/adapters/validation.d.ts.map +1 -1
  15. package/dist/adapters/validation.js +11 -2
  16. package/dist/adapters/validation.js.map +1 -1
  17. package/dist/bridge-worker.d.ts +3 -0
  18. package/dist/bridge-worker.d.ts.map +1 -0
  19. package/dist/bridge-worker.js +48 -0
  20. package/dist/bridge-worker.js.map +1 -0
  21. package/dist/bridge.d.ts +33 -0
  22. package/dist/bridge.d.ts.map +1 -0
  23. package/dist/bridge.js +46 -0
  24. package/dist/bridge.js.map +1 -0
  25. package/dist/bundle-source.d.ts +1 -2
  26. package/dist/bundle-source.d.ts.map +1 -1
  27. package/dist/bundle-source.js +1 -1
  28. package/dist/bundle-source.js.map +1 -1
  29. package/dist/compatibility-execution.d.ts +1 -0
  30. package/dist/compatibility-execution.d.ts.map +1 -1
  31. package/dist/image-generation.d.ts +25 -0
  32. package/dist/image-generation.d.ts.map +1 -0
  33. package/dist/image-generation.js +59 -0
  34. package/dist/image-generation.js.map +1 -0
  35. package/dist/index.d.ts +3 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +3 -0
  38. package/dist/index.js.map +1 -1
  39. package/dist/route-client.d.ts +3 -0
  40. package/dist/route-client.d.ts.map +1 -1
  41. package/dist/route-client.js +4 -1
  42. package/dist/route-client.js.map +1 -1
  43. package/dist/route-readiness.d.ts.map +1 -1
  44. package/dist/route-readiness.js +23 -6
  45. package/dist/route-readiness.js.map +1 -1
  46. package/dist/run.d.ts.map +1 -1
  47. package/dist/run.js +96 -25
  48. package/dist/run.js.map +1 -1
  49. package/dist/scoped-source.d.ts +1 -1
  50. package/dist/scoped-source.js +2 -2
  51. package/dist/scoped-source.js.map +1 -1
  52. package/dist/types.d.ts +1 -1
  53. package/dist/types.d.ts.map +1 -1
  54. package/dist/version.d.ts +1 -1
  55. package/dist/version.js +1 -1
  56. package/package.json +10 -4
  57. package/python/model_routes/__init__.py +141 -0
  58. package/python/pyproject.toml +12 -0
@@ -0,0 +1,141 @@
1
+ """Thin client for the packaged Model Routes Runtime. This module never calls a provider or retries a call."""
2
+ import json
3
+ import os
4
+ import subprocess
5
+ import threading
6
+ import time
7
+ from pathlib import Path
8
+
9
+ PROTOCOL_VERSION = 1
10
+
11
+
12
+ class RuntimeCallError(Exception):
13
+ def __init__(self, reply):
14
+ self.reply = reply
15
+ self.code = reply["error"]["code"]
16
+ self.receipt = reply.get("receipt")
17
+ self.dispatch = reply["dispatch"]
18
+ super().__init__(reply["error"]["message"])
19
+
20
+
21
+ def _transport_error(code, message):
22
+ # A missing terminal reply cannot prove whether a provider accepted the request. Never retry automatically.
23
+ return RuntimeCallError({"version": 1, "status": "failed", "dispatch": "unknown", "receipt": None,
24
+ "error": {"code": code, "message": message}})
25
+
26
+
27
+ def _valid_reply(reply, returncode):
28
+ if (not isinstance(reply, dict) or reply.get("version") != 1 or "receipt" not in reply
29
+ or reply.get("status") not in ("succeeded", "unassigned", "failed")
30
+ or reply.get("dispatch") not in ("started", "not-started", "unknown")
31
+ or returncode != (1 if reply["status"] == "failed" else 0)):
32
+ return False
33
+ receipt = reply["receipt"]
34
+ if receipt is not None:
35
+ if (not isinstance(receipt, dict) or not isinstance(receipt.get("receiptId"), str)
36
+ or not isinstance(receipt.get("attempts"), list)
37
+ or any(not isinstance(attempt, dict) or not isinstance(attempt.get("providerRequestStarted"), bool)
38
+ for attempt in receipt["attempts"])):
39
+ return False
40
+ dispatch = "started" if any(attempt["providerRequestStarted"] for attempt in receipt["attempts"]) else "not-started"
41
+ if reply["dispatch"] != dispatch:
42
+ return False
43
+ elif reply["dispatch"] == "started":
44
+ return False
45
+ if reply["status"] == "unassigned":
46
+ return receipt is None and reply["dispatch"] == "not-started" and "error" not in reply and "result" not in reply
47
+ if reply["status"] == "succeeded":
48
+ return receipt is not None and "result" in reply and "error" not in reply
49
+ error = reply.get("error")
50
+ return (isinstance(error, dict) and isinstance(error.get("code"), str) and bool(error["code"])
51
+ and isinstance(error.get("message"), str) and "result" not in reply)
52
+
53
+
54
+ class RuntimeClient:
55
+ def __init__(self, host_module, *, worker, node="node", context=None, env=None, transport_timeout=None):
56
+ self.host_module = str(Path(host_module).resolve())
57
+ self.worker = str(Path(worker).resolve())
58
+ self.node = str(node)
59
+ self.context = context or {}
60
+ self.env = dict(os.environ if env is None else env)
61
+ self.env["ELECTRON_RUN_AS_NODE"] = "1"
62
+ self.transport_timeout = transport_timeout
63
+
64
+ def call(self, operation_id, request, *, method="generate", timeout_ms=None, cancel_event=None):
65
+ payload = {"version": 1, "operationId": operation_id, "method": method, "request": request,
66
+ "hostModule": self.host_module, "context": self.context,
67
+ "cancelled": bool(cancel_event and cancel_event.is_set())}
68
+ if timeout_ms is not None:
69
+ payload["timeoutMs"] = timeout_ms
70
+ encoded = json.dumps(payload, ensure_ascii=False) + "\n"
71
+ try:
72
+ proc = subprocess.Popen([self.node, self.worker], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
73
+ text=True, encoding="utf-8", env=self.env, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
74
+ except OSError as exc:
75
+ raise RuntimeCallError({"version": 1, "status": "failed", "dispatch": "not-started", "receipt": None,
76
+ "error": {"code": "bridge-start-failed", "message": "Could not start the Runtime worker."}}) from exc
77
+ stdout, write_errors = [], []
78
+ written = threading.Event()
79
+
80
+ def write_request():
81
+ try:
82
+ proc.stdin.write(encoded)
83
+ proc.stdin.flush()
84
+ except OSError as exc:
85
+ write_errors.append(exc)
86
+ finally:
87
+ written.set()
88
+
89
+ def discard_stderr():
90
+ while proc.stderr.read(8192):
91
+ pass
92
+
93
+ readers = [threading.Thread(target=lambda: stdout.append(proc.stdout.read()), daemon=True),
94
+ threading.Thread(target=discard_stderr, daemon=True)]
95
+ for reader in readers:
96
+ reader.start()
97
+ started = time.monotonic()
98
+ cancellation_sent = payload["cancelled"]
99
+ cancelled_at = started if cancellation_sent else None
100
+ writer = threading.Thread(target=write_request, daemon=True)
101
+ writer.start()
102
+ try:
103
+ while proc.poll() is None:
104
+ if write_errors:
105
+ raise _transport_error("bridge-transport-error", "The Runtime worker connection was lost.")
106
+ if cancel_event and cancel_event.is_set() and cancelled_at is None:
107
+ cancelled_at = time.monotonic()
108
+ if cancel_event and cancel_event.is_set() and not cancellation_sent and written.is_set():
109
+ proc.stdin.write('{"version":1,"type":"cancel"}\n')
110
+ proc.stdin.flush()
111
+ cancellation_sent = True
112
+ if (self.transport_timeout is not None and time.monotonic() - started > self.transport_timeout
113
+ or cancelled_at is not None and time.monotonic() - cancelled_at > 10):
114
+ proc.kill()
115
+ raise _transport_error("bridge-timeout", "The Runtime worker did not return a terminal receipt.")
116
+ time.sleep(0.01)
117
+ for reader in readers:
118
+ reader.join()
119
+ try:
120
+ reply = json.loads("".join(stdout))
121
+ if not _valid_reply(reply, proc.returncode):
122
+ raise ValueError("Invalid protocol reply")
123
+ except (ValueError, AttributeError) as exc:
124
+ raise _transport_error("bridge-protocol-error", "The Runtime worker returned no valid terminal reply.") from exc
125
+ if reply["status"] == "failed":
126
+ raise RuntimeCallError(reply)
127
+ return reply
128
+ except (BrokenPipeError, OSError) as exc:
129
+ raise _transport_error("bridge-transport-error", "The Runtime worker connection was lost.") from exc
130
+ finally:
131
+ if proc.poll() is None:
132
+ proc.kill()
133
+ proc.wait()
134
+ writer.join()
135
+ for reader in readers:
136
+ reader.join()
137
+ for stream in (proc.stdin, proc.stdout, proc.stderr):
138
+ try:
139
+ stream.close()
140
+ except OSError:
141
+ pass
@@ -0,0 +1,12 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "techis-model-routes"
7
+ version = "0.6.0"
8
+ description = "Python client for the application-owned Model Routes Runtime"
9
+ requires-python = ">=3.10"
10
+
11
+ [tool.setuptools]
12
+ packages = ["model_routes"]