sentiogate-python 1.2.2__tar.gz → 1.3.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,2 @@
1
+ global-exclude *.py[cod]
2
+ prune **/__pycache__
@@ -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)
@@ -6,7 +6,7 @@
6
6
  [![Website](https://img.shields.io/badge/Website-sentiogate.app-2563eb?style=for-the-badge&logo=google-chrome&logoColor=white)](https://sentiogate.app)
7
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
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.
9
+ 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.
10
10
 
11
11
  * 🐍 **PyPI Package**: [`https://pypi.org/project/sentiogate-python/`](https://pypi.org/project/sentiogate-python/)
12
12
  * 📦 **TypeScript SDK (NPM)**: [`https://www.npmjs.com/package/@sentiogate/sdk`](https://www.npmjs.com/package/@sentiogate/sdk)
@@ -34,8 +34,8 @@ client = AutoRouterClient(
34
34
  api_key=os.environ.get("SENTIOGATE_API_KEY"),
35
35
  )
36
36
 
37
- response = client.create_chat_completion(
38
- model="auto:fastest", # Intelligently selects lowest TTFT model replica
37
+ response = client.chat(
38
+ model="auto", # SentioGate picks the model; cheapest suitable by default
39
39
  messages=[
40
40
  {"role": "system", "content": "You are a helpful software architect."},
41
41
  {"role": "user", "content": "What is the difference between gRPC and REST?"}
@@ -55,9 +55,10 @@ from sentiogate import AutoRouterClient
55
55
 
56
56
  client = AutoRouterClient(api_key=os.environ.get("SENTIOGATE_API_KEY"))
57
57
 
58
- for chunk in client.stream_chat_completion(
59
- model="auto:cost-efficient",
58
+ for chunk in client.stream_chat(
59
+ model="auto",
60
60
  messages=[{"role": "user", "content": "Write a binary search in Python."}],
61
+ extra_body={"route_preference": "latency"}, # "cost" (default), "quality" or "latency"
61
62
  ):
62
63
  delta = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
63
64
  print(delta, end="", flush=True)
@@ -66,6 +67,17 @@ print()
66
67
 
67
68
  ---
68
69
 
70
+ ## 🛠️ Routing preference
71
+
72
+ Send `model="auto"` and set `route_preference` through `extra_body` to `"cost"` (default), `"quality"` or
73
+ `"latency"`. You can also request a specific `provider/model`. SentioGate automatically falls back to another
74
+ model if one fails.
75
+
76
+ Retries are off by default. Set `max_retries` to retry transient 429s after the server's Retry-After
77
+ (the server may ask you to wait); waits longer than `max_retry_wait` raise `RouterClientError` instead.
78
+
79
+ ---
80
+
69
81
  ## 🔗 Useful Links
70
82
 
71
83
  * 🏠 [SentioGate Official Site](https://sentiogate.app)
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sentiogate-python"
7
- version = "1.2.2"
7
+ version = "1.3.1"
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"
@@ -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
  ]
@@ -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)
@@ -1,4 +1,5 @@
1
1
  LICENSE
2
+ MANIFEST.in
2
3
  README.md
3
4
  pyproject.toml
4
5
  sentiogate/__init__.py
@@ -7,4 +8,5 @@ sentiogate/py.typed
7
8
  sentiogate_python.egg-info/PKG-INFO
8
9
  sentiogate_python.egg-info/SOURCES.txt
9
10
  sentiogate_python.egg-info/dependency_links.txt
10
- sentiogate_python.egg-info/top_level.txt
11
+ sentiogate_python.egg-info/top_level.txt
12
+ tests/test_client.py
@@ -0,0 +1,87 @@
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()