sousml 0.1.0__tar.gz
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-0.1.0/.gitignore +4 -0
- sousml-0.1.0/PKG-INFO +36 -0
- sousml-0.1.0/README.md +22 -0
- sousml-0.1.0/pyproject.toml +36 -0
- sousml-0.1.0/src/sousml/__init__.py +19 -0
- sousml-0.1.0/src/sousml/_auto.py +135 -0
- sousml-0.1.0/src/sousml/_sender.py +132 -0
- sousml-0.1.0/src/sousml/_wrap.py +505 -0
- sousml-0.1.0/src/sousml/bootstrap/sitecustomize.py +41 -0
- sousml-0.1.0/tests/test_auto.py +58 -0
- sousml-0.1.0/tests/test_sousml.py +265 -0
sousml-0.1.0/.gitignore
ADDED
sousml-0.1.0/PKG-INFO
ADDED
|
@@ -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
|
+
```
|
sousml-0.1.0/README.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# sousml
|
|
2
|
+
|
|
3
|
+
Train a smaller model on your app's own OpenAI or Anthropic calls, then switch to it.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install sousml
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from openai import OpenAI
|
|
11
|
+
from sousml import Sous
|
|
12
|
+
|
|
13
|
+
client = Sous(OpenAI(), model="your-model-id") # SOUS_API_KEY from the environment
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
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.
|
|
17
|
+
|
|
18
|
+
To leave the app's code as it is:
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
SOUS_MODEL=your-model-id sous-run python app.py
|
|
22
|
+
```
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "sousml"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Train a smaller model on your app's own OpenAI or Anthropic calls, then switch to it."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.9"
|
|
7
|
+
dependencies = []
|
|
8
|
+
license = "MIT"
|
|
9
|
+
|
|
10
|
+
[project.urls]
|
|
11
|
+
Homepage = "https://sousml.com"
|
|
12
|
+
Documentation = "https://sousml.com/docs"
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
sous-run = "sousml._auto:main"
|
|
16
|
+
hatch-run = "sousml._auto:main"
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
openai = ["openai>=1.40"]
|
|
20
|
+
anthropic = ["anthropic>=0.40"]
|
|
21
|
+
|
|
22
|
+
[dependency-groups]
|
|
23
|
+
dev = ["openai>=1.40", "anthropic>=0.40", "pytest>=8", "pytest-asyncio>=0.23"]
|
|
24
|
+
|
|
25
|
+
[build-system]
|
|
26
|
+
requires = ["hatchling"]
|
|
27
|
+
build-backend = "hatchling.build"
|
|
28
|
+
|
|
29
|
+
[tool.hatch.build.targets.sdist]
|
|
30
|
+
exclude = ["uv.lock"]
|
|
31
|
+
|
|
32
|
+
[tool.hatch.build.targets.wheel]
|
|
33
|
+
packages = ["src/sousml"]
|
|
34
|
+
|
|
35
|
+
[tool.pytest.ini_options]
|
|
36
|
+
asyncio_mode = "auto"
|
|
@@ -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__"]
|
|
@@ -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()
|
|
@@ -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)
|
|
@@ -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,58 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import subprocess
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
APP = """
|
|
6
|
+
import anthropic, openai
|
|
7
|
+
plain = openai.OpenAI(api_key="sk-test")
|
|
8
|
+
azure = openai.AzureOpenAI(api_key="sk-test", api_version="2024-06-01", azure_endpoint="https://x.openai.azure.com")
|
|
9
|
+
claude = anthropic.Anthropic(api_key="sk-test")
|
|
10
|
+
copy = plain.with_options(timeout=5)
|
|
11
|
+
calls = [plain.chat.completions.create, azure.chat.completions.create, claude.messages.create,
|
|
12
|
+
copy.chat.completions.create]
|
|
13
|
+
links = {getattr(c, "__sous__", None) for c in calls}
|
|
14
|
+
link = next(iter(links))
|
|
15
|
+
own = link.sous_client(plain) if link else None
|
|
16
|
+
print("wrapped" if None not in links else "plain", len(links),
|
|
17
|
+
"own-plain" if own is not None and not hasattr(own.chat.completions.create, "__sous__") else "-")
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def run(*command, **env):
|
|
22
|
+
full = {k: v for k, v in os.environ.items() if not k.startswith(("SOUS_", "HATCH_"))}
|
|
23
|
+
full.update(SOUS_BASE_URL="http://127.0.0.1:9", **env)
|
|
24
|
+
return subprocess.run([sys.executable, "-m", "sousml._auto", *command], env=full, capture_output=True,
|
|
25
|
+
text=True, timeout=60, check=False)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_sous_run_wraps_each_client_the_app_makes_with_one_link_and_leaves_its_own_alone():
|
|
29
|
+
done = run(sys.executable, "-c", APP, SOUS_MODEL="abcdef12", SOUS_API_KEY="hk_test")
|
|
30
|
+
assert done.returncode == 0, done.stderr
|
|
31
|
+
assert done.stdout.split() == ["wrapped", "1", "own-plain"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_without_a_model_the_app_runs_as_it_did_and_sous_run_says_why():
|
|
35
|
+
done = run(sys.executable, "-c", APP, SOUS_API_KEY="hk_test")
|
|
36
|
+
assert done.returncode == 0, done.stderr
|
|
37
|
+
assert done.stdout.split() == ["plain", "1", "-"]
|
|
38
|
+
assert "set SOUS_MODEL" in done.stderr
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_the_apps_own_sitecustomize_still_loads(tmp_path):
|
|
42
|
+
(tmp_path / "sitecustomize.py").write_text("print('theirs')\n")
|
|
43
|
+
done = run(sys.executable, "-c", APP, SOUS_MODEL="abcdef12", SOUS_API_KEY="hk_test", PYTHONPATH=str(tmp_path))
|
|
44
|
+
assert done.returncode == 0, done.stderr
|
|
45
|
+
assert done.stdout.split() == ["theirs", "wrapped", "1", "own-plain"]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_the_names_from_before_the_rename_still_work():
|
|
49
|
+
done = run(sys.executable, "-c", APP, HATCH_MODEL="abcdef12", HATCH_API_KEY="hk_test")
|
|
50
|
+
assert done.returncode == 0, done.stderr
|
|
51
|
+
assert done.stdout.split() == ["wrapped", "1", "own-plain"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_sous_run_passes_on_the_commands_exit_code_and_explains_itself():
|
|
55
|
+
assert run(sys.executable, "-c", "raise SystemExit(3)", SOUS_MODEL="m", SOUS_API_KEY="k").returncode == 3
|
|
56
|
+
usage = run()
|
|
57
|
+
assert usage.returncode == 2 and "SOUS_MODEL" in usage.stdout
|
|
58
|
+
assert run("no-such-command-anywhere").returncode == 127
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
import anthropic
|
|
5
|
+
import httpx2
|
|
6
|
+
import openai
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
import sousml
|
|
10
|
+
from sousml import _sender, _wrap
|
|
11
|
+
|
|
12
|
+
CHAT = {"id": "c1", "object": "chat.completion", "created": 1, "model": "gpt-x",
|
|
13
|
+
"choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "Refund it."}}],
|
|
14
|
+
"usage": {"prompt_tokens": 9, "completion_tokens": 3, "total_tokens": 12}}
|
|
15
|
+
CHUNKS = [{"id": "c1", "object": "chat.completion.chunk", "created": 1, "model": "gpt-x",
|
|
16
|
+
"choices": [{"index": 0, "delta": {"role": "assistant", "content": "Refund"}, "finish_reason": None}]},
|
|
17
|
+
{"id": "c1", "object": "chat.completion.chunk", "created": 1, "model": "gpt-x",
|
|
18
|
+
"choices": [{"index": 0, "delta": {"content": " it."}, "finish_reason": "stop"}]}]
|
|
19
|
+
MESSAGE = {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-x", "stop_reason": "end_turn",
|
|
20
|
+
"content": [{"type": "text", "text": "Refund it."}], "usage": {"input_tokens": 9, "output_tokens": 3}}
|
|
21
|
+
EVENTS = [("message_start", {"message": {**MESSAGE, "content": [], "stop_reason": None}}),
|
|
22
|
+
("content_block_start", {"index": 0, "content_block": {"type": "text", "text": ""}}),
|
|
23
|
+
("content_block_delta", {"index": 0, "delta": {"type": "text_delta", "text": "Refund it."}}),
|
|
24
|
+
("content_block_stop", {"index": 0}),
|
|
25
|
+
("message_delta", {"delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 3}}),
|
|
26
|
+
("message_stop", {})]
|
|
27
|
+
ASK = [{"role": "user", "content": "I was charged twice."}]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def sse(items) -> str:
|
|
31
|
+
return "".join(f"data: {json.dumps(i)}\n\n" for i in items) + "data: [DONE]\n\n"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def anthropic_sse() -> str:
|
|
35
|
+
return "".join(f"event: {kind}\ndata: {json.dumps({'type': kind, **data})}\n\n" for kind, data in EVENTS)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class FakeSous:
|
|
39
|
+
"""The Sous API: keeps the calls sent to it, says who answers, and answers like a trained model."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, monkeypatch, answered_by="teacher"):
|
|
42
|
+
self.answered_by, self.kept, self.asked, self.fail = answered_by, [], [], False
|
|
43
|
+
self.starting: int | None = None # seconds until the model's server is up, while it starts
|
|
44
|
+
self.share = 0.0 # of calls the app's own model keeps answering, for the model to learn from
|
|
45
|
+
self.own_model: list[str | None] = []
|
|
46
|
+
self.learns: list[str | None] = []
|
|
47
|
+
monkeypatch.setattr(_sender, "request", self.request)
|
|
48
|
+
|
|
49
|
+
def request(self, method, url, key, body=None, timeout=30):
|
|
50
|
+
assert key == "hk_test" and url.startswith("https://sous.test/v1/models/abcdef12")
|
|
51
|
+
if method == "GET":
|
|
52
|
+
return 200, {"id": "abcdef12", "answered_by": self.answered_by, "learning_share": self.share}
|
|
53
|
+
calls = json.loads(body)["calls"]
|
|
54
|
+
self.kept += calls
|
|
55
|
+
return 200, {"kept": len(calls), "rejected": []}
|
|
56
|
+
|
|
57
|
+
def answer(self, request: httpx2.Request) -> httpx2.Response:
|
|
58
|
+
assert request.headers.get("authorization") == "Bearer hk_test" or request.headers.get("x-api-key") == "hk_test"
|
|
59
|
+
self.own_model.append(request.headers.get("x-sous-own-model"))
|
|
60
|
+
self.learns.append(request.headers.get("x-sous-learns"))
|
|
61
|
+
if self.fail:
|
|
62
|
+
return httpx2.Response(500, json={"error": {"message": "down"}})
|
|
63
|
+
if self.starting is not None:
|
|
64
|
+
return httpx2.Response(503, headers={"retry-after": str(self.starting)}, json={"error": {
|
|
65
|
+
"message": "abcdef12 is starting.", "type": "server_error", "code": "model_starting"}})
|
|
66
|
+
self.asked.append((request.url.path, json.loads(request.content)))
|
|
67
|
+
if request.url.path == "/v1/chat/completions":
|
|
68
|
+
return httpx2.Response(200, json={**CHAT, "model": "abcdef12"})
|
|
69
|
+
return httpx2.Response(200, json={**MESSAGE, "model": "abcdef12"})
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def transport(sous: FakeSous, reply: dict, stream: str):
|
|
73
|
+
"""The provider's API, and the Sous API for calls a client copied to point at Sous sends."""
|
|
74
|
+
sent = []
|
|
75
|
+
|
|
76
|
+
def handle(request: httpx2.Request) -> httpx2.Response:
|
|
77
|
+
if request.url.host == "sous.test":
|
|
78
|
+
return sous.answer(request)
|
|
79
|
+
body = json.loads(request.content)
|
|
80
|
+
sent.append(body)
|
|
81
|
+
if body.get("stream"):
|
|
82
|
+
return httpx2.Response(200, text=stream, headers={"content-type": "text/event-stream"})
|
|
83
|
+
return httpx2.Response(200, json=reply)
|
|
84
|
+
|
|
85
|
+
return sent, httpx2.MockTransport(handle)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@pytest.fixture(autouse=True)
|
|
89
|
+
def quick_checks(monkeypatch):
|
|
90
|
+
monkeypatch.setattr(_wrap, "CHECK_EVERY", 0.0)
|
|
91
|
+
monkeypatch.setattr(_wrap, "_links", {})
|
|
92
|
+
yield
|
|
93
|
+
sousml.flush(3)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def wait_for(condition, seconds=3.0):
|
|
97
|
+
end = time.monotonic() + seconds
|
|
98
|
+
while not condition():
|
|
99
|
+
assert time.monotonic() < end, "timed out"
|
|
100
|
+
time.sleep(0.01)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def wrapped_openai(sous: FakeSous, **kwargs):
|
|
104
|
+
sent, mock = transport(sous, CHAT, sse(CHUNKS))
|
|
105
|
+
client = openai.OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=mock))
|
|
106
|
+
return sent, sousml.Sous(client, "abcdef12", api_key="hk_test", base_url="https://sous.test/v1", **kwargs)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_calls_still_go_to_your_model_and_sous_keeps_each_one(monkeypatch):
|
|
110
|
+
sous = FakeSous(monkeypatch)
|
|
111
|
+
sent, client = wrapped_openai(sous)
|
|
112
|
+
assert isinstance(client, openai.OpenAI)
|
|
113
|
+
messages = list(ASK)
|
|
114
|
+
reply = client.chat.completions.create(model="gpt-x", messages=messages, timeout=5)
|
|
115
|
+
assert reply.choices[0].message.content == "Refund it." and sent[0]["model"] == "gpt-x"
|
|
116
|
+
messages.append(reply.choices[0].message)
|
|
117
|
+
assert sousml.flush(3)
|
|
118
|
+
call = sous.kept[0]
|
|
119
|
+
assert (call["api"], call["request"], call["response"]["choices"][0]["message"]["content"]) == (
|
|
120
|
+
"chat", {"model": "gpt-x", "messages": ASK}, "Refund it.")
|
|
121
|
+
|
|
122
|
+
stream = client.chat.completions.create(model="gpt-x", messages=ASK, stream=True)
|
|
123
|
+
assert "".join(c.choices[0].delta.content or "" for c in stream) == "Refund it."
|
|
124
|
+
assert sousml.flush(3)
|
|
125
|
+
assert [e["choices"][0]["delta"].get("content") for e in sous.kept[1]["stream"]] == ["Refund", " it."]
|
|
126
|
+
|
|
127
|
+
copy = client.with_options(timeout=10)
|
|
128
|
+
copy.chat.completions.create(model="gpt-x", messages=ASK)
|
|
129
|
+
assert sousml.flush(3) and len(sous.kept) == 3
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def test_once_you_switch_sous_answers_and_your_model_takes_over_when_it_cant(monkeypatch):
|
|
133
|
+
sous = FakeSous(monkeypatch, "student")
|
|
134
|
+
sent, client = wrapped_openai(sous)
|
|
135
|
+
client.chat.completions.create(model="gpt-x", messages=ASK)
|
|
136
|
+
link = client.chat.completions.create.__sous__
|
|
137
|
+
wait_for(lambda: link.student)
|
|
138
|
+
reply = client.chat.completions.create(model="gpt-x", messages=ASK)
|
|
139
|
+
assert reply.model == "abcdef12"
|
|
140
|
+
assert sous.asked[-1] == ("/v1/chat/completions", {"model": "abcdef12", "messages": ASK})
|
|
141
|
+
sous.fail = True
|
|
142
|
+
assert sousml.flush(3)
|
|
143
|
+
before = (len(sent), len(sous.kept))
|
|
144
|
+
reply = client.chat.completions.create(model="gpt-x", messages=ASK)
|
|
145
|
+
assert reply.model == "gpt-x" and len(sent) == before[0] + 1
|
|
146
|
+
assert sousml.flush(3) and len(sous.kept) == before[1] + 1
|
|
147
|
+
|
|
148
|
+
sous = FakeSous(monkeypatch, "student")
|
|
149
|
+
_, only_learns = wrapped_openai(sous, route=False)
|
|
150
|
+
only_learns.chat.completions.create(model="gpt-x", messages=ASK)
|
|
151
|
+
time.sleep(0.05)
|
|
152
|
+
assert only_learns.chat.completions.create(model="gpt-x", messages=ASK).model == "gpt-x" and not sous.asked
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def test_once_you_switch_your_model_keeps_the_share_of_conversations_sous_learns_from(monkeypatch):
|
|
156
|
+
sous = FakeSous(monkeypatch, "student")
|
|
157
|
+
sous.share = 0.5
|
|
158
|
+
sent, client = wrapped_openai(sous)
|
|
159
|
+
asks = [[{"role": "user", "content": f"Order {n} never came."}] for n in range(40)]
|
|
160
|
+
for ask in asks:
|
|
161
|
+
client.chat.completions.create(model="gpt-x", messages=ask)
|
|
162
|
+
mine = [a for a in asks if any(s["messages"] == a for s in sent)]
|
|
163
|
+
assert 8 < len(mine) < 32 and len(sous.asked) == 40 - len(mine)
|
|
164
|
+
later = [*mine[0], {"role": "assistant", "content": "Sorry."}, {"role": "user", "content": "Any news?"}]
|
|
165
|
+
client.chat.completions.create(model="gpt-x", messages=later) # the rest of a conversation stays on its side
|
|
166
|
+
assert sent[-1]["messages"] == later
|
|
167
|
+
assert sousml.flush(3) and len(sous.kept) == len(mine) + 1
|
|
168
|
+
assert set(sous.learns) == {"1"}
|
|
169
|
+
|
|
170
|
+
sous.share = 0.0
|
|
171
|
+
link = client.chat.completions.create.__sous__
|
|
172
|
+
wait_for(lambda: link.answers(wait=False) and link.share == 0.0)
|
|
173
|
+
client.chat.completions.create(model="gpt-x", messages=mine[0])
|
|
174
|
+
assert sous.asked[-1][1]["messages"] == mine[0]
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def test_a_scripts_first_call_goes_to_the_model_you_switched_to(monkeypatch):
|
|
178
|
+
sous = FakeSous(monkeypatch, "student")
|
|
179
|
+
sent, client = wrapped_openai(sous)
|
|
180
|
+
assert client.chat.completions.create(model="gpt-x", messages=ASK).model == "abcdef12" and not sent
|
|
181
|
+
|
|
182
|
+
slow = FakeSous(monkeypatch, "student")
|
|
183
|
+
answer = slow.request
|
|
184
|
+
monkeypatch.setattr(_sender, "request", lambda *args, **kwargs: (time.sleep(1), answer(*args, **kwargs))[1])
|
|
185
|
+
monkeypatch.setattr(_wrap, "FIRST_CHECK_WAIT", 0.1)
|
|
186
|
+
monkeypatch.setattr(_wrap, "_links", {}) # a new process: clients wrapped in this one share what it knows
|
|
187
|
+
sent, late = wrapped_openai(slow)
|
|
188
|
+
started = time.monotonic()
|
|
189
|
+
assert late.chat.completions.create(model="gpt-x", messages=ASK).model == "gpt-x" # Sous is slow to say
|
|
190
|
+
assert time.monotonic() - started < 0.9 and len(sent) == 1
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def test_while_the_sous_model_starts_your_model_answers_until_sous_says_it_is_up(monkeypatch):
|
|
194
|
+
warned = []
|
|
195
|
+
monkeypatch.setattr(_wrap, "warn_once", lambda key, message: warned.append(message))
|
|
196
|
+
sous = FakeSous(monkeypatch, "student")
|
|
197
|
+
sent, client = wrapped_openai(sous)
|
|
198
|
+
client.chat.completions.create(model="gpt-x", messages=ASK)
|
|
199
|
+
link = client.chat.completions.create.__sous__
|
|
200
|
+
wait_for(lambda: link.student)
|
|
201
|
+
client.chat.completions.create(model="gpt-x", messages=ASK)
|
|
202
|
+
assert sous.own_model[-1] == "1" # Sous hears the app can answer for itself
|
|
203
|
+
|
|
204
|
+
sous.starting = 170
|
|
205
|
+
reply = client.chat.completions.create(model="gpt-x", messages=ASK)
|
|
206
|
+
assert reply.model == "gpt-x" and sent[-1]["model"] == "gpt-x"
|
|
207
|
+
assert warned[-1] == "Your Sous model abcdef12 is starting, which takes about 3 min. Your own model answers until it's up."
|
|
208
|
+
asked = len(sous.asked)
|
|
209
|
+
assert not link.answers() # nor asks Sous again before it said it would be up
|
|
210
|
+
assert client.chat.completions.create(model="gpt-x", messages=ASK).model == "gpt-x"
|
|
211
|
+
assert len(sous.asked) == asked
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def test_anthropic_calls_and_streams_are_kept_and_switch_too(monkeypatch):
|
|
215
|
+
sous = FakeSous(monkeypatch)
|
|
216
|
+
_, mock = transport(sous, MESSAGE, anthropic_sse())
|
|
217
|
+
client = sousml.Sous(anthropic.Anthropic(api_key="sk-ant", http_client=httpx2.Client(transport=mock)),
|
|
218
|
+
"abcdef12", api_key="hk_test", base_url="https://sous.test")
|
|
219
|
+
client.messages.create(model="claude-x", max_tokens=100, system="Sort it.", messages=ASK)
|
|
220
|
+
with client.messages.stream(model="claude-x", max_tokens=100, messages=ASK) as stream:
|
|
221
|
+
assert "".join(stream.text_stream) == "Refund it."
|
|
222
|
+
assert sousml.flush(3)
|
|
223
|
+
assert [c["api"] for c in sous.kept] == ["messages", "messages"]
|
|
224
|
+
assert sous.kept[0]["request"]["system"] == "Sort it." and sous.kept[1]["response"]["stop_reason"] == "end_turn"
|
|
225
|
+
|
|
226
|
+
sous.answered_by = "student"
|
|
227
|
+
link = client.messages.create.__sous__
|
|
228
|
+
wait_for(link.answers)
|
|
229
|
+
reply = client.messages.create(model="claude-x", max_tokens=100, messages=ASK)
|
|
230
|
+
assert reply.model == "abcdef12" and sous.asked[-1][0] == "/v1/messages"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
async def test_async_clients_are_kept_without_waiting(monkeypatch):
|
|
234
|
+
sous = FakeSous(monkeypatch)
|
|
235
|
+
_, mock = transport(sous, CHAT, sse(CHUNKS))
|
|
236
|
+
client = sousml.Sous(openai.AsyncOpenAI(api_key="sk-test", http_client=httpx2.AsyncClient(transport=mock)),
|
|
237
|
+
"abcdef12", api_key="hk_test", base_url="https://sous.test")
|
|
238
|
+
assert (await client.chat.completions.create(model="gpt-x", messages=ASK)).choices[0].message.content
|
|
239
|
+
stream = await client.chat.completions.create(model="gpt-x", messages=ASK, stream=True)
|
|
240
|
+
assert [c async for c in stream]
|
|
241
|
+
assert sousml.flush(3)
|
|
242
|
+
assert [("response" in c, "stream" in c) for c in sous.kept] == [(True, False), (False, True)]
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def test_wrapping_says_what_is_missing(monkeypatch):
|
|
246
|
+
for name in ("SOUS_API_KEY", "SOUS_MODEL", "HATCH_API_KEY", "HATCH_MODEL"):
|
|
247
|
+
monkeypatch.delenv(name, raising=False)
|
|
248
|
+
with pytest.raises(ValueError, match="SOUS_MODEL"):
|
|
249
|
+
sousml.Sous(openai.OpenAI(api_key="x"))
|
|
250
|
+
with pytest.raises(ValueError, match="SOUS_API_KEY"):
|
|
251
|
+
sousml.Sous(openai.OpenAI(api_key="x"), "abcdef12")
|
|
252
|
+
with pytest.raises(TypeError, match="OpenAI"):
|
|
253
|
+
sousml.Sous(object(), "abcdef12", api_key="hk_test")
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def test_the_names_from_before_the_rename_still_work(monkeypatch):
|
|
257
|
+
FakeSous(monkeypatch)
|
|
258
|
+
for name in ("SOUS_API_KEY", "SOUS_MODEL", "SOUS_BASE_URL"):
|
|
259
|
+
monkeypatch.delenv(name, raising=False)
|
|
260
|
+
monkeypatch.setenv("HATCH_MODEL", "abcdef12")
|
|
261
|
+
monkeypatch.setenv("HATCH_API_KEY", "hk_test")
|
|
262
|
+
monkeypatch.setenv("HATCH_BASE_URL", "https://sous.test/v1")
|
|
263
|
+
link = sousml.Hatch(openai.OpenAI(api_key="x")).chat.completions.create.__sous__
|
|
264
|
+
assert sousml.Hatch is sousml.Sous
|
|
265
|
+
assert (link.model, link.key, link.base) == ("abcdef12", "hk_test", "https://sous.test")
|