livekit-plugins-rabel 1.8.13__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.
@@ -0,0 +1,47 @@
1
+ # Copyright 2026 Rabel Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Rabel plugin for LiveKit Agents
16
+
17
+ Bell guesses the caller's final words before the speech-to-text has them. This plugin wraps
18
+ any streaming speech-to-text and sends one guess a turn as a preflight transcript, on which
19
+ LiveKit starts the LLM early. LiveKit's own end-of-turn check keeps or drops that reply.
20
+ """
21
+
22
+ from .stt import STT, SpeechStream
23
+ from .version import __version__
24
+
25
+ __all__ = ["STT", "SpeechStream", "__version__"]
26
+
27
+
28
+ from livekit.agents import Plugin
29
+
30
+ from .log import logger
31
+
32
+
33
+ class RabelPlugin(Plugin):
34
+ def __init__(self) -> None:
35
+ super().__init__(__name__, __version__, __package__, logger)
36
+
37
+
38
+ Plugin.register_plugin(RabelPlugin())
39
+
40
+ # Cleanup docs of unexported modules
41
+ _module = dir()
42
+ NOT_IN_ALL = [m for m in _module if m not in __all__]
43
+
44
+ __pdoc__ = {}
45
+
46
+ for n in NOT_IN_ALL:
47
+ __pdoc__[n] = False
@@ -0,0 +1,340 @@
1
+ # Copyright 2026 Rabel Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """One conversation with the Rabel API (`WS /v1/conversation`, its version 2), kept open for a speech stream.
16
+
17
+ Hello: the first message carries `key`, `v` (2), `agent`, `host`, `host_version`, `hookup`, `vendor`, `min_chance`
18
+ and `learn`, and `user` when the developer set one. It is sent without a `type` field: a version 2 API reads a first
19
+ message with a `key` and no `type` as the hello, and that is the form a version 1 API has always read.
20
+ In: `{"type": "heard", "text"}` with the turn's words so far, `{"type": "end_of_turn", "text"}` with its final words
21
+ and, unless the report is off, `guess` ("none", "kept" or "dropped") and with "kept" `head_start_ms`.
22
+ Out: `ready` (version 2 adds `min_chance` and `hold_line`), `guess` (`text`, `heard`; version 2 adds `chance`),
23
+ `end_of_turn`, `error` (`status`, `error`, `message`, `retry_after_s`). Fields this client does not know are ignored, so a version 1 API works.
24
+
25
+ Nothing here ever raises into the caller. Words are sent only while the API is ready; before that, and after any failure,
26
+ they are dropped and the speech stream runs as a plain pass-through. Each kind of failure is logged once.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import asyncio
32
+ import contextlib
33
+ import json
34
+ import time
35
+ from collections.abc import Callable
36
+ from typing import Any
37
+
38
+ import aiohttp
39
+
40
+ from livekit.agents import utils
41
+
42
+ from .log import logger
43
+
44
+ # The reopening rules (the Rabel API's docs).
45
+ # A refusal that will not clear by itself during a call: no new conversation is opened for this stream
46
+ # (400 bad_message, 401 bad_key, 402 no_seconds, 404 unknown_agent, 409 read_only_agent).
47
+ _STOP_STATUSES = {400, 401, 402, 404, 409}
48
+ # Anything else that ends a conversation (408, 429, 503, 529, a dropped connection, a timeout) is retried after these
49
+ # waits in turn, the last one repeating; the API's retry_after_s is used instead when it is longer, up to the cap.
50
+ _BACKOFF_S = (1.0, 2.0, 4.0, 8.0, 16.0, 30.0)
51
+ _MAX_RETRY_AFTER_S = 300.0
52
+ # A conversation that was open this long and then closed cleanly (the API closes one after an hour) reopens at once.
53
+ _LONG_CONVERSATION_S = 60.0
54
+ # One timeout from opening the connection until the API's ready; past it the attempt counts as a timeout and is retried.
55
+ _OPEN_TIMEOUT_S = 2.0
56
+
57
+
58
+ def _backoff(attempt: int) -> float:
59
+ return _BACKOFF_S[min(attempt, len(_BACKOFF_S) - 1)]
60
+
61
+
62
+ class BellConnection:
63
+ def __init__(
64
+ self,
65
+ *,
66
+ url: str,
67
+ api_key: str,
68
+ hello: dict[str, Any],
69
+ on_guess: Callable[[dict[str, Any]], None],
70
+ http_session: aiohttp.ClientSession | None = None,
71
+ ) -> None:
72
+ self._url = url
73
+ self._api_key = api_key
74
+ self._hello = hello
75
+ self._on_guess = on_guess
76
+ self._own_session = http_session is None
77
+ self._session = http_session
78
+ self._ws: aiohttp.ClientWebSocketResponse | None = None
79
+ self._ready = False
80
+ self._hold_line: float | None = None
81
+ self._min_chance: float | None = None
82
+ self._conversation = 0 # counts the conversations that reached ready
83
+ self._closed = False
84
+ self._logged: set[str] = set()
85
+ self._out: asyncio.Queue[str] = asyncio.Queue()
86
+ self._task: asyncio.Task[None] | None = None
87
+ self._wake = asyncio.Event()
88
+ self.stats: dict[str, int] = {
89
+ "sent": 0,
90
+ "dropped_not_ready": 0,
91
+ "guesses": 0,
92
+ "connects": 0,
93
+ }
94
+
95
+ @property
96
+ def ready(self) -> bool:
97
+ return self._ready
98
+
99
+ @property
100
+ def conversation(self) -> int:
101
+ """Which conversation is open: a new number each time one reaches ready, 0 before the first."""
102
+ return self._conversation
103
+
104
+ @property
105
+ def hold_line(self) -> float | None:
106
+ """Rule 3's line from the API's `ready` (version 2), or None when the API did not send one."""
107
+ return self._hold_line
108
+
109
+ @property
110
+ def min_chance(self) -> float | None:
111
+ """The min_chance in force, from the API's `ready` (version 2), or None when the API did not send one."""
112
+ return self._min_chance
113
+
114
+ def log_once(self, kind: str, line: str) -> None:
115
+ """One logged line for each kind of failure on this stream."""
116
+ self._log_once(kind, line)
117
+
118
+ def start(self) -> None:
119
+ if self._task is None:
120
+ self._task = asyncio.create_task(self._run(), name="rabel.BellConnection")
121
+
122
+ def heard(self, text: str) -> None:
123
+ """The turn's words so far, and nothing else."""
124
+ self._send({"type": "heard", "text": text})
125
+
126
+ def end_of_turn(
127
+ self, text: str, guess: str | None = None, head_start_ms: int | None = None
128
+ ) -> None:
129
+ """The turn's final words, and when given, the report of what happened to Bell's guess in the turn (the Rabel
130
+ API's docs): `guess` "none", "kept" or "dropped", and with "kept" the head start in ms."""
131
+ msg: dict[str, Any] = {"type": "end_of_turn", "text": text}
132
+ if guess is not None:
133
+ msg["guess"] = guess
134
+ if guess == "kept" and head_start_ms is not None:
135
+ msg["head_start_ms"] = head_start_ms
136
+ self._send(msg)
137
+
138
+ def _send(self, msg: dict[str, Any]) -> None:
139
+ if not self._ready or self._closed:
140
+ self.stats["dropped_not_ready"] += 1
141
+ return
142
+ try:
143
+ self._out.put_nowait(json.dumps(msg))
144
+ except Exception as e: # noqa: BLE001
145
+ self._log_once(
146
+ "encode",
147
+ f"Bell: a message could not be sent ({e!r}); the speech-to-text passes through",
148
+ )
149
+
150
+ def _log_once(self, kind: str, line: str) -> None:
151
+ if kind not in self._logged:
152
+ self._logged.add(kind)
153
+ logger.warning(line)
154
+
155
+ async def aclose(self) -> None:
156
+ self._closed = True
157
+ self._ready = False
158
+ self._wake.set()
159
+ if self._task is not None:
160
+ await utils.aio.cancel_and_wait(self._task)
161
+ if self._ws is not None:
162
+ with contextlib.suppress(Exception):
163
+ await self._ws.close()
164
+ if self._own_session and self._session is not None:
165
+ with contextlib.suppress(Exception):
166
+ await self._session.close()
167
+
168
+ async def _run(self) -> None:
169
+ attempt = 0 # failed attempts since the last conversation that reached ready
170
+ while not self._closed:
171
+ opened_at: float | None = None
172
+ refusal: dict[str, Any] | None = None
173
+ clean = False
174
+ try:
175
+ opened_at, refusal, clean = await self._converse()
176
+ except asyncio.CancelledError:
177
+ raise
178
+ except (asyncio.TimeoutError, TimeoutError):
179
+ self._log_once(
180
+ "timeout",
181
+ f"Bell: the Rabel API was not ready within {_OPEN_TIMEOUT_S} s; "
182
+ "the speech-to-text passes through unchanged until it is",
183
+ )
184
+ except Exception as e: # noqa: BLE001 -- down, unreachable, a broken socket
185
+ self._log_once(
186
+ "down",
187
+ f"Bell: the Rabel API is not reachable ({type(e).__name__}: {e}); "
188
+ "the speech-to-text passes through unchanged",
189
+ )
190
+ finally:
191
+ self._ready = False
192
+ self._ws = None
193
+ while not self._out.empty():
194
+ self._out.get_nowait()
195
+ if self._closed:
196
+ return
197
+ if opened_at is not None:
198
+ attempt = 0
199
+ wait = self._wait_after(attempt, opened_at, refusal, clean)
200
+ if wait is None:
201
+ return # refused for good: the stream passes through for the rest of the call
202
+ if wait > 0:
203
+ attempt += 1
204
+ self._wake.clear()
205
+ with contextlib.suppress(asyncio.TimeoutError):
206
+ await asyncio.wait_for(self._wake.wait(), wait)
207
+
208
+ def _wait_after(
209
+ self,
210
+ attempt: int,
211
+ opened_at: float | None,
212
+ refusal: dict[str, Any] | None,
213
+ clean: bool,
214
+ ) -> float | None:
215
+ """The wait before the next conversation, by the API's reopening rules; None: open no other."""
216
+ if refusal is not None:
217
+ status = refusal.get("status")
218
+ if status in _STOP_STATUSES:
219
+ return None
220
+ wait = _backoff(attempt)
221
+ retry_after = refusal.get("retry_after_s")
222
+ if (
223
+ isinstance(retry_after, (int, float))
224
+ and not isinstance(retry_after, bool)
225
+ and retry_after > wait
226
+ ):
227
+ wait = min(float(retry_after), _MAX_RETRY_AFTER_S)
228
+ return wait
229
+ if opened_at is not None and clean and time.monotonic() - opened_at >= _LONG_CONVERSATION_S:
230
+ return 0.0
231
+ if opened_at is not None:
232
+ self._log_once(
233
+ "closed",
234
+ "Bell: the Rabel API closed the conversation early; "
235
+ "the speech-to-text passes through unchanged until it reopens",
236
+ )
237
+ return _backoff(attempt)
238
+
239
+ def _log_refusal(self, m: dict[str, Any]) -> None:
240
+ status, err = m.get("status"), m.get("error")
241
+ self._log_once(
242
+ f"refused:{status}:{err}",
243
+ f"Bell: the Rabel API refused ({status} {err}: {m.get('message')}); "
244
+ "the speech-to-text passes through unchanged",
245
+ )
246
+
247
+ async def _converse(self) -> tuple[float | None, dict[str, Any] | None, bool]:
248
+ """One conversation -> (when it reached ready or None, the API's error message if any, closed cleanly)."""
249
+ if self._session is None:
250
+ try:
251
+ # in a LiveKit job, the job's shared session, as LiveKit's own plugins use it
252
+ self._session = utils.http_context.http_session()
253
+ self._own_session = False
254
+ except RuntimeError:
255
+ self._session = (
256
+ aiohttp.ClientSession()
257
+ ) # outside a job: one of its own, closed with it
258
+ ws_url = (
259
+ self._url.rstrip("/").replace("https://", "wss://").replace("http://", "ws://")
260
+ + "/v1/conversation"
261
+ )
262
+ self.stats["connects"] += 1
263
+ deadline = time.monotonic() + _OPEN_TIMEOUT_S
264
+ ws = await asyncio.wait_for(
265
+ self._session.ws_connect(
266
+ ws_url,
267
+ timeout=aiohttp.ClientWSTimeout(ws_close=2.0),
268
+ heartbeat=None,
269
+ max_msg_size=1 << 20,
270
+ autoclose=True,
271
+ ),
272
+ _OPEN_TIMEOUT_S,
273
+ )
274
+ self._ws = ws
275
+ sender: asyncio.Task[None] | None = None
276
+ opened_at: float | None = None
277
+ refusal: dict[str, Any] | None = None
278
+ clean = False
279
+ try:
280
+ # the hello: the key and no `type`, which version 1 and version 2 both read as the hello
281
+ await ws.send_str(json.dumps({"key": self._api_key, **self._hello}))
282
+ while True:
283
+ if opened_at is None:
284
+ # until ready, the open timeout runs; a timeout ends this attempt (retried on the back-off)
285
+ msg = await asyncio.wait_for(
286
+ ws.receive(), max(deadline - time.monotonic(), 0.0)
287
+ )
288
+ else:
289
+ msg = await ws.receive()
290
+ if msg.type != aiohttp.WSMsgType.TEXT:
291
+ break
292
+ try:
293
+ m = json.loads(msg.data)
294
+ except ValueError:
295
+ self._log_once(
296
+ "wrong_data", "Bell: the Rabel API sent a message that is not JSON; ignored"
297
+ )
298
+ continue
299
+ kind = m.get("type") if isinstance(m, dict) else None
300
+ if kind == "ready" and opened_at is None:
301
+ self._hold_line = _unit_number(m.get("hold_line"))
302
+ self._min_chance = _unit_number(m.get("min_chance"))
303
+ self._conversation += 1
304
+ opened_at = time.monotonic()
305
+ self._ready = True
306
+ sender = asyncio.create_task(self._send_loop(ws))
307
+ elif kind == "guess" and opened_at is not None:
308
+ self.stats["guesses"] += 1
309
+ try:
310
+ self._on_guess(m)
311
+ except Exception as e: # noqa: BLE001
312
+ self._log_once(
313
+ "guess",
314
+ f"Bell: a guess could not be handled ({e!r}); the speech-to-text passes through",
315
+ )
316
+ elif kind == "error":
317
+ refusal = m
318
+ self._log_refusal(m)
319
+ # other message types (end_of_turn, ones this version does not know) are ignored
320
+ clean = ws.close_code == aiohttp.WSCloseCode.OK
321
+ return opened_at, refusal, clean
322
+ finally:
323
+ self._ready = False
324
+ if sender is not None:
325
+ await utils.aio.cancel_and_wait(sender)
326
+ with contextlib.suppress(Exception):
327
+ await ws.close()
328
+
329
+ async def _send_loop(self, ws: aiohttp.ClientWebSocketResponse) -> None:
330
+ while True:
331
+ data = await self._out.get()
332
+ await ws.send_str(data)
333
+ self.stats["sent"] += 1
334
+
335
+
336
+ def _unit_number(v: Any) -> float | None:
337
+ """A number in [0, 1] from the API, else None (missing, from a version 1 API, or malformed)."""
338
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or not 0.0 <= v <= 1.0:
339
+ return None
340
+ return float(v)
@@ -0,0 +1,97 @@
1
+ # Copyright 2026 Rabel Labs
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Bell's guess written the way the speech-to-text writes its final transcript.
16
+
17
+ Why: under LiveKit's default turn detection (its turn detector, with preemptive generation on), when the final transcript
18
+ arrives after the turn has ended LiveKit restarts the early reply unless the final's string is exactly the early start's
19
+ string (livekit-agents 1.8.13, voice/audio_recognition.py: `transcript_changed = self._audio_transcript !=
20
+ self._audio_preflight_transcript`). Bell's guesses come in lower case with no punctuation, while speech-to-texts
21
+ send cased, punctuated finals, so a right guess was never kept there. (With the speech-to-text's own end of turn, LiveKit
22
+ compares words, `_transcripts_equivalent`, and either form is kept.)
23
+
24
+ So the guess is written from the speech-to-text's own text of the words so far, exactly as it last showed them, and only
25
+ the words Bell adds are formed here: "i" and the common contractions restored, "AM"/"PM" after an hour, the first word
26
+ capitalised when it opens a sentence; the turn closed with "?" when its last sentence opens like a question and "." otherwise. A guess written this way is kept when the
27
+ final has that form; when the speech-to-text writes the end of the turn otherwise (a comma, a name not yet heard, a number), it is
28
+ not, and LiveKit starts on the final as it does without Bell.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import re
34
+
35
+ # the words Bell's guesses carry without their apostrophe (LiveKit's comparison drops it), restored; a word that is also an
36
+ # English word without one ("ill", "were", "well", "its", "hell", "shell", "wed", "id") is left out unless measured
37
+ _CONTRACTIONS = {
38
+ w.replace("'", ""): w
39
+ for w in (
40
+ "i'm i'd i've i'll don't doesn't didn't can't couldn't won't wouldn't shouldn't isn't aren't wasn't weren't "
41
+ "haven't hasn't hadn't that's what's there's here's where's who's how's let's you're you've you'll you'd "
42
+ "they're they've they'll we're we've it's he's she's"
43
+ ).split()
44
+ }
45
+ _QUESTION_OPENERS = frozenset(
46
+ "can could would will do does did is are am was were should shall may might have has what whats how where when "
47
+ "why who which whose whom isnt arent dont doesnt didnt wont wouldnt couldnt cant".split()
48
+ )
49
+ _ENDS = (".", "?", "!")
50
+ _HOURS = frozenset(
51
+ "one two three four five six seven eight nine ten eleven twelve thirty fifteen fortyfive".split()
52
+ )
53
+ _PUNCT = re.compile(r"[^\w]", re.UNICODE)
54
+
55
+
56
+ def norm_word(token: str) -> str:
57
+ """A shown token in the form Bell's guesses and LiveKit's comparison use: punctuation dropped, case-folded."""
58
+ return _PUNCT.sub("", token).casefold()
59
+
60
+
61
+ def _form(word: str) -> str:
62
+ if word == "i":
63
+ return "I"
64
+ if word in _CONTRACTIONS:
65
+ f = _CONTRACTIONS[word]
66
+ return "I" + f[1:] if f.startswith("i'") else f
67
+ return word
68
+
69
+
70
+ def _cap(w: str) -> str:
71
+ return w[:1].upper() + w[1:]
72
+
73
+
74
+ def _sentence_opener(toks: list[str]) -> str:
75
+ start = 0
76
+ for i, t in enumerate(toks[:-1]):
77
+ if t.endswith(_ENDS):
78
+ start = i + 1
79
+ return norm_word(toks[start]) if toks[start:] else ""
80
+
81
+
82
+ def final_form(shown: str, added: tuple[str, ...]) -> str:
83
+ """The guess in the final's form: `shown` (the speech-to-text's text of the words so far, as it showed them) and the
84
+ words Bell adds after them. With no shown text, the added words are the whole turn."""
85
+ shown = shown.strip()
86
+ if not added:
87
+ return shown
88
+ words = [_form(w) for w in added]
89
+ before = [norm_word(t) for t in shown.split()[-1:]] + list(added)
90
+ for i, w in enumerate(added): # "five pm" -> "five PM": the hour's mark, after a number
91
+ prev = before[i]
92
+ if w in ("am", "pm") and (prev in _HOURS or prev.isdigit()):
93
+ words[i] = w.upper()
94
+ if not shown or shown.endswith(_ENDS):
95
+ words[0] = _cap(words[0])
96
+ toks = (shown.split() if shown else []) + words
97
+ return " ".join(toks) + ("?" if _sentence_opener(toks) in _QUESTION_OPENERS else ".")
@@ -0,0 +1,3 @@
1
+ import logging
2
+
3
+ logger = logging.getLogger("livekit.plugins.rabel")
File without changes