sentiogate-python 1.2.2__tar.gz → 1.3.0__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.0
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.0"
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,
@@ -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.0"
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,19 @@ 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
 
109
108
  class AutoRouterClient:
110
- """Thin, zero-leak client SDK for connecting applications to AI Auto Router.
109
+ """Thin, zero-leak client SDK for connecting applications to SentioGate.
111
110
 
112
111
  Retries are off by default (``max_retries=0``): a 429 raises ``RouterClientError`` with ``code`` and
113
112
  ``retry_after`` set. With ``max_retries > 0`` the client waits the server's Retry-After and tries again,
114
113
  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).
114
+ ``max_retry_wait`` seconds (the server may ask you to wait via Retry-After).
116
115
 
117
116
  Example:
118
117
  >>> client = AutoRouterClient(api_key="sg_live_...") # https://api.sentiogate.dev
@@ -378,23 +377,6 @@ class AutoRouterClient:
378
377
  except Exception as exc:
379
378
  raise RouterClientError(f"Failed to report outcome: {exc}") from exc
380
379
 
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
380
  def list_models(self) -> list[dict[str, Any]]:
399
381
  """List available models and meta-routers from the registry."""
400
382
  url = f"{self.base_url}/v1/models"
@@ -499,7 +481,7 @@ class AutoRouterClient:
499
481
  raise RouterClientError(f"Failed to delete custom provider: {exc}") from exc
500
482
 
501
483
  def get_cache_stats(self) -> dict[str, Any]:
502
- """Fetch router cache hit/miss statistics and entry counts."""
484
+ """Fetch cache hit/miss statistics for your account."""
503
485
  url = f"{self.base_url}/v1/cache/stats"
504
486
  req = urllib.request.Request(url, headers=self._headers(), method="GET")
505
487
  try:
@@ -508,11 +490,9 @@ class AutoRouterClient:
508
490
  except Exception as exc:
509
491
  raise RouterClientError(f"Failed to fetch cache stats: {exc}") from exc
510
492
 
511
- def clear_cache(self, user_id: str | None = None) -> dict[str, Any]:
512
- """Flush cache entries."""
493
+ def clear_cache(self) -> dict[str, Any]:
494
+ """Flush your own cached responses (the signed-in account's cache)."""
513
495
  url = f"{self.base_url}/v1/cache"
514
- if user_id:
515
- url += f"?user_id={urllib.parse.quote(user_id)}"
516
496
  req = urllib.request.Request(url, headers=self._headers(), method="DELETE")
517
497
  try:
518
498
  with urllib.request.urlopen(req, timeout=self.timeout) as resp:
@@ -520,71 +500,6 @@ class AutoRouterClient:
520
500
  except Exception as exc:
521
501
  raise RouterClientError(f"Failed to clear cache: {exc}") from exc
522
502
 
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
503
  def get_capacity_pool(self) -> dict[str, Any]:
589
504
  """Fetch real-time dynamic free capacity pool status and scarcity metrics."""
590
505
  url = f"{self.base_url}/v1/capacity"
@@ -596,7 +511,7 @@ class AutoRouterClient:
596
511
  raise RouterClientError(f"Failed to fetch capacity pool: {exc}") from exc
597
512
 
598
513
  def redeem_license(self, code: str, user_id: str = "local") -> dict[str, Any]:
599
- """Redeem AppSumo / lifetime deal license voucher code."""
514
+ """Redeem a license code for the signed-in account."""
600
515
  url = f"{self.base_url}/v1/licenses/redeem"
601
516
  data = json.dumps({"code": code, "user_id": user_id}).encode("utf-8")
602
517
  req = urllib.request.Request(url, data=data, headers=self._headers(), method="POST")
@@ -615,24 +530,3 @@ class AutoRouterClient:
615
530
  return json.loads(resp.read().decode("utf-8"))
616
531
  except Exception as exc:
617
532
  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.0
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,79 @@
1
+ """Stdlib-only unit tests: python -m unittest discover -s tests"""
2
+
3
+ import json
4
+ import unittest
5
+ import urllib.request
6
+ from unittest import mock
7
+
8
+ import sentiogate
9
+ from sentiogate import AutoRouterClient, VERSION
10
+
11
+
12
+ class _Resp:
13
+ def __init__(self, body):
14
+ self._body = json.dumps(body).encode("utf-8")
15
+
16
+ def read(self):
17
+ return self._body
18
+
19
+ def __enter__(self):
20
+ return self
21
+
22
+ def __exit__(self, *exc):
23
+ return False
24
+
25
+
26
+ class ClientTests(unittest.TestCase):
27
+ def test_version_and_user_agent(self):
28
+ self.assertEqual(sentiogate.__version__, VERSION)
29
+ self.assertTrue(sentiogate.USER_AGENT.startswith(f"sentiogate-python/{VERSION} ("))
30
+
31
+ def test_default_base_url(self):
32
+ self.assertEqual(AutoRouterClient().base_url, "https://api.sentiogate.dev")
33
+
34
+ def test_internal_methods_removed(self):
35
+ client = AutoRouterClient()
36
+ for name in (
37
+ "get_cluster_health",
38
+ "broadcast_cluster_breaker",
39
+ "get_edge_status",
40
+ "verify_turnstile",
41
+ "evaluate_decision",
42
+ "get_evaluations",
43
+ "fork_evaluation",
44
+ ):
45
+ self.assertFalse(hasattr(client, name), name)
46
+
47
+ def test_clear_cache_is_caller_scoped(self):
48
+ seen = []
49
+
50
+ def fake_urlopen(req, timeout=None):
51
+ seen.append((req.full_url, req.get_method()))
52
+ return _Resp({"status": "cleared"})
53
+
54
+ with mock.patch.object(urllib.request, "urlopen", fake_urlopen):
55
+ AutoRouterClient(base_url="https://api.test.com").clear_cache()
56
+ self.assertEqual(seen, [("https://api.test.com/v1/cache", "DELETE")])
57
+ with self.assertRaises(TypeError):
58
+ AutoRouterClient().clear_cache("someone_else")
59
+
60
+ def test_chat_sends_auto_and_route_preference(self):
61
+ sent = {}
62
+
63
+ def fake_urlopen(req, timeout=None):
64
+ sent.update(json.loads(req.data.decode("utf-8")))
65
+ sent["_ua"] = req.get_header("User-agent")
66
+ return _Resp({"choices": [{"message": {"content": "hi"}}]})
67
+
68
+ with mock.patch.object(urllib.request, "urlopen", fake_urlopen):
69
+ out = AutoRouterClient(base_url="https://api.test.com").chat(
70
+ messages=[{"role": "user", "content": "x"}], extra_body={"route_preference": "latency"}
71
+ )
72
+ self.assertEqual(out["choices"][0]["message"]["content"], "hi")
73
+ self.assertEqual(sent["model"], "auto")
74
+ self.assertEqual(sent["route_preference"], "latency")
75
+ self.assertTrue(sent["_ua"].startswith("sentiogate-python/"))
76
+
77
+
78
+ if __name__ == "__main__":
79
+ unittest.main()