sentiogate-python 1.2.1__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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: sentiogate-python
3
+ Version: 1.2.1
4
+ Summary: Thin, zero-dependency Python client for SentioGate intelligent LLM router
5
+ Author-email: SentioGate Team <dev@sentiogate.app>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://sentiogate.app
8
+ Project-URL: Documentation, https://sentiogate.app/docs
9
+ Project-URL: Repository, https://github.com/SentioGate/sentiogate-python
10
+ Project-URL: Issues, https://github.com/SentioGate/sentiogate-python/issues
11
+ Project-URL: Benchmarks, https://sentiogate.app/benchmarks
12
+ Keywords: llm,ai,router,gateway,byok,openai,anthropic,gemini,groq,deepseek
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Requires-Python: >=3.8
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Dynamic: license-file
28
+
29
+ # SentioGate Python SDK (`sentiogate`)
30
+
31
+ [![PyPI version](https://img.shields.io/pypi/v/sentiogate?style=for-the-badge&color=3775a9&logo=pypi&logoColor=white)](https://pypi.org/project/sentiogate/)
32
+ [![Python versions](https://img.shields.io/pypi/pyversions/sentiogate?style=for-the-badge&logo=python&logoColor=white)](https://pypi.org/project/sentiogate/)
33
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg?style=for-the-badge)](https://opensource.org/licenses/Apache-2.0)
34
+ [![Website](https://img.shields.io/badge/Website-sentiogate.app-2563eb?style=for-the-badge&logo=google-chrome&logoColor=white)](https://sentiogate.app)
35
+ [![Live Benchmarks](https://img.shields.io/badge/Benchmarks-Live_Latency-7c3aed?style=for-the-badge&logo=speedtest&logoColor=white)](https://sentiogate.app/benchmarks)
36
+
37
+ Thin, zero-dependency Python client for [SentioGate](https://sentiogate.app) — the zero-markup AI LLM router offering intelligent latency-based routing, instant failover, and strict BYOK privacy.
38
+
39
+ * 🐍 **PyPI Package**: [`https://pypi.org/project/sentiogate/`](https://pypi.org/project/sentiogate/)
40
+ * 📦 **TypeScript SDK (NPM)**: [`https://www.npmjs.com/package/@sentiogate/sdk`](https://www.npmjs.com/package/@sentiogate/sdk)
41
+ * 🌐 **Developer Hub & Simulator**: [`https://sentiogate.github.io`](https://sentiogate.github.io)
42
+
43
+ ---
44
+
45
+ ## ⚡ Installation
46
+
47
+ ```bash
48
+ pip install sentiogate
49
+ ```
50
+
51
+ *(Zero external dependencies: uses Python standard library for maximum reliability and minimal container footprint).*
52
+
53
+ ---
54
+
55
+ ## 🚀 Quickstart
56
+
57
+ ```python
58
+ import os
59
+ from sentiogate import AutoRouterClient
60
+
61
+ client = AutoRouterClient(
62
+ api_key=os.environ.get("SENTIOGATE_API_KEY"),
63
+ )
64
+
65
+ response = client.create_chat_completion(
66
+ model="auto:fastest", # Intelligently selects lowest TTFT model replica
67
+ messages=[
68
+ {"role": "system", "content": "You are a helpful software architect."},
69
+ {"role": "user", "content": "What is the difference between gRPC and REST?"}
70
+ ]
71
+ )
72
+
73
+ print(response["choices"][0]["message"]["content"])
74
+ ```
75
+
76
+ ---
77
+
78
+ ## 🌊 Streaming Completions
79
+
80
+ ```python
81
+ import os
82
+ from sentiogate import AutoRouterClient
83
+
84
+ client = AutoRouterClient(api_key=os.environ.get("SENTIOGATE_API_KEY"))
85
+
86
+ for chunk in client.stream_chat_completion(
87
+ model="auto:cost-efficient",
88
+ messages=[{"role": "user", "content": "Write a binary search in Python."}],
89
+ ):
90
+ delta = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
91
+ print(delta, end="", flush=True)
92
+ print()
93
+ ```
94
+
95
+ ---
96
+
97
+ ## 🔗 Useful Links
98
+
99
+ * 🏠 [SentioGate Official Site](https://sentiogate.app)
100
+ * 📖 [API Documentation & Guides](https://sentiogate.app/docs)
101
+ * 📊 [Live Latency Benchmarks](https://sentiogate.app/benchmarks)
102
+ * ⚖️ [Comparison: SentioGate vs OpenRouter & LiteLLM](https://sentiogate.app/compare)
103
+ * 📦 [NPM Package (@sentiogate/sdk)](https://www.npmjs.com/package/@sentiogate/sdk)
104
+ * 🌐 [Developer Hub](https://sentiogate.github.io)
@@ -0,0 +1,76 @@
1
+ # SentioGate Python SDK (`sentiogate`)
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/sentiogate?style=for-the-badge&color=3775a9&logo=pypi&logoColor=white)](https://pypi.org/project/sentiogate/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/sentiogate?style=for-the-badge&logo=python&logoColor=white)](https://pypi.org/project/sentiogate/)
5
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg?style=for-the-badge)](https://opensource.org/licenses/Apache-2.0)
6
+ [![Website](https://img.shields.io/badge/Website-sentiogate.app-2563eb?style=for-the-badge&logo=google-chrome&logoColor=white)](https://sentiogate.app)
7
+ [![Live Benchmarks](https://img.shields.io/badge/Benchmarks-Live_Latency-7c3aed?style=for-the-badge&logo=speedtest&logoColor=white)](https://sentiogate.app/benchmarks)
8
+
9
+ Thin, zero-dependency Python client for [SentioGate](https://sentiogate.app) — the zero-markup AI LLM router offering intelligent latency-based routing, instant failover, and strict BYOK privacy.
10
+
11
+ * 🐍 **PyPI Package**: [`https://pypi.org/project/sentiogate/`](https://pypi.org/project/sentiogate/)
12
+ * 📦 **TypeScript SDK (NPM)**: [`https://www.npmjs.com/package/@sentiogate/sdk`](https://www.npmjs.com/package/@sentiogate/sdk)
13
+ * 🌐 **Developer Hub & Simulator**: [`https://sentiogate.github.io`](https://sentiogate.github.io)
14
+
15
+ ---
16
+
17
+ ## ⚡ Installation
18
+
19
+ ```bash
20
+ pip install sentiogate
21
+ ```
22
+
23
+ *(Zero external dependencies: uses Python standard library for maximum reliability and minimal container footprint).*
24
+
25
+ ---
26
+
27
+ ## 🚀 Quickstart
28
+
29
+ ```python
30
+ import os
31
+ from sentiogate import AutoRouterClient
32
+
33
+ client = AutoRouterClient(
34
+ api_key=os.environ.get("SENTIOGATE_API_KEY"),
35
+ )
36
+
37
+ response = client.create_chat_completion(
38
+ model="auto:fastest", # Intelligently selects lowest TTFT model replica
39
+ messages=[
40
+ {"role": "system", "content": "You are a helpful software architect."},
41
+ {"role": "user", "content": "What is the difference between gRPC and REST?"}
42
+ ]
43
+ )
44
+
45
+ print(response["choices"][0]["message"]["content"])
46
+ ```
47
+
48
+ ---
49
+
50
+ ## 🌊 Streaming Completions
51
+
52
+ ```python
53
+ import os
54
+ from sentiogate import AutoRouterClient
55
+
56
+ client = AutoRouterClient(api_key=os.environ.get("SENTIOGATE_API_KEY"))
57
+
58
+ for chunk in client.stream_chat_completion(
59
+ model="auto:cost-efficient",
60
+ messages=[{"role": "user", "content": "Write a binary search in Python."}],
61
+ ):
62
+ delta = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
63
+ print(delta, end="", flush=True)
64
+ print()
65
+ ```
66
+
67
+ ---
68
+
69
+ ## 🔗 Useful Links
70
+
71
+ * 🏠 [SentioGate Official Site](https://sentiogate.app)
72
+ * 📖 [API Documentation & Guides](https://sentiogate.app/docs)
73
+ * 📊 [Live Latency Benchmarks](https://sentiogate.app/benchmarks)
74
+ * ⚖️ [Comparison: SentioGate vs OpenRouter & LiteLLM](https://sentiogate.app/compare)
75
+ * 📦 [NPM Package (@sentiogate/sdk)](https://www.npmjs.com/package/@sentiogate/sdk)
76
+ * 🌐 [Developer Hub](https://sentiogate.github.io)
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sentiogate-python"
7
+ version = "1.2.1"
8
+ description = "Thin, zero-dependency Python client for SentioGate intelligent LLM router"
9
+ authors = [{name = "SentioGate Team", email = "dev@sentiogate.app"}]
10
+ readme = "README.md"
11
+ requires-python = ">=3.8"
12
+ license = "Apache-2.0"
13
+ license-files = ["LICENSE"]
14
+ keywords = ["llm", "ai", "router", "gateway", "byok", "openai", "anthropic", "gemini", "groq", "deepseek"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.8",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Topic :: Software Development :: Libraries :: Python Modules",
27
+ ]
28
+ dependencies = []
29
+
30
+ [project.urls]
31
+ Homepage = "https://sentiogate.app"
32
+ Documentation = "https://sentiogate.app/docs"
33
+ Repository = "https://github.com/SentioGate/sentiogate-python"
34
+ Issues = "https://github.com/SentioGate/sentiogate-python/issues"
35
+ Benchmarks = "https://sentiogate.app/benchmarks"
36
+
37
+ [tool.setuptools.packages.find]
38
+ where = ["."]
39
+ include = ["sentiogate*"]
40
+
41
+ [tool.setuptools.package-data]
42
+ sentiogate = ["py.typed"]
@@ -0,0 +1,23 @@
1
+ """AI Auto Router Python Thin Client SDK."""
2
+
3
+ from .client import (
4
+ DEFAULT_BASE_URL,
5
+ DEFAULT_TIMEOUT,
6
+ RETRYABLE_CODES,
7
+ USER_AGENT,
8
+ VERSION,
9
+ AutoRouterClient,
10
+ RouterClientError,
11
+ parse_retry_after,
12
+ )
13
+
14
+ __version__ = VERSION
15
+ __all__ = [
16
+ "DEFAULT_BASE_URL",
17
+ "DEFAULT_TIMEOUT",
18
+ "RETRYABLE_CODES",
19
+ "USER_AGENT",
20
+ "AutoRouterClient",
21
+ "RouterClientError",
22
+ "parse_retry_after",
23
+ ]
@@ -0,0 +1,638 @@
1
+ """AI Auto Router Client SDK.
2
+
3
+ Zero-inference-markup client for the AI Auto Router BYOK service.
4
+ Supports sync and streaming chat completions, model listing, provider health,
5
+ and cache operations. Outcome reporting, decisions, evaluations, session compaction and cluster
6
+ helpers are kept for compatibility only: the hosted gateway answers them with
7
+ ``{"accepted": false, "status": "not_implemented"}`` and stores nothing.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import email.utils
13
+ import json
14
+ import platform
15
+ import time
16
+ import urllib.error
17
+ import urllib.parse
18
+ import urllib.request
19
+ from collections.abc import Callable, Iterator
20
+ from typing import Any
21
+
22
+ VERSION = "1.2.1"
23
+ # Sent on every request: honest, names this SDK, its real version and the OS it runs on (never a browser string,
24
+ # never Python-urllib, which Cloudflare's browser integrity check refuses with error 1010).
25
+ USER_AGENT = f"SentioGate-Python/{VERSION} ({platform.system() or 'unknown'})"
26
+
27
+ # 429 codes that are worth retrying after the server's Retry-After (community-pool cooldown, per-key rate
28
+ # limit, upstream circuit). Quota codes such as community_pool_exhausted or monthly_request_limit are not.
29
+ RETRYABLE_CODES = frozenset({"upstream_rate_limited", "rate_limited", "upstream_circuit_open"})
30
+
31
+
32
+ def parse_retry_after(value: str | None, now: float | None = None) -> float | None:
33
+ """Retry-After header -> seconds (delta-seconds or HTTP-date), or None when absent / unparseable."""
34
+ if value is None or not str(value).strip():
35
+ return None
36
+ v = str(value).strip()
37
+ try:
38
+ return max(0.0, float(v))
39
+ except ValueError:
40
+ pass
41
+ try:
42
+ when = email.utils.parsedate_to_datetime(v)
43
+ except (TypeError, ValueError, IndexError):
44
+ return None
45
+ if when is None:
46
+ return None
47
+ return max(0.0, when.timestamp() - (time.time() if now is None else now))
48
+
49
+
50
+ class RouterClientError(Exception):
51
+ """Raised when the router returns an error or fails communication.
52
+
53
+ ``code`` / ``error_type`` come from the JSON error body (e.g. ``upstream_rate_limited`` /
54
+ ``rate_limit_error``); ``retry_after`` is the server's Retry-After in seconds, when sent.
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ message: str,
60
+ status_code: int | None = None,
61
+ response_body: Any = None,
62
+ code: str | None = None,
63
+ error_type: str | None = None,
64
+ retry_after: float | None = None,
65
+ ) -> None:
66
+ super().__init__(message)
67
+ self.status_code = status_code
68
+ self.response_body = response_body
69
+ self.code = code
70
+ self.error_type = error_type
71
+ self.retry_after = retry_after
72
+
73
+ @property
74
+ def retryable(self) -> bool:
75
+ """True for a 429 the server asked us to retry later (Retry-After present, transient code)."""
76
+ return self.status_code == 429 and self.retry_after is not None and (self.code in RETRYABLE_CODES)
77
+
78
+
79
+ def _http_error(exc: urllib.error.HTTPError, prefix: str) -> RouterClientError:
80
+ try:
81
+ body_str = exc.read().decode("utf-8", errors="replace")
82
+ except Exception:
83
+ body_str = ""
84
+ try:
85
+ parsed: Any = json.loads(body_str)
86
+ except Exception:
87
+ parsed = body_str
88
+ err = parsed.get("error") if isinstance(parsed, dict) else None
89
+ err = err if isinstance(err, dict) else {}
90
+ server_msg = err.get("message") or (parsed.get("detail") if isinstance(parsed, dict) else None)
91
+ message = f"{prefix} {exc.code}: {exc.reason}" + (f" - {server_msg}" if isinstance(server_msg, str) else "")
92
+ headers = getattr(exc, "headers", None)
93
+ return RouterClientError(
94
+ message,
95
+ status_code=exc.code,
96
+ response_body=parsed,
97
+ code=err.get("code"),
98
+ error_type=err.get("type"),
99
+ retry_after=parse_retry_after(headers.get("Retry-After") if headers is not None else None),
100
+ )
101
+
102
+
103
+ # Production SentioGate API (DEC-043). Host only: the client appends /v1/... itself.
104
+ DEFAULT_BASE_URL = "https://api.sentiogate.dev"
105
+ # Default request timeout (seconds): above the server's 120 s single-attempt deadline for community-pool calls.
106
+ DEFAULT_TIMEOUT = 130.0
107
+
108
+
109
+ class AutoRouterClient:
110
+ """Thin, zero-leak client SDK for connecting applications to AI Auto Router.
111
+
112
+ Retries are off by default (``max_retries=0``): a 429 raises ``RouterClientError`` with ``code`` and
113
+ ``retry_after`` set. With ``max_retries > 0`` the client waits the server's Retry-After and tries again,
114
+ only for transient 429 codes, never without a Retry-After, and never when the wait is longer than
115
+ ``max_retry_wait`` seconds (the community pool can ask for up to 15 minutes).
116
+
117
+ Example:
118
+ >>> client = AutoRouterClient(api_key="sg_live_...") # https://api.sentiogate.dev
119
+ >>> resp = client.chat(
120
+ ... messages=[{"role": "user", "content": "Hello"}],
121
+ ... provider_keys={"openai": "sk-..."}
122
+ ... )
123
+ >>> print(resp["choices"][0]["message"]["content"])
124
+ """
125
+
126
+ def __init__(
127
+ self,
128
+ base_url: str = DEFAULT_BASE_URL,
129
+ api_key: str | None = None,
130
+ timeout: float = DEFAULT_TIMEOUT,
131
+ max_retries: int = 0,
132
+ max_retry_wait: float = 60.0,
133
+ user_agent: str | None = None,
134
+ ) -> None:
135
+ self.base_url = base_url.rstrip("/")
136
+ self.api_key = api_key
137
+ self.timeout = timeout
138
+ self.max_retries = max(0, int(max_retries))
139
+ self.max_retry_wait = float(max_retry_wait)
140
+ self.user_agent = user_agent or USER_AGENT
141
+ self._sleep: Callable[[float], None] = time.sleep
142
+
143
+ def _headers(self, custom: dict[str, str] | None = None) -> dict[str, str]:
144
+ headers = {
145
+ "Content-Type": "application/json",
146
+ "Accept": "application/json",
147
+ "User-Agent": self.user_agent,
148
+ }
149
+ if self.api_key:
150
+ headers["Authorization"] = f"Bearer {self.api_key}"
151
+ if custom:
152
+ headers.update(custom)
153
+ return headers
154
+
155
+ def _should_retry(self, err: RouterClientError, attempt: int) -> bool:
156
+ if not err.retryable or attempt >= self.max_retries:
157
+ return False
158
+ wait = float(err.retry_after or 0)
159
+ if wait > self.max_retry_wait:
160
+ return False
161
+ self._sleep(max(1.0, wait)) # never a hot loop: at least 1 s, and only what the server asked for
162
+ return True
163
+
164
+ def chat(
165
+ self,
166
+ messages: list[dict[str, Any]],
167
+ model: str = "auto",
168
+ provider_keys: dict[str, str] | None = None,
169
+ user_id: str = "default_user",
170
+ difficulty: float | None = None,
171
+ mode: str | None = None,
172
+ constraints: dict[str, Any] | None = None,
173
+ plugins: list[dict[str, Any]] | None = None,
174
+ router_metadata: bool = True,
175
+ tier: str = "free",
176
+ hedging_mode: str | None = None, # deprecated no-op: ignored by the gateway
177
+ hedge_delay_ms: int | None = None, # deprecated no-op: ignored by the gateway
178
+ cache: bool = False,
179
+ cache_bypass: bool = False,
180
+ extra_body: dict[str, Any] | None = None,
181
+ ) -> dict[str, Any]:
182
+ """Send a chat completion request to the router.
183
+
184
+ ``hedging_mode`` and ``hedge_delay_ms`` are deprecated and ignored: providers are tried one at a
185
+ time with fallback. They are still forwarded so existing callers keep working.
186
+ """
187
+ url = f"{self.base_url}/v1/chat/completions"
188
+ payload: dict[str, Any] = {
189
+ "model": model,
190
+ "messages": messages,
191
+ "user_id": user_id,
192
+ "provider_keys": provider_keys or {},
193
+ "tier": tier,
194
+ "cache": cache,
195
+ }
196
+ if hedging_mode is not None:
197
+ payload["hedging_mode"] = hedging_mode
198
+ if hedge_delay_ms is not None:
199
+ payload["hedge_delay_ms"] = hedge_delay_ms
200
+ if difficulty is not None:
201
+ payload["difficulty"] = difficulty
202
+ if mode is not None:
203
+ payload["mode"] = mode
204
+ if constraints is not None:
205
+ payload["constraints"] = constraints
206
+ if plugins is not None:
207
+ payload["plugins"] = plugins
208
+ if router_metadata:
209
+ payload["router_metadata"] = True
210
+ if extra_body:
211
+ payload.update(extra_body)
212
+
213
+ extra_headers: dict[str, str] = {}
214
+ if router_metadata:
215
+ extra_headers["X-Router-Metadata"] = "enabled"
216
+ if cache_bypass:
217
+ extra_headers["X-Cache-Bypass"] = "true"
218
+ if extra_body and (extra_body.get("allow_queue") or extra_body.get("allowQueue")):
219
+ extra_headers["X-SentioGate-Allow-Queue"] = "true"
220
+
221
+ data = json.dumps(payload).encode("utf-8")
222
+ req_headers = self._headers(extra_headers if extra_headers else None)
223
+ req = urllib.request.Request(url, data=data, headers=req_headers, method="POST")
224
+
225
+ attempt = 0
226
+ while True:
227
+ try:
228
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
229
+ resp_bytes = resp.read()
230
+ return json.loads(resp_bytes.decode("utf-8"))
231
+ except urllib.error.HTTPError as exc:
232
+ err = _http_error(exc, "Router HTTP")
233
+ if exc.code == 202 and isinstance(err.response_body, dict):
234
+ return err.response_body
235
+ if self._should_retry(err, attempt):
236
+ attempt += 1
237
+ continue
238
+ raise err from None
239
+ except Exception as exc:
240
+ raise RouterClientError(f"Router request failed: {exc}") from exc
241
+
242
+ def enqueue_batch(
243
+ self,
244
+ messages: list[dict[str, Any]] | None = None,
245
+ item_text: str | None = None,
246
+ model: str = "sentiogate-community",
247
+ extra: dict[str, Any] | None = None,
248
+ ) -> dict[str, Any]:
249
+ """Enqueue an asynchronous batch inference task."""
250
+ url = f"{self.base_url}/v1/batch/enqueue"
251
+ payload: dict[str, Any] = {"model": model}
252
+ if messages is not None:
253
+ payload["messages"] = messages
254
+ if item_text is not None:
255
+ payload["item_text"] = item_text
256
+ if extra:
257
+ payload.update(extra)
258
+
259
+ data = json.dumps(payload).encode("utf-8")
260
+ req = urllib.request.Request(url, data=data, headers=self._headers(), method="POST")
261
+ try:
262
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
263
+ return json.loads(resp.read().decode("utf-8"))
264
+ except urllib.error.HTTPError as exc:
265
+ err = _http_error(exc, "Enqueue batch HTTP")
266
+ if exc.code == 202 and isinstance(err.response_body, dict):
267
+ return err.response_body
268
+ err.args = (f"Enqueue batch failed ({exc.code}): {err.response_body}",)
269
+ raise err from None
270
+
271
+ def poll_batch(self, job_id: str) -> dict[str, Any]:
272
+ """Poll status and output of an enqueued batch job."""
273
+ clean_id = job_id.replace("/api/batch/poll/", "").replace("/v1/batch/poll/", "")
274
+ url = f"{self.base_url}/v1/batch/poll/{urllib.parse.quote(clean_id, safe='')}"
275
+ req = urllib.request.Request(url, headers=self._headers(), method="GET")
276
+ try:
277
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
278
+ return json.loads(resp.read().decode("utf-8"))
279
+ except urllib.error.HTTPError as exc:
280
+ err = _http_error(exc, "Poll batch HTTP")
281
+ err.args = (f"Poll batch failed ({exc.code}): {err.response_body}",)
282
+ raise err from None
283
+
284
+ def stream_chat(
285
+ self,
286
+ messages: list[dict[str, Any]],
287
+ model: str = "auto",
288
+ provider_keys: dict[str, str] | None = None,
289
+ user_id: str = "default_user",
290
+ difficulty: float | None = None,
291
+ mode: str | None = None,
292
+ constraints: dict[str, Any] | None = None,
293
+ plugins: list[dict[str, Any]] | None = None,
294
+ tier: str = "free",
295
+ extra_body: dict[str, Any] | None = None,
296
+ ) -> Iterator[dict[str, Any]]:
297
+ """Stream chat completion chunks (SSE) from the router.
298
+
299
+ Errors (429 ``upstream_rate_limited`` with Retry-After, 403 ``community_pool_disabled_with_byok``, ...)
300
+ arrive as an HTTP status before the first chunk and raise ``RouterClientError`` with ``code`` and
301
+ ``retry_after``; ``max_retries`` applies only before any chunk has been yielded.
302
+ """
303
+ url = f"{self.base_url}/v1/chat/completions"
304
+ payload: dict[str, Any] = {
305
+ "model": model,
306
+ "messages": messages,
307
+ "user_id": user_id,
308
+ "provider_keys": provider_keys or {},
309
+ "stream": True,
310
+ "tier": tier,
311
+ }
312
+ if difficulty is not None:
313
+ payload["difficulty"] = difficulty
314
+ if mode is not None:
315
+ payload["mode"] = mode
316
+ if constraints is not None:
317
+ payload["constraints"] = constraints
318
+ if plugins is not None:
319
+ payload["plugins"] = plugins
320
+ if extra_body:
321
+ payload.update(extra_body)
322
+
323
+ data = json.dumps(payload).encode("utf-8")
324
+ req_headers = self._headers({"Accept": "text/event-stream"})
325
+ req = urllib.request.Request(url, data=data, headers=req_headers, method="POST")
326
+
327
+ attempt = 0
328
+ while True:
329
+ try:
330
+ resp_cm = urllib.request.urlopen(req, timeout=self.timeout)
331
+ except urllib.error.HTTPError as exc:
332
+ err = _http_error(exc, "Router stream HTTP")
333
+ if self._should_retry(err, attempt):
334
+ attempt += 1
335
+ continue
336
+ raise err from None
337
+ except Exception as exc:
338
+ raise RouterClientError(f"Router stream failed: {exc}") from exc
339
+ break
340
+ try:
341
+ with resp_cm as resp:
342
+ for line in resp:
343
+ decoded = line.decode("utf-8").strip()
344
+ if decoded.startswith("data: "):
345
+ raw_data = decoded[6:].strip()
346
+ if raw_data == "[DONE]":
347
+ break
348
+ try:
349
+ yield json.loads(raw_data)
350
+ except json.JSONDecodeError:
351
+ continue
352
+ except RouterClientError:
353
+ raise
354
+ except Exception as exc:
355
+ raise RouterClientError(f"Router stream failed: {exc}") from exc
356
+
357
+ def report_outcome(
358
+ self,
359
+ request_id: str,
360
+ signals: dict[str, bool],
361
+ provider: str | None = None,
362
+ task_class: str | None = None,
363
+ ) -> dict[str, Any]:
364
+ """Compatibility only: the hosted gateway answers ``accepted: false``; nothing is stored or used for routing."""
365
+ url = f"{self.base_url}/v1/outcomes"
366
+ payload = {
367
+ "request_id": request_id,
368
+ "signals": signals,
369
+ "provider": provider,
370
+ "task_class": task_class,
371
+ }
372
+ data = json.dumps(payload).encode("utf-8")
373
+ req = urllib.request.Request(url, data=data, headers=self._headers(), method="POST")
374
+
375
+ try:
376
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
377
+ return json.loads(resp.read().decode("utf-8"))
378
+ except Exception as exc:
379
+ raise RouterClientError(f"Failed to report outcome: {exc}") from exc
380
+
381
+ def evaluate_decision(
382
+ self,
383
+ state: dict[str, Any],
384
+ questions: dict[str, Any] | None = None,
385
+ ) -> dict[str, Any]:
386
+ """Compatibility only: decisions are not available on the hosted gateway (answers ``accepted: false``)."""
387
+ url = f"{self.base_url}/v1/decisions"
388
+ payload = {"state": state, "questions": questions}
389
+ data = json.dumps(payload).encode("utf-8")
390
+ req = urllib.request.Request(url, data=data, headers=self._headers(), method="POST")
391
+
392
+ try:
393
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
394
+ return json.loads(resp.read().decode("utf-8"))
395
+ except Exception as exc:
396
+ raise RouterClientError(f"Failed to evaluate decision: {exc}") from exc
397
+
398
+ def list_models(self) -> list[dict[str, Any]]:
399
+ """List available models and meta-routers from the registry."""
400
+ url = f"{self.base_url}/v1/models"
401
+ req = urllib.request.Request(url, headers=self._headers(), method="GET")
402
+ try:
403
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
404
+ data = json.loads(resp.read().decode("utf-8"))
405
+ return data.get("data", [])
406
+ except Exception as exc:
407
+ raise RouterClientError(f"Failed to list models: {exc}") from exc
408
+
409
+ def get_benchmarks(self) -> list[dict[str, Any]]:
410
+ """Fetch open public provider benchmarks dataset."""
411
+ url = f"{self.base_url}/v1/benchmarks"
412
+ req = urllib.request.Request(url, headers=self._headers(), method="GET")
413
+ try:
414
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
415
+ data = json.loads(resp.read().decode("utf-8"))
416
+ return data.get("benchmarks", [])
417
+ except Exception as exc:
418
+ raise RouterClientError(f"Failed to fetch benchmarks: {exc}") from exc
419
+
420
+ def get_session_handoff(self, session_id: str) -> dict[str, Any]:
421
+ """Fetch active session handoff summary and state."""
422
+ url = f"{self.base_url}/v1/sessions/{urllib.parse.quote(session_id, safe='')}/handoff"
423
+ req = urllib.request.Request(url, headers=self._headers(), method="GET")
424
+ try:
425
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
426
+ return json.loads(resp.read().decode("utf-8"))
427
+ except Exception as exc:
428
+ raise RouterClientError(f"Failed to fetch session handoff: {exc}") from exc
429
+
430
+ def compact_session(
431
+ self,
432
+ session_id: str,
433
+ messages: list[dict[str, Any]],
434
+ user_id: str = "default_user",
435
+ ) -> dict[str, Any]:
436
+ """Compatibility only: nothing is compacted or stored (answers ``accepted: false, compacted: false``)."""
437
+ url = f"{self.base_url}/v1/sessions/{urllib.parse.quote(session_id, safe='')}/compact"
438
+ payload = {"messages": messages, "user_id": user_id}
439
+ data = json.dumps(payload).encode("utf-8")
440
+ req = urllib.request.Request(url, data=data, headers=self._headers(), method="POST")
441
+ try:
442
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
443
+ return json.loads(resp.read().decode("utf-8"))
444
+ except Exception as exc:
445
+ raise RouterClientError(f"Failed to compact session: {exc}") from exc
446
+
447
+ def list_custom_providers(self, user_id: str = "default_user") -> list[dict[str, Any]]:
448
+ """List registered custom OpenAI-compatible providers."""
449
+ url = f"{self.base_url}/v1/custom-providers?user_id={urllib.parse.quote(user_id)}"
450
+ req = urllib.request.Request(url, headers=self._headers(), method="GET")
451
+ try:
452
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
453
+ data = json.loads(resp.read().decode("utf-8"))
454
+ return data.get("data", [])
455
+ except Exception as exc:
456
+ raise RouterClientError(f"Failed to list custom providers: {exc}") from exc
457
+
458
+ def register_custom_provider(
459
+ self,
460
+ provider_id: str,
461
+ display_name: str,
462
+ base_url: str,
463
+ api_key: str | None = None,
464
+ api_type: str = "openai_compatible",
465
+ models: list[dict[str, Any]] | None = None,
466
+ headers: dict[str, str] | None = None,
467
+ user_id: str = "default_user",
468
+ ) -> dict[str, Any]:
469
+ """Register or update a custom OpenAI-compatible provider."""
470
+ url = f"{self.base_url}/v1/custom-providers"
471
+ payload = {
472
+ "provider_id": provider_id,
473
+ "display_name": display_name,
474
+ "base_url": base_url,
475
+ "api_key": api_key,
476
+ "api_type": api_type,
477
+ "models": models or [],
478
+ "headers": headers or {},
479
+ "user_id": user_id,
480
+ }
481
+ data = json.dumps(payload).encode("utf-8")
482
+ req = urllib.request.Request(url, data=data, headers=self._headers(), method="POST")
483
+ try:
484
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
485
+ return json.loads(resp.read().decode("utf-8"))
486
+ except Exception as exc:
487
+ raise RouterClientError(f"Failed to register custom provider: {exc}") from exc
488
+
489
+ def delete_custom_provider(self, provider_id: str, user_id: str = "default_user") -> dict[str, Any]:
490
+ """Delete a registered custom provider."""
491
+ enc_id = urllib.parse.quote(provider_id, safe='')
492
+ enc_user = urllib.parse.quote(user_id, safe='')
493
+ url = f"{self.base_url}/v1/custom-providers/{enc_id}?user_id={enc_user}"
494
+ req = urllib.request.Request(url, headers=self._headers(), method="DELETE")
495
+ try:
496
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
497
+ return json.loads(resp.read().decode("utf-8"))
498
+ except Exception as exc:
499
+ raise RouterClientError(f"Failed to delete custom provider: {exc}") from exc
500
+
501
+ def get_cache_stats(self) -> dict[str, Any]:
502
+ """Fetch router cache hit/miss statistics and entry counts."""
503
+ url = f"{self.base_url}/v1/cache/stats"
504
+ req = urllib.request.Request(url, headers=self._headers(), method="GET")
505
+ try:
506
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
507
+ return json.loads(resp.read().decode("utf-8"))
508
+ except Exception as exc:
509
+ raise RouterClientError(f"Failed to fetch cache stats: {exc}") from exc
510
+
511
+ def clear_cache(self, user_id: str | None = None) -> dict[str, Any]:
512
+ """Flush cache entries."""
513
+ url = f"{self.base_url}/v1/cache"
514
+ if user_id:
515
+ url += f"?user_id={urllib.parse.quote(user_id)}"
516
+ req = urllib.request.Request(url, headers=self._headers(), method="DELETE")
517
+ try:
518
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
519
+ return json.loads(resp.read().decode("utf-8"))
520
+ except Exception as exc:
521
+ raise RouterClientError(f"Failed to clear cache: {exc}") from exc
522
+
523
+ def get_evaluations(self, limit: int = 50, task_class: str | None = None) -> list[dict[str, Any]]:
524
+ """Compatibility only: shadow evaluations are not available on the hosted gateway; returns an empty list."""
525
+ url = f"{self.base_url}/v1/evaluations?limit={limit}"
526
+ if task_class:
527
+ url += f"&task_class={urllib.parse.quote(task_class)}"
528
+ req = urllib.request.Request(url, headers=self._headers(), method="GET")
529
+ try:
530
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
531
+ data = json.loads(resp.read().decode("utf-8"))
532
+ return data.get("evaluations", [])
533
+ except Exception as exc:
534
+ raise RouterClientError(f"Failed to fetch evaluations: {exc}") from exc
535
+
536
+ def fork_evaluation(
537
+ self,
538
+ primary: dict[str, Any],
539
+ shadow: dict[str, Any],
540
+ task_class: str | None = None,
541
+ request_id: str | None = None,
542
+ ) -> dict[str, Any]:
543
+ """Compatibility only: shadow evaluations are not available on the hosted gateway (answers ``accepted: false``)."""
544
+ url = f"{self.base_url}/v1/evaluations/fork"
545
+ payload = {
546
+ "primary": primary,
547
+ "shadow": shadow,
548
+ "task_class": task_class,
549
+ "request_id": request_id,
550
+ }
551
+ data = json.dumps(payload).encode("utf-8")
552
+ req = urllib.request.Request(url, data=data, headers=self._headers(), method="POST")
553
+ try:
554
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
555
+ return json.loads(resp.read().decode("utf-8"))
556
+ except Exception as exc:
557
+ raise RouterClientError(f"Failed to fork evaluation: {exc}") from exc
558
+
559
+ def get_cluster_health(self) -> dict[str, Any]:
560
+ """Compatibility only: cluster status is not available on the hosted gateway; use GET /health for liveness."""
561
+ url = f"{self.base_url}/v1/cluster/health"
562
+ req = urllib.request.Request(url, headers=self._headers(), method="GET")
563
+ try:
564
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
565
+ return json.loads(resp.read().decode("utf-8"))
566
+ except Exception as exc:
567
+ raise RouterClientError(f"Failed to fetch cluster health: {exc}") from exc
568
+
569
+ def broadcast_cluster_breaker(
570
+ self, provider: str, reason: str = "manual_override", error_rate: float = 1.0, ttl_seconds: float = 60.0
571
+ ) -> dict[str, Any]:
572
+ """Compatibility only: manual breaker control is not available on the hosted gateway (answers ``accepted: false``)."""
573
+ url = f"{self.base_url}/v1/cluster/breakers"
574
+ payload = {
575
+ "provider": provider,
576
+ "reason": reason,
577
+ "error_rate": error_rate,
578
+ "ttl_seconds": ttl_seconds,
579
+ }
580
+ data = json.dumps(payload).encode("utf-8")
581
+ req = urllib.request.Request(url, data=data, headers=self._headers(), method="POST")
582
+ try:
583
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
584
+ return json.loads(resp.read().decode("utf-8"))
585
+ except Exception as exc:
586
+ raise RouterClientError(f"Failed to broadcast cluster breaker: {exc}") from exc
587
+
588
+ def get_capacity_pool(self) -> dict[str, Any]:
589
+ """Fetch real-time dynamic free capacity pool status and scarcity metrics."""
590
+ url = f"{self.base_url}/v1/capacity"
591
+ req = urllib.request.Request(url, headers=self._headers(), method="GET")
592
+ try:
593
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
594
+ return json.loads(resp.read().decode("utf-8"))
595
+ except Exception as exc:
596
+ raise RouterClientError(f"Failed to fetch capacity pool: {exc}") from exc
597
+
598
+ def redeem_license(self, code: str, user_id: str = "local") -> dict[str, Any]:
599
+ """Redeem AppSumo / lifetime deal license voucher code."""
600
+ url = f"{self.base_url}/v1/licenses/redeem"
601
+ data = json.dumps({"code": code, "user_id": user_id}).encode("utf-8")
602
+ req = urllib.request.Request(url, data=data, headers=self._headers(), method="POST")
603
+ try:
604
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
605
+ return json.loads(resp.read().decode("utf-8"))
606
+ except Exception as exc:
607
+ raise RouterClientError(f"Failed to redeem license: {exc}") from exc
608
+
609
+ def get_user_license(self, user_id: str = "local") -> dict[str, Any]:
610
+ """Fetch active license voucher details for a user."""
611
+ url = f"{self.base_url}/v1/licenses/user/{urllib.parse.quote(user_id, safe='')}"
612
+ req = urllib.request.Request(url, headers=self._headers(), method="GET")
613
+ try:
614
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
615
+ return json.loads(resp.read().decode("utf-8"))
616
+ except Exception as exc:
617
+ raise RouterClientError(f"Failed to fetch user license: {exc}") from exc
618
+
619
+ def get_edge_status(self) -> dict[str, Any]:
620
+ """Fetch Cloudflare Edge proxy and Turnstile configuration status."""
621
+ url = f"{self.base_url}/v1/edge/status"
622
+ req = urllib.request.Request(url, headers=self._headers(), method="GET")
623
+ try:
624
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
625
+ return json.loads(resp.read().decode("utf-8"))
626
+ except Exception as exc:
627
+ raise RouterClientError(f"Failed to fetch edge status: {exc}") from exc
628
+
629
+ def verify_turnstile(self, token: str) -> dict[str, Any]:
630
+ """Verify Cloudflare Turnstile token via backend edge verification."""
631
+ url = f"{self.base_url}/v1/edge/turnstile/verify"
632
+ data = json.dumps({"token": token}).encode("utf-8")
633
+ req = urllib.request.Request(url, data=data, headers=self._headers(), method="POST")
634
+ try:
635
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
636
+ return json.loads(resp.read().decode("utf-8"))
637
+ except Exception as exc:
638
+ raise RouterClientError(f"Failed to verify turnstile token: {exc}") from exc
@@ -0,0 +1 @@
1
+ # py.typed marker file for PEP 561
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: sentiogate-python
3
+ Version: 1.2.1
4
+ Summary: Thin, zero-dependency Python client for SentioGate intelligent LLM router
5
+ Author-email: SentioGate Team <dev@sentiogate.app>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://sentiogate.app
8
+ Project-URL: Documentation, https://sentiogate.app/docs
9
+ Project-URL: Repository, https://github.com/SentioGate/sentiogate-python
10
+ Project-URL: Issues, https://github.com/SentioGate/sentiogate-python/issues
11
+ Project-URL: Benchmarks, https://sentiogate.app/benchmarks
12
+ Keywords: llm,ai,router,gateway,byok,openai,anthropic,gemini,groq,deepseek
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Requires-Python: >=3.8
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Dynamic: license-file
28
+
29
+ # SentioGate Python SDK (`sentiogate`)
30
+
31
+ [![PyPI version](https://img.shields.io/pypi/v/sentiogate?style=for-the-badge&color=3775a9&logo=pypi&logoColor=white)](https://pypi.org/project/sentiogate/)
32
+ [![Python versions](https://img.shields.io/pypi/pyversions/sentiogate?style=for-the-badge&logo=python&logoColor=white)](https://pypi.org/project/sentiogate/)
33
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg?style=for-the-badge)](https://opensource.org/licenses/Apache-2.0)
34
+ [![Website](https://img.shields.io/badge/Website-sentiogate.app-2563eb?style=for-the-badge&logo=google-chrome&logoColor=white)](https://sentiogate.app)
35
+ [![Live Benchmarks](https://img.shields.io/badge/Benchmarks-Live_Latency-7c3aed?style=for-the-badge&logo=speedtest&logoColor=white)](https://sentiogate.app/benchmarks)
36
+
37
+ Thin, zero-dependency Python client for [SentioGate](https://sentiogate.app) — the zero-markup AI LLM router offering intelligent latency-based routing, instant failover, and strict BYOK privacy.
38
+
39
+ * 🐍 **PyPI Package**: [`https://pypi.org/project/sentiogate/`](https://pypi.org/project/sentiogate/)
40
+ * 📦 **TypeScript SDK (NPM)**: [`https://www.npmjs.com/package/@sentiogate/sdk`](https://www.npmjs.com/package/@sentiogate/sdk)
41
+ * 🌐 **Developer Hub & Simulator**: [`https://sentiogate.github.io`](https://sentiogate.github.io)
42
+
43
+ ---
44
+
45
+ ## ⚡ Installation
46
+
47
+ ```bash
48
+ pip install sentiogate
49
+ ```
50
+
51
+ *(Zero external dependencies: uses Python standard library for maximum reliability and minimal container footprint).*
52
+
53
+ ---
54
+
55
+ ## 🚀 Quickstart
56
+
57
+ ```python
58
+ import os
59
+ from sentiogate import AutoRouterClient
60
+
61
+ client = AutoRouterClient(
62
+ api_key=os.environ.get("SENTIOGATE_API_KEY"),
63
+ )
64
+
65
+ response = client.create_chat_completion(
66
+ model="auto:fastest", # Intelligently selects lowest TTFT model replica
67
+ messages=[
68
+ {"role": "system", "content": "You are a helpful software architect."},
69
+ {"role": "user", "content": "What is the difference between gRPC and REST?"}
70
+ ]
71
+ )
72
+
73
+ print(response["choices"][0]["message"]["content"])
74
+ ```
75
+
76
+ ---
77
+
78
+ ## 🌊 Streaming Completions
79
+
80
+ ```python
81
+ import os
82
+ from sentiogate import AutoRouterClient
83
+
84
+ client = AutoRouterClient(api_key=os.environ.get("SENTIOGATE_API_KEY"))
85
+
86
+ for chunk in client.stream_chat_completion(
87
+ model="auto:cost-efficient",
88
+ messages=[{"role": "user", "content": "Write a binary search in Python."}],
89
+ ):
90
+ delta = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
91
+ print(delta, end="", flush=True)
92
+ print()
93
+ ```
94
+
95
+ ---
96
+
97
+ ## 🔗 Useful Links
98
+
99
+ * 🏠 [SentioGate Official Site](https://sentiogate.app)
100
+ * 📖 [API Documentation & Guides](https://sentiogate.app/docs)
101
+ * 📊 [Live Latency Benchmarks](https://sentiogate.app/benchmarks)
102
+ * ⚖️ [Comparison: SentioGate vs OpenRouter & LiteLLM](https://sentiogate.app/compare)
103
+ * 📦 [NPM Package (@sentiogate/sdk)](https://www.npmjs.com/package/@sentiogate/sdk)
104
+ * 🌐 [Developer Hub](https://sentiogate.github.io)
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ sentiogate/__init__.py
5
+ sentiogate/client.py
6
+ sentiogate/py.typed
7
+ sentiogate_python.egg-info/PKG-INFO
8
+ sentiogate_python.egg-info/SOURCES.txt
9
+ sentiogate_python.egg-info/dependency_links.txt
10
+ sentiogate_python.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+