sentiogate-python 1.3.1__tar.gz → 1.3.2__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.
- {sentiogate_python-1.3.1/sentiogate_python.egg-info → sentiogate_python-1.3.2}/PKG-INFO +1 -1
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/pyproject.toml +1 -1
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/sentiogate/client.py +25 -1
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.2/sentiogate_python.egg-info}/PKG-INFO +1 -1
- sentiogate_python-1.3.2/tests/test_client.py +208 -0
- sentiogate_python-1.3.1/tests/test_client.py +0 -87
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/LICENSE +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/MANIFEST.in +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/README.md +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/sentiogate/__init__.py +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/sentiogate/py.typed +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/sentiogate_python.egg-info/SOURCES.txt +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/sentiogate_python.egg-info/dependency_links.txt +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/sentiogate_python.egg-info/top_level.txt +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/setup.cfg +0 -0
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "sentiogate-python"
|
|
7
|
-
version = "1.3.
|
|
7
|
+
version = "1.3.2"
|
|
8
8
|
description = "Thin, zero-dependency Python client for SentioGate intelligent LLM router"
|
|
9
9
|
authors = [{name = "SentioGate Team", email = "dev@sentiogate.app"}]
|
|
10
10
|
readme = "README.md"
|
|
@@ -18,7 +18,7 @@ import urllib.request
|
|
|
18
18
|
from collections.abc import Callable, Iterator
|
|
19
19
|
from typing import Any
|
|
20
20
|
|
|
21
|
-
VERSION = "1.3.
|
|
21
|
+
VERSION = "1.3.2"
|
|
22
22
|
# Sent on every request: honest, names this SDK, its real version and the OS it runs on (never a browser string,
|
|
23
23
|
# never the default Python-urllib agent, which the gateway's bot check may refuse).
|
|
24
24
|
USER_AGENT = f"sentiogate-python/{VERSION} ({platform.system() or 'unknown'})"
|
|
@@ -187,6 +187,10 @@ class AutoRouterClient:
|
|
|
187
187
|
hedge_delay_ms: int | None = None, # deprecated no-op: ignored by the gateway
|
|
188
188
|
cache: bool = False,
|
|
189
189
|
cache_bypass: bool = False,
|
|
190
|
+
max_cost_usd: float | None = None,
|
|
191
|
+
max_latency_ms: int | None = None,
|
|
192
|
+
strict_cost: bool = False,
|
|
193
|
+
tool_search: str | bool | None = None,
|
|
190
194
|
extra_body: dict[str, Any] | None = None,
|
|
191
195
|
) -> dict[str, Any]:
|
|
192
196
|
"""Send a chat completion request to the router.
|
|
@@ -217,6 +221,14 @@ class AutoRouterClient:
|
|
|
217
221
|
payload["plugins"] = plugins
|
|
218
222
|
if router_metadata:
|
|
219
223
|
payload["router_metadata"] = True
|
|
224
|
+
if max_cost_usd is not None:
|
|
225
|
+
payload["max_cost_usd"] = max_cost_usd
|
|
226
|
+
if max_latency_ms is not None:
|
|
227
|
+
payload["max_latency_ms"] = max_latency_ms
|
|
228
|
+
if strict_cost:
|
|
229
|
+
payload["strict_cost"] = True
|
|
230
|
+
if tool_search is not None:
|
|
231
|
+
payload["tool_search"] = tool_search
|
|
220
232
|
if extra_body:
|
|
221
233
|
payload.update(extra_body)
|
|
222
234
|
|
|
@@ -302,6 +314,10 @@ class AutoRouterClient:
|
|
|
302
314
|
constraints: dict[str, Any] | None = None,
|
|
303
315
|
plugins: list[dict[str, Any]] | None = None,
|
|
304
316
|
tier: str = "free",
|
|
317
|
+
max_cost_usd: float | None = None,
|
|
318
|
+
max_latency_ms: int | None = None,
|
|
319
|
+
strict_cost: bool = False,
|
|
320
|
+
tool_search: str | bool | None = None,
|
|
305
321
|
extra_body: dict[str, Any] | None = None,
|
|
306
322
|
) -> Iterator[dict[str, Any]]:
|
|
307
323
|
"""Stream chat completion chunks (SSE) from the router.
|
|
@@ -327,6 +343,14 @@ class AutoRouterClient:
|
|
|
327
343
|
payload["constraints"] = constraints
|
|
328
344
|
if plugins is not None:
|
|
329
345
|
payload["plugins"] = plugins
|
|
346
|
+
if max_cost_usd is not None:
|
|
347
|
+
payload["max_cost_usd"] = max_cost_usd
|
|
348
|
+
if max_latency_ms is not None:
|
|
349
|
+
payload["max_latency_ms"] = max_latency_ms
|
|
350
|
+
if strict_cost:
|
|
351
|
+
payload["strict_cost"] = True
|
|
352
|
+
if tool_search is not None:
|
|
353
|
+
payload["tool_search"] = tool_search
|
|
330
354
|
if extra_body:
|
|
331
355
|
payload.update(extra_body)
|
|
332
356
|
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Stdlib-only unit tests: python -m unittest discover -s tests"""
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
import json
|
|
5
|
+
import unittest
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.request
|
|
8
|
+
from unittest import mock
|
|
9
|
+
|
|
10
|
+
import sentiogate
|
|
11
|
+
from sentiogate import AutoRouterClient, RouterClientError, VERSION, parse_retry_after
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _Resp:
|
|
15
|
+
def __init__(self, body, lines=None):
|
|
16
|
+
self._body = json.dumps(body).encode("utf-8") if body is not None else b""
|
|
17
|
+
self._lines = lines or []
|
|
18
|
+
|
|
19
|
+
def read(self):
|
|
20
|
+
return self._body
|
|
21
|
+
|
|
22
|
+
def __iter__(self):
|
|
23
|
+
return iter(self._lines)
|
|
24
|
+
|
|
25
|
+
def __enter__(self):
|
|
26
|
+
return self
|
|
27
|
+
|
|
28
|
+
def __exit__(self, *exc):
|
|
29
|
+
return False
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _http_err(code, reason, body_dict, headers=None):
|
|
33
|
+
raw = json.dumps(body_dict).encode("utf-8")
|
|
34
|
+
return urllib.error.HTTPError(
|
|
35
|
+
"https://api.test.com/v1/chat/completions",
|
|
36
|
+
code,
|
|
37
|
+
reason,
|
|
38
|
+
headers or {},
|
|
39
|
+
io.BytesIO(raw),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ClientTests(unittest.TestCase):
|
|
44
|
+
def test_version_and_user_agent(self):
|
|
45
|
+
self.assertEqual(sentiogate.__version__, VERSION)
|
|
46
|
+
self.assertTrue(sentiogate.USER_AGENT.startswith(f"sentiogate-python/{VERSION} ("))
|
|
47
|
+
|
|
48
|
+
def test_default_base_url(self):
|
|
49
|
+
self.assertEqual(AutoRouterClient().base_url, "https://api.sentiogate.dev")
|
|
50
|
+
|
|
51
|
+
def test_validate_base_url_scheme(self):
|
|
52
|
+
with self.assertRaises(ValueError):
|
|
53
|
+
AutoRouterClient(base_url="file:///etc/passwd")
|
|
54
|
+
with self.assertRaises(ValueError):
|
|
55
|
+
AutoRouterClient(base_url="ftp://evil.com")
|
|
56
|
+
with self.assertRaises(ValueError):
|
|
57
|
+
AutoRouterClient(base_url="not-a-url")
|
|
58
|
+
|
|
59
|
+
def test_internal_methods_removed(self):
|
|
60
|
+
client = AutoRouterClient()
|
|
61
|
+
for name in (
|
|
62
|
+
"get_cluster_health",
|
|
63
|
+
"broadcast_cluster_breaker",
|
|
64
|
+
"get_edge_status",
|
|
65
|
+
"verify_turnstile",
|
|
66
|
+
"evaluate_decision",
|
|
67
|
+
"get_evaluations",
|
|
68
|
+
"fork_evaluation",
|
|
69
|
+
):
|
|
70
|
+
self.assertFalse(hasattr(client, name), name)
|
|
71
|
+
|
|
72
|
+
def test_parse_retry_after(self):
|
|
73
|
+
self.assertIsNone(parse_retry_after(None))
|
|
74
|
+
self.assertIsNone(parse_retry_after(" "))
|
|
75
|
+
self.assertIsNone(parse_retry_after("not-a-date"))
|
|
76
|
+
self.assertEqual(parse_retry_after("5"), 5.0)
|
|
77
|
+
self.assertEqual(parse_retry_after("-2"), 0.0)
|
|
78
|
+
self.assertAlmostEqual(
|
|
79
|
+
parse_retry_after("Wed, 21 Oct 2015 07:28:10 GMT", now=1445412480.0),
|
|
80
|
+
10.0,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
def test_clear_cache_is_caller_scoped(self):
|
|
84
|
+
seen = []
|
|
85
|
+
|
|
86
|
+
def fake_urlopen(req, timeout=None):
|
|
87
|
+
seen.append((req.full_url, req.get_method()))
|
|
88
|
+
return _Resp({"status": "cleared"})
|
|
89
|
+
|
|
90
|
+
with mock.patch.object(urllib.request, "urlopen", fake_urlopen):
|
|
91
|
+
AutoRouterClient(base_url="https://api.test.com").clear_cache()
|
|
92
|
+
self.assertEqual(seen, [("https://api.test.com/v1/cache", "DELETE")])
|
|
93
|
+
with self.assertRaises(TypeError):
|
|
94
|
+
AutoRouterClient().clear_cache("someone_else")
|
|
95
|
+
|
|
96
|
+
def test_chat_sends_auto_and_route_preference(self):
|
|
97
|
+
sent = {}
|
|
98
|
+
|
|
99
|
+
def fake_urlopen(req, timeout=None):
|
|
100
|
+
sent.update(json.loads(req.data.decode("utf-8")))
|
|
101
|
+
sent["_ua"] = req.get_header("User-agent")
|
|
102
|
+
sent["_auth"] = req.get_header("Authorization")
|
|
103
|
+
return _Resp({"choices": [{"message": {"content": "hi"}}]})
|
|
104
|
+
|
|
105
|
+
with mock.patch.object(urllib.request, "urlopen", fake_urlopen):
|
|
106
|
+
out = AutoRouterClient(base_url="https://api.test.com", api_key="sg_live_abc").chat(
|
|
107
|
+
messages=[{"role": "user", "content": "x"}],
|
|
108
|
+
cache_bypass=True,
|
|
109
|
+
extra_body={"route_preference": "latency", "allow_queue": True},
|
|
110
|
+
)
|
|
111
|
+
self.assertEqual(out["choices"][0]["message"]["content"], "hi")
|
|
112
|
+
self.assertEqual(sent["model"], "auto")
|
|
113
|
+
self.assertEqual(sent["route_preference"], "latency")
|
|
114
|
+
self.assertEqual(sent["_auth"], "Bearer sg_live_abc")
|
|
115
|
+
self.assertTrue(sent["_ua"].startswith("sentiogate-python/"))
|
|
116
|
+
|
|
117
|
+
def test_chat_retries_transient_429_and_respects_non_retryable(self):
|
|
118
|
+
calls = {"n": 0}
|
|
119
|
+
sleeps = []
|
|
120
|
+
|
|
121
|
+
def fake_urlopen(req, timeout=None):
|
|
122
|
+
calls["n"] += 1
|
|
123
|
+
if calls["n"] == 1:
|
|
124
|
+
raise _http_err(
|
|
125
|
+
429,
|
|
126
|
+
"Too Many Requests",
|
|
127
|
+
{"error": {"code": "upstream_rate_limited", "type": "rate_limit_error", "message": "busy"}},
|
|
128
|
+
headers={"Retry-After": "2"},
|
|
129
|
+
)
|
|
130
|
+
return _Resp({"choices": [{"message": {"content": "recovered"}}]})
|
|
131
|
+
|
|
132
|
+
client = AutoRouterClient(base_url="https://api.test.com", max_retries=1)
|
|
133
|
+
client._sleep = sleeps.append
|
|
134
|
+
with mock.patch.object(urllib.request, "urlopen", fake_urlopen):
|
|
135
|
+
out = client.chat(messages=[{"role": "user", "content": "hi"}])
|
|
136
|
+
self.assertEqual(out["choices"][0]["message"]["content"], "recovered")
|
|
137
|
+
self.assertEqual(sleeps, [2.0])
|
|
138
|
+
|
|
139
|
+
# Non-retryable quota code should not retry even with Retry-After
|
|
140
|
+
def fail_quota(req, timeout=None):
|
|
141
|
+
raise _http_err(
|
|
142
|
+
429,
|
|
143
|
+
"Too Many Requests",
|
|
144
|
+
{"error": {"code": "community_pool_exhausted", "type": "rate_limit_error"}},
|
|
145
|
+
headers={"Retry-After": "5"},
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
with mock.patch.object(urllib.request, "urlopen", fail_quota):
|
|
149
|
+
with self.assertRaises(RouterClientError) as ctx:
|
|
150
|
+
client.chat(messages=[{"role": "user", "content": "hi"}])
|
|
151
|
+
self.assertFalse(ctx.exception.retryable)
|
|
152
|
+
self.assertEqual(ctx.exception.code, "community_pool_exhausted")
|
|
153
|
+
|
|
154
|
+
def test_stream_chat_parses_sse_and_skips_bad_lines(self):
|
|
155
|
+
sse_lines = [
|
|
156
|
+
b": heartbeat\n",
|
|
157
|
+
b'data: {"choices":[{"delta":{"content":"hello"}}]}\n',
|
|
158
|
+
b"data: {not-json}\n",
|
|
159
|
+
b'data: {"choices":[{"delta":{"content":" world"}}]}\n',
|
|
160
|
+
b"data: [DONE]\n",
|
|
161
|
+
]
|
|
162
|
+
|
|
163
|
+
def fake_urlopen(req, timeout=None):
|
|
164
|
+
return _Resp(None, lines=sse_lines)
|
|
165
|
+
|
|
166
|
+
with mock.patch.object(urllib.request, "urlopen", fake_urlopen):
|
|
167
|
+
chunks = list(
|
|
168
|
+
AutoRouterClient(base_url="https://api.test.com").stream_chat(
|
|
169
|
+
messages=[{"role": "user", "content": "hi"}]
|
|
170
|
+
)
|
|
171
|
+
)
|
|
172
|
+
self.assertEqual(len(chunks), 2)
|
|
173
|
+
self.assertEqual(chunks[0]["choices"][0]["delta"]["content"], "hello")
|
|
174
|
+
self.assertEqual(chunks[1]["choices"][0]["delta"]["content"], " world")
|
|
175
|
+
|
|
176
|
+
def test_batch_and_resource_endpoints(self):
|
|
177
|
+
seen = []
|
|
178
|
+
|
|
179
|
+
def fake_urlopen(req, timeout=None):
|
|
180
|
+
seen.append((req.get_method(), req.full_url))
|
|
181
|
+
if req.full_url.endswith("/v1/models"):
|
|
182
|
+
return _Resp({"data": [{"id": "auto"}]})
|
|
183
|
+
if req.full_url.endswith("/v1/benchmarks"):
|
|
184
|
+
return _Resp({"benchmarks": [{"provider": "openai"}]})
|
|
185
|
+
if req.full_url.endswith("/v1/custom-providers?user_id=u1"):
|
|
186
|
+
return _Resp({"data": [{"provider_id": "ollama"}]})
|
|
187
|
+
return _Resp({"ok": True})
|
|
188
|
+
|
|
189
|
+
c = AutoRouterClient(base_url="https://api.test.com")
|
|
190
|
+
with mock.patch.object(urllib.request, "urlopen", fake_urlopen):
|
|
191
|
+
c.enqueue_batch(messages=[{"role": "user", "content": "q"}])
|
|
192
|
+
c.poll_batch("/v1/batch/poll/job/with/slash")
|
|
193
|
+
models = c.list_models()
|
|
194
|
+
benches = c.get_benchmarks()
|
|
195
|
+
custom = c.list_custom_providers(user_id="u1")
|
|
196
|
+
c.delete_custom_provider("my/prov", user_id="u1")
|
|
197
|
+
c.get_cache_stats()
|
|
198
|
+
c.get_capacity_pool()
|
|
199
|
+
|
|
200
|
+
self.assertEqual(models, [{"id": "auto"}])
|
|
201
|
+
self.assertEqual(benches, [{"provider": "openai"}])
|
|
202
|
+
self.assertEqual(custom, [{"provider_id": "ollama"}])
|
|
203
|
+
self.assertIn(("GET", "https://api.test.com/v1/batch/poll/job%2Fwith%2Fslash"), seen)
|
|
204
|
+
self.assertIn(("DELETE", "https://api.test.com/v1/custom-providers/my%2Fprov?user_id=u1"), seen)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
if __name__ == "__main__":
|
|
208
|
+
unittest.main()
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
"""Stdlib-only unit tests: python -m unittest discover -s tests"""
|
|
2
|
-
|
|
3
|
-
import json
|
|
4
|
-
import unittest
|
|
5
|
-
import urllib.request
|
|
6
|
-
from unittest import mock
|
|
7
|
-
|
|
8
|
-
import sentiogate
|
|
9
|
-
from sentiogate import AutoRouterClient, VERSION
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
class _Resp:
|
|
13
|
-
def __init__(self, body):
|
|
14
|
-
self._body = json.dumps(body).encode("utf-8")
|
|
15
|
-
|
|
16
|
-
def read(self):
|
|
17
|
-
return self._body
|
|
18
|
-
|
|
19
|
-
def __enter__(self):
|
|
20
|
-
return self
|
|
21
|
-
|
|
22
|
-
def __exit__(self, *exc):
|
|
23
|
-
return False
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
class ClientTests(unittest.TestCase):
|
|
27
|
-
def test_version_and_user_agent(self):
|
|
28
|
-
self.assertEqual(sentiogate.__version__, VERSION)
|
|
29
|
-
self.assertTrue(sentiogate.USER_AGENT.startswith(f"sentiogate-python/{VERSION} ("))
|
|
30
|
-
|
|
31
|
-
def test_default_base_url(self):
|
|
32
|
-
self.assertEqual(AutoRouterClient().base_url, "https://api.sentiogate.dev")
|
|
33
|
-
|
|
34
|
-
def test_validate_base_url_scheme(self):
|
|
35
|
-
with self.assertRaises(ValueError):
|
|
36
|
-
AutoRouterClient(base_url="file:///etc/passwd")
|
|
37
|
-
with self.assertRaises(ValueError):
|
|
38
|
-
AutoRouterClient(base_url="ftp://evil.com")
|
|
39
|
-
with self.assertRaises(ValueError):
|
|
40
|
-
AutoRouterClient(base_url="not-a-url")
|
|
41
|
-
|
|
42
|
-
def test_internal_methods_removed(self):
|
|
43
|
-
client = AutoRouterClient()
|
|
44
|
-
for name in (
|
|
45
|
-
"get_cluster_health",
|
|
46
|
-
"broadcast_cluster_breaker",
|
|
47
|
-
"get_edge_status",
|
|
48
|
-
"verify_turnstile",
|
|
49
|
-
"evaluate_decision",
|
|
50
|
-
"get_evaluations",
|
|
51
|
-
"fork_evaluation",
|
|
52
|
-
):
|
|
53
|
-
self.assertFalse(hasattr(client, name), name)
|
|
54
|
-
|
|
55
|
-
def test_clear_cache_is_caller_scoped(self):
|
|
56
|
-
seen = []
|
|
57
|
-
|
|
58
|
-
def fake_urlopen(req, timeout=None):
|
|
59
|
-
seen.append((req.full_url, req.get_method()))
|
|
60
|
-
return _Resp({"status": "cleared"})
|
|
61
|
-
|
|
62
|
-
with mock.patch.object(urllib.request, "urlopen", fake_urlopen):
|
|
63
|
-
AutoRouterClient(base_url="https://api.test.com").clear_cache()
|
|
64
|
-
self.assertEqual(seen, [("https://api.test.com/v1/cache", "DELETE")])
|
|
65
|
-
with self.assertRaises(TypeError):
|
|
66
|
-
AutoRouterClient().clear_cache("someone_else")
|
|
67
|
-
|
|
68
|
-
def test_chat_sends_auto_and_route_preference(self):
|
|
69
|
-
sent = {}
|
|
70
|
-
|
|
71
|
-
def fake_urlopen(req, timeout=None):
|
|
72
|
-
sent.update(json.loads(req.data.decode("utf-8")))
|
|
73
|
-
sent["_ua"] = req.get_header("User-agent")
|
|
74
|
-
return _Resp({"choices": [{"message": {"content": "hi"}}]})
|
|
75
|
-
|
|
76
|
-
with mock.patch.object(urllib.request, "urlopen", fake_urlopen):
|
|
77
|
-
out = AutoRouterClient(base_url="https://api.test.com").chat(
|
|
78
|
-
messages=[{"role": "user", "content": "x"}], extra_body={"route_preference": "latency"}
|
|
79
|
-
)
|
|
80
|
-
self.assertEqual(out["choices"][0]["message"]["content"], "hi")
|
|
81
|
-
self.assertEqual(sent["model"], "auto")
|
|
82
|
-
self.assertEqual(sent["route_preference"], "latency")
|
|
83
|
-
self.assertTrue(sent["_ua"].startswith("sentiogate-python/"))
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
if __name__ == "__main__":
|
|
87
|
-
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/sentiogate_python.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
{sentiogate_python-1.3.1 → sentiogate_python-1.3.2}/sentiogate_python.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|