sousml 0.1.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.
sousml/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """Sous for apps that call OpenAI, Azure OpenAI, or Anthropic. Wrap the client you have, and Sous learns from its
2
+ calls; once you switch to the model Sous trained, the same calls go to it.
3
+
4
+ from openai import OpenAI
5
+ from sousml import Sous
6
+
7
+ client = Sous(OpenAI(), model="abcdef12") # SOUS_API_KEY from the environment
8
+
9
+ Calls work as before and return what they always did. Each call and its answer go to Sous in the background, so
10
+ they add no wait, and nothing Sous does can fail a call: if Sous can't answer, your own model does. Hatch, the
11
+ SDK's name before it was Sous, still works.
12
+ """
13
+
14
+ from sousml._sender import VERSION as __version__
15
+ from sousml._wrap import Sous, flush
16
+
17
+ Hatch = Sous
18
+
19
+ __all__ = ["Sous", "Hatch", "flush", "__version__"]
sousml/_auto.py ADDED
@@ -0,0 +1,135 @@
1
+ """Sous for an app without changing its code. `sous-run python app.py`, or any command, wraps each OpenAI, Azure
2
+ OpenAI, and Anthropic client the app makes with Sous(client), from SOUS_MODEL and SOUS_API_KEY (or the HATCH_
3
+ names they had before the rename; hatch-run is the same command). It puts this
4
+ package's bootstrap folder first on PYTHONPATH, so every Python process the command starts loads it before the app,
5
+ and it patches the client classes as their packages are imported."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import functools
10
+ import importlib.abc
11
+ import importlib.machinery
12
+ import os
13
+ import subprocess
14
+ import sys
15
+ import threading
16
+ from typing import Any, Callable, Optional
17
+
18
+ from sousml._sender import setting, warn_once
19
+
20
+ BOOTSTRAP = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bootstrap")
21
+ CLASSES = {"openai": ("OpenAI", "AsyncOpenAI", "AzureOpenAI", "AsyncAzureOpenAI"),
22
+ "anthropic": ("Anthropic", "AsyncAnthropic")}
23
+ USAGE = """\
24
+ Usage: sous-run COMMAND [ARGS...]
25
+
26
+ Runs COMMAND, such as `python app.py`, with each OpenAI, Azure OpenAI, and Anthropic client its Python code makes
27
+ wrapped by Sous, so Sous learns from the calls and, once you switch to the model it trained, answers them.
28
+ Set SOUS_MODEL to the model's id and SOUS_API_KEY to a Sous API key first."""
29
+
30
+ _depth = threading.local()
31
+ _installed = False
32
+
33
+
34
+ def install() -> bool:
35
+ """Wrap each model client made from now on. Without SOUS_MODEL or SOUS_API_KEY, says so once and wraps
36
+ nothing, so the app runs as it always did. Returns whether it wraps them."""
37
+ global _installed
38
+ missing = [f"SOUS_{name}" for name in ("MODEL", "API_KEY") if not setting(name)]
39
+ if missing:
40
+ warn_once("auto-env", f"sous-run: set {' and '.join(missing)}, or the app's calls don't reach Sous.")
41
+ return False
42
+ if _installed:
43
+ return True
44
+ _installed = True
45
+ for name in CLASSES:
46
+ if name in sys.modules:
47
+ _patch_package(sys.modules[name])
48
+ sys.meta_path.insert(0, _Finder())
49
+ return True
50
+
51
+
52
+ def _patch_package(module: Any) -> None:
53
+ for name in CLASSES.get(module.__name__, ()):
54
+ cls = getattr(module, name, None)
55
+ if isinstance(cls, type) and "__init__" in vars(cls):
56
+ _patch_init(cls)
57
+
58
+
59
+ def _patch_init(cls: type) -> None:
60
+ original = vars(cls)["__init__"]
61
+ if getattr(original, "__sous_auto__", False):
62
+ return
63
+
64
+ @functools.wraps(original)
65
+ def __init__(self: Any, *args: Any, **kwargs: Any) -> None:
66
+ depth = getattr(_depth, "value", 0)
67
+ _depth.value = depth + 1
68
+ try:
69
+ original(self, *args, **kwargs)
70
+ finally:
71
+ _depth.value = depth
72
+ if depth == 0: # the outermost of the patched __init__s, as AzureOpenAI's runs OpenAI's
73
+ _wrap_quietly(self)
74
+
75
+ __init__.__sous_auto__ = True # type: ignore[attr-defined]
76
+ cls.__init__ = __init__ # type: ignore[misc]
77
+
78
+
79
+ def _wrap_quietly(client: Any) -> None:
80
+ from sousml._wrap import Sous, making_own_client
81
+
82
+ if making_own_client():
83
+ return
84
+ try:
85
+ Sous(client)
86
+ except Exception as exc: # noqa: BLE001 - an app's client keeps working when Sous can't wrap it
87
+ warn_once(f"auto-{type(client).__name__}", f"sous-run couldn't wrap a {type(client).__name__} ({exc}); "
88
+ "its calls go on as before.")
89
+
90
+
91
+ class _Finder(importlib.abc.MetaPathFinder):
92
+ """Patches openai and anthropic right after they're imported."""
93
+
94
+ def find_spec(self, fullname: str, path: Any, target: Any = None) -> Optional[importlib.machinery.ModuleSpec]:
95
+ if fullname not in CLASSES:
96
+ return None
97
+ for finder in sys.meta_path:
98
+ if finder is self or not hasattr(finder, "find_spec"):
99
+ continue
100
+ spec = finder.find_spec(fullname, path, target)
101
+ if spec is not None and spec.loader is not None and hasattr(spec.loader, "exec_module"):
102
+ spec.loader.exec_module = _then_patch(spec.loader.exec_module) # type: ignore[method-assign]
103
+ return spec
104
+ return None
105
+
106
+
107
+ def _then_patch(exec_module: Callable[[Any], None]) -> Callable[[Any], None]:
108
+ def run(module: Any) -> None:
109
+ exec_module(module)
110
+ try:
111
+ _patch_package(module)
112
+ except Exception as exc: # noqa: BLE001
113
+ warn_once("auto-patch", f"sous-run couldn't set up {module.__name__} ({exc}); its calls go on as before.")
114
+
115
+ return run
116
+
117
+
118
+ def main(argv: Optional[list[str]] = None) -> None:
119
+ args = sys.argv[1:] if argv is None else argv
120
+ if not args or args[0] in ("-h", "--help"):
121
+ print(USAGE)
122
+ sys.exit(0 if args else 2)
123
+ path = os.environ.get("PYTHONPATH")
124
+ os.environ["PYTHONPATH"] = BOOTSTRAP + (os.pathsep + path if path else "")
125
+ if os.name == "nt":
126
+ sys.exit(subprocess.call(args))
127
+ try:
128
+ os.execvp(args[0], args)
129
+ except FileNotFoundError:
130
+ print(f"sous-run: couldn't find {args[0]}.", file=sys.stderr)
131
+ sys.exit(127)
132
+
133
+
134
+ if __name__ == "__main__":
135
+ main()
sousml/_sender.py ADDED
@@ -0,0 +1,132 @@
1
+ """Sends calls to Sous from a background thread, in batches, so they add no wait to the app's own calls. Uses only
2
+ the standard library, so the SDK works next to any version of the OpenAI and Anthropic clients."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import atexit
7
+ import json
8
+ import logging
9
+ import os
10
+ import queue
11
+ import threading
12
+ import time
13
+ import urllib.error
14
+ import urllib.request
15
+ import weakref
16
+ from typing import Any, Optional
17
+
18
+ VERSION = "0.1.0"
19
+ BATCH_CALLS = 20
20
+ BATCH_BYTES = 4_000_000
21
+ MAX_QUEUED = 1000
22
+ TRIES = 3
23
+
24
+ log = logging.getLogger("sousml")
25
+ _warned: set[str] = set()
26
+ _senders: weakref.WeakSet[Sender] = weakref.WeakSet()
27
+
28
+
29
+ def setting(name: str) -> Optional[str]:
30
+ """SOUS_<name> from the environment, or HATCH_<name>, as apps set it before the rename."""
31
+ return os.environ.get(f"SOUS_{name}") or os.environ.get(f"HATCH_{name}")
32
+
33
+
34
+ def warn_once(key: str, message: str) -> None:
35
+ if key not in _warned:
36
+ _warned.add(key)
37
+ log.warning(message)
38
+
39
+
40
+ def request(method: str, url: str, key: str, body: Optional[bytes] = None, timeout: float = 30) -> tuple[int, Any]:
41
+ """(status, JSON body) of one request to Sous. Status 0 when Sous can't be reached."""
42
+ headers = {"Authorization": f"Bearer {key}", "User-Agent": f"sousml-python/{VERSION}"}
43
+ if body is not None:
44
+ headers["Content-Type"] = "application/json"
45
+ try:
46
+ with urllib.request.urlopen(urllib.request.Request(url, body, headers, method=method), timeout=timeout) as res:
47
+ status, raw = res.status, res.read()
48
+ except urllib.error.HTTPError as err:
49
+ status, raw = err.code, err.read()
50
+ except (OSError, ValueError):
51
+ return 0, None
52
+ try:
53
+ return status, json.loads(raw or b"null")
54
+ except ValueError:
55
+ return status, None
56
+
57
+
58
+ def _reason(body: Any) -> str:
59
+ error = body.get("error") if isinstance(body, dict) else body
60
+ return str(error.get("message") if isinstance(error, dict) else error)
61
+
62
+
63
+ class Sender:
64
+ def __init__(self, url: str, key: str):
65
+ self.url, self.key = url, key
66
+ self.queue: queue.Queue[str] = queue.Queue(MAX_QUEUED)
67
+ self.thread: Optional[threading.Thread] = None
68
+ self.lock = threading.Lock()
69
+ _senders.add(self)
70
+
71
+ def put(self, call: str) -> None:
72
+ try:
73
+ self.queue.put_nowait(call)
74
+ except queue.Full:
75
+ warn_once("full", "Sous is behind on sending calls, so some weren't kept.")
76
+ return
77
+ with self.lock:
78
+ if self.thread is None or not self.thread.is_alive():
79
+ self.thread = threading.Thread(target=self._run, name="sous-sender", daemon=True)
80
+ self.thread.start()
81
+
82
+ def _run(self) -> None:
83
+ while True:
84
+ batch = [self.queue.get()]
85
+ size = len(batch[0])
86
+ while len(batch) < BATCH_CALLS and size < BATCH_BYTES:
87
+ try:
88
+ call = self.queue.get(timeout=0.5)
89
+ except queue.Empty:
90
+ break
91
+ batch.append(call)
92
+ size += len(call)
93
+ try:
94
+ self._send(batch)
95
+ finally:
96
+ for _ in batch:
97
+ self.queue.task_done()
98
+
99
+ def _send(self, batch: list[str]) -> None:
100
+ body = ('{"calls":[' + ",".join(batch) + "]}").encode()
101
+ for attempt in range(TRIES):
102
+ status, reply = request("POST", self.url, self.key, body)
103
+ if status and status < 500 and status != 429:
104
+ if status >= 400:
105
+ warn_once(f"status-{status}", f"Sous didn't keep calls: {_reason(reply)}")
106
+ elif isinstance(reply, dict) and reply.get("rejected"):
107
+ warn_once("rejected", f"Sous couldn't learn from a call: {reply['rejected'][0].get('error')}")
108
+ return
109
+ time.sleep(2 ** attempt)
110
+ warn_once("unreachable", f"Couldn't reach Sous at {self.url}, so {len(batch)} calls weren't kept.")
111
+
112
+ def flush(self, timeout: Optional[float] = None) -> bool:
113
+ end = None if timeout is None else time.monotonic() + timeout
114
+ with self.queue.all_tasks_done:
115
+ while self.queue.unfinished_tasks:
116
+ left = None if end is None else end - time.monotonic()
117
+ if left is not None and left <= 0:
118
+ return False
119
+ self.queue.all_tasks_done.wait(left)
120
+ return True
121
+
122
+
123
+ def flush_all(timeout: Optional[float] = None) -> bool:
124
+ end = None if timeout is None else time.monotonic() + timeout
125
+ done = True
126
+ for sender in list(_senders):
127
+ left = None if end is None else max(0.0, end - time.monotonic())
128
+ done = sender.flush(left) and done
129
+ return done
130
+
131
+
132
+ atexit.register(flush_all, 5.0)
sousml/_wrap.py ADDED
@@ -0,0 +1,505 @@
1
+ """Sous(client) patches the client's call methods in place, so the client stays itself: its type, its options, and
2
+ everything it doesn't call through are untouched."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import functools
8
+ import hashlib
9
+ import inspect
10
+ import json
11
+ import threading
12
+ import time
13
+ from typing import Any, Callable, Optional, TypeVar
14
+
15
+ from sousml import _sender
16
+ from sousml._sender import Sender, flush_all, setting, warn_once
17
+
18
+ T = TypeVar("T")
19
+ DEFAULT_BASE_URL = "https://api.sousml.com"
20
+ CHECK_EVERY = 60.0
21
+ # The longest a call made before Sous first said who answers waits to hear it.
22
+ FIRST_CHECK_WAIT = 3.0
23
+ OWN_MODEL_HEADER = "x-sous-own-model"
24
+ # Says this client answers the share of calls the model learns from with the app's own model, so Sous doesn't.
25
+ LEARNS_HEADER = "x-sous-learns"
26
+ DAY = 24 * 60 * 60
27
+
28
+ # Where the calls Sous learns from live on a client, and the API each speaks. The "stream" ones are the clients'
29
+ # stream helpers, which return a context manager.
30
+ CALLS = {
31
+ ("chat", "completions", "create"): "chat",
32
+ ("chat", "completions", "parse"): "chat",
33
+ ("chat", "completions", "stream"): "chat",
34
+ ("beta", "chat", "completions", "parse"): "chat",
35
+ ("beta", "chat", "completions", "stream"): "chat",
36
+ ("responses", "create"): "responses",
37
+ ("responses", "parse"): "responses",
38
+ ("messages", "create"): "messages",
39
+ ("messages", "stream"): "messages",
40
+ ("beta", "messages", "create"): "messages",
41
+ ("beta", "messages", "stream"): "messages",
42
+ }
43
+ SKIP = {"extra_headers", "extra_query", "extra_body", "timeout"}
44
+ FAMILIES = ("openai", "anthropic")
45
+
46
+ _links: dict[tuple, _Link] = {}
47
+ _links_lock = threading.Lock()
48
+ _making = threading.local()
49
+
50
+
51
+ def making_own_client() -> bool:
52
+ """Whether Sous is making the client it calls itself with, on this thread: one sous-run mustn't wrap."""
53
+ return getattr(_making, "active", False)
54
+
55
+
56
+ def _family(client: Any) -> Optional[str]:
57
+ """"openai" or "anthropic" for one of their clients, or a class built on one."""
58
+ for cls in type(client).__mro__:
59
+ family = cls.__module__.split(".")[0]
60
+ if family in FAMILIES:
61
+ return family
62
+ return None
63
+
64
+
65
+ def flush(timeout: Optional[float] = None) -> bool:
66
+ """Wait until every call so far has gone to Sous, for scripts that exit right after their last call. Returns
67
+ False if `timeout` seconds pass first."""
68
+ return flush_all(timeout)
69
+
70
+
71
+ def Sous(client: T, model: Optional[str] = None, *, api_key: Optional[str] = None, base_url: Optional[str] = None,
72
+ route: bool = True) -> T:
73
+ """Wrap an OpenAI, AzureOpenAI, or Anthropic client (sync or async) so Sous learns from its calls, and returns
74
+ the same client.
75
+
76
+ model: the id of the Sous model the calls train (or SOUS_MODEL).
77
+ api_key: a Sous API key (or SOUS_API_KEY). base_url: the Sous API's address (or SOUS_BASE_URL), by default
78
+ https://api.sousml.com. HATCH_MODEL, HATCH_API_KEY, and HATCH_BASE_URL work too.
79
+ route: once you switch to the model Sous trained, send the calls to it, and to your own model whenever it
80
+ can't answer. Off, Sous only learns from them.
81
+ """
82
+ if _family(client) is None:
83
+ raise TypeError("Sous wraps OpenAI, AzureOpenAI, and Anthropic clients, sync or async.")
84
+ model = model or setting("MODEL")
85
+ api_key = api_key or setting("API_KEY")
86
+ if not model:
87
+ raise ValueError("Say which Sous model these calls train: Sous(client, model=\"...\"), or set SOUS_MODEL.")
88
+ if not api_key:
89
+ raise ValueError("Sous needs an API key: make one in Sous under API keys, and set SOUS_API_KEY.")
90
+ base = (base_url or setting("BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
91
+ base = base[:-3] if base.endswith("/v1") else base
92
+ # Clients that train the same model share one link: one queue of calls, and one check of who answers.
93
+ with _links_lock:
94
+ link = _links.get((model, api_key, base, route))
95
+ if link is None:
96
+ link = _links[(model, api_key, base, route)] = _Link(model, api_key, base, route)
97
+ _patch(client, link)
98
+ return client
99
+
100
+
101
+ class _Link:
102
+ """What a wrapped client knows about its Sous model: where its calls go, and whether Sous answers them yet."""
103
+
104
+ def __init__(self, model: str, key: str, base: str, route: bool):
105
+ self.model, self.key, self.base, self.route = model, key, base, route
106
+ self.sender = Sender(f"{base}/v1/models/{model}/calls", key)
107
+ self.student, self.checked, self.checking = False, float("-inf"), False
108
+ self.share = 0.0
109
+ self.first = threading.Event()
110
+ self.clients: dict[tuple[str, bool], Any] = {}
111
+ self.lock = threading.Lock()
112
+ self.answers(wait=False)
113
+
114
+ def answers(self, wait: bool = True) -> bool:
115
+ """Whether the model Sous trained answers these calls now. Checked in the background once a minute, so a
116
+ switch reaches the app within a minute. The first check starts when the client is wrapped, and only calls
117
+ made before it's done wait for it, a few seconds at most, so a script's first call goes to the right model."""
118
+ if not self.route:
119
+ return False
120
+ with self.lock:
121
+ if not self.checking and time.monotonic() - self.checked > CHECK_EVERY:
122
+ self.checking = True
123
+ threading.Thread(target=self._check, name="sous-status", daemon=True).start()
124
+ if wait:
125
+ self.first.wait(FIRST_CHECK_WAIT)
126
+ return self.student
127
+
128
+ async def answers_async(self) -> bool:
129
+ """answers() without holding up the event loop while the first check is out."""
130
+ if self.route and not self.first.is_set():
131
+ await asyncio.get_running_loop().run_in_executor(None, self.first.wait, FIRST_CHECK_WAIT)
132
+ return self.answers(wait=False)
133
+
134
+ def _check(self) -> None:
135
+ try:
136
+ status, body = _sender.request("GET", f"{self.base}/v1/models/{self.model}", self.key, timeout=10)
137
+ if status == 200 and isinstance(body, dict):
138
+ self.student = body.get("answered_by") == "student"
139
+ share = body.get("learning_share")
140
+ self.share = float(share) if isinstance(share, (int, float)) and 0 < share < 1 else 0.0
141
+ elif status in (401, 404):
142
+ self.student = False
143
+ warn_once(f"check-{status}", f"Sous has no model {self.model} for this API key.")
144
+ finally:
145
+ self.checked, self.checking = time.monotonic(), False
146
+ self.first.set()
147
+
148
+ def keeps(self, api: str, kwargs: dict) -> bool:
149
+ """Whether the app's own model answers this call though Sous's answers the rest: the share of calls Sous
150
+ asks for to keep learning from, whole conversations at a time, picked each day by how they open."""
151
+ if self.share <= 0:
152
+ return False
153
+ try:
154
+ head = _opening(api, _request(kwargs))
155
+ except Exception: # noqa: BLE001 - a call Sous can't read goes to Sous
156
+ return False
157
+ if head is None:
158
+ return False
159
+ seed = json.dumps([self.model, int(time.time() // DAY), head], sort_keys=True, default=str)
160
+ return int.from_bytes(hashlib.sha256(seed.encode()).digest()[:8], "big") / 2**64 < self.share
161
+
162
+ def sous_answers(self, api: str, kwargs: dict) -> bool:
163
+ return self.answers() and not self.keeps(api, kwargs)
164
+
165
+ async def sous_answers_async(self, api: str, kwargs: dict) -> bool:
166
+ return await self.answers_async() and not self.keeps(api, kwargs)
167
+
168
+ def routed(self, kwargs: dict) -> dict:
169
+ """A call's arguments as they go to Sous: to the Sous model, saying the app has a model of its own, so
170
+ Sous hands a call back at once rather than make it wait while the model's server starts, and keeps the
171
+ calls Sous learns from on it."""
172
+ headers = {**(kwargs.get("extra_headers") or {}), OWN_MODEL_HEADER: "1", LEARNS_HEADER: "1"}
173
+ return {**kwargs, "model": self.model, "extra_headers": headers}
174
+
175
+ def failed(self, exc: BaseException) -> None:
176
+ """Sous couldn't answer: the app's own model takes the calls until the next check, or, while the Sous
177
+ model's server starts, until Sous said it would be up."""
178
+ wait = _starting(exc)
179
+ self.student = False
180
+ self.checked = time.monotonic() + (max(0.0, wait - CHECK_EVERY) if wait is not None else 0.0)
181
+ if wait is not None:
182
+ warn_once("starting", f"Your Sous model {self.model} is starting, which takes about "
183
+ f"{max(1, round(wait / 60))} min. Your own model answers until it's up.")
184
+ else:
185
+ warn_once(f"fallback-{type(exc).__name__}", f"Sous couldn't answer ({exc}), so your own model did.")
186
+
187
+ def sous_client(self, client: Any) -> Any:
188
+ """The app's client pointed at Sous, so its proxies and timeouts still apply, with no retries so a failure
189
+ falls back at once. Azure's clients put the deployment in the path, so those get a plain OpenAI client. One per
190
+ HTTP client, so a client and its copies share one."""
191
+ key = (type(client).__module__, type(client).__name__, id(getattr(client, "_client", None)))
192
+ with self.lock:
193
+ if key not in self.clients:
194
+ name = type(client).__name__
195
+ _making.active = True
196
+ try:
197
+ if "Azure" in name:
198
+ import openai
199
+
200
+ cls = openai.AsyncOpenAI if name.startswith("Async") else openai.OpenAI
201
+ made = cls(api_key=self.key, base_url=f"{self.base}/v1", max_retries=0,
202
+ timeout=client.timeout)
203
+ else:
204
+ copy = getattr(client.with_options, "__wrapped_original__", client.with_options)
205
+ base = self.base if _family(client) == "anthropic" else f"{self.base}/v1"
206
+ made = copy(api_key=self.key, base_url=base, max_retries=0)
207
+ finally:
208
+ _making.active = False
209
+ self.clients[key] = made
210
+ return self.clients[key]
211
+
212
+ def keep(self, api: str, request: dict, seconds: float, response: Any = None, events: Any = None) -> None:
213
+ """Queue a call for Sous. Never raises: a call Sous can't read is one Sous doesn't learn from."""
214
+ try:
215
+ call: dict = {"api": api, "request": request, "seconds": round(seconds, 3)}
216
+ if events is not None:
217
+ call["stream"] = [_dump(e) for e in events]
218
+ else:
219
+ call["response"] = _dump(response)
220
+ self.sender.put(json.dumps(call, ensure_ascii=False, default=_jsonable))
221
+ except Exception as exc: # noqa: BLE001
222
+ warn_once("dump", f"Sous couldn't read a call to send it ({exc}).")
223
+
224
+
225
+ def _starting(exc: BaseException) -> Optional[float]:
226
+ """Seconds until the Sous model is up, when it didn't answer because its server is starting: Sous answers
227
+ 503 with Retry-After then (model_starting)."""
228
+ response = getattr(exc, "response", None)
229
+ if getattr(exc, "status_code", None) != 503 or response is None:
230
+ return None
231
+ try:
232
+ return max(0.0, float(response.headers.get("retry-after")))
233
+ except (TypeError, ValueError):
234
+ return None
235
+
236
+
237
+ def _patch(client: Any, link: _Link) -> None:
238
+ for path, api in CALLS.items():
239
+ owner = client
240
+ try:
241
+ for part in path[:-1]:
242
+ owner = getattr(owner, part)
243
+ original = getattr(owner, path[-1])
244
+ except Exception: # noqa: BLE001 - not every client version has every call
245
+ continue
246
+ if getattr(original, "__sous__", None) is link:
247
+ continue
248
+ wrapped = _wrap(link, client, path, api, getattr(original, "__wrapped_original__", original))
249
+ setattr(owner, path[-1], wrapped)
250
+ for name in ("with_options", "copy"):
251
+ original = getattr(client, name, None)
252
+ if callable(original) and not getattr(original, "__sous__", None):
253
+ def copied(*args: Any, _original: Callable = original, **kwargs: Any) -> Any:
254
+ made = _original(*args, **kwargs)
255
+ _patch(made, link)
256
+ return made
257
+
258
+ copied.__sous__ = link # type: ignore[attr-defined]
259
+ copied.__wrapped_original__ = original # type: ignore[attr-defined]
260
+ setattr(client, name, copied)
261
+
262
+
263
+ def _wrap(link: _Link, client: Any, path: tuple, api: str, original: Callable) -> Callable:
264
+ def at_sous() -> Callable:
265
+ return functools.reduce(getattr, path, link.sous_client(client))
266
+
267
+ if path[-1] == "stream":
268
+ def stream(*args: Any, **kwargs: Any) -> Any:
269
+ return _Manager(link, api, kwargs, lambda: original(*args, **kwargs),
270
+ lambda: at_sous()(*args, **link.routed(kwargs)))
271
+
272
+ call: Callable = stream
273
+ elif type(client).__name__.startswith("Async") or inspect.iscoroutinefunction(original):
274
+ # The SDKs wrap create() in a plain function, so only the client says the call is async.
275
+ async def acall(*args: Any, **kwargs: Any) -> Any:
276
+ if await link.sous_answers_async(api, kwargs):
277
+ try:
278
+ return await at_sous()(*args, **link.routed(kwargs))
279
+ except Exception as exc: # noqa: BLE001
280
+ link.failed(exc)
281
+ started = time.monotonic()
282
+ result = await original(*args, **kwargs)
283
+ return _observe(link, api, kwargs, result, started)
284
+
285
+ call = acall
286
+ else:
287
+ def scall(*args: Any, **kwargs: Any) -> Any:
288
+ if link.sous_answers(api, kwargs):
289
+ try:
290
+ return at_sous()(*args, **link.routed(kwargs))
291
+ except Exception as exc: # noqa: BLE001
292
+ link.failed(exc)
293
+ started = time.monotonic()
294
+ result = original(*args, **kwargs)
295
+ return _observe(link, api, kwargs, result, started)
296
+
297
+ call = scall
298
+ functools.update_wrapper(call, original)
299
+ call.__sous__ = link # type: ignore[attr-defined]
300
+ call.__wrapped_original__ = original # type: ignore[attr-defined]
301
+ return call
302
+
303
+
304
+ def _observe(link: _Link, api: str, kwargs: dict, result: Any, started: float) -> Any:
305
+ try:
306
+ request = _request(kwargs)
307
+ except Exception as exc: # noqa: BLE001
308
+ warn_once("dump", f"Sous couldn't read a call to send it ({exc}).")
309
+ return result
310
+ if type(result).__name__ in ("Stream", "AsyncStream"):
311
+ return _Tee(result, lambda events: link.keep(api, request, time.monotonic() - started, events=events))
312
+ link.keep(api, request, time.monotonic() - started, response=result)
313
+ return result
314
+
315
+
316
+ def _opening(api: str, body: dict) -> Optional[list]:
317
+ """A call's messages up to the first reply, which every later call of its conversation repeats; None for one
318
+ that brings none of its own, like one that continues a stored response."""
319
+ if body.get("previous_response_id"):
320
+ return None
321
+ system = body.get("instructions") if api == "responses" else body.get("system") if api == "messages" else None
322
+ messages = [{"role": "system", "content": system}] if system else []
323
+ sent = body.get("input") if api == "responses" else body.get("messages")
324
+ messages += [{"role": "user", "content": sent}] if isinstance(sent, str) else list(sent or [])
325
+ head = []
326
+ for m in messages:
327
+ if not isinstance(m, dict) or m.get("role") not in ("system", "developer", "user") \
328
+ or m.get("type", "message") != "message":
329
+ break
330
+ head.append(m)
331
+ return head if any(m["role"] == "user" for m in head) else None
332
+
333
+
334
+ def _request(kwargs: dict) -> dict:
335
+ """The body the call sent, as JSON, taken now: apps often add the answer to the same messages list next."""
336
+ out: dict = {}
337
+ for key, value in kwargs.items():
338
+ if key in SKIP or type(value).__name__ in ("NotGiven", "Omit"):
339
+ continue
340
+ if key == "response_format" and isinstance(value, type):
341
+ value = {"type": "json_schema", "json_schema": {"name": value.__name__, "schema": _schema(value),
342
+ "strict": True}}
343
+ elif key == "text_format" and isinstance(value, type):
344
+ key, value = "text", {"format": {"type": "json_schema", "name": value.__name__, "schema": _schema(value),
345
+ "strict": True}}
346
+ out[key] = value
347
+ if isinstance(kwargs.get("extra_body"), dict):
348
+ out.update(kwargs["extra_body"])
349
+ return json.loads(json.dumps(out, default=_jsonable))
350
+
351
+
352
+ def _schema(cls: type) -> dict:
353
+ try:
354
+ from openai.lib._pydantic import to_strict_json_schema
355
+
356
+ return to_strict_json_schema(cls)
357
+ except Exception: # noqa: BLE001
358
+ return cls.model_json_schema() if hasattr(cls, "model_json_schema") else {}
359
+
360
+
361
+ def _dump(value: Any) -> Any:
362
+ if hasattr(value, "to_dict"):
363
+ try:
364
+ return value.to_dict(mode="json")
365
+ except TypeError:
366
+ return value.to_dict()
367
+ if hasattr(value, "model_dump"):
368
+ return value.model_dump(mode="json", exclude_unset=True)
369
+ return value
370
+
371
+
372
+ def _jsonable(value: Any) -> Any:
373
+ if isinstance(value, type) and hasattr(value, "model_json_schema"):
374
+ return _schema(value)
375
+ if hasattr(value, "to_dict") or hasattr(value, "model_dump"):
376
+ return _dump(value)
377
+ if isinstance(value, (set, tuple)):
378
+ return list(value)
379
+ if isinstance(value, bytes):
380
+ return value.decode("utf-8", "replace")
381
+ return str(value)
382
+
383
+
384
+ class _Tee:
385
+ """A stream that hands each event to the app as it comes, and sends Sous the call once the stream finishes."""
386
+
387
+ def __init__(self, stream: Any, done: Callable[[list], None]):
388
+ self._stream, self._done, self._events = stream, done, []
389
+ self._it: Any = None
390
+ self._ended = False
391
+
392
+ def _end(self) -> None:
393
+ if not self._ended:
394
+ self._ended = True
395
+ self._done(self._events)
396
+
397
+ def __iter__(self) -> _Tee:
398
+ return self
399
+
400
+ def __next__(self) -> Any:
401
+ if self._it is None:
402
+ self._it = iter(self._stream)
403
+ try:
404
+ event = next(self._it)
405
+ except StopIteration:
406
+ self._end()
407
+ raise
408
+ self._events.append(event)
409
+ return event
410
+
411
+ def __aiter__(self) -> _Tee:
412
+ return self
413
+
414
+ async def __anext__(self) -> Any:
415
+ if self._it is None:
416
+ self._it = self._stream.__aiter__()
417
+ try:
418
+ event = await self._it.__anext__()
419
+ except StopAsyncIteration:
420
+ self._end()
421
+ raise
422
+ self._events.append(event)
423
+ return event
424
+
425
+ def __enter__(self) -> _Tee:
426
+ self._stream.__enter__()
427
+ return self
428
+
429
+ def __exit__(self, *exc: Any) -> Any:
430
+ return self._stream.__exit__(*exc)
431
+
432
+ async def __aenter__(self) -> _Tee:
433
+ await self._stream.__aenter__()
434
+ return self
435
+
436
+ async def __aexit__(self, *exc: Any) -> Any:
437
+ return await self._stream.__aexit__(*exc)
438
+
439
+ def __getattr__(self, name: str) -> Any:
440
+ return getattr(self._stream, name)
441
+
442
+
443
+ class _Manager:
444
+ """A stream helper's context manager. Opens the stream at Sous when the trained model answers, and the app's
445
+ own when it doesn't or Sous fails to open it; sends Sous the call when the app's own stream finished."""
446
+
447
+ def __init__(self, link: _Link, api: str, kwargs: dict, own: Callable, sous: Callable):
448
+ self._link, self._api, self._kwargs, self._own, self._sous = link, api, kwargs, own, sous
449
+ self._inner: Any = None
450
+ self._stream: Any = None
451
+ self._routed = False
452
+ self._started = time.monotonic()
453
+
454
+ def __enter__(self) -> Any:
455
+ if self._link.sous_answers(self._api, self._kwargs):
456
+ try:
457
+ self._inner = self._sous()
458
+ self._stream, self._routed = self._inner.__enter__(), True
459
+ return self._stream
460
+ except Exception as exc: # noqa: BLE001
461
+ self._link.failed(exc)
462
+ self._inner = self._own()
463
+ self._stream = self._inner.__enter__()
464
+ return self._stream
465
+
466
+ def __exit__(self, *exc: Any) -> Any:
467
+ if exc[0] is None and not self._routed:
468
+ self._keep()
469
+ return self._inner.__exit__(*exc)
470
+
471
+ async def __aenter__(self) -> Any:
472
+ if await self._link.sous_answers_async(self._api, self._kwargs):
473
+ try:
474
+ self._inner = self._sous()
475
+ self._stream, self._routed = await self._inner.__aenter__(), True
476
+ return self._stream
477
+ except Exception as exc: # noqa: BLE001
478
+ self._link.failed(exc)
479
+ self._inner = self._own()
480
+ self._stream = await self._inner.__aenter__()
481
+ return self._stream
482
+
483
+ async def __aexit__(self, *exc: Any) -> Any:
484
+ if exc[0] is None and not self._routed:
485
+ self._keep()
486
+ return await self._inner.__aexit__(*exc)
487
+
488
+ def _keep(self) -> None:
489
+ """Sends the finished message (Anthropic) or completion (OpenAI) the helper put together; nothing if the
490
+ app stopped reading before the end."""
491
+ for name in ("current_message_snapshot", "current_completion_snapshot"):
492
+ try:
493
+ snapshot = getattr(self._stream, name)
494
+ except Exception: # noqa: BLE001 - the helper raises when nothing streamed yet
495
+ continue
496
+ finished = (getattr(snapshot, "stop_reason", None) if name == "current_message_snapshot"
497
+ else all(c.finish_reason for c in snapshot.choices) and snapshot.choices)
498
+ if finished:
499
+ try:
500
+ request = _request(self._kwargs)
501
+ except Exception as exc: # noqa: BLE001
502
+ warn_once("dump", f"Sous couldn't read a call to send it ({exc}).")
503
+ return
504
+ self._link.keep(self._api, request, time.monotonic() - self._started, response=snapshot)
505
+ return
@@ -0,0 +1,41 @@
1
+ """Loaded before the app by each Python process sous-run starts: wraps the app's model clients with Sous, then
2
+ loads the sitecustomize the environment had of its own, if any. sousml comes from where sous-run is installed
3
+ when the app's own environment doesn't have it; it needs nothing else."""
4
+
5
+ import importlib.machinery
6
+ import importlib.util
7
+ import os
8
+ import sys
9
+
10
+ _here = os.path.dirname(os.path.abspath(__file__))
11
+
12
+
13
+ def _sousml():
14
+ try:
15
+ import sousml
16
+ except ImportError:
17
+ package = os.path.dirname(_here)
18
+ spec = importlib.util.spec_from_file_location("sousml", os.path.join(package, "__init__.py"),
19
+ submodule_search_locations=[package])
20
+ sousml = importlib.util.module_from_spec(spec)
21
+ sys.modules["sousml"] = sousml
22
+ spec.loader.exec_module(sousml)
23
+ return sousml
24
+
25
+
26
+ def _theirs():
27
+ others = [p for p in sys.path if os.path.abspath(p or os.curdir) != _here]
28
+ spec = importlib.machinery.PathFinder.find_spec("sitecustomize", others)
29
+ if spec is not None and spec.loader is not None:
30
+ module = importlib.util.module_from_spec(spec)
31
+ spec.loader.exec_module(module)
32
+
33
+
34
+ try:
35
+ _sousml()
36
+ from sousml import _auto
37
+
38
+ _auto.install()
39
+ except Exception as exc: # noqa: BLE001 - the app runs, with or without Sous
40
+ print(f"[sous] sous-run couldn't set up ({exc}); the app runs without Sous.", file=sys.stderr)
41
+ _theirs()
@@ -0,0 +1,36 @@
1
+ Metadata-Version: 2.5
2
+ Name: sousml
3
+ Version: 0.1.0
4
+ Summary: Train a smaller model on your app's own OpenAI or Anthropic calls, then switch to it.
5
+ Project-URL: Homepage, https://sousml.com
6
+ Project-URL: Documentation, https://sousml.com/docs
7
+ License-Expression: MIT
8
+ Requires-Python: >=3.9
9
+ Provides-Extra: anthropic
10
+ Requires-Dist: anthropic>=0.40; extra == 'anthropic'
11
+ Provides-Extra: openai
12
+ Requires-Dist: openai>=1.40; extra == 'openai'
13
+ Description-Content-Type: text/markdown
14
+
15
+ # sousml
16
+
17
+ Train a smaller model on your app's own OpenAI or Anthropic calls, then switch to it.
18
+
19
+ ```bash
20
+ pip install sousml
21
+ ```
22
+
23
+ ```python
24
+ from openai import OpenAI
25
+ from sousml import Sous
26
+
27
+ client = Sous(OpenAI(), model="your-model-id") # SOUS_API_KEY from the environment
28
+ ```
29
+
30
+ Calls keep working as they did. Each one is sent to [Sous](https://sousml.com) in the background, and once you switch to the trained model, the same calls go to it.
31
+
32
+ To leave the app's code as it is:
33
+
34
+ ```bash
35
+ SOUS_MODEL=your-model-id sous-run python app.py
36
+ ```
@@ -0,0 +1,9 @@
1
+ sousml/__init__.py,sha256=VuZOaKY8ig2IkCjQ2hBDI5mECPSv5hj9GnBddoyKkWw,759
2
+ sousml/_auto.py,sha256=rZBFI6xU_Uu5_ZGDesEiC6oK59T53xYtIq0uNVQYeNY,5101
3
+ sousml/_sender.py,sha256=fdM-hjwiTz3Sj_oQ-21H4kPkrSvbGoEOSzA6JiWTpC0,4785
4
+ sousml/_wrap.py,sha256=fR1DkoxD8bFR6Xh7nIUjV7CqrvcqjBoBZs3dJI4uXro,22291
5
+ sousml/bootstrap/sitecustomize.py,sha256=qMQo3IzyvKlaC_-MXbCynixsokZ-1XmiL3PFSfvcqKw,1456
6
+ sousml-0.1.0.dist-info/METADATA,sha256=sVqovzpYmOmSJLJXFT8NsxVMYF5DT5LAloyFpeDaFoU,1016
7
+ sousml-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ sousml-0.1.0.dist-info/entry_points.txt,sha256=jXJbgUZJDkvEsWy_vFlyhGMfinbHMket49lSG6keckM,77
9
+ sousml-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ hatch-run = sousml._auto:main
3
+ sous-run = sousml._auto:main