antarya 0.1.0__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.
- antarya/__init__.py +33 -0
- antarya/_base.py +38 -0
- antarya/_client.py +218 -0
- antarya/_errors.py +84 -0
- antarya/_streaming.py +365 -0
- antarya/_types.py +227 -0
- antarya/py.typed +0 -0
- antarya/resources/__init__.py +12 -0
- antarya/resources/_common.py +120 -0
- antarya/resources/batches.py +53 -0
- antarya/resources/chat.py +112 -0
- antarya/resources/files.py +41 -0
- antarya/resources/models.py +26 -0
- antarya/resources/sessions.py +41 -0
- antarya-0.1.0.dist-info/METADATA +120 -0
- antarya-0.1.0.dist-info/RECORD +18 -0
- antarya-0.1.0.dist-info/WHEEL +4 -0
- antarya-0.1.0.dist-info/licenses/LICENSE +21 -0
antarya/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from ._client import AsyncAntarya, Antarya # noqa: E402
|
|
6
|
+
from ._errors import (
|
|
7
|
+
APIConnectionError, APIError, APITimeoutError, AuthenticationError, BadRequestError,
|
|
8
|
+
InternalServerError, NotFoundError, OverloadedError, PermissionDeniedError,
|
|
9
|
+
RateLimitError, RequestTooLargeError,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
from ._streaming import (
|
|
13
|
+
AsyncChatStream, ChatStream, ContentDelta, ReplyDone, ReplyStart, StreamEvent, ThinkingEvent,
|
|
14
|
+
UnknownEvent,
|
|
15
|
+
)
|
|
16
|
+
from ._types import (
|
|
17
|
+
ArtifactPart, BatchCounts, BatchError, BatchObject, BatchResultLine, ChatReply,
|
|
18
|
+
DeletedObject, FileObject, ListPage, ModelCapabilities, ModelObject, ReplyPart,
|
|
19
|
+
SessionObject, SessionWithMessages, TextPart, ThinkingNote, TokenCount, ToolCallPart,
|
|
20
|
+
UnknownPart, Usage,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"Antarya", "AsyncAntarya", "APIError", "APIConnectionError", "APITimeoutError",
|
|
25
|
+
"AuthenticationError", "BadRequestError", "InternalServerError", "NotFoundError",
|
|
26
|
+
"OverloadedError", "PermissionDeniedError", "RateLimitError", "RequestTooLargeError",
|
|
27
|
+
"ArtifactPart", "BatchCounts", "BatchError", "BatchObject", "BatchResultLine", "ChatReply",
|
|
28
|
+
"DeletedObject", "FileObject", "ListPage", "ModelCapabilities", "ModelObject", "ReplyPart",
|
|
29
|
+
"SessionObject", "SessionWithMessages", "TextPart", "ThinkingNote", "TokenCount",
|
|
30
|
+
"ToolCallPart", "UnknownPart", "Usage",
|
|
31
|
+
"AsyncChatStream", "ChatStream", "ContentDelta", "ReplyDone", "ReplyStart", "StreamEvent",
|
|
32
|
+
"ThinkingEvent", "UnknownEvent", "__version__",
|
|
33
|
+
]
|
antarya/_base.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import dataclasses
|
|
4
|
+
import random
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
DEFAULT_BASE_URL = "https://antarya.ai/v1"
|
|
8
|
+
RETRY_STATUS = {429, 500, 503}
|
|
9
|
+
MAX_RETRY_AFTER = 60.0
|
|
10
|
+
# What a wrong-shaped body raises while it is read into a type.
|
|
11
|
+
MALFORMED = (KeyError, TypeError, ValueError, AttributeError, IndexError)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def retry_wait(attempt: int, retry_after: Optional[float]) -> float:
|
|
15
|
+
if retry_after is not None:
|
|
16
|
+
return min(retry_after, MAX_RETRY_AFTER)
|
|
17
|
+
return min(8.0, 0.5 * 2**attempt) * (0.75 + random.random() * 0.5)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def strip_none(d: dict) -> dict:
|
|
21
|
+
return {k: v for k, v in d.items() if v is not None}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def to_wire(value):
|
|
25
|
+
"""Turns request values into wire dicts: dataclasses drop their None fields, UnknownPart is flattened."""
|
|
26
|
+
from ._types import UnknownPart
|
|
27
|
+
|
|
28
|
+
if isinstance(value, UnknownPart):
|
|
29
|
+
head = {} if value.type is None else {"type": value.type}
|
|
30
|
+
return {**head, **to_wire(value.data)}
|
|
31
|
+
if dataclasses.is_dataclass(value) and not isinstance(value, type):
|
|
32
|
+
return {f.name: to_wire(getattr(value, f.name)) for f in dataclasses.fields(value)
|
|
33
|
+
if getattr(value, f.name) is not None}
|
|
34
|
+
if isinstance(value, dict):
|
|
35
|
+
return {k: to_wire(v) for k, v in value.items()}
|
|
36
|
+
if isinstance(value, (list, tuple)):
|
|
37
|
+
return [to_wire(v) for v in value]
|
|
38
|
+
return value
|
antarya/_client.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Optional, Union
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from . import _base, resources
|
|
11
|
+
from ._errors import (
|
|
12
|
+
APIConnectionError, APIError, APITimeoutError, AuthenticationError, error_from,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
from . import __version__ as VERSION # noqa: E402
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class _NotGiven:
|
|
19
|
+
def __repr__(self) -> str:
|
|
20
|
+
return "NOT_GIVEN"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
NOT_GIVEN = _NotGiven()
|
|
24
|
+
DEFAULT_TIMEOUT = 600.0
|
|
25
|
+
NO_KEY = "No API key. Set ANTARYA_API_KEY or pass api_key."
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _Core:
|
|
29
|
+
def __init__(self, api_key, base_url, max_retries, timeout, has_client=False):
|
|
30
|
+
self._api_key = api_key if api_key is not None else os.environ.get("ANTARYA_API_KEY")
|
|
31
|
+
self.base_url = (base_url or _base.DEFAULT_BASE_URL).rstrip("/")
|
|
32
|
+
self.max_retries = max_retries
|
|
33
|
+
# A supplied http_client keeps its own timeout unless `timeout=` was passed.
|
|
34
|
+
self._client_timeout = has_client and timeout is NOT_GIVEN
|
|
35
|
+
self.timeout = DEFAULT_TIMEOUT if timeout is NOT_GIVEN else timeout
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def api_key(self) -> Optional[str]:
|
|
39
|
+
return self._api_key
|
|
40
|
+
|
|
41
|
+
def __repr__(self) -> str:
|
|
42
|
+
return f"{type(self).__name__}(base_url={self.base_url!r})"
|
|
43
|
+
|
|
44
|
+
def _prepare(self, path: str, json: Any, files: Any, params: Any):
|
|
45
|
+
if not self._api_key:
|
|
46
|
+
raise AuthenticationError(NO_KEY, type="authentication_error")
|
|
47
|
+
headers = {"authorization": f"Bearer {self._api_key}", "user-agent": f"antarya-python/{VERSION}"}
|
|
48
|
+
url = self.base_url + (path if path.startswith("/") else "/" + path)
|
|
49
|
+
kwargs: dict = {"headers": headers, "params": params}
|
|
50
|
+
if not self._client_timeout:
|
|
51
|
+
kwargs["timeout"] = self.timeout
|
|
52
|
+
if files is not None:
|
|
53
|
+
kwargs["files"] = files
|
|
54
|
+
elif json is not None:
|
|
55
|
+
kwargs["json"] = json
|
|
56
|
+
return url, kwargs
|
|
57
|
+
|
|
58
|
+
def _failure(self, res: httpx.Response) -> APIError:
|
|
59
|
+
try:
|
|
60
|
+
parsed = res.json()
|
|
61
|
+
except (ValueError, httpx.StreamError):
|
|
62
|
+
parsed = None
|
|
63
|
+
return error_from(res.status_code, parsed, res.headers)
|
|
64
|
+
|
|
65
|
+
@staticmethod
|
|
66
|
+
def _unreadable(res: httpx.Response) -> APIError:
|
|
67
|
+
return APIError(
|
|
68
|
+
"The API returned a reply that could not be read.",
|
|
69
|
+
status=res.status_code, type="api_error", request_id=res.headers.get("request-id"),
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def _transport_error(e: httpx.TransportError) -> APIError:
|
|
74
|
+
err = APITimeoutError() if isinstance(e, httpx.TimeoutException) else APIConnectionError()
|
|
75
|
+
err.__cause__ = e
|
|
76
|
+
return err
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Antarya(_Core):
|
|
80
|
+
def __init__(
|
|
81
|
+
self,
|
|
82
|
+
api_key: Optional[str] = None,
|
|
83
|
+
base_url: Optional[str] = None,
|
|
84
|
+
max_retries: int = 2,
|
|
85
|
+
timeout: Union[float, None, _NotGiven] = NOT_GIVEN,
|
|
86
|
+
http_client: Optional[httpx.Client] = None,
|
|
87
|
+
_sleep=time.sleep,
|
|
88
|
+
) -> None:
|
|
89
|
+
super().__init__(api_key, base_url, max_retries, timeout, http_client is not None)
|
|
90
|
+
self._owns_http = http_client is None
|
|
91
|
+
self._http = http_client or httpx.Client()
|
|
92
|
+
self.chat = resources.Chat(self)
|
|
93
|
+
self.models = resources.Models(self)
|
|
94
|
+
self.files = resources.Files(self)
|
|
95
|
+
self.sessions = resources.Sessions(self)
|
|
96
|
+
self.batches = resources.Batches(self)
|
|
97
|
+
self._sleep = _sleep
|
|
98
|
+
|
|
99
|
+
def close(self) -> None:
|
|
100
|
+
if self._owns_http:
|
|
101
|
+
self._http.close()
|
|
102
|
+
|
|
103
|
+
def __enter__(self) -> "Antarya":
|
|
104
|
+
return self
|
|
105
|
+
|
|
106
|
+
def __exit__(self, *exc) -> None:
|
|
107
|
+
self.close()
|
|
108
|
+
|
|
109
|
+
def _request(self, method: str, path: str, *, json=None, files=None, params=None, stream: bool = False, parse=None):
|
|
110
|
+
url, kwargs = self._prepare(path, json, files, params)
|
|
111
|
+
attempt = 0
|
|
112
|
+
while True:
|
|
113
|
+
wait = None
|
|
114
|
+
try:
|
|
115
|
+
req = self._http.build_request(method, url, **kwargs)
|
|
116
|
+
res = self._http.send(req, stream=True)
|
|
117
|
+
except httpx.TransportError as e:
|
|
118
|
+
failure = self._transport_error(e)
|
|
119
|
+
else:
|
|
120
|
+
if res.is_success:
|
|
121
|
+
if stream:
|
|
122
|
+
return res
|
|
123
|
+
try:
|
|
124
|
+
res.read()
|
|
125
|
+
try:
|
|
126
|
+
data = res.json()
|
|
127
|
+
return parse(data) if parse is not None else data
|
|
128
|
+
except _base.MALFORMED:
|
|
129
|
+
raise self._unreadable(res)
|
|
130
|
+
except httpx.TransportError as e:
|
|
131
|
+
failure = self._transport_error(e)
|
|
132
|
+
finally:
|
|
133
|
+
res.close()
|
|
134
|
+
else:
|
|
135
|
+
try:
|
|
136
|
+
res.read()
|
|
137
|
+
except httpx.TransportError:
|
|
138
|
+
pass # no readable body: fall back to the status alone
|
|
139
|
+
res.close()
|
|
140
|
+
failure = self._failure(res)
|
|
141
|
+
if res.status_code not in _base.RETRY_STATUS:
|
|
142
|
+
raise failure
|
|
143
|
+
wait = failure.retry_after
|
|
144
|
+
if attempt >= self.max_retries:
|
|
145
|
+
raise failure
|
|
146
|
+
self._sleep(_base.retry_wait(attempt, wait))
|
|
147
|
+
attempt += 1
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class AsyncAntarya(_Core):
|
|
151
|
+
def __init__(
|
|
152
|
+
self,
|
|
153
|
+
api_key: Optional[str] = None,
|
|
154
|
+
base_url: Optional[str] = None,
|
|
155
|
+
max_retries: int = 2,
|
|
156
|
+
timeout: Union[float, None, _NotGiven] = NOT_GIVEN,
|
|
157
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
158
|
+
_sleep=asyncio.sleep,
|
|
159
|
+
) -> None:
|
|
160
|
+
super().__init__(api_key, base_url, max_retries, timeout, http_client is not None)
|
|
161
|
+
self._owns_http = http_client is None
|
|
162
|
+
self._http = http_client or httpx.AsyncClient()
|
|
163
|
+
self.chat = resources.AsyncChat(self)
|
|
164
|
+
self.models = resources.AsyncModels(self)
|
|
165
|
+
self.files = resources.AsyncFiles(self)
|
|
166
|
+
self.sessions = resources.AsyncSessions(self)
|
|
167
|
+
self.batches = resources.AsyncBatches(self)
|
|
168
|
+
self._sleep = _sleep
|
|
169
|
+
|
|
170
|
+
async def aclose(self) -> None:
|
|
171
|
+
if self._owns_http:
|
|
172
|
+
await self._http.aclose()
|
|
173
|
+
|
|
174
|
+
async def __aenter__(self) -> "AsyncAntarya":
|
|
175
|
+
return self
|
|
176
|
+
|
|
177
|
+
async def __aexit__(self, *exc) -> None:
|
|
178
|
+
await self.aclose()
|
|
179
|
+
|
|
180
|
+
async def _request(self, method: str, path: str, *, json=None, files=None, params=None, stream: bool = False, parse=None):
|
|
181
|
+
url, kwargs = self._prepare(path, json, files, params)
|
|
182
|
+
attempt = 0
|
|
183
|
+
while True:
|
|
184
|
+
wait = None
|
|
185
|
+
try:
|
|
186
|
+
req = self._http.build_request(method, url, **kwargs)
|
|
187
|
+
res = await self._http.send(req, stream=True)
|
|
188
|
+
except httpx.TransportError as e:
|
|
189
|
+
failure = self._transport_error(e)
|
|
190
|
+
else:
|
|
191
|
+
if res.is_success:
|
|
192
|
+
if stream:
|
|
193
|
+
return res
|
|
194
|
+
try:
|
|
195
|
+
await res.aread()
|
|
196
|
+
try:
|
|
197
|
+
data = res.json()
|
|
198
|
+
return parse(data) if parse is not None else data
|
|
199
|
+
except _base.MALFORMED:
|
|
200
|
+
raise self._unreadable(res)
|
|
201
|
+
except httpx.TransportError as e:
|
|
202
|
+
failure = self._transport_error(e)
|
|
203
|
+
finally:
|
|
204
|
+
await res.aclose()
|
|
205
|
+
else:
|
|
206
|
+
try:
|
|
207
|
+
await res.aread()
|
|
208
|
+
except httpx.TransportError:
|
|
209
|
+
pass # no readable body: fall back to the status alone
|
|
210
|
+
await res.aclose()
|
|
211
|
+
failure = self._failure(res)
|
|
212
|
+
if res.status_code not in _base.RETRY_STATUS:
|
|
213
|
+
raise failure
|
|
214
|
+
wait = failure.retry_after
|
|
215
|
+
if attempt >= self.max_retries:
|
|
216
|
+
raise failure
|
|
217
|
+
await self._sleep(_base.retry_wait(attempt, wait))
|
|
218
|
+
attempt += 1
|
antarya/_errors.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Mapping, Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class APIError(Exception):
|
|
7
|
+
"""Base class for every error the SDK raises for an API call."""
|
|
8
|
+
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
message: str,
|
|
12
|
+
*,
|
|
13
|
+
status: Optional[int] = None,
|
|
14
|
+
type: str = "api_error",
|
|
15
|
+
request_id: Optional[str] = None,
|
|
16
|
+
retry_after: Optional[float] = None,
|
|
17
|
+
) -> None:
|
|
18
|
+
super().__init__(message)
|
|
19
|
+
self.message = message
|
|
20
|
+
self.status = status
|
|
21
|
+
self.type = type
|
|
22
|
+
self.request_id = request_id
|
|
23
|
+
self.retry_after = retry_after
|
|
24
|
+
|
|
25
|
+
def __str__(self) -> str:
|
|
26
|
+
return self.message
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class BadRequestError(APIError): ...
|
|
30
|
+
class AuthenticationError(APIError): ...
|
|
31
|
+
class PermissionDeniedError(APIError): ...
|
|
32
|
+
class NotFoundError(APIError): ...
|
|
33
|
+
class RequestTooLargeError(APIError): ...
|
|
34
|
+
class RateLimitError(APIError): ...
|
|
35
|
+
class InternalServerError(APIError): ...
|
|
36
|
+
class OverloadedError(APIError): ...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class APIConnectionError(APIError):
|
|
40
|
+
def __init__(self, message: str = "Could not reach the API.") -> None:
|
|
41
|
+
super().__init__(message, type="connection_error")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class APITimeoutError(APIConnectionError):
|
|
45
|
+
def __init__(self, message: str = "The request timed out.") -> None:
|
|
46
|
+
super().__init__(message)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
_BY_TYPE = {
|
|
50
|
+
"invalid_request": BadRequestError,
|
|
51
|
+
"authentication_error": AuthenticationError,
|
|
52
|
+
"permission_error": PermissionDeniedError,
|
|
53
|
+
"not_found": NotFoundError,
|
|
54
|
+
"request_too_large": RequestTooLargeError,
|
|
55
|
+
"rate_limit_error": RateLimitError,
|
|
56
|
+
"api_error": InternalServerError,
|
|
57
|
+
"overloaded": OverloadedError,
|
|
58
|
+
}
|
|
59
|
+
_BY_STATUS = {
|
|
60
|
+
400: "invalid_request", 401: "authentication_error", 403: "permission_error",
|
|
61
|
+
404: "not_found", 413: "request_too_large", 429: "rate_limit_error", 503: "overloaded",
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def error_from(status: int, body: object, headers: Mapping[str, str]) -> APIError:
|
|
66
|
+
"""Build the error class that matches a failed reply. The body may be anything, including HTML."""
|
|
67
|
+
err = body.get("error") if isinstance(body, dict) else None
|
|
68
|
+
err = err if isinstance(err, dict) else {}
|
|
69
|
+
body_id = body.get("request_id") if isinstance(body, dict) else None
|
|
70
|
+
t = err.get("type")
|
|
71
|
+
t = t if isinstance(t, str) and t in _BY_TYPE else _BY_STATUS.get(status, "api_error")
|
|
72
|
+
msg = err.get("message")
|
|
73
|
+
message = msg if isinstance(msg, str) and msg else f"The API returned an error ({status})."
|
|
74
|
+
request_id = body_id if isinstance(body_id, str) else headers.get("request-id")
|
|
75
|
+
retry_after = None
|
|
76
|
+
raw = headers.get("retry-after")
|
|
77
|
+
if raw is not None:
|
|
78
|
+
try:
|
|
79
|
+
v = float(raw)
|
|
80
|
+
if v >= 0 and v != float("inf"):
|
|
81
|
+
retry_after = v
|
|
82
|
+
except ValueError:
|
|
83
|
+
pass
|
|
84
|
+
return _BY_TYPE[t](message, status=status, type=t, request_id=request_id, retry_after=retry_after)
|