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/_ws/_common.py ADDED
@@ -0,0 +1,176 @@
1
+ """Pieces the async and sync WebSocket clients share."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import logging
8
+ import re
9
+ import secrets
10
+ from collections.abc import Mapping, Sequence
11
+ from typing import cast
12
+
13
+ from websockets.exceptions import InvalidStatus, InvalidURI, WebSocketException
14
+ from websockets.frames import Frame
15
+
16
+ from .._exceptions import (
17
+ APIConnectionError,
18
+ APIStatusError,
19
+ APITimeoutError,
20
+ BakbakError,
21
+ make_status_error,
22
+ )
23
+ from .._utils import logger
24
+ from ..audio import stream_sample_size
25
+
26
+ __all__ = [
27
+ "WEBSOCKET_LOGGER",
28
+ "build_request",
29
+ "check_context_id",
30
+ "connect_error",
31
+ "new_context_id",
32
+ "open_failure",
33
+ "text_delta",
34
+ ]
35
+
36
+ _CONTEXT_ID = re.compile(r"[A-Za-z0-9._-]{1,128}")
37
+
38
+
39
+ class _Redact(logging.Filter):
40
+ """Keeps the key and the synthesis text out of the websockets library's
41
+ debug log: it logs every handshake header and every frame."""
42
+
43
+ def filter(self, record: logging.LogRecord) -> bool:
44
+ args = record.args
45
+ if isinstance(args, tuple) and args:
46
+ first: object = args[0]
47
+ if isinstance(first, Frame):
48
+ record.args = (f"{first.opcode.name} frame ({len(first.data)} bytes)", *args[1:])
49
+ elif len(args) == 2 and isinstance(first, str) and first.lower() == "x-api-key":
50
+ record.args = (first, "***")
51
+ return True
52
+
53
+
54
+ WEBSOCKET_LOGGER = logging.getLogger("bakbak.websockets")
55
+ """The logger the websockets library writes to for this SDK's connections."""
56
+ WEBSOCKET_LOGGER.addFilter(_Redact())
57
+
58
+
59
+ def new_context_id() -> str:
60
+ """``ctx_`` plus 32 hex digits from a CSPRNG."""
61
+ return f"ctx_{secrets.token_hex(16)}"
62
+
63
+
64
+ def check_context_id(context_id: str | None) -> str:
65
+ if context_id is None:
66
+ return new_context_id()
67
+ if not isinstance(context_id, str) or not _CONTEXT_ID.fullmatch(context_id): # pyright: ignore[reportUnnecessaryIsInstance]
68
+ raise BakbakError("context_id must be 1 to 128 characters of A-Z a-z 0-9 . _ -")
69
+ return context_id
70
+
71
+
72
+ def build_request(
73
+ defaults: Mapping[str, object],
74
+ params: Mapping[str, object],
75
+ extra_body: Mapping[str, object] | None,
76
+ context_id: str,
77
+ ) -> tuple[str, int]:
78
+ """The JSON message of one request and the sample width of its audio."""
79
+ payload: dict[str, object] = {**defaults, **params}
80
+ if extra_body:
81
+ payload.update(extra_body)
82
+ payload["context_id"] = context_id
83
+ wire = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
84
+ return wire, stream_sample_size(payload.get("output_format"))
85
+
86
+
87
+ # Typed items whose ``text`` or ``content`` is a piece of the reply: Anthropic's
88
+ # text delta, a text block, and LangChain's message chunk. Other typed items
89
+ # (tool calls, reasoning, a final "done" event with the whole text) are skipped.
90
+ _TEXT_KINDS = frozenset({"text", "text_delta", "AIMessageChunk"})
91
+
92
+
93
+ def _field(obj: object, name: str) -> object:
94
+ if isinstance(obj, Mapping):
95
+ return cast("Mapping[str, object]", obj).get(name)
96
+ try:
97
+ return getattr(obj, name, None)
98
+ except Exception: # a property that raises, e.g. a response with no text part
99
+ return None
100
+
101
+
102
+ def text_delta(item: object) -> str | None:
103
+ """The text a stream item carries, found by duck typing.
104
+
105
+ Accepts ``str``; OpenAI chat chunks (``choices[0].delta.content``);
106
+ OpenAI Responses events (``response.output_text.delta``); Anthropic
107
+ ``content_block_delta`` events (``delta.text``); Gemini chunks (``.text``);
108
+ and objects or dicts with a ``content`` string. Anything else, such as a
109
+ tool call, a reasoning delta or a usage event, carries no text: ``None``.
110
+ """
111
+ if isinstance(item, str):
112
+ return item
113
+ if item is None:
114
+ return None
115
+ if isinstance(item, (bytes, bytearray, memoryview)):
116
+ raise TypeError("send_stream() takes text, not bytes")
117
+ choices = _field(item, "choices")
118
+ if choices is not None:
119
+ if isinstance(choices, Sequence) and choices and not isinstance(choices, str):
120
+ content = _field(_field(cast("Sequence[object]", choices)[0], "delta"), "content")
121
+ return content if isinstance(content, str) else None
122
+ return None
123
+ kind = _field(item, "type")
124
+ delta = _field(item, "delta")
125
+ if isinstance(delta, str):
126
+ accepted = kind is None or (isinstance(kind, str) and kind.endswith("output_text.delta"))
127
+ return delta if accepted else None
128
+ if delta is not None:
129
+ text = _field(delta, "text")
130
+ return text if isinstance(text, str) else None
131
+ if kind is not None and kind not in _TEXT_KINDS:
132
+ return None
133
+ text = _field(item, "text")
134
+ if isinstance(text, str):
135
+ return text
136
+ content = _field(item, "content")
137
+ return content if isinstance(content, str) else None
138
+
139
+
140
+ def connect_error(exc: BaseException) -> tuple[BakbakError, str | None] | None:
141
+ """Map a failure to open the WebSocket onto the error hierarchy, with the
142
+ refusal's Retry-After header. ``None`` for exceptions that are not about
143
+ connecting (they propagate)."""
144
+ if isinstance(exc, InvalidStatus):
145
+ response = exc.response
146
+ raw = response.body or b""
147
+ try:
148
+ body: object = json.loads(raw) if raw else None
149
+ except ValueError:
150
+ body = None
151
+ error: APIStatusError = make_status_error(
152
+ response.status_code,
153
+ body,
154
+ header_request_id=response.headers.get("X-Request-Id"),
155
+ reason=response.reason_phrase,
156
+ )
157
+ return error, response.headers.get("Retry-After")
158
+ if isinstance(exc, (TimeoutError, asyncio.TimeoutError)):
159
+ return APITimeoutError("Timed out opening the WebSocket."), None
160
+ if isinstance(exc, InvalidURI):
161
+ return BakbakError("The WebSocket URL is not valid; check base_url."), None
162
+ if isinstance(exc, (OSError, WebSocketException)):
163
+ return APIConnectionError(f"Could not open the WebSocket: {type(exc).__name__}."), None
164
+ return None
165
+
166
+
167
+ def open_failure(exc: BaseException) -> BakbakError:
168
+ """What a request waiting for a connection fails with when opening one
169
+ raised ``exc``: the SDK error itself, or a connection error that names
170
+ an unexpected one (every waiting request must get an outcome)."""
171
+ if isinstance(exc, BakbakError):
172
+ return exc
173
+ logger.debug("opening the WebSocket raised an unexpected error", exc_info=exc)
174
+ return APIConnectionError(
175
+ f"Could not open the WebSocket: {type(exc).__name__}: {exc}", retryable=False
176
+ )