sentiogate-python 1.3.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sentiogate-python
3
- Version: 1.3.0
3
+ Version: 1.3.2
4
4
  Summary: Thin, zero-dependency Python client for SentioGate intelligent LLM router
5
5
  Author-email: SentioGate Team <dev@sentiogate.app>
6
6
  License-Expression: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sentiogate-python"
7
- version = "1.3.0"
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"
@@ -9,6 +9,7 @@ from .client import (
9
9
  AutoRouterClient,
10
10
  RouterClientError,
11
11
  parse_retry_after,
12
+ validate_base_url,
12
13
  )
13
14
 
14
15
  __version__ = VERSION
@@ -20,4 +21,5 @@ __all__ = [
20
21
  "AutoRouterClient",
21
22
  "RouterClientError",
22
23
  "parse_retry_after",
24
+ "validate_base_url",
23
25
  ]
@@ -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.0"
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'})"
@@ -105,6 +105,17 @@ DEFAULT_BASE_URL = "https://api.sentiogate.dev"
105
105
  DEFAULT_TIMEOUT = 130.0
106
106
 
107
107
 
108
+ def validate_base_url(url: str | None) -> str:
109
+ """Validates and normalizes client base_url to ensure safe protocol scheme."""
110
+ target = (url or DEFAULT_BASE_URL).strip()
111
+ parsed = urllib.parse.urlsplit(target)
112
+ if parsed.scheme not in ("http", "https"):
113
+ raise ValueError(f"Invalid base_url scheme '{parsed.scheme}'. Only 'http' and 'https' are allowed.")
114
+ if not parsed.netloc:
115
+ raise ValueError(f"Invalid base_url '{target}': missing host.")
116
+ return target.rstrip("/")
117
+
118
+
108
119
  class AutoRouterClient:
109
120
  """Thin, zero-leak client SDK for connecting applications to SentioGate.
110
121
 
@@ -131,7 +142,7 @@ class AutoRouterClient:
131
142
  max_retry_wait: float = 60.0,
132
143
  user_agent: str | None = None,
133
144
  ) -> None:
134
- self.base_url = base_url.rstrip("/")
145
+ self.base_url = validate_base_url(base_url)
135
146
  self.api_key = api_key
136
147
  self.timeout = timeout
137
148
  self.max_retries = max(0, int(max_retries))
@@ -176,6 +187,10 @@ class AutoRouterClient:
176
187
  hedge_delay_ms: int | None = None, # deprecated no-op: ignored by the gateway
177
188
  cache: bool = False,
178
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,
179
194
  extra_body: dict[str, Any] | None = None,
180
195
  ) -> dict[str, Any]:
181
196
  """Send a chat completion request to the router.
@@ -206,6 +221,14 @@ class AutoRouterClient:
206
221
  payload["plugins"] = plugins
207
222
  if router_metadata:
208
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
209
232
  if extra_body:
210
233
  payload.update(extra_body)
211
234
 
@@ -291,6 +314,10 @@ class AutoRouterClient:
291
314
  constraints: dict[str, Any] | None = None,
292
315
  plugins: list[dict[str, Any]] | None = None,
293
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,
294
321
  extra_body: dict[str, Any] | None = None,
295
322
  ) -> Iterator[dict[str, Any]]:
296
323
  """Stream chat completion chunks (SSE) from the router.
@@ -316,6 +343,14 @@ class AutoRouterClient:
316
343
  payload["constraints"] = constraints
317
344
  if plugins is not None:
318
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
319
354
  if extra_body:
320
355
  payload.update(extra_body)
321
356
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sentiogate-python
3
- Version: 1.3.0
3
+ Version: 1.3.2
4
4
  Summary: Thin, zero-dependency Python client for SentioGate intelligent LLM router
5
5
  Author-email: SentioGate Team <dev@sentiogate.app>
6
6
  License-Expression: Apache-2.0
@@ -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,79 +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_internal_methods_removed(self):
35
- client = AutoRouterClient()
36
- for name in (
37
- "get_cluster_health",
38
- "broadcast_cluster_breaker",
39
- "get_edge_status",
40
- "verify_turnstile",
41
- "evaluate_decision",
42
- "get_evaluations",
43
- "fork_evaluation",
44
- ):
45
- self.assertFalse(hasattr(client, name), name)
46
-
47
- def test_clear_cache_is_caller_scoped(self):
48
- seen = []
49
-
50
- def fake_urlopen(req, timeout=None):
51
- seen.append((req.full_url, req.get_method()))
52
- return _Resp({"status": "cleared"})
53
-
54
- with mock.patch.object(urllib.request, "urlopen", fake_urlopen):
55
- AutoRouterClient(base_url="https://api.test.com").clear_cache()
56
- self.assertEqual(seen, [("https://api.test.com/v1/cache", "DELETE")])
57
- with self.assertRaises(TypeError):
58
- AutoRouterClient().clear_cache("someone_else")
59
-
60
- def test_chat_sends_auto_and_route_preference(self):
61
- sent = {}
62
-
63
- def fake_urlopen(req, timeout=None):
64
- sent.update(json.loads(req.data.decode("utf-8")))
65
- sent["_ua"] = req.get_header("User-agent")
66
- return _Resp({"choices": [{"message": {"content": "hi"}}]})
67
-
68
- with mock.patch.object(urllib.request, "urlopen", fake_urlopen):
69
- out = AutoRouterClient(base_url="https://api.test.com").chat(
70
- messages=[{"role": "user", "content": "x"}], extra_body={"route_preference": "latency"}
71
- )
72
- self.assertEqual(out["choices"][0]["message"]["content"], "hi")
73
- self.assertEqual(sent["model"], "auto")
74
- self.assertEqual(sent["route_preference"], "latency")
75
- self.assertTrue(sent["_ua"].startswith("sentiogate-python/"))
76
-
77
-
78
- if __name__ == "__main__":
79
- unittest.main()