sentiogate-python 1.3.1__tar.gz → 1.3.3__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.3}/PKG-INFO +1 -1
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.3}/pyproject.toml +1 -1
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.3}/sentiogate/client.py +99 -18
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.3/sentiogate_python.egg-info}/PKG-INFO +1 -1
- sentiogate_python-1.3.3/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.3}/LICENSE +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.3}/MANIFEST.in +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.3}/README.md +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.3}/sentiogate/__init__.py +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.3}/sentiogate/py.typed +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.3}/sentiogate_python.egg-info/SOURCES.txt +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.3}/sentiogate_python.egg-info/dependency_links.txt +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.3}/sentiogate_python.egg-info/top_level.txt +0 -0
- {sentiogate_python-1.3.1 → sentiogate_python-1.3.3}/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.3"
|
|
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.3"
|
|
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.
|
|
@@ -210,21 +214,30 @@ class AutoRouterClient:
|
|
|
210
214
|
if difficulty is not None:
|
|
211
215
|
payload["difficulty"] = difficulty
|
|
212
216
|
if mode is not None:
|
|
213
|
-
payload["mode"] = mode
|
|
217
|
+
payload["mode"] = mode # legacy field, ignored by current gateway
|
|
218
|
+
payload.setdefault("route_preference", mode)
|
|
214
219
|
if constraints is not None:
|
|
215
220
|
payload["constraints"] = constraints
|
|
216
221
|
if plugins is not None:
|
|
217
222
|
payload["plugins"] = plugins
|
|
218
223
|
if router_metadata:
|
|
219
224
|
payload["router_metadata"] = True
|
|
225
|
+
if max_cost_usd is not None:
|
|
226
|
+
payload["max_cost_usd"] = max_cost_usd
|
|
227
|
+
if max_latency_ms is not None:
|
|
228
|
+
payload["max_latency_ms"] = max_latency_ms
|
|
229
|
+
if strict_cost:
|
|
230
|
+
payload["strict_cost"] = True
|
|
231
|
+
if tool_search is not None:
|
|
232
|
+
payload["tool_search"] = tool_search
|
|
220
233
|
if extra_body:
|
|
221
234
|
payload.update(extra_body)
|
|
222
235
|
|
|
223
236
|
extra_headers: dict[str, str] = {}
|
|
224
237
|
if router_metadata:
|
|
225
|
-
extra_headers["X-
|
|
238
|
+
extra_headers["X-SentioGate-Metadata"] = "enabled"
|
|
226
239
|
if cache_bypass:
|
|
227
|
-
extra_headers["X-Cache
|
|
240
|
+
extra_headers["X-SentioGate-Cache"] = "bypass"
|
|
228
241
|
if extra_body and (extra_body.get("allow_queue") or extra_body.get("allowQueue")):
|
|
229
242
|
extra_headers["X-SentioGate-Allow-Queue"] = "true"
|
|
230
243
|
|
|
@@ -277,6 +290,10 @@ class AutoRouterClient:
|
|
|
277
290
|
return err.response_body
|
|
278
291
|
err.args = (f"Enqueue batch failed ({exc.code}): {err.response_body}",)
|
|
279
292
|
raise err from None
|
|
293
|
+
except RouterClientError:
|
|
294
|
+
raise
|
|
295
|
+
except Exception as exc:
|
|
296
|
+
raise RouterClientError(f"Enqueue batch failed: {exc}") from exc
|
|
280
297
|
|
|
281
298
|
def poll_batch(self, job_id: str) -> dict[str, Any]:
|
|
282
299
|
"""Poll status and output of an enqueued batch job."""
|
|
@@ -290,6 +307,10 @@ class AutoRouterClient:
|
|
|
290
307
|
err = _http_error(exc, "Poll batch HTTP")
|
|
291
308
|
err.args = (f"Poll batch failed ({exc.code}): {err.response_body}",)
|
|
292
309
|
raise err from None
|
|
310
|
+
except RouterClientError:
|
|
311
|
+
raise
|
|
312
|
+
except Exception as exc:
|
|
313
|
+
raise RouterClientError(f"Poll batch failed: {exc}") from exc
|
|
293
314
|
|
|
294
315
|
def stream_chat(
|
|
295
316
|
self,
|
|
@@ -302,6 +323,10 @@ class AutoRouterClient:
|
|
|
302
323
|
constraints: dict[str, Any] | None = None,
|
|
303
324
|
plugins: list[dict[str, Any]] | None = None,
|
|
304
325
|
tier: str = "free",
|
|
326
|
+
max_cost_usd: float | None = None,
|
|
327
|
+
max_latency_ms: int | None = None,
|
|
328
|
+
strict_cost: bool = False,
|
|
329
|
+
tool_search: str | bool | None = None,
|
|
305
330
|
extra_body: dict[str, Any] | None = None,
|
|
306
331
|
) -> Iterator[dict[str, Any]]:
|
|
307
332
|
"""Stream chat completion chunks (SSE) from the router.
|
|
@@ -322,16 +347,28 @@ class AutoRouterClient:
|
|
|
322
347
|
if difficulty is not None:
|
|
323
348
|
payload["difficulty"] = difficulty
|
|
324
349
|
if mode is not None:
|
|
325
|
-
payload["mode"] = mode
|
|
350
|
+
payload["mode"] = mode # legacy field, ignored by current gateway
|
|
351
|
+
payload.setdefault("route_preference", mode)
|
|
326
352
|
if constraints is not None:
|
|
327
353
|
payload["constraints"] = constraints
|
|
328
354
|
if plugins is not None:
|
|
329
355
|
payload["plugins"] = plugins
|
|
356
|
+
if max_cost_usd is not None:
|
|
357
|
+
payload["max_cost_usd"] = max_cost_usd
|
|
358
|
+
if max_latency_ms is not None:
|
|
359
|
+
payload["max_latency_ms"] = max_latency_ms
|
|
360
|
+
if strict_cost:
|
|
361
|
+
payload["strict_cost"] = True
|
|
362
|
+
if tool_search is not None:
|
|
363
|
+
payload["tool_search"] = tool_search
|
|
330
364
|
if extra_body:
|
|
331
365
|
payload.update(extra_body)
|
|
332
366
|
|
|
333
367
|
data = json.dumps(payload).encode("utf-8")
|
|
334
|
-
|
|
368
|
+
extra_headers: dict[str, str] = {"Accept": "text/event-stream"}
|
|
369
|
+
if extra_body and (extra_body.get("allow_queue") or extra_body.get("allowQueue")):
|
|
370
|
+
extra_headers["X-SentioGate-Allow-Queue"] = "true"
|
|
371
|
+
req_headers = self._headers(extra_headers)
|
|
335
372
|
req = urllib.request.Request(url, data=data, headers=req_headers, method="POST")
|
|
336
373
|
|
|
337
374
|
attempt = 0
|
|
@@ -349,10 +386,29 @@ class AutoRouterClient:
|
|
|
349
386
|
break
|
|
350
387
|
try:
|
|
351
388
|
with resp_cm as resp:
|
|
389
|
+
ctype = ""
|
|
390
|
+
try:
|
|
391
|
+
ctype = resp.headers.get("Content-Type", "") or ""
|
|
392
|
+
except Exception:
|
|
393
|
+
pass
|
|
394
|
+
if getattr(resp, "status", 200) == 202 or (ctype and "text/event-stream" not in ctype.lower()):
|
|
395
|
+
raw = resp.read().decode("utf-8")
|
|
396
|
+
try:
|
|
397
|
+
yield json.loads(raw)
|
|
398
|
+
except json.JSONDecodeError:
|
|
399
|
+
if raw.lstrip().startswith("data:"):
|
|
400
|
+
for ln in raw.splitlines():
|
|
401
|
+
ln = ln.strip()
|
|
402
|
+
if ln.startswith("data:") and ln[5:].strip() not in ("", "[DONE]"):
|
|
403
|
+
try:
|
|
404
|
+
yield json.loads(ln[5:].strip())
|
|
405
|
+
except json.JSONDecodeError:
|
|
406
|
+
continue
|
|
407
|
+
return
|
|
352
408
|
for line in resp:
|
|
353
409
|
decoded = line.decode("utf-8").strip()
|
|
354
|
-
if decoded.startswith("data:
|
|
355
|
-
raw_data = decoded[
|
|
410
|
+
if decoded.startswith("data:"):
|
|
411
|
+
raw_data = decoded[5:].strip()
|
|
356
412
|
if raw_data == "[DONE]":
|
|
357
413
|
break
|
|
358
414
|
try:
|
|
@@ -367,24 +423,40 @@ class AutoRouterClient:
|
|
|
367
423
|
def report_outcome(
|
|
368
424
|
self,
|
|
369
425
|
request_id: str,
|
|
370
|
-
signals: dict[str, bool],
|
|
426
|
+
signals: dict[str, bool] | None = None,
|
|
371
427
|
provider: str | None = None,
|
|
372
428
|
task_class: str | None = None,
|
|
429
|
+
model: str | None = None,
|
|
430
|
+
success: bool | None = None,
|
|
431
|
+
score: float | None = None,
|
|
432
|
+
latency_ms: int | None = None,
|
|
373
433
|
) -> dict[str, Any]:
|
|
374
|
-
"""
|
|
434
|
+
"""Report an outcome. The gateway requires ``model`` (legacy ``provider`` accepted) and a boolean
|
|
435
|
+
``success`` (or numeric ``score``; legacy ``signals`` are folded into ``success``)."""
|
|
375
436
|
url = f"{self.base_url}/v1/outcomes"
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
"task_class"
|
|
381
|
-
|
|
437
|
+
if success is None and signals:
|
|
438
|
+
success = all(bool(v) for v in signals.values())
|
|
439
|
+
payload: dict[str, Any] = {"request_id": request_id, "model": model or provider}
|
|
440
|
+
if task_class is not None:
|
|
441
|
+
payload["task_class"] = task_class
|
|
442
|
+
if success is not None:
|
|
443
|
+
payload["success"] = bool(success)
|
|
444
|
+
if score is not None:
|
|
445
|
+
payload["score"] = score
|
|
446
|
+
if latency_ms is not None:
|
|
447
|
+
payload["latency_ms"] = latency_ms
|
|
448
|
+
if signals:
|
|
449
|
+
payload["signals"] = signals
|
|
450
|
+
if provider:
|
|
451
|
+
payload["provider"] = provider
|
|
382
452
|
data = json.dumps(payload).encode("utf-8")
|
|
383
453
|
req = urllib.request.Request(url, data=data, headers=self._headers(), method="POST")
|
|
384
454
|
|
|
385
455
|
try:
|
|
386
456
|
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
387
457
|
return json.loads(resp.read().decode("utf-8"))
|
|
458
|
+
except urllib.error.HTTPError as exc:
|
|
459
|
+
raise _http_error(exc, "Outcome report HTTP") from None
|
|
388
460
|
except Exception as exc:
|
|
389
461
|
raise RouterClientError(f"Failed to report outcome: {exc}") from exc
|
|
390
462
|
|
|
@@ -532,8 +604,17 @@ class AutoRouterClient:
|
|
|
532
604
|
except Exception as exc:
|
|
533
605
|
raise RouterClientError(f"Failed to redeem license: {exc}") from exc
|
|
534
606
|
|
|
535
|
-
def get_user_license(self, user_id: str =
|
|
536
|
-
"""Fetch active license voucher details
|
|
607
|
+
def get_user_license(self, user_id: str | None = None) -> dict[str, Any]:
|
|
608
|
+
"""Fetch active license voucher details (defaults to the signed-in user, resolved via /v1/auth/me)."""
|
|
609
|
+
if not user_id:
|
|
610
|
+
me_req = urllib.request.Request(f"{self.base_url}/v1/auth/me", headers=self._headers(), method="GET")
|
|
611
|
+
try:
|
|
612
|
+
with urllib.request.urlopen(me_req, timeout=self.timeout) as resp:
|
|
613
|
+
user_id = (json.loads(resp.read().decode("utf-8")).get("user") or {}).get("id")
|
|
614
|
+
except Exception as exc:
|
|
615
|
+
raise RouterClientError(f"Failed to fetch user license: {exc}") from exc
|
|
616
|
+
if not user_id:
|
|
617
|
+
raise RouterClientError("Failed to fetch user license: could not resolve current user id")
|
|
537
618
|
url = f"{self.base_url}/v1/licenses/user/{urllib.parse.quote(user_id, safe='')}"
|
|
538
619
|
req = urllib.request.Request(url, headers=self._headers(), method="GET")
|
|
539
620
|
try:
|
|
@@ -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.3}/sentiogate_python.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
{sentiogate_python-1.3.1 → sentiogate_python-1.3.3}/sentiogate_python.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|