sentiogate-python 1.2.2__py3-none-any.whl → 1.3.1__py3-none-any.whl

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/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- """AI Auto Router Python Thin Client SDK."""
1
+ """SentioGate Python thin client SDK (sentiogate-python)."""
2
2
 
3
3
  from .client import (
4
4
  DEFAULT_BASE_URL,
@@ -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
  ]
sentiogate/client.py CHANGED
@@ -1,10 +1,9 @@
1
- """AI Auto Router Client SDK.
1
+ """SentioGate Python client SDK (sentiogate-python).
2
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.
3
+ Zero-inference-markup client for the SentioGate BYOK gateway.
4
+ Supports sync and streaming chat completions, batch jobs, model listing, sessions, custom providers,
5
+ and cache operations. Outcome reporting and session compaction are kept for compatibility only:
6
+ the hosted gateway answers them with ``{"accepted": false, "status": "not_implemented"}`` and stores nothing.
8
7
  """
9
8
 
10
9
  from __future__ import annotations
@@ -19,13 +18,13 @@ import urllib.request
19
18
  from collections.abc import Callable, Iterator
20
19
  from typing import Any
21
20
 
22
- VERSION = "1.2.1"
21
+ VERSION = "1.3.1"
23
22
  # 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'})"
23
+ # never the default Python-urllib agent, which the gateway's bot check may refuse).
24
+ USER_AGENT = f"sentiogate-python/{VERSION} ({platform.system() or 'unknown'})"
26
25
 
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.
26
+ # 429 codes that are worth retrying after the server's Retry-After (the server may ask you to wait, per-key rate
27
+ # limit, upstream temporarily unavailable). Quota codes such as community_pool_exhausted or monthly_request_limit are not.
29
28
  RETRYABLE_CODES = frozenset({"upstream_rate_limited", "rate_limited", "upstream_circuit_open"})
30
29
 
31
30
 
@@ -100,19 +99,30 @@ def _http_error(exc: urllib.error.HTTPError, prefix: str) -> RouterClientError:
100
99
  )
101
100
 
102
101
 
103
- # Production SentioGate API (DEC-043). Host only: the client appends /v1/... itself.
102
+ # Hosted SentioGate API. Host only: the client appends /v1/... itself.
104
103
  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.
104
+ # Default request timeout (seconds): generous enough for long-running requests.
106
105
  DEFAULT_TIMEOUT = 130.0
107
106
 
108
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
+
109
119
  class AutoRouterClient:
110
- """Thin, zero-leak client SDK for connecting applications to AI Auto Router.
120
+ """Thin, zero-leak client SDK for connecting applications to SentioGate.
111
121
 
112
122
  Retries are off by default (``max_retries=0``): a 429 raises ``RouterClientError`` with ``code`` and
113
123
  ``retry_after`` set. With ``max_retries > 0`` the client waits the server's Retry-After and tries again,
114
124
  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).
125
+ ``max_retry_wait`` seconds (the server may ask you to wait via Retry-After).
116
126
 
117
127
  Example:
118
128
  >>> client = AutoRouterClient(api_key="sg_live_...") # https://api.sentiogate.dev
@@ -132,7 +142,7 @@ class AutoRouterClient:
132
142
  max_retry_wait: float = 60.0,
133
143
  user_agent: str | None = None,
134
144
  ) -> None:
135
- self.base_url = base_url.rstrip("/")
145
+ self.base_url = validate_base_url(base_url)
136
146
  self.api_key = api_key
137
147
  self.timeout = timeout
138
148
  self.max_retries = max(0, int(max_retries))
@@ -378,23 +388,6 @@ class AutoRouterClient:
378
388
  except Exception as exc:
379
389
  raise RouterClientError(f"Failed to report outcome: {exc}") from exc
380
390
 
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
391
  def list_models(self) -> list[dict[str, Any]]:
399
392
  """List available models and meta-routers from the registry."""
400
393
  url = f"{self.base_url}/v1/models"
@@ -499,7 +492,7 @@ class AutoRouterClient:
499
492
  raise RouterClientError(f"Failed to delete custom provider: {exc}") from exc
500
493
 
501
494
  def get_cache_stats(self) -> dict[str, Any]:
502
- """Fetch router cache hit/miss statistics and entry counts."""
495
+ """Fetch cache hit/miss statistics for your account."""
503
496
  url = f"{self.base_url}/v1/cache/stats"
504
497
  req = urllib.request.Request(url, headers=self._headers(), method="GET")
505
498
  try:
@@ -508,11 +501,9 @@ class AutoRouterClient:
508
501
  except Exception as exc:
509
502
  raise RouterClientError(f"Failed to fetch cache stats: {exc}") from exc
510
503
 
511
- def clear_cache(self, user_id: str | None = None) -> dict[str, Any]:
512
- """Flush cache entries."""
504
+ def clear_cache(self) -> dict[str, Any]:
505
+ """Flush your own cached responses (the signed-in account's cache)."""
513
506
  url = f"{self.base_url}/v1/cache"
514
- if user_id:
515
- url += f"?user_id={urllib.parse.quote(user_id)}"
516
507
  req = urllib.request.Request(url, headers=self._headers(), method="DELETE")
517
508
  try:
518
509
  with urllib.request.urlopen(req, timeout=self.timeout) as resp:
@@ -520,71 +511,6 @@ class AutoRouterClient:
520
511
  except Exception as exc:
521
512
  raise RouterClientError(f"Failed to clear cache: {exc}") from exc
522
513
 
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
514
  def get_capacity_pool(self) -> dict[str, Any]:
589
515
  """Fetch real-time dynamic free capacity pool status and scarcity metrics."""
590
516
  url = f"{self.base_url}/v1/capacity"
@@ -596,7 +522,7 @@ class AutoRouterClient:
596
522
  raise RouterClientError(f"Failed to fetch capacity pool: {exc}") from exc
597
523
 
598
524
  def redeem_license(self, code: str, user_id: str = "local") -> dict[str, Any]:
599
- """Redeem AppSumo / lifetime deal license voucher code."""
525
+ """Redeem a license code for the signed-in account."""
600
526
  url = f"{self.base_url}/v1/licenses/redeem"
601
527
  data = json.dumps({"code": code, "user_id": user_id}).encode("utf-8")
602
528
  req = urllib.request.Request(url, data=data, headers=self._headers(), method="POST")
@@ -615,24 +541,3 @@ class AutoRouterClient:
615
541
  return json.loads(resp.read().decode("utf-8"))
616
542
  except Exception as exc:
617
543
  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
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sentiogate-python
3
- Version: 1.2.2
3
+ Version: 1.3.1
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
@@ -34,7 +34,7 @@ Dynamic: license-file
34
34
  [![Website](https://img.shields.io/badge/Website-sentiogate.app-2563eb?style=for-the-badge&logo=google-chrome&logoColor=white)](https://sentiogate.app)
35
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
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.
37
+ Thin, zero-dependency Python client for [SentioGate](https://sentiogate.app) — the zero-markup, OpenAI-compatible LLM router for your own provider keys (BYOK). It picks a suitable model for each request and automatically falls back to another model if one fails.
38
38
 
39
39
  * 🐍 **PyPI Package**: [`https://pypi.org/project/sentiogate-python/`](https://pypi.org/project/sentiogate-python/)
40
40
  * 📦 **TypeScript SDK (NPM)**: [`https://www.npmjs.com/package/@sentiogate/sdk`](https://www.npmjs.com/package/@sentiogate/sdk)
@@ -62,8 +62,8 @@ client = AutoRouterClient(
62
62
  api_key=os.environ.get("SENTIOGATE_API_KEY"),
63
63
  )
64
64
 
65
- response = client.create_chat_completion(
66
- model="auto:fastest", # Intelligently selects lowest TTFT model replica
65
+ response = client.chat(
66
+ model="auto", # SentioGate picks the model; cheapest suitable by default
67
67
  messages=[
68
68
  {"role": "system", "content": "You are a helpful software architect."},
69
69
  {"role": "user", "content": "What is the difference between gRPC and REST?"}
@@ -83,9 +83,10 @@ from sentiogate import AutoRouterClient
83
83
 
84
84
  client = AutoRouterClient(api_key=os.environ.get("SENTIOGATE_API_KEY"))
85
85
 
86
- for chunk in client.stream_chat_completion(
87
- model="auto:cost-efficient",
86
+ for chunk in client.stream_chat(
87
+ model="auto",
88
88
  messages=[{"role": "user", "content": "Write a binary search in Python."}],
89
+ extra_body={"route_preference": "latency"}, # "cost" (default), "quality" or "latency"
89
90
  ):
90
91
  delta = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
91
92
  print(delta, end="", flush=True)
@@ -94,6 +95,17 @@ print()
94
95
 
95
96
  ---
96
97
 
98
+ ## 🛠️ Routing preference
99
+
100
+ Send `model="auto"` and set `route_preference` through `extra_body` to `"cost"` (default), `"quality"` or
101
+ `"latency"`. You can also request a specific `provider/model`. SentioGate automatically falls back to another
102
+ model if one fails.
103
+
104
+ Retries are off by default. Set `max_retries` to retry transient 429s after the server's Retry-After
105
+ (the server may ask you to wait); waits longer than `max_retry_wait` raise `RouterClientError` instead.
106
+
107
+ ---
108
+
97
109
  ## 🔗 Useful Links
98
110
 
99
111
  * 🏠 [SentioGate Official Site](https://sentiogate.app)
@@ -0,0 +1,8 @@
1
+ sentiogate/__init__.py,sha256=29ukbIt-wtLmQrTZqO06A20-fO6RiDzhTO2L_VMA-uQ,494
2
+ sentiogate/client.py,sha256=7Yma-EQfAEz-mDyhdrvrgaitvcBcx70CLSOfKwXyUN8,23902
3
+ sentiogate/py.typed,sha256=-yl3TJziRnBGR4RQVDoLxLVJCMoslIXZL48QaM0ulXI,35
4
+ sentiogate_python-1.3.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
5
+ sentiogate_python-1.3.1.dist-info/METADATA,sha256=thBCu-XrFdjLVpAG7lGCun-ZAn3zk37xvlSEycP-k0o,4921
6
+ sentiogate_python-1.3.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ sentiogate_python-1.3.1.dist-info/top_level.txt,sha256=fxARYgd5oUze_a7WfsncfYRu5Qfu75FhwXhKE97He4c,11
8
+ sentiogate_python-1.3.1.dist-info/RECORD,,
@@ -1,8 +0,0 @@
1
- sentiogate/__init__.py,sha256=0CbPjZRTLcPKT0wVUldeM8D85llMnn7TBhmVbnpgLb0,430
2
- sentiogate/client.py,sha256=aQUwepaMPgmNIjXBVwDFY9aOODKwOeQ74qwteLigJvQ,28695
3
- sentiogate/py.typed,sha256=-yl3TJziRnBGR4RQVDoLxLVJCMoslIXZL48QaM0ulXI,35
4
- sentiogate_python-1.2.2.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
5
- sentiogate_python-1.2.2.dist-info/METADATA,sha256=Fnv80XjUWpHJMaDfyFyLBd3W0QTQWeq4mb_mRo8lm8U,4326
6
- sentiogate_python-1.2.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
- sentiogate_python-1.2.2.dist-info/top_level.txt,sha256=fxARYgd5oUze_a7WfsncfYRu5Qfu75FhwXhKE97He4c,11
8
- sentiogate_python-1.2.2.dist-info/RECORD,,