bakbak-python 1.0.0rc2__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.
- bakbak/__init__.py +77 -0
- bakbak/_base_client.py +642 -0
- bakbak/_client.py +219 -0
- bakbak/_constants.py +43 -0
- bakbak/_exceptions.py +410 -0
- bakbak/_models.py +93 -0
- bakbak/_response.py +51 -0
- bakbak/_retry.py +52 -0
- bakbak/_sse.py +68 -0
- bakbak/_streaming.py +432 -0
- bakbak/_types.py +79 -0
- bakbak/_utils.py +62 -0
- bakbak/_version.py +3 -0
- bakbak/_ws/__init__.py +1 -0
- bakbak/_ws/_async.py +657 -0
- bakbak/_ws/_common.py +176 -0
- bakbak/_ws/_core.py +819 -0
- bakbak/_ws/_sync.py +649 -0
- bakbak/_ws/events.py +67 -0
- bakbak/audio.py +75 -0
- bakbak/py.typed +0 -0
- bakbak/resources/__init__.py +6 -0
- bakbak/resources/tts.py +339 -0
- bakbak/resources/voices.py +139 -0
- bakbak/text.py +463 -0
- bakbak/types.py +100 -0
- bakbak/websocket.py +23 -0
- bakbak_python-1.0.0rc2.dist-info/METADATA +416 -0
- bakbak_python-1.0.0rc2.dist-info/RECORD +31 -0
- bakbak_python-1.0.0rc2.dist-info/WHEEL +4 -0
- bakbak_python-1.0.0rc2.dist-info/licenses/LICENSE +202 -0
bakbak/_client.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""``Bakbak`` and ``AsyncBakbak``: the two clients, with identical surfaces."""
|
|
2
|
+
|
|
3
|
+
# pyright: reportPrivateUsage=false
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from types import TracebackType
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
from typing_extensions import Self
|
|
12
|
+
|
|
13
|
+
from ._base_client import AsyncAPIClient, CallOptions, SyncAPIClient
|
|
14
|
+
from ._constants import DEFAULT_MAX_RETRIES, VOICES_PATH
|
|
15
|
+
from ._types import NOT_GIVEN, NotGiven, TimeoutLike
|
|
16
|
+
from .resources.tts import TTS, AsyncTTS
|
|
17
|
+
from .resources.voices import AsyncVoices, Voices
|
|
18
|
+
|
|
19
|
+
__all__ = ["AsyncBakbak", "Bakbak"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Bakbak(SyncAPIClient):
|
|
23
|
+
"""The Bakbak text-to-speech client.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
api_key: your API key. Defaults to the ``BAKBAK_API_KEY`` environment
|
|
27
|
+
variable, read here (not at import).
|
|
28
|
+
base_url: defaults to ``BAKBAK_BASE_URL``, then
|
|
29
|
+
``https://hub.getraya.app``.
|
|
30
|
+
timeout: a ``bakbak.Timeout``; a number of seconds, which sets the
|
|
31
|
+
read timeout; or ``None`` for no timeouts. The default is 5 s to
|
|
32
|
+
connect and 60 s between bytes (including the time to first audio).
|
|
33
|
+
max_retries: retries of a failed request before any audio (default 2).
|
|
34
|
+
default_headers: headers to send with every request.
|
|
35
|
+
http_client: an ``httpx.Client`` to use, e.g. with a proxy. The client
|
|
36
|
+
does not close it.
|
|
37
|
+
|
|
38
|
+
Raises:
|
|
39
|
+
BakbakError: if there is no API key.
|
|
40
|
+
|
|
41
|
+
Example::
|
|
42
|
+
|
|
43
|
+
from bakbak import Bakbak
|
|
44
|
+
|
|
45
|
+
client = Bakbak()
|
|
46
|
+
audio = client.tts.generate(text="नमस्ते", voice_id="…", language="hi")
|
|
47
|
+
audio.save("hello.wav")
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
tts: TTS
|
|
51
|
+
voices: Voices
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
*,
|
|
56
|
+
api_key: str | None = None,
|
|
57
|
+
base_url: str | None = None,
|
|
58
|
+
timeout: TimeoutLike | NotGiven = NOT_GIVEN,
|
|
59
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
60
|
+
default_headers: Mapping[str, str] | None = None,
|
|
61
|
+
http_client: httpx.Client | None = None,
|
|
62
|
+
) -> None:
|
|
63
|
+
super().__init__(
|
|
64
|
+
api_key=api_key,
|
|
65
|
+
base_url=base_url,
|
|
66
|
+
timeout=timeout,
|
|
67
|
+
max_retries=max_retries,
|
|
68
|
+
default_headers=default_headers,
|
|
69
|
+
http_client=http_client,
|
|
70
|
+
)
|
|
71
|
+
self.tts = TTS(self)
|
|
72
|
+
self.voices = Voices(self)
|
|
73
|
+
|
|
74
|
+
def with_options(
|
|
75
|
+
self,
|
|
76
|
+
*,
|
|
77
|
+
api_key: str | None = None,
|
|
78
|
+
base_url: str | None = None,
|
|
79
|
+
timeout: TimeoutLike | NotGiven = NOT_GIVEN,
|
|
80
|
+
max_retries: int | NotGiven = NOT_GIVEN,
|
|
81
|
+
default_headers: Mapping[str, str] | None = None,
|
|
82
|
+
http_client: httpx.Client | None = None,
|
|
83
|
+
) -> Bakbak:
|
|
84
|
+
"""A copy of this client with some options changed.
|
|
85
|
+
|
|
86
|
+
The copy shares this client's connection pool unless ``http_client``
|
|
87
|
+
is given; ``default_headers`` are added to this client's.
|
|
88
|
+
"""
|
|
89
|
+
copy = Bakbak(
|
|
90
|
+
api_key=api_key or self.api_key,
|
|
91
|
+
base_url=base_url or self.base_url,
|
|
92
|
+
timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
|
|
93
|
+
max_retries=self.max_retries if isinstance(max_retries, NotGiven) else max_retries,
|
|
94
|
+
default_headers={**self._default_headers, **(default_headers or {})},
|
|
95
|
+
http_client=http_client or self._client,
|
|
96
|
+
)
|
|
97
|
+
copy._sleep = self._sleep
|
|
98
|
+
return copy
|
|
99
|
+
|
|
100
|
+
def prewarm(self) -> None:
|
|
101
|
+
"""Open a connection to the API now, so the next request pays no TCP
|
|
102
|
+
or TLS handshake. It lists the voices once, which also checks the key.
|
|
103
|
+
|
|
104
|
+
Raises:
|
|
105
|
+
AuthenticationError: the key was refused.
|
|
106
|
+
APIConnectionError: the API could not be reached.
|
|
107
|
+
"""
|
|
108
|
+
self._request(
|
|
109
|
+
"GET",
|
|
110
|
+
VOICES_PATH,
|
|
111
|
+
body=None,
|
|
112
|
+
accept="application/json",
|
|
113
|
+
options=CallOptions(timeout=self.timeout, max_retries=0, extra_headers=None),
|
|
114
|
+
handle=self._read_voices,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
def __enter__(self) -> Self:
|
|
118
|
+
return self
|
|
119
|
+
|
|
120
|
+
def __exit__(
|
|
121
|
+
self,
|
|
122
|
+
exc_type: type[BaseException] | None,
|
|
123
|
+
exc: BaseException | None,
|
|
124
|
+
tb: TracebackType | None,
|
|
125
|
+
) -> None:
|
|
126
|
+
self.close()
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class AsyncBakbak(AsyncAPIClient):
|
|
130
|
+
"""The Bakbak text-to-speech client for asyncio.
|
|
131
|
+
|
|
132
|
+
Takes the same arguments as :class:`Bakbak` (``http_client`` is an
|
|
133
|
+
``httpx.AsyncClient``).
|
|
134
|
+
|
|
135
|
+
Example::
|
|
136
|
+
|
|
137
|
+
from bakbak import AsyncBakbak
|
|
138
|
+
|
|
139
|
+
client = AsyncBakbak()
|
|
140
|
+
audio = await client.tts.generate(text="नमस्ते", voice_id="…", language="hi")
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
tts: AsyncTTS
|
|
144
|
+
voices: AsyncVoices
|
|
145
|
+
|
|
146
|
+
def __init__(
|
|
147
|
+
self,
|
|
148
|
+
*,
|
|
149
|
+
api_key: str | None = None,
|
|
150
|
+
base_url: str | None = None,
|
|
151
|
+
timeout: TimeoutLike | NotGiven = NOT_GIVEN,
|
|
152
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
153
|
+
default_headers: Mapping[str, str] | None = None,
|
|
154
|
+
http_client: httpx.AsyncClient | None = None,
|
|
155
|
+
) -> None:
|
|
156
|
+
super().__init__(
|
|
157
|
+
api_key=api_key,
|
|
158
|
+
base_url=base_url,
|
|
159
|
+
timeout=timeout,
|
|
160
|
+
max_retries=max_retries,
|
|
161
|
+
default_headers=default_headers,
|
|
162
|
+
http_client=http_client,
|
|
163
|
+
)
|
|
164
|
+
self.tts = AsyncTTS(self)
|
|
165
|
+
self.voices = AsyncVoices(self)
|
|
166
|
+
|
|
167
|
+
def with_options(
|
|
168
|
+
self,
|
|
169
|
+
*,
|
|
170
|
+
api_key: str | None = None,
|
|
171
|
+
base_url: str | None = None,
|
|
172
|
+
timeout: TimeoutLike | NotGiven = NOT_GIVEN,
|
|
173
|
+
max_retries: int | NotGiven = NOT_GIVEN,
|
|
174
|
+
default_headers: Mapping[str, str] | None = None,
|
|
175
|
+
http_client: httpx.AsyncClient | None = None,
|
|
176
|
+
) -> AsyncBakbak:
|
|
177
|
+
"""A copy of this client with some options changed.
|
|
178
|
+
|
|
179
|
+
The copy shares this client's connection pool unless ``http_client``
|
|
180
|
+
is given; ``default_headers`` are added to this client's.
|
|
181
|
+
"""
|
|
182
|
+
copy = AsyncBakbak(
|
|
183
|
+
api_key=api_key or self.api_key,
|
|
184
|
+
base_url=base_url or self.base_url,
|
|
185
|
+
timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
|
|
186
|
+
max_retries=self.max_retries if isinstance(max_retries, NotGiven) else max_retries,
|
|
187
|
+
default_headers={**self._default_headers, **(default_headers or {})},
|
|
188
|
+
http_client=http_client or self._client,
|
|
189
|
+
)
|
|
190
|
+
copy._sleep = self._sleep
|
|
191
|
+
return copy
|
|
192
|
+
|
|
193
|
+
async def prewarm(self) -> None:
|
|
194
|
+
"""Open a connection to the API now, so the next request pays no TCP
|
|
195
|
+
or TLS handshake. It lists the voices once, which also checks the key.
|
|
196
|
+
|
|
197
|
+
Raises:
|
|
198
|
+
AuthenticationError: the key was refused.
|
|
199
|
+
APIConnectionError: the API could not be reached.
|
|
200
|
+
"""
|
|
201
|
+
await self._request(
|
|
202
|
+
"GET",
|
|
203
|
+
VOICES_PATH,
|
|
204
|
+
body=None,
|
|
205
|
+
accept="application/json",
|
|
206
|
+
options=CallOptions(timeout=self.timeout, max_retries=0, extra_headers=None),
|
|
207
|
+
handle=self._read_voices,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
async def __aenter__(self) -> Self:
|
|
211
|
+
return self
|
|
212
|
+
|
|
213
|
+
async def __aexit__(
|
|
214
|
+
self,
|
|
215
|
+
exc_type: type[BaseException] | None,
|
|
216
|
+
exc: BaseException | None,
|
|
217
|
+
tb: TracebackType | None,
|
|
218
|
+
) -> None:
|
|
219
|
+
await self.close()
|
bakbak/_constants.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Defaults and limits shared by the HTTP and WebSocket clients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
DEFAULT_BASE_URL = "https://hub.getraya.app"
|
|
6
|
+
API_KEY_ENV = "BAKBAK_API_KEY"
|
|
7
|
+
BASE_URL_ENV = "BAKBAK_BASE_URL"
|
|
8
|
+
|
|
9
|
+
PACKAGE_NAME = "bakbak-python"
|
|
10
|
+
|
|
11
|
+
TTS_PATH = "/v1/text-to-speech"
|
|
12
|
+
STREAM_PATH = "/v1/text-to-speech/stream"
|
|
13
|
+
WEBSOCKET_PATH = "/v1/text-to-speech/ws"
|
|
14
|
+
VOICES_PATH = "/v1/voices"
|
|
15
|
+
|
|
16
|
+
DEFAULT_MAX_RETRIES = 2
|
|
17
|
+
DEFAULT_CONNECT_TIMEOUT = 5.0
|
|
18
|
+
DEFAULT_READ_TIMEOUT = 60.0
|
|
19
|
+
|
|
20
|
+
# Backoff (BEHAVIOR.md §4.3): retry n waits min(0.5 * 2^(n-1), 8) * (1 - 0.25 * r).
|
|
21
|
+
INITIAL_RETRY_DELAY = 0.5
|
|
22
|
+
MAX_RETRY_DELAY = 8.0
|
|
23
|
+
RETRY_JITTER = 0.25
|
|
24
|
+
MAX_RETRY_AFTER = 60.0
|
|
25
|
+
|
|
26
|
+
# Statuses that are worth retrying when the body does not say otherwise (§3.3).
|
|
27
|
+
RETRYABLE_STATUSES = frozenset({408, 429, 500, 502, 503, 504})
|
|
28
|
+
|
|
29
|
+
# Idle HTTP connections are kept this long, so a request a few seconds after the
|
|
30
|
+
# previous one (or after prewarm()) skips the TCP and TLS handshakes.
|
|
31
|
+
KEEPALIVE_EXPIRY = 30.0
|
|
32
|
+
|
|
33
|
+
# WebSocket limits of one connection (§1). The client never exceeds them.
|
|
34
|
+
WS_MAX_UNFINISHED = 64
|
|
35
|
+
WS_MAX_CONTEXTS = 16
|
|
36
|
+
# Large enough for any server message; one chunk's base64 can be big.
|
|
37
|
+
WS_MAX_MESSAGE_BYTES = 16 * 1024 * 1024
|
|
38
|
+
# How long the client waits for its own close handshake before it drops the
|
|
39
|
+
# connection: closing never waits much longer on an unresponsive peer.
|
|
40
|
+
WS_CLOSE_TIMEOUT = 1.0
|
|
41
|
+
# A connection that stayed open this long counts as healthy even if it never
|
|
42
|
+
# received a message, so dropping it does not count as a failed reconnect.
|
|
43
|
+
WS_HEALTHY_AFTER = 10.0
|
bakbak/_exceptions.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
"""The error hierarchy of BEHAVIOR.md §3, and how errors are built from responses.
|
|
2
|
+
|
|
3
|
+
No error ever holds the API key or the request headers: not in its message, not
|
|
4
|
+
in ``repr()``/``str()``, and not in any attribute.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import http
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from typing import Any, cast
|
|
12
|
+
|
|
13
|
+
from typing_extensions import override
|
|
14
|
+
|
|
15
|
+
from ._constants import RETRYABLE_STATUSES
|
|
16
|
+
from ._utils import as_mapping
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"APIConnectionError",
|
|
20
|
+
"APIError",
|
|
21
|
+
"APIStatusError",
|
|
22
|
+
"APITimeoutError",
|
|
23
|
+
"AuthenticationError",
|
|
24
|
+
"BadRequestError",
|
|
25
|
+
"BakbakError",
|
|
26
|
+
"InsufficientCreditsError",
|
|
27
|
+
"InternalServerError",
|
|
28
|
+
"NotFoundError",
|
|
29
|
+
"PermissionDeniedError",
|
|
30
|
+
"RateLimitError",
|
|
31
|
+
"RequestTooLargeError",
|
|
32
|
+
"StreamInterruptedError",
|
|
33
|
+
"UnprocessableEntityError",
|
|
34
|
+
"WebSocketClosedError",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _restore(cls: type[BakbakError], message: str, state: dict[str, Any]) -> BakbakError:
|
|
39
|
+
error = cls.__new__(cls)
|
|
40
|
+
Exception.__init__(error, message)
|
|
41
|
+
error.__dict__.update(state)
|
|
42
|
+
return error
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class BakbakError(Exception):
|
|
46
|
+
"""Anything raised by the SDK."""
|
|
47
|
+
|
|
48
|
+
message: str
|
|
49
|
+
|
|
50
|
+
def __init__(self, message: str) -> None:
|
|
51
|
+
super().__init__(message)
|
|
52
|
+
self.message = message
|
|
53
|
+
|
|
54
|
+
@override
|
|
55
|
+
def __reduce__(self) -> tuple[Any, ...]:
|
|
56
|
+
# Errors cross process boundaries (multiprocessing, task queues) intact.
|
|
57
|
+
return (_restore, (type(self), self.message, dict(self.__dict__)))
|
|
58
|
+
|
|
59
|
+
@override
|
|
60
|
+
def __str__(self) -> str:
|
|
61
|
+
return self.message
|
|
62
|
+
|
|
63
|
+
@override
|
|
64
|
+
def __repr__(self) -> str:
|
|
65
|
+
return f"{type(self).__name__}({self.message!r})"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class APIError(BakbakError):
|
|
69
|
+
"""The service answered with an error, or a stream broke.
|
|
70
|
+
|
|
71
|
+
Attributes:
|
|
72
|
+
status: the HTTP status, or the event's ``status_code``; ``None`` for a
|
|
73
|
+
truncated stream.
|
|
74
|
+
error_code: the body's ``error_code``, if it had one.
|
|
75
|
+
message: a sentence to show a person.
|
|
76
|
+
retryable: whether sending the same request again can succeed.
|
|
77
|
+
request_id: ``X-Request-Id``, else the body's or the event's
|
|
78
|
+
``request_id``. Quote it to support.
|
|
79
|
+
body: the parsed JSON body (or stream event), so extra fields such as
|
|
80
|
+
``required_inr`` stay readable.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
status: int | None
|
|
84
|
+
error_code: str | None
|
|
85
|
+
retryable: bool
|
|
86
|
+
request_id: str | None
|
|
87
|
+
body: object | None
|
|
88
|
+
|
|
89
|
+
def __init__(
|
|
90
|
+
self,
|
|
91
|
+
message: str,
|
|
92
|
+
*,
|
|
93
|
+
status: int | None = None,
|
|
94
|
+
error_code: str | None = None,
|
|
95
|
+
retryable: bool = False,
|
|
96
|
+
request_id: str | None = None,
|
|
97
|
+
body: object | None = None,
|
|
98
|
+
) -> None:
|
|
99
|
+
super().__init__(message)
|
|
100
|
+
self.status = status
|
|
101
|
+
self.error_code = error_code
|
|
102
|
+
self.retryable = retryable
|
|
103
|
+
self.request_id = request_id
|
|
104
|
+
self.body = body
|
|
105
|
+
|
|
106
|
+
@override
|
|
107
|
+
def __str__(self) -> str:
|
|
108
|
+
details = [
|
|
109
|
+
f"status {self.status}" if self.status is not None else None,
|
|
110
|
+
f"error_code {self.error_code}" if self.error_code else None,
|
|
111
|
+
f"request_id {self.request_id}" if self.request_id else None,
|
|
112
|
+
]
|
|
113
|
+
shown = ", ".join(d for d in details if d)
|
|
114
|
+
return f"{self.message} ({shown})" if shown else self.message
|
|
115
|
+
|
|
116
|
+
@override
|
|
117
|
+
def __repr__(self) -> str:
|
|
118
|
+
return (
|
|
119
|
+
f"{type(self).__name__}(status={self.status!r}, error_code={self.error_code!r}, "
|
|
120
|
+
f"message={self.message!r}, retryable={self.retryable!r}, "
|
|
121
|
+
f"request_id={self.request_id!r})"
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class APIStatusError(APIError):
|
|
126
|
+
"""An HTTP error status, or an in-band error before any audio."""
|
|
127
|
+
|
|
128
|
+
status: int | None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class BadRequestError(APIStatusError):
|
|
132
|
+
"""400."""
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class AuthenticationError(APIStatusError):
|
|
136
|
+
"""401: the API key is missing, wrong or revoked."""
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class InsufficientCreditsError(APIStatusError):
|
|
140
|
+
"""402: the account's balance does not cover the request."""
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class PermissionDeniedError(APIStatusError):
|
|
144
|
+
"""403."""
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class NotFoundError(APIStatusError):
|
|
148
|
+
"""404: for example an unknown ``voice_id``."""
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class RequestTooLargeError(APIStatusError):
|
|
152
|
+
"""413: the text or the body is too long."""
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class UnprocessableEntityError(APIStatusError):
|
|
156
|
+
"""422: the request failed validation."""
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class RateLimitError(APIStatusError):
|
|
160
|
+
"""429: for example the account's concurrency limit."""
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class InternalServerError(APIStatusError):
|
|
164
|
+
"""5xx: the service or the model failed, or is out of capacity."""
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class StreamInterruptedError(APIError):
|
|
168
|
+
"""The request failed after audio was delivered. It is never retried
|
|
169
|
+
automatically, because the audio already played would play twice.
|
|
170
|
+
|
|
171
|
+
Attributes:
|
|
172
|
+
audio_bytes: how much audio was handed out before the failure.
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
audio_bytes: int
|
|
176
|
+
|
|
177
|
+
def __init__(
|
|
178
|
+
self,
|
|
179
|
+
message: str,
|
|
180
|
+
*,
|
|
181
|
+
audio_bytes: int,
|
|
182
|
+
status: int | None = None,
|
|
183
|
+
error_code: str | None = None,
|
|
184
|
+
retryable: bool = True,
|
|
185
|
+
request_id: str | None = None,
|
|
186
|
+
body: object | None = None,
|
|
187
|
+
) -> None:
|
|
188
|
+
super().__init__(
|
|
189
|
+
message,
|
|
190
|
+
status=status,
|
|
191
|
+
error_code=error_code,
|
|
192
|
+
retryable=retryable,
|
|
193
|
+
request_id=request_id,
|
|
194
|
+
body=body,
|
|
195
|
+
)
|
|
196
|
+
self.audio_bytes = audio_bytes
|
|
197
|
+
|
|
198
|
+
@override
|
|
199
|
+
def __repr__(self) -> str:
|
|
200
|
+
return f"{super().__repr__()[:-1]}, audio_bytes={self.audio_bytes!r})"
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class APIConnectionError(BakbakError):
|
|
204
|
+
"""No usable answer: a network, TLS or DNS failure.
|
|
205
|
+
|
|
206
|
+
Attributes:
|
|
207
|
+
retryable: whether trying again can succeed.
|
|
208
|
+
"""
|
|
209
|
+
|
|
210
|
+
retryable: bool
|
|
211
|
+
|
|
212
|
+
def __init__(
|
|
213
|
+
self, message: str = "Could not connect to the API.", *, retryable: bool = True
|
|
214
|
+
) -> None:
|
|
215
|
+
super().__init__(message)
|
|
216
|
+
self.retryable = retryable
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class APITimeoutError(APIConnectionError):
|
|
220
|
+
"""A timeout before any audio arrived."""
|
|
221
|
+
|
|
222
|
+
def __init__(self, message: str = "The request timed out.") -> None:
|
|
223
|
+
super().__init__(message, retryable=True)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
class WebSocketClosedError(APIConnectionError):
|
|
227
|
+
"""The WebSocket closed and a request could not continue.
|
|
228
|
+
|
|
229
|
+
Attributes:
|
|
230
|
+
code: the close code, if the server sent one.
|
|
231
|
+
reason: the close reason, if any.
|
|
232
|
+
"""
|
|
233
|
+
|
|
234
|
+
code: int | None
|
|
235
|
+
reason: str
|
|
236
|
+
|
|
237
|
+
def __init__(
|
|
238
|
+
self, message: str, *, code: int | None = None, reason: str = "", retryable: bool = False
|
|
239
|
+
) -> None:
|
|
240
|
+
super().__init__(message, retryable=retryable)
|
|
241
|
+
self.code = code
|
|
242
|
+
self.reason = reason
|
|
243
|
+
|
|
244
|
+
@override
|
|
245
|
+
def __repr__(self) -> str:
|
|
246
|
+
return (
|
|
247
|
+
f"{type(self).__name__}(code={self.code!r}, message={self.message!r}, "
|
|
248
|
+
f"retryable={self.retryable!r})"
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
_STATUS_CLASSES: dict[int, type[APIStatusError]] = {
|
|
253
|
+
400: BadRequestError,
|
|
254
|
+
401: AuthenticationError,
|
|
255
|
+
402: InsufficientCreditsError,
|
|
256
|
+
403: PermissionDeniedError,
|
|
257
|
+
404: NotFoundError,
|
|
258
|
+
413: RequestTooLargeError,
|
|
259
|
+
422: UnprocessableEntityError,
|
|
260
|
+
429: RateLimitError,
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def status_error_class(status: int | None) -> type[APIStatusError]:
|
|
265
|
+
"""The ``APIStatusError`` subclass for an HTTP status."""
|
|
266
|
+
if status is None:
|
|
267
|
+
return APIStatusError
|
|
268
|
+
if status >= 500:
|
|
269
|
+
return InternalServerError
|
|
270
|
+
return _STATUS_CLASSES.get(status, APIStatusError)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _nonempty(value: object) -> str | None:
|
|
274
|
+
return value if isinstance(value, str) and value.strip() else None
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _render_detail(detail: list[object]) -> str | None:
|
|
278
|
+
"""Render a validation ``detail`` list as ``"<loc> : <msg>"`` entries."""
|
|
279
|
+
parts: list[str] = []
|
|
280
|
+
for item in detail:
|
|
281
|
+
entry = as_mapping(item)
|
|
282
|
+
if entry is None:
|
|
283
|
+
text = _nonempty(item)
|
|
284
|
+
if text:
|
|
285
|
+
parts.append(text)
|
|
286
|
+
continue
|
|
287
|
+
msg = _nonempty(entry.get("msg"))
|
|
288
|
+
loc = entry.get("loc")
|
|
289
|
+
path = [str(p) for p in cast("list[object]", loc)] if isinstance(loc, list) else []
|
|
290
|
+
if path and path[0] == "body":
|
|
291
|
+
path = path[1:]
|
|
292
|
+
if msg:
|
|
293
|
+
parts.append(f"{'.'.join(path)}: {msg}" if path else msg)
|
|
294
|
+
return "; ".join(parts) or None
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _reason(status: int | None) -> str | None:
|
|
298
|
+
if status is None:
|
|
299
|
+
return None
|
|
300
|
+
try:
|
|
301
|
+
return http.HTTPStatus(status).phrase
|
|
302
|
+
except ValueError:
|
|
303
|
+
return None
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def error_message(body: object, status: int | None, reason: str | None = None) -> str:
|
|
307
|
+
"""The message of BEHAVIOR.md §3.2.
|
|
308
|
+
|
|
309
|
+
When the body has both a ``message`` and a ``detail`` list whose rendering
|
|
310
|
+
the message does not already contain, the rendering is appended (after a
|
|
311
|
+
space if the message ends a sentence, else after ": "), so a generic "The
|
|
312
|
+
request is malformed or invalid." still says which field was wrong.
|
|
313
|
+
"""
|
|
314
|
+
fields = as_mapping(body)
|
|
315
|
+
if fields is not None:
|
|
316
|
+
message = _nonempty(fields.get("message"))
|
|
317
|
+
detail = fields.get("detail")
|
|
318
|
+
detail_text = (
|
|
319
|
+
_render_detail(cast("list[object]", detail)) if isinstance(detail, list) else None
|
|
320
|
+
)
|
|
321
|
+
if message:
|
|
322
|
+
if detail_text and detail_text not in message:
|
|
323
|
+
base = message.rstrip() # trailing whitespace does not count
|
|
324
|
+
joiner = " " if base.endswith((".", "!", "?")) else ": "
|
|
325
|
+
return f"{base}{joiner}{detail_text}"
|
|
326
|
+
return message
|
|
327
|
+
if isinstance(detail, str) and detail.strip():
|
|
328
|
+
return detail
|
|
329
|
+
if detail_text:
|
|
330
|
+
return detail_text
|
|
331
|
+
error = _nonempty(fields.get("error"))
|
|
332
|
+
if error:
|
|
333
|
+
return error
|
|
334
|
+
phrase = _nonempty(reason) or _reason(status)
|
|
335
|
+
if phrase:
|
|
336
|
+
return phrase
|
|
337
|
+
return f"HTTP {status}" if status is not None else "The request failed."
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def is_retryable(body: object, status: int | None) -> bool:
|
|
341
|
+
"""The rule of BEHAVIOR.md §3.3."""
|
|
342
|
+
fields = as_mapping(body)
|
|
343
|
+
flag = fields.get("retryable") if fields is not None else None
|
|
344
|
+
if isinstance(flag, bool):
|
|
345
|
+
return flag
|
|
346
|
+
return status in RETRYABLE_STATUSES
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def make_status_error(
|
|
350
|
+
status: int | None,
|
|
351
|
+
body: object,
|
|
352
|
+
*,
|
|
353
|
+
header_request_id: str | None = None,
|
|
354
|
+
reason: str | None = None,
|
|
355
|
+
) -> APIStatusError:
|
|
356
|
+
"""Build the ``APIStatusError`` for an HTTP error or an in-band error event."""
|
|
357
|
+
request_id = _nonempty(header_request_id)
|
|
358
|
+
error_code = None
|
|
359
|
+
fields = as_mapping(body)
|
|
360
|
+
if fields is not None:
|
|
361
|
+
if request_id is None:
|
|
362
|
+
request_id = _nonempty(fields.get("request_id"))
|
|
363
|
+
error_code = _nonempty(fields.get("error_code"))
|
|
364
|
+
cls = status_error_class(status)
|
|
365
|
+
return cls(
|
|
366
|
+
error_message(body, status, reason),
|
|
367
|
+
status=status,
|
|
368
|
+
error_code=error_code,
|
|
369
|
+
retryable=is_retryable(body, status),
|
|
370
|
+
request_id=request_id,
|
|
371
|
+
body=body,
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def make_interrupted_error(
|
|
376
|
+
event: Mapping[str, object] | None,
|
|
377
|
+
*,
|
|
378
|
+
audio_bytes: int,
|
|
379
|
+
header_request_id: str | None = None,
|
|
380
|
+
default_message: str = "The audio stream ended before it was complete.",
|
|
381
|
+
) -> StreamInterruptedError:
|
|
382
|
+
"""Build the ``StreamInterruptedError`` for a failure after audio.
|
|
383
|
+
|
|
384
|
+
``event`` is the error event, or ``None`` when the stream simply stopped
|
|
385
|
+
(then the status is ``None`` and the error is retryable).
|
|
386
|
+
"""
|
|
387
|
+
if event is not None:
|
|
388
|
+
base = make_status_error(event_status(event), event, header_request_id=header_request_id)
|
|
389
|
+
return StreamInterruptedError(
|
|
390
|
+
base.message,
|
|
391
|
+
audio_bytes=audio_bytes,
|
|
392
|
+
status=base.status,
|
|
393
|
+
error_code=base.error_code,
|
|
394
|
+
retryable=base.retryable,
|
|
395
|
+
request_id=base.request_id,
|
|
396
|
+
body=event,
|
|
397
|
+
)
|
|
398
|
+
return StreamInterruptedError(
|
|
399
|
+
default_message,
|
|
400
|
+
audio_bytes=audio_bytes,
|
|
401
|
+
status=None,
|
|
402
|
+
retryable=True,
|
|
403
|
+
request_id=_nonempty(header_request_id),
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def event_status(event: Mapping[str, object]) -> int | None:
|
|
408
|
+
"""The ``status_code`` of a stream or WebSocket event, if it is an int."""
|
|
409
|
+
value = event.get("status_code")
|
|
410
|
+
return value if isinstance(value, int) and not isinstance(value, bool) else None
|