antarya 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.
@@ -0,0 +1,6 @@
1
+ .venv*/
2
+ __pycache__/
3
+ dist/
4
+ .superpowers/
5
+ *.egg-info/
6
+ .pytest_cache/
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 - 2026-11-27
4
+
5
+ First release. Sync and async clients for chat, streaming, token counting, models, files, sessions and batches, with typed replies, retries and typed errors.
antarya-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Humblepaper, 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.
antarya-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.5
2
+ Name: antarya
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Antarya API.
5
+ Project-URL: Documentation, https://antarya.ai/docs/sdk/python
6
+ Project-URL: Repository, https://github.com/AntaryaAI/antarya-python
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.9
15
+ Requires-Dist: httpx<1,>=0.24
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest; extra == 'dev'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # antarya
21
+
22
+ The Python SDK for the Antarya API. Antarya is a frontier model for conversations, documents and tools. This package covers chat, streaming, files, sessions, batches and model listing, with sync and async clients.
23
+
24
+ Full reference: https://antarya.ai/docs/sdk/python
25
+
26
+ ## Install
27
+
28
+ ```
29
+ pip install antarya
30
+ ```
31
+
32
+ Python 3.9 or later. The only dependency is `httpx`.
33
+
34
+ ## Client
35
+
36
+ The client reads `ANTARYA_API_KEY`. Pass `api_key="ak-..."` to use a different key.
37
+
38
+ ```python
39
+ from antarya import Antarya
40
+
41
+ client = Antarya()
42
+
43
+ reply = client.chat.create(
44
+ messages=[{"role": "user", "content": "Summarise this contract's termination clause."}],
45
+ )
46
+ print(reply.content[0].text)
47
+ ```
48
+
49
+ Fields keep the names the API uses, such as `max_output_tokens` and `session_id`. Arguments left as `None` are not sent.
50
+
51
+ ## Streaming
52
+
53
+ ```python
54
+ with client.chat.stream(
55
+ messages=[{"role": "user", "content": "Draft a reply that declines the meeting."}],
56
+ ) as stream:
57
+ for text in stream.text:
58
+ print(text, end="")
59
+ ```
60
+
61
+ Iterate the stream itself for every event, or call `stream.final_reply()` to read to the end and get the full reply. Leaving the `with` block early closes the connection.
62
+
63
+ Events are `ReplyStart`, `ContentDelta`, `ReplyDone`, `ThinkingEvent` (sent when you pass `include_thinking=True`) and `UnknownEvent` for any event name this version does not know. `StreamEvent` is the union of them. With `include_thinking=True`, `final_reply().thinking` holds the same notes that `create()` returns.
64
+
65
+ ## Sessions
66
+
67
+ A session keeps the conversation on Antarya's side, so you send only the new turn.
68
+
69
+ ```python
70
+ session = client.sessions.create(metadata={"matter": "acme-msa"})
71
+
72
+ reply = client.chat.create(
73
+ session_id=session.id,
74
+ messages=[{"role": "user", "content": "Summarise the termination clause."}],
75
+ )
76
+
77
+ page = client.sessions.list(limit=20)
78
+ if page.has_more:
79
+ page = client.sessions.list(limit=20, after=page.data[-1].id)
80
+
81
+ client.sessions.delete(session.id)
82
+ ```
83
+
84
+ ## Errors and retries
85
+
86
+ A failed request raises `antarya.APIError` or one of its subclasses, such as `RateLimitError` or `AuthenticationError`. Each carries `status`, `type`, `message` and `request_id`.
87
+
88
+ ```python
89
+ import antarya
90
+
91
+ try:
92
+ client.chat.create(messages=[{"role": "user", "content": "Hello"}])
93
+ except antarya.APIError as e:
94
+ print(e.status, e.type, e.request_id)
95
+ ```
96
+
97
+ The client retries 429, 500 and 503 replies, connection errors and timeouts twice, waiting for the `retry-after` time when the reply gives one. Change that with `Antarya(max_retries=4)`. The default timeout is 600 seconds; change it with `timeout=`.
98
+
99
+ ## Async
100
+
101
+ ```python
102
+ import asyncio
103
+ from antarya import AsyncAntarya
104
+
105
+ client = AsyncAntarya()
106
+
107
+ async def main():
108
+ reply = await client.chat.create(
109
+ messages=[{"role": "user", "content": "Summarise this contract's termination clause."}],
110
+ )
111
+ print(reply.content[0].text)
112
+
113
+ asyncio.run(main())
114
+ ```
115
+
116
+ Streams use `async with` and `async for`. Batch results use `async for`.
117
+
118
+ ## License
119
+
120
+ MIT
@@ -0,0 +1,101 @@
1
+ # antarya
2
+
3
+ The Python SDK for the Antarya API. Antarya is a frontier model for conversations, documents and tools. This package covers chat, streaming, files, sessions, batches and model listing, with sync and async clients.
4
+
5
+ Full reference: https://antarya.ai/docs/sdk/python
6
+
7
+ ## Install
8
+
9
+ ```
10
+ pip install antarya
11
+ ```
12
+
13
+ Python 3.9 or later. The only dependency is `httpx`.
14
+
15
+ ## Client
16
+
17
+ The client reads `ANTARYA_API_KEY`. Pass `api_key="ak-..."` to use a different key.
18
+
19
+ ```python
20
+ from antarya import Antarya
21
+
22
+ client = Antarya()
23
+
24
+ reply = client.chat.create(
25
+ messages=[{"role": "user", "content": "Summarise this contract's termination clause."}],
26
+ )
27
+ print(reply.content[0].text)
28
+ ```
29
+
30
+ Fields keep the names the API uses, such as `max_output_tokens` and `session_id`. Arguments left as `None` are not sent.
31
+
32
+ ## Streaming
33
+
34
+ ```python
35
+ with client.chat.stream(
36
+ messages=[{"role": "user", "content": "Draft a reply that declines the meeting."}],
37
+ ) as stream:
38
+ for text in stream.text:
39
+ print(text, end="")
40
+ ```
41
+
42
+ Iterate the stream itself for every event, or call `stream.final_reply()` to read to the end and get the full reply. Leaving the `with` block early closes the connection.
43
+
44
+ Events are `ReplyStart`, `ContentDelta`, `ReplyDone`, `ThinkingEvent` (sent when you pass `include_thinking=True`) and `UnknownEvent` for any event name this version does not know. `StreamEvent` is the union of them. With `include_thinking=True`, `final_reply().thinking` holds the same notes that `create()` returns.
45
+
46
+ ## Sessions
47
+
48
+ A session keeps the conversation on Antarya's side, so you send only the new turn.
49
+
50
+ ```python
51
+ session = client.sessions.create(metadata={"matter": "acme-msa"})
52
+
53
+ reply = client.chat.create(
54
+ session_id=session.id,
55
+ messages=[{"role": "user", "content": "Summarise the termination clause."}],
56
+ )
57
+
58
+ page = client.sessions.list(limit=20)
59
+ if page.has_more:
60
+ page = client.sessions.list(limit=20, after=page.data[-1].id)
61
+
62
+ client.sessions.delete(session.id)
63
+ ```
64
+
65
+ ## Errors and retries
66
+
67
+ A failed request raises `antarya.APIError` or one of its subclasses, such as `RateLimitError` or `AuthenticationError`. Each carries `status`, `type`, `message` and `request_id`.
68
+
69
+ ```python
70
+ import antarya
71
+
72
+ try:
73
+ client.chat.create(messages=[{"role": "user", "content": "Hello"}])
74
+ except antarya.APIError as e:
75
+ print(e.status, e.type, e.request_id)
76
+ ```
77
+
78
+ The client retries 429, 500 and 503 replies, connection errors and timeouts twice, waiting for the `retry-after` time when the reply gives one. Change that with `Antarya(max_retries=4)`. The default timeout is 600 seconds; change it with `timeout=`.
79
+
80
+ ## Async
81
+
82
+ ```python
83
+ import asyncio
84
+ from antarya import AsyncAntarya
85
+
86
+ client = AsyncAntarya()
87
+
88
+ async def main():
89
+ reply = await client.chat.create(
90
+ messages=[{"role": "user", "content": "Summarise this contract's termination clause."}],
91
+ )
92
+ print(reply.content[0].text)
93
+
94
+ asyncio.run(main())
95
+ ```
96
+
97
+ Streams use `async with` and `async for`. Batch results use `async for`.
98
+
99
+ ## License
100
+
101
+ MIT
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "antarya"
7
+ dynamic = ["version"]
8
+ description = "Python SDK for the Antarya API."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ dependencies = ["httpx>=0.24,<1"]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.9",
16
+ "Programming Language :: Python :: 3.13",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Typing :: Typed",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ dev = ["pytest"]
23
+
24
+ [project.urls]
25
+ Documentation = "https://antarya.ai/docs/sdk/python"
26
+ Repository = "https://github.com/AntaryaAI/antarya-python"
27
+
28
+ [tool.hatch.version]
29
+ path = "src/antarya/__init__.py"
30
+
31
+ [tool.hatch.build.targets.sdist]
32
+ include = ["src/antarya", "README.md", "LICENSE", "CHANGELOG.md", "pyproject.toml"]
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["src/antarya"]
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
39
+ pythonpath = ["tests"]
@@ -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
+ ]
@@ -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
@@ -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
@@ -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)