ninjachat 0.1.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.
- ninjachat-0.1.0/LICENSE +21 -0
- ninjachat-0.1.0/PKG-INFO +73 -0
- ninjachat-0.1.0/README.md +46 -0
- ninjachat-0.1.0/ninjachat/__init__.py +20 -0
- ninjachat-0.1.0/ninjachat/client.py +298 -0
- ninjachat-0.1.0/ninjachat/contract.py +3 -0
- ninjachat-0.1.0/ninjachat/errors.py +67 -0
- ninjachat-0.1.0/ninjachat/py.typed +1 -0
- ninjachat-0.1.0/ninjachat/types.py +105 -0
- ninjachat-0.1.0/ninjachat/webhooks.py +50 -0
- ninjachat-0.1.0/ninjachat.egg-info/PKG-INFO +73 -0
- ninjachat-0.1.0/ninjachat.egg-info/SOURCES.txt +16 -0
- ninjachat-0.1.0/ninjachat.egg-info/dependency_links.txt +1 -0
- ninjachat-0.1.0/ninjachat.egg-info/requires.txt +4 -0
- ninjachat-0.1.0/ninjachat.egg-info/top_level.txt +1 -0
- ninjachat-0.1.0/pyproject.toml +37 -0
- ninjachat-0.1.0/setup.cfg +4 -0
- ninjachat-0.1.0/tests/test_smoke.py +32 -0
ninjachat-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Helium Technologies, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
ninjachat-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ninjachat
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for the NinjaChat API — one typed client for chat, responses, media, routing, usage, and webhooks.
|
|
5
|
+
Author: Helium Technologies, Inc.
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Documentation, https://docs.ninjachat.ai
|
|
8
|
+
Project-URL: OpenAPI spec, https://www.ninjachat.ai/api/v1/openapi
|
|
9
|
+
Project-URL: Source, https://github.com/bloon-ai/ninjachat-sdk/tree/main/packages/python
|
|
10
|
+
Project-URL: Issues, https://github.com/bloon-ai/ninjachat-sdk/issues
|
|
11
|
+
Keywords: ninjachat,ai,llm,openai-compatible,sdk
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: requests>=2.28
|
|
25
|
+
Requires-Dist: typing-extensions>=4.8; python_version < "3.11"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# NinjaChat Python SDK
|
|
29
|
+
|
|
30
|
+
Typed client for the clean NinjaChat API v1.
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install ninjachat
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import os
|
|
38
|
+
from ninjachat import NinjaChat
|
|
39
|
+
|
|
40
|
+
client = NinjaChat(api_key=os.environ["NINJACHAT_API_KEY"])
|
|
41
|
+
response = client.responses.create(
|
|
42
|
+
model="ninja/auto",
|
|
43
|
+
input="Write one sentence about clean APIs.",
|
|
44
|
+
max_output_tokens=64,
|
|
45
|
+
routing={"strategy": "balanced", "data_policy": "no_training"},
|
|
46
|
+
)
|
|
47
|
+
print(response["output_text"], response["cost_usd"], response["request_id"])
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Ordered fallbacks and provider constraints are explicit:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
completion = client.chat.completions.create(
|
|
54
|
+
models=["gpt-5", "claude-sonnet-4"],
|
|
55
|
+
messages=[{"role": "user", "content": "Hello"}],
|
|
56
|
+
max_completion_tokens=100,
|
|
57
|
+
routing={"strategy": "latency", "allow_fallbacks": True, "caching": "auto", "max_cost_usd": 0.10},
|
|
58
|
+
)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Streams return iterators of typed-shape dictionaries:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
for event in client.responses.create(model="ninja/auto", input="Hello", stream=True):
|
|
65
|
+
if event.get("type") == "response.output_text.delta":
|
|
66
|
+
print(event.get("delta", ""), end="")
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Models and prices come from `client.models.list()`. Images use `client.images.generate()`, videos use `client.videos.generate()` and `client.videos.wait_for()`, and account observability is available through `client.usage()`, `client.balance()`, and `client.requests.get()`.
|
|
70
|
+
|
|
71
|
+
Signed webhooks replace video polling and fire spend alerts: `client.webhooks.create(...)` or the [console](https://www.ninjachat.ai/developers/keys#webhooks). Verify deliveries with `verify_webhook_signature`.
|
|
72
|
+
|
|
73
|
+
The base URL is `https://www.ninjachat.ai/api/v1`. Chat and Responses are billed by actual token usage. See [docs.ninjachat.ai](https://docs.ninjachat.ai).
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# NinjaChat Python SDK
|
|
2
|
+
|
|
3
|
+
Typed client for the clean NinjaChat API v1.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install ninjachat
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
import os
|
|
11
|
+
from ninjachat import NinjaChat
|
|
12
|
+
|
|
13
|
+
client = NinjaChat(api_key=os.environ["NINJACHAT_API_KEY"])
|
|
14
|
+
response = client.responses.create(
|
|
15
|
+
model="ninja/auto",
|
|
16
|
+
input="Write one sentence about clean APIs.",
|
|
17
|
+
max_output_tokens=64,
|
|
18
|
+
routing={"strategy": "balanced", "data_policy": "no_training"},
|
|
19
|
+
)
|
|
20
|
+
print(response["output_text"], response["cost_usd"], response["request_id"])
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Ordered fallbacks and provider constraints are explicit:
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
completion = client.chat.completions.create(
|
|
27
|
+
models=["gpt-5", "claude-sonnet-4"],
|
|
28
|
+
messages=[{"role": "user", "content": "Hello"}],
|
|
29
|
+
max_completion_tokens=100,
|
|
30
|
+
routing={"strategy": "latency", "allow_fallbacks": True, "caching": "auto", "max_cost_usd": 0.10},
|
|
31
|
+
)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Streams return iterators of typed-shape dictionaries:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
for event in client.responses.create(model="ninja/auto", input="Hello", stream=True):
|
|
38
|
+
if event.get("type") == "response.output_text.delta":
|
|
39
|
+
print(event.get("delta", ""), end="")
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Models and prices come from `client.models.list()`. Images use `client.images.generate()`, videos use `client.videos.generate()` and `client.videos.wait_for()`, and account observability is available through `client.usage()`, `client.balance()`, and `client.requests.get()`.
|
|
43
|
+
|
|
44
|
+
Signed webhooks replace video polling and fire spend alerts: `client.webhooks.create(...)` or the [console](https://www.ninjachat.ai/developers/keys#webhooks). Verify deliveries with `verify_webhook_signature`.
|
|
45
|
+
|
|
46
|
+
The base URL is `https://www.ninjachat.ai/api/v1`. Chat and Responses are billed by actual token usage. See [docs.ninjachat.ai](https://docs.ninjachat.ai).
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""ninjachat — Python SDK for the NinjaChat v1 API.
|
|
2
|
+
|
|
3
|
+
Docs: https://docs.ninjachat.ai
|
|
4
|
+
OpenAPI spec: https://www.ninjachat.ai/api/v1/openapi
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .client import DEFAULT_BASE_URL, NinjaChat
|
|
8
|
+
from .contract import CONTRACT_SHA256
|
|
9
|
+
from .errors import NinjaChatError
|
|
10
|
+
from .webhooks import verify_webhook_signature
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"NinjaChat",
|
|
14
|
+
"NinjaChatError",
|
|
15
|
+
"verify_webhook_signature",
|
|
16
|
+
"DEFAULT_BASE_URL",
|
|
17
|
+
"CONTRACT_SHA256",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
"""Synchronous, typed NinjaChat API v1 client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json as _json
|
|
6
|
+
import random
|
|
7
|
+
import time
|
|
8
|
+
import uuid
|
|
9
|
+
from typing import Any, Dict, Iterator, List, Optional, Union
|
|
10
|
+
from urllib.parse import quote
|
|
11
|
+
|
|
12
|
+
import requests as http_requests
|
|
13
|
+
|
|
14
|
+
try:
|
|
15
|
+
from typing import Unpack
|
|
16
|
+
except ImportError: # Python 3.9-3.10
|
|
17
|
+
from typing_extensions import Unpack
|
|
18
|
+
|
|
19
|
+
from .errors import NinjaChatError
|
|
20
|
+
from .types import ChatCompletionParams, ImageGenerateParams, ResponseCreateParams, SearchParams, VideoGenerateParams
|
|
21
|
+
|
|
22
|
+
DEFAULT_BASE_URL = "https://www.ninjachat.ai/api/v1"
|
|
23
|
+
DEFAULT_MAX_RETRIES = 2
|
|
24
|
+
MAX_BACKOFF_SECONDS = 30.0
|
|
25
|
+
RETRIABLE_STATUSES = {429, 500, 502, 503, 504}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _retry_delay(response: Optional[http_requests.Response], attempt: int) -> float:
|
|
29
|
+
if response is not None:
|
|
30
|
+
retry_after = response.headers.get("retry-after")
|
|
31
|
+
if retry_after:
|
|
32
|
+
try:
|
|
33
|
+
return min(max(float(retry_after), 0.0), MAX_BACKOFF_SECONDS)
|
|
34
|
+
except ValueError:
|
|
35
|
+
pass
|
|
36
|
+
base = 0.5 * (2**attempt)
|
|
37
|
+
return min(base + random.random() * base, MAX_BACKOFF_SECONDS)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _iterate_sse(response: http_requests.Response) -> Iterator[Dict[str, Any]]:
|
|
41
|
+
try:
|
|
42
|
+
for raw in response.iter_lines(decode_unicode=True):
|
|
43
|
+
if not raw or not raw.startswith("data:"):
|
|
44
|
+
continue
|
|
45
|
+
data = raw[5:].lstrip()
|
|
46
|
+
if data == "[DONE]":
|
|
47
|
+
return
|
|
48
|
+
try:
|
|
49
|
+
event = _json.loads(data)
|
|
50
|
+
except ValueError:
|
|
51
|
+
continue
|
|
52
|
+
if not isinstance(event, dict):
|
|
53
|
+
continue
|
|
54
|
+
nested = event.get("error") if isinstance(event.get("error"), dict) else None
|
|
55
|
+
if nested is not None or event.get("type") == "error":
|
|
56
|
+
error = nested or event
|
|
57
|
+
raise NinjaChatError(
|
|
58
|
+
str(error.get("message") or "Stream failed."),
|
|
59
|
+
status=response.status_code,
|
|
60
|
+
code=str(error.get("code") or "stream_error"),
|
|
61
|
+
type=error.get("type"),
|
|
62
|
+
body=event,
|
|
63
|
+
)
|
|
64
|
+
yield event
|
|
65
|
+
finally:
|
|
66
|
+
response.close()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class NinjaChat:
|
|
70
|
+
"""Client for the canonical NinjaChat API v1 surface."""
|
|
71
|
+
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
api_key: str,
|
|
75
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
76
|
+
*,
|
|
77
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
78
|
+
timeout: float = 120.0,
|
|
79
|
+
session: Optional[http_requests.Session] = None,
|
|
80
|
+
) -> None:
|
|
81
|
+
if not api_key:
|
|
82
|
+
raise NinjaChatError(
|
|
83
|
+
"Missing api_key. Create one at https://www.ninjachat.ai/developers/keys",
|
|
84
|
+
code="missing_api_key",
|
|
85
|
+
)
|
|
86
|
+
self.api_key = api_key
|
|
87
|
+
self.base_url = base_url.rstrip("/")
|
|
88
|
+
self.max_retries = max_retries
|
|
89
|
+
self.timeout = timeout
|
|
90
|
+
self._session = session or http_requests.Session()
|
|
91
|
+
self.responses = _Responses(self)
|
|
92
|
+
self.chat = _Chat(self)
|
|
93
|
+
self.models = _Models(self)
|
|
94
|
+
self.images = _Images(self)
|
|
95
|
+
self.videos = _Videos(self)
|
|
96
|
+
self.search = _Search(self)
|
|
97
|
+
self.requests = _Requests(self)
|
|
98
|
+
self.webhooks = _Webhooks(self)
|
|
99
|
+
|
|
100
|
+
def balance(self) -> Dict[str, Any]:
|
|
101
|
+
return self._request("GET", "/balance", idempotent_method=True)
|
|
102
|
+
|
|
103
|
+
def usage(self, period: str = "7d") -> Dict[str, Any]:
|
|
104
|
+
return self._request("GET", "/usage", params={"period": period}, idempotent_method=True)
|
|
105
|
+
|
|
106
|
+
def _request(
|
|
107
|
+
self,
|
|
108
|
+
method: str,
|
|
109
|
+
path: str,
|
|
110
|
+
*,
|
|
111
|
+
json: Optional[Dict[str, Any]] = None,
|
|
112
|
+
params: Optional[Dict[str, str]] = None,
|
|
113
|
+
supports_idempotency: bool = False,
|
|
114
|
+
idempotent_method: bool = False,
|
|
115
|
+
idempotency_key: Optional[str] = None,
|
|
116
|
+
max_retries: Optional[int] = None,
|
|
117
|
+
stream: bool = False,
|
|
118
|
+
timeout: Optional[float] = None,
|
|
119
|
+
) -> Any:
|
|
120
|
+
retries = self.max_retries if max_retries is None else max_retries
|
|
121
|
+
if supports_idempotency and idempotency_key is None and retries > 0:
|
|
122
|
+
idempotency_key = str(uuid.uuid4())
|
|
123
|
+
retriable = idempotent_method or idempotency_key is not None
|
|
124
|
+
attempts = retries + 1 if retriable else 1
|
|
125
|
+
headers = {
|
|
126
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
127
|
+
"Accept": "text/event-stream" if stream else "application/json",
|
|
128
|
+
}
|
|
129
|
+
if idempotency_key:
|
|
130
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
131
|
+
url = self.base_url + path
|
|
132
|
+
last_error: Optional[NinjaChatError] = None
|
|
133
|
+
for attempt in range(attempts):
|
|
134
|
+
try:
|
|
135
|
+
response = self._session.request(
|
|
136
|
+
method, url, json=json, params=params, headers=headers,
|
|
137
|
+
stream=stream, timeout=timeout or self.timeout,
|
|
138
|
+
)
|
|
139
|
+
except http_requests.RequestException as exc:
|
|
140
|
+
last_error = NinjaChatError(f"Network error: {exc}", code="network_error")
|
|
141
|
+
if attempt == attempts - 1:
|
|
142
|
+
raise last_error from exc
|
|
143
|
+
time.sleep(_retry_delay(None, attempt))
|
|
144
|
+
continue
|
|
145
|
+
if response.ok:
|
|
146
|
+
return response if stream else response.json()
|
|
147
|
+
try:
|
|
148
|
+
body = response.json()
|
|
149
|
+
except ValueError:
|
|
150
|
+
body = None
|
|
151
|
+
error = NinjaChatError.from_response(response.status_code, body, response.headers.get("x-request-id"))
|
|
152
|
+
last_error = error
|
|
153
|
+
in_flight = response.status_code == 409 and error.code == "request_in_flight" and idempotency_key is not None
|
|
154
|
+
if not (retriable and attempt < attempts - 1 and (response.status_code in RETRIABLE_STATUSES or in_flight)):
|
|
155
|
+
raise error
|
|
156
|
+
time.sleep(_retry_delay(response, attempt))
|
|
157
|
+
raise last_error or NinjaChatError("Request failed.")
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class _Responses:
|
|
161
|
+
def __init__(self, client: NinjaChat) -> None:
|
|
162
|
+
self._client = client
|
|
163
|
+
|
|
164
|
+
def create(
|
|
165
|
+
self, *, idempotency_key: Optional[str] = None, max_retries: Optional[int] = None,
|
|
166
|
+
**params: Unpack[ResponseCreateParams],
|
|
167
|
+
) -> Union[Dict[str, Any], Iterator[Dict[str, Any]]]:
|
|
168
|
+
response = self._client._request(
|
|
169
|
+
"POST", "/responses", json=dict(params), supports_idempotency=True,
|
|
170
|
+
idempotency_key=idempotency_key, max_retries=max_retries,
|
|
171
|
+
stream=bool(params.get("stream")),
|
|
172
|
+
)
|
|
173
|
+
return _iterate_sse(response) if params.get("stream") else response
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class _Chat:
|
|
177
|
+
def __init__(self, client: NinjaChat) -> None:
|
|
178
|
+
self.completions = _ChatCompletions(client)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class _ChatCompletions:
|
|
182
|
+
def __init__(self, client: NinjaChat) -> None:
|
|
183
|
+
self._client = client
|
|
184
|
+
|
|
185
|
+
def create(
|
|
186
|
+
self, *, idempotency_key: Optional[str] = None, max_retries: Optional[int] = None,
|
|
187
|
+
**params: Unpack[ChatCompletionParams],
|
|
188
|
+
) -> Union[Dict[str, Any], Iterator[Dict[str, Any]]]:
|
|
189
|
+
response = self._client._request(
|
|
190
|
+
"POST", "/chat/completions", json=dict(params), supports_idempotency=True,
|
|
191
|
+
idempotency_key=idempotency_key, max_retries=max_retries,
|
|
192
|
+
stream=bool(params.get("stream")),
|
|
193
|
+
)
|
|
194
|
+
return _iterate_sse(response) if params.get("stream") else response
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class _Models:
|
|
198
|
+
def __init__(self, client: NinjaChat) -> None:
|
|
199
|
+
self._client = client
|
|
200
|
+
|
|
201
|
+
def list(self) -> Dict[str, Any]:
|
|
202
|
+
return self._client._request("GET", "/models", idempotent_method=True)
|
|
203
|
+
|
|
204
|
+
def retrieve(self, model_id: str) -> Dict[str, Any]:
|
|
205
|
+
return self._client._request("GET", f"/models/{quote(model_id, safe='')}", idempotent_method=True)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class _Images:
|
|
209
|
+
def __init__(self, client: NinjaChat) -> None:
|
|
210
|
+
self._client = client
|
|
211
|
+
|
|
212
|
+
def generate(
|
|
213
|
+
self, *, idempotency_key: Optional[str] = None, max_retries: Optional[int] = None,
|
|
214
|
+
**params: Unpack[ImageGenerateParams],
|
|
215
|
+
) -> Dict[str, Any]:
|
|
216
|
+
return self._client._request(
|
|
217
|
+
"POST", "/images/generations", json=dict(params), supports_idempotency=True,
|
|
218
|
+
idempotency_key=idempotency_key, max_retries=max_retries, timeout=300.0,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class _Videos:
|
|
223
|
+
def __init__(self, client: NinjaChat) -> None:
|
|
224
|
+
self._client = client
|
|
225
|
+
|
|
226
|
+
def generate(
|
|
227
|
+
self, *, idempotency_key: Optional[str] = None, max_retries: Optional[int] = None,
|
|
228
|
+
**params: Unpack[VideoGenerateParams],
|
|
229
|
+
) -> Dict[str, Any]:
|
|
230
|
+
return self._client._request(
|
|
231
|
+
"POST", "/videos", json=dict(params), supports_idempotency=True,
|
|
232
|
+
idempotency_key=idempotency_key, max_retries=max_retries, timeout=300.0,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
def retrieve(self, video_id: str) -> Dict[str, Any]:
|
|
236
|
+
return self._client._request("GET", f"/videos/{quote(video_id, safe='')}", idempotent_method=True)
|
|
237
|
+
|
|
238
|
+
def wait_for(self, video_id: str, *, poll_seconds: float = 5.0, timeout_seconds: float = 600.0) -> Dict[str, Any]:
|
|
239
|
+
deadline = time.monotonic() + timeout_seconds
|
|
240
|
+
while True:
|
|
241
|
+
result = self.retrieve(video_id)
|
|
242
|
+
if result.get("status") == "completed":
|
|
243
|
+
return result
|
|
244
|
+
if result.get("status") == "failed":
|
|
245
|
+
raise NinjaChatError(str(result.get("error") or "Video generation failed."), status=200, code="generation_failed", request_id=video_id, body=result)
|
|
246
|
+
if time.monotonic() + poll_seconds > deadline:
|
|
247
|
+
raise NinjaChatError(f"Timed out waiting for video job {video_id}.", code="poll_timeout", request_id=video_id)
|
|
248
|
+
time.sleep(poll_seconds)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class _Search:
|
|
252
|
+
def __init__(self, client: NinjaChat) -> None:
|
|
253
|
+
self._client = client
|
|
254
|
+
|
|
255
|
+
def query(
|
|
256
|
+
self, *, idempotency_key: Optional[str] = None, max_retries: Optional[int] = None,
|
|
257
|
+
**params: Unpack[SearchParams],
|
|
258
|
+
) -> Dict[str, Any]:
|
|
259
|
+
return self._client._request(
|
|
260
|
+
"POST", "/search", json=dict(params), supports_idempotency=True,
|
|
261
|
+
idempotency_key=idempotency_key, max_retries=max_retries,
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
class _Requests:
|
|
266
|
+
def __init__(self, client: NinjaChat) -> None:
|
|
267
|
+
self._client = client
|
|
268
|
+
|
|
269
|
+
def get(self, request_id: str) -> Dict[str, Any]:
|
|
270
|
+
return self._client._request("GET", f"/requests/{quote(request_id, safe='')}", idempotent_method=True)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class _Webhooks:
|
|
274
|
+
def __init__(self, client: NinjaChat) -> None:
|
|
275
|
+
self._client = client
|
|
276
|
+
|
|
277
|
+
def list(self) -> List[Dict[str, Any]]:
|
|
278
|
+
return self._client._request("GET", "/webhooks", idempotent_method=True)["endpoints"]
|
|
279
|
+
|
|
280
|
+
def create(self, *, url: str, events: Optional[List[str]] = None) -> Dict[str, Any]:
|
|
281
|
+
body: Dict[str, Any] = {"url": url}
|
|
282
|
+
if events is not None:
|
|
283
|
+
body["events"] = events
|
|
284
|
+
return self._client._request("POST", "/webhooks", json=body, max_retries=0)
|
|
285
|
+
|
|
286
|
+
def delete(self, endpoint_id: str) -> Dict[str, Any]:
|
|
287
|
+
return self._client._request("DELETE", "/webhooks", params={"id": endpoint_id}, idempotent_method=True)
|
|
288
|
+
|
|
289
|
+
def list_deliveries(self, *, endpoint_id: Optional[str] = None, limit: Optional[int] = None) -> List[Dict[str, Any]]:
|
|
290
|
+
params: Dict[str, str] = {}
|
|
291
|
+
if endpoint_id is not None:
|
|
292
|
+
params["endpoint_id"] = endpoint_id
|
|
293
|
+
if limit is not None:
|
|
294
|
+
params["limit"] = str(limit)
|
|
295
|
+
return self._client._request("GET", "/webhooks/deliveries", params=params, idempotent_method=True)["deliveries"]
|
|
296
|
+
|
|
297
|
+
def test(self, endpoint_id: str) -> Dict[str, Any]:
|
|
298
|
+
return self._client._request("POST", "/webhooks/test", json={"endpoint_id": endpoint_id}, max_retries=0)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Typed errors for the NinjaChat SDK.
|
|
2
|
+
|
|
3
|
+
The API returns an OpenAI-compatible envelope::
|
|
4
|
+
|
|
5
|
+
{"error": {"message", "type", "code", "param"}}
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Dict, Optional
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class NinjaChatError(Exception):
|
|
14
|
+
"""Raised for every non-2xx API response, network failure, or SDK-level failure.
|
|
15
|
+
|
|
16
|
+
Attributes:
|
|
17
|
+
status: HTTP status (0 for network/timeout errors raised before a response).
|
|
18
|
+
code: Machine-readable code (e.g. ``insufficient_credits``, ``rate_limit_exceeded``).
|
|
19
|
+
request_id: The X-Request-ID / request_id, when the server produced one.
|
|
20
|
+
type: OpenAI-style error type (e.g. ``invalid_request_error``).
|
|
21
|
+
param: The offending parameter, when reported.
|
|
22
|
+
body: The full parsed error body (extra fields: balance, retry_after, ...).
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
message: str,
|
|
28
|
+
*,
|
|
29
|
+
status: int = 0,
|
|
30
|
+
code: str = "unknown",
|
|
31
|
+
request_id: Optional[str] = None,
|
|
32
|
+
type: Optional[str] = None,
|
|
33
|
+
param: Optional[str] = None,
|
|
34
|
+
body: Optional[Dict[str, Any]] = None,
|
|
35
|
+
) -> None:
|
|
36
|
+
super().__init__(message)
|
|
37
|
+
self.message = message
|
|
38
|
+
self.status = status
|
|
39
|
+
self.code = code
|
|
40
|
+
self.request_id = request_id
|
|
41
|
+
self.type = type
|
|
42
|
+
self.param = param
|
|
43
|
+
self.body = body or {}
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def from_response(
|
|
47
|
+
cls, status: int, body: Any, header_request_id: Optional[str] = None
|
|
48
|
+
) -> "NinjaChatError":
|
|
49
|
+
b: Dict[str, Any] = body if isinstance(body, dict) else {}
|
|
50
|
+
nested = b.get("error") if isinstance(b.get("error"), dict) else {}
|
|
51
|
+
message = nested.get("message") or f"HTTP {status}"
|
|
52
|
+
code = nested.get("code") or f"http_{status}"
|
|
53
|
+
return cls(
|
|
54
|
+
str(message),
|
|
55
|
+
status=status,
|
|
56
|
+
code=str(code),
|
|
57
|
+
request_id=header_request_id,
|
|
58
|
+
type=nested.get("type"),
|
|
59
|
+
param=nested.get("param"),
|
|
60
|
+
body=b,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
def __repr__(self) -> str: # pragma: no cover - cosmetic
|
|
64
|
+
return (
|
|
65
|
+
f"NinjaChatError(status={self.status}, code={self.code!r}, "
|
|
66
|
+
f"request_id={self.request_id!r}, message={self.message!r})"
|
|
67
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Typed request objects for NinjaChat API v1."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict, List, Literal, Union
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
from typing import NotRequired, Required, TypedDict
|
|
7
|
+
except ImportError: # Python 3.9-3.10
|
|
8
|
+
from typing_extensions import NotRequired, Required, TypedDict
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ProviderPolicy(TypedDict, total=False):
|
|
12
|
+
only: List[str]
|
|
13
|
+
exclude: List[str]
|
|
14
|
+
order: List[str]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class RoutingPolicy(TypedDict, total=False):
|
|
18
|
+
strategy: Literal["balanced", "cost", "latency", "quality"]
|
|
19
|
+
providers: ProviderPolicy
|
|
20
|
+
allow_fallbacks: bool
|
|
21
|
+
require_parameters: bool
|
|
22
|
+
data_policy: Literal["default", "no_training", "zero_retention"]
|
|
23
|
+
caching: Literal["auto"]
|
|
24
|
+
max_cost_usd: float
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ChatMessage(TypedDict, total=False):
|
|
28
|
+
role: Required[Literal["developer", "system", "user", "assistant", "tool"]]
|
|
29
|
+
content: Union[str, List[Dict[str, Any]], None]
|
|
30
|
+
tool_call_id: str
|
|
31
|
+
tool_calls: List[Dict[str, Any]]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ChatCompletionParams(TypedDict, total=False):
|
|
35
|
+
model: str
|
|
36
|
+
models: List[str]
|
|
37
|
+
messages: Required[List[ChatMessage]]
|
|
38
|
+
max_completion_tokens: int
|
|
39
|
+
temperature: float
|
|
40
|
+
top_p: float
|
|
41
|
+
stop: Union[str, List[str]]
|
|
42
|
+
frequency_penalty: float
|
|
43
|
+
presence_penalty: float
|
|
44
|
+
seed: int
|
|
45
|
+
user: str
|
|
46
|
+
response_format: Dict[str, Any]
|
|
47
|
+
stream: bool
|
|
48
|
+
stream_options: Dict[str, bool]
|
|
49
|
+
tools: List[Dict[str, Any]]
|
|
50
|
+
tool_choice: Union[str, Dict[str, Any]]
|
|
51
|
+
parallel_tool_calls: bool
|
|
52
|
+
routing: RoutingPolicy
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ResponseCreateParams(TypedDict, total=False):
|
|
56
|
+
model: str
|
|
57
|
+
models: List[str]
|
|
58
|
+
input: Required[Union[str, List[Dict[str, Any]]]]
|
|
59
|
+
instructions: str
|
|
60
|
+
max_output_tokens: int
|
|
61
|
+
temperature: float
|
|
62
|
+
top_p: float
|
|
63
|
+
tools: List[Dict[str, Any]]
|
|
64
|
+
tool_choice: Union[str, Dict[str, Any]]
|
|
65
|
+
parallel_tool_calls: bool
|
|
66
|
+
text: Dict[str, Any]
|
|
67
|
+
routing: RoutingPolicy
|
|
68
|
+
metadata: Dict[str, str]
|
|
69
|
+
user: str
|
|
70
|
+
stream: bool
|
|
71
|
+
store: Literal[False]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class ImageGenerateParams(TypedDict, total=False):
|
|
75
|
+
prompt: Required[str]
|
|
76
|
+
model: str
|
|
77
|
+
n: int
|
|
78
|
+
size: str
|
|
79
|
+
aspect_ratio: str
|
|
80
|
+
image: str
|
|
81
|
+
width: int
|
|
82
|
+
height: int
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class VideoGenerateParams(TypedDict, total=False):
|
|
86
|
+
prompt: Required[str]
|
|
87
|
+
model: str
|
|
88
|
+
duration: int
|
|
89
|
+
aspect_ratio: Literal["16:9", "9:16"]
|
|
90
|
+
image_url: str
|
|
91
|
+
reference_images: List[str]
|
|
92
|
+
reference_video: str
|
|
93
|
+
reference_audio: str
|
|
94
|
+
generate_audio: bool
|
|
95
|
+
watermark: bool
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class SearchParams(TypedDict, total=False):
|
|
99
|
+
query: Required[str]
|
|
100
|
+
group: Literal["web", "news"]
|
|
101
|
+
max_results: int
|
|
102
|
+
search_depth: Literal["basic", "advanced"]
|
|
103
|
+
topic: Literal["general", "news", "finance"]
|
|
104
|
+
include_answer: bool
|
|
105
|
+
include_images: bool
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Outbound-webhook signature verification.
|
|
2
|
+
|
|
3
|
+
NinjaChat signs every delivery with::
|
|
4
|
+
|
|
5
|
+
X-Ninja-Signature: hex( HMAC-SHA256( secret, f"{timestamp}.{raw_body}" ) )
|
|
6
|
+
X-Ninja-Timestamp: unix seconds at send time
|
|
7
|
+
|
|
8
|
+
Verify with the RAW request body bytes exactly as received — re-serializing the
|
|
9
|
+
parsed JSON changes the bytes and breaks the signature.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import hmac
|
|
16
|
+
import time
|
|
17
|
+
from typing import Optional, Union
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def verify_webhook_signature(
|
|
21
|
+
raw_body: Union[str, bytes],
|
|
22
|
+
signature: str,
|
|
23
|
+
timestamp: Union[str, int],
|
|
24
|
+
secret: str,
|
|
25
|
+
*,
|
|
26
|
+
tolerance_seconds: Optional[int] = 300,
|
|
27
|
+
) -> bool:
|
|
28
|
+
"""Return True iff ``signature`` is a valid signature of ``raw_body``.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
raw_body: The raw request body (str or bytes), byte-exact.
|
|
32
|
+
signature: The ``X-Ninja-Signature`` header value (hex).
|
|
33
|
+
timestamp: The ``X-Ninja-Timestamp`` header value (unix seconds).
|
|
34
|
+
secret: The endpoint's signing secret (returned once at creation).
|
|
35
|
+
tolerance_seconds: Reject deliveries whose timestamp is further than
|
|
36
|
+
this many seconds from now (replay protection). Default 300;
|
|
37
|
+
pass ``None`` to skip the check.
|
|
38
|
+
"""
|
|
39
|
+
try:
|
|
40
|
+
ts = int(timestamp)
|
|
41
|
+
except (TypeError, ValueError):
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
if tolerance_seconds is not None and abs(time.time() - ts) > tolerance_seconds:
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
body_bytes = raw_body.encode("utf-8") if isinstance(raw_body, str) else raw_body
|
|
48
|
+
signed_payload = f"{ts}.".encode("utf-8") + body_bytes
|
|
49
|
+
expected = hmac.new(secret.encode("utf-8"), signed_payload, hashlib.sha256).hexdigest()
|
|
50
|
+
return hmac.compare_digest(expected, signature.strip().lower())
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ninjachat
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for the NinjaChat API — one typed client for chat, responses, media, routing, usage, and webhooks.
|
|
5
|
+
Author: Helium Technologies, Inc.
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Documentation, https://docs.ninjachat.ai
|
|
8
|
+
Project-URL: OpenAPI spec, https://www.ninjachat.ai/api/v1/openapi
|
|
9
|
+
Project-URL: Source, https://github.com/bloon-ai/ninjachat-sdk/tree/main/packages/python
|
|
10
|
+
Project-URL: Issues, https://github.com/bloon-ai/ninjachat-sdk/issues
|
|
11
|
+
Keywords: ninjachat,ai,llm,openai-compatible,sdk
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: requests>=2.28
|
|
25
|
+
Requires-Dist: typing-extensions>=4.8; python_version < "3.11"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# NinjaChat Python SDK
|
|
29
|
+
|
|
30
|
+
Typed client for the clean NinjaChat API v1.
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install ninjachat
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import os
|
|
38
|
+
from ninjachat import NinjaChat
|
|
39
|
+
|
|
40
|
+
client = NinjaChat(api_key=os.environ["NINJACHAT_API_KEY"])
|
|
41
|
+
response = client.responses.create(
|
|
42
|
+
model="ninja/auto",
|
|
43
|
+
input="Write one sentence about clean APIs.",
|
|
44
|
+
max_output_tokens=64,
|
|
45
|
+
routing={"strategy": "balanced", "data_policy": "no_training"},
|
|
46
|
+
)
|
|
47
|
+
print(response["output_text"], response["cost_usd"], response["request_id"])
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Ordered fallbacks and provider constraints are explicit:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
completion = client.chat.completions.create(
|
|
54
|
+
models=["gpt-5", "claude-sonnet-4"],
|
|
55
|
+
messages=[{"role": "user", "content": "Hello"}],
|
|
56
|
+
max_completion_tokens=100,
|
|
57
|
+
routing={"strategy": "latency", "allow_fallbacks": True, "caching": "auto", "max_cost_usd": 0.10},
|
|
58
|
+
)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Streams return iterators of typed-shape dictionaries:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
for event in client.responses.create(model="ninja/auto", input="Hello", stream=True):
|
|
65
|
+
if event.get("type") == "response.output_text.delta":
|
|
66
|
+
print(event.get("delta", ""), end="")
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Models and prices come from `client.models.list()`. Images use `client.images.generate()`, videos use `client.videos.generate()` and `client.videos.wait_for()`, and account observability is available through `client.usage()`, `client.balance()`, and `client.requests.get()`.
|
|
70
|
+
|
|
71
|
+
Signed webhooks replace video polling and fire spend alerts: `client.webhooks.create(...)` or the [console](https://www.ninjachat.ai/developers/keys#webhooks). Verify deliveries with `verify_webhook_signature`.
|
|
72
|
+
|
|
73
|
+
The base URL is `https://www.ninjachat.ai/api/v1`. Chat and Responses are billed by actual token usage. See [docs.ninjachat.ai](https://docs.ninjachat.ai).
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
ninjachat/__init__.py
|
|
5
|
+
ninjachat/client.py
|
|
6
|
+
ninjachat/contract.py
|
|
7
|
+
ninjachat/errors.py
|
|
8
|
+
ninjachat/py.typed
|
|
9
|
+
ninjachat/types.py
|
|
10
|
+
ninjachat/webhooks.py
|
|
11
|
+
ninjachat.egg-info/PKG-INFO
|
|
12
|
+
ninjachat.egg-info/SOURCES.txt
|
|
13
|
+
ninjachat.egg-info/dependency_links.txt
|
|
14
|
+
ninjachat.egg-info/requires.txt
|
|
15
|
+
ninjachat.egg-info/top_level.txt
|
|
16
|
+
tests/test_smoke.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ninjachat
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ninjachat"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Official Python SDK for the NinjaChat API — one typed client for chat, responses, media, routing, usage, and webhooks."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Helium Technologies, Inc." }]
|
|
13
|
+
dependencies = ["requests>=2.28", "typing-extensions>=4.8; python_version < '3.11'"]
|
|
14
|
+
keywords = ["ninjachat", "ai", "llm", "openai-compatible", "sdk"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.9",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Documentation = "https://docs.ninjachat.ai"
|
|
29
|
+
"OpenAPI spec" = "https://www.ninjachat.ai/api/v1/openapi"
|
|
30
|
+
Source = "https://github.com/bloon-ai/ninjachat-sdk/tree/main/packages/python"
|
|
31
|
+
Issues = "https://github.com/bloon-ai/ninjachat-sdk/issues"
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.packages.find]
|
|
34
|
+
include = ["ninjachat*"]
|
|
35
|
+
|
|
36
|
+
[tool.setuptools.package-data]
|
|
37
|
+
ninjachat = ["py.typed"]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
from unittest.mock import Mock
|
|
3
|
+
|
|
4
|
+
from ninjachat import NinjaChat, NinjaChatError, __version__
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class NinjaChatSmokeTest(unittest.TestCase):
|
|
8
|
+
def test_lists_models_with_expected_auth_and_base_url(self) -> None:
|
|
9
|
+
session = Mock()
|
|
10
|
+
response = Mock()
|
|
11
|
+
response.ok = True
|
|
12
|
+
response.json.return_value = {"object": "list", "data": []}
|
|
13
|
+
session.request.return_value = response
|
|
14
|
+
client = NinjaChat(api_key="nj_sk_test", max_retries=0, session=session)
|
|
15
|
+
|
|
16
|
+
self.assertEqual(client.models.list(), {"object": "list", "data": []})
|
|
17
|
+
session.request.assert_called_once()
|
|
18
|
+
args, kwargs = session.request.call_args
|
|
19
|
+
self.assertEqual(args[:2], ("GET", "https://www.ninjachat.ai/api/v1/models"))
|
|
20
|
+
self.assertEqual(kwargs["headers"]["Authorization"], "Bearer nj_sk_test")
|
|
21
|
+
|
|
22
|
+
def test_missing_key_fails_clearly(self) -> None:
|
|
23
|
+
with self.assertRaises(NinjaChatError) as raised:
|
|
24
|
+
NinjaChat(api_key="")
|
|
25
|
+
self.assertEqual(raised.exception.code, "missing_api_key")
|
|
26
|
+
|
|
27
|
+
def test_preview_version_is_synchronized(self) -> None:
|
|
28
|
+
self.assertEqual(__version__, "0.1.0")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
if __name__ == "__main__":
|
|
32
|
+
unittest.main()
|