pipecat-rabel 0.3.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.
@@ -0,0 +1,24 @@
1
+ #
2
+ # Copyright (c) 2026, Rabel Labs Inc.
3
+ #
4
+ # SPDX-License-Identifier: BSD 2-Clause License
5
+ #
6
+
7
+ """Bell for Pipecat: start the reply on Bell's guess at the caller's words, before the caller finishes."""
8
+
9
+ __version__ = "0.3.0"
10
+
11
+ from pipecat_rabel.strategy import ( # noqa: E402
12
+ RABEL_API_URL,
13
+ BellStats,
14
+ RabelBellUserTurnStopStrategy,
15
+ RabelBellUserTurnStrategies,
16
+ )
17
+
18
+ __all__ = [
19
+ "RABEL_API_URL",
20
+ "BellStats",
21
+ "RabelBellUserTurnStopStrategy",
22
+ "RabelBellUserTurnStrategies",
23
+ "__version__",
24
+ ]
@@ -0,0 +1,1029 @@
1
+ #
2
+ # Copyright (c) 2026, Rabel Labs Inc.
3
+ #
4
+ # SPDX-License-Identifier: BSD 2-Clause License
5
+ #
6
+
7
+ """Bell, as a Pipecat user turn stop strategy: an early reply started on Bell's guess at the caller's words.
8
+
9
+ The strategy sits in the user aggregator's turn strategies, where Pipecat's own eager end of turn sits. It reads the words
10
+ as the speech-to-text sends them, sends them to Rabel's API (version 2 of its contract), and when Bell guesses the rest of
11
+ the turn it starts Pipecat's early reply on the guess with ``start_user_turn_speculation()``. At the turn's end it keeps
12
+ that reply only when the committed transcript matches the guess, by the strategy's match policy (``NormalizedMatch`` by
13
+ default), and withdraws it with ``cancel_user_turn_speculation()`` otherwise, so a wrong guess costs one model call and
14
+ nothing the caller hears. It pushes no frame and changes none: the speech-to-text's frames reach the aggregator as they
15
+ were sent. With the API down, slow, refusing, closing or sending something the strategy cannot read, Bell starts no early
16
+ reply, the turn ends as Pipecat's own eager strategy ends it, and one line is logged for each kind of failure.
17
+ """
18
+
19
+ import asyncio
20
+ import json
21
+ import os
22
+ import re
23
+ import time
24
+ from dataclasses import dataclass, field
25
+ from importlib.metadata import PackageNotFoundError
26
+ from importlib.metadata import version as _package_version
27
+ from typing import Any
28
+
29
+ import websockets
30
+ from loguru import logger
31
+ from pipecat.frames.frames import (
32
+ CancelFrame,
33
+ EndFrame,
34
+ Frame,
35
+ InterimTranscriptionFrame,
36
+ ProposedUserStartedSpeakingFrame,
37
+ TranscriptionFrame,
38
+ UserStartedSpeakingFrame,
39
+ UserTurnResponseCancelFrame,
40
+ VADUserStartedSpeakingFrame,
41
+ )
42
+ from pipecat.processors.frame_processor import FrameProcessorSetup
43
+ from pipecat.turns.types import UserTurnSpeculation
44
+ from pipecat.turns.user_stop import EagerMatchPolicy, EagerUserTurnStopStrategy
45
+ from pipecat.turns.user_turn_strategies import ExternalUserTurnStrategies
46
+ from websockets.exceptions import InvalidStatus
47
+
48
+ from pipecat_rabel import __version__
49
+
50
+ RABEL_API_URL = "wss://api.rabellabs.com/v1/conversation"
51
+ """The address of Bell's conversation endpoint."""
52
+
53
+ DEFAULT_AGENT = "default"
54
+ DEFAULT_MIN_CHANCE = 0.7
55
+ MIN_CHANCE_RANGE = (0.67, 0.99) # the API's range; a value outside it is clamped here, as the API would bring it in
56
+
57
+ _AGENT_NAME = re.compile(r"^[a-z0-9_-]{1,64}$")
58
+ # the hello's `user`: 1 to 128 of A-Z, a-z, 0-9, '.', '_', ':' and '-'
59
+ _USER = re.compile(r"[A-Za-z0-9._:-]{1,128}")
60
+ # the report's head start is a number of ms from 0 to the conversation's limit (an hour)
61
+ _MAX_HEAD_START_MS = 3_600_000
62
+
63
+ # The API's refusals. A refusal in STOP ends Bell for the rest of the call: retrying cannot change
64
+ # the answer. One in RETRY is retried with the back-off below, or after the API's retry_after_s when that is longer.
65
+ _STOP_STATUSES = {400, 401, 402, 404, 409}
66
+ _RETRY_STATUSES = {408, 429, 503, 529}
67
+
68
+ # Waits between attempts to open a conversation after a failure, in seconds; the last one repeats.
69
+ _BACKOFF = (1.0, 2.0, 4.0, 8.0, 16.0, 30.0)
70
+ # A conversation that stayed open this long and then closed cleanly (the API closes one after an hour) is reopened at once.
71
+ _LONG_CONVERSATION_S = 60.0
72
+
73
+
74
+ def _pipecat_version() -> str:
75
+ try:
76
+ return _package_version("pipecat-ai")
77
+ except PackageNotFoundError: # pragma: no cover - only when Pipecat runs from a source tree
78
+ return "unknown"
79
+
80
+
81
+ def _ws_url(url: str) -> str:
82
+ """Accepts the endpoint itself, or the API's base address in http(s) or ws(s) form."""
83
+ url = url.rstrip("/")
84
+ if url.startswith("https://"):
85
+ url = "wss://" + url[len("https://") :]
86
+ elif url.startswith("http://"):
87
+ url = "ws://" + url[len("http://") :]
88
+ if not url.endswith("/v1/conversation"):
89
+ url += "/v1/conversation"
90
+ return url
91
+
92
+
93
+ @dataclass
94
+ class _Conversation:
95
+ """One open conversation with the API."""
96
+
97
+ ws: Any
98
+ opened_at: float
99
+ hold_line: float | None = None
100
+ hold_always: bool | None = None
101
+ hold_updates: int | None = None
102
+ calls_heard: int | None = None
103
+ refusal: dict | None = None # an error message the API sent before closing
104
+
105
+
106
+ @dataclass
107
+ class BellStats:
108
+ """Counts kept for one call, for logs and tests.
109
+
110
+ Parameters:
111
+ conversations: Conversations opened with the API.
112
+ turns_sent: Turns whose words were sent to Bell.
113
+ guesses_received: Guesses Bell sent.
114
+ guesses_pushed: Early replies started on Bell's guesses.
115
+ guesses_dropped: Guesses not used: late, outside the turn, unreadable, under ``min_chance``, or never started
116
+ in their turn.
117
+ guesses_right: Turns whose guess equalled the final words, as the match policy compares them.
118
+ eager_held_back: The speech-to-text's own early ends of turn not started because Bell's early reply on the same
119
+ words was already under way.
120
+ failures: Failures by kind, each kind logged once.
121
+ """
122
+
123
+ conversations: int = 0
124
+ turns_sent: int = 0
125
+ guesses_received: int = 0
126
+ guesses_pushed: int = 0
127
+ guesses_dropped: int = 0
128
+ guesses_right: int = 0
129
+ eager_held_back: int = 0
130
+ failures: dict[str, int] = field(default_factory=dict)
131
+
132
+
133
+ class RabelBellUserTurnStopStrategy(EagerUserTurnStopStrategy):
134
+ """Starts Pipecat's early reply on Bell's guess at the caller's words, and keeps it only when the turn matches.
135
+
136
+ A user turn stop strategy, installed with :class:`RabelBellUserTurnStrategies` as Pipecat's
137
+ ``EagerUserTurnStopStrategy`` is installed with ``EagerUserTurnStrategies``. It is that eager strategy with Bell added,
138
+ so a speech-to-text's own eager end of turn (Deepgram Flux's, when switched on) keeps working beside Bell, and decides
139
+ the turn's end as it does. What it adds:
140
+
141
+ - The words: each :class:`~pipecat.frames.frames.InterimTranscriptionFrame` with words is sent to Bell as ``heard``,
142
+ each :class:`~pipecat.frames.frames.TranscriptionFrame` with words as ``end_of_turn``.
143
+ - Bell's guess at the whole turn: an early reply is started on it with ``start_user_turn_speculation()``, the call
144
+ Pipecat's docs give a stop strategy for answering ahead of the turn ending. Pipecat holds the reply until the turn
145
+ is confirmed and never writes the guess to the conversation.
146
+ - The turn's end: the reply is kept when the transcript committed since the guess matches it by the match policy
147
+ (``NormalizedMatch`` unless another is given), and withdrawn with ``cancel_user_turn_speculation()`` when it does
148
+ not, when the caller resumes, or when the turn stays unresolved for ``speculation_timeout``. So a wrong guess is
149
+ never heard when the turn ends through these strategies. When the app or an upstream turn processor such as
150
+ Pipecat's ``UserTurnProcessor`` ends the turn itself, Pipecat releases the held reply before the check, and the
151
+ caller can hear both the reply to the guess and the reply to the final words.
152
+
153
+ One early reply runs at a time. A newer guess withdraws the reply under way before it starts its own. The
154
+ speech-to-text's early end of turn on the words of Bell's reply under way is not started (it would replace that reply
155
+ with an identical one started later; counted in ``stats.eager_held_back``); one on other words withdraws Bell's
156
+ reply, then starts. When a VAD hears the caller go on after a pause, Pipecat voids the reply under way, and Bell's
157
+ no longer counts as running.
158
+
159
+ Failing open: the connection to the API is opened in the background when the pipeline is set up, and nothing waits
160
+ for it. Until the API answers ``ready``, while it is down, when it refuses, when it closes the conversation mid-call,
161
+ and when it sends a message this strategy cannot read, Bell starts no early reply and the turn ends exactly as
162
+ Pipecat's eager strategy ends it. Each kind of failure is logged once a call at WARNING, and again only at DEBUG.
163
+
164
+ Event handlers available:
165
+
166
+ - on_ready(strategy, ready): the API answered the hello; ``ready`` is a dict with the API's ``hold_line`` and
167
+ ``calls_heard`` (how many of this agent's calls Bell has learned from).
168
+ - on_guess(strategy, text, chance): an early reply was started on a guess. ``chance`` is None when an earlier guess
169
+ is started again because the words heard have reached it.
170
+ - on_turn_end(strategy, final, guess, right): a turn sent to Bell ended; ``guess`` is the guess started in that
171
+ turn or None, ``right`` whether it equals the final words as the match policy compares them.
172
+
173
+ The report: at each turn's end the strategy tells the API whether Bell's guess was kept or dropped, with the head
174
+ start of a kept one, so the agent's status can show them. Kept means Bell's early reply is still the one under way
175
+ when the final words arrive and the match policy finds the final words equal to it. One DEBUG line is logged for
176
+ each kept guess, and one INFO line with the call's totals when it ends; neither carries a word of the call.
177
+ """
178
+
179
+ def __init__(
180
+ self,
181
+ *,
182
+ api_key: str | None = None,
183
+ agent: str = DEFAULT_AGENT,
184
+ min_chance: float = DEFAULT_MIN_CHANCE,
185
+ learn: bool = True,
186
+ url: str | None = None,
187
+ vendor: str | None = None,
188
+ connect_timeout: float = 2.0,
189
+ answer_timeout: float = 0.5,
190
+ user: str | None = None,
191
+ report: bool = True,
192
+ match_policy: EagerMatchPolicy | None = None,
193
+ speculation_timeout: float = 5.0,
194
+ **kwargs,
195
+ ):
196
+ """Initialize the strategy.
197
+
198
+ Args:
199
+ api_key: The Rabel API key. Defaults to the ``RABEL_API_KEY`` environment variable. Without one Bell stays
200
+ off and the strategy is Pipecat's eager strategy.
201
+ agent: Your agent's name, which Bell learns for: lower-case letters, digits, ``-`` and ``_``, 1 to
202
+ 64 characters. ``demo-bank`` is a demonstration agent every account can use.
203
+ min_chance: How sure Bell must be before it guesses, 0.67 to 0.99. Out of range is clamped.
204
+ learn: False means this call teaches Bell nothing.
205
+ url: The conversation endpoint, or the API's base address. Defaults to the ``RABEL_API_URL`` environment
206
+ variable, and without it to Rabel's API.
207
+ vendor: The speech-to-text in front of the aggregator (for example ``deepgram/flux-general-en``). Sent to
208
+ the API for its usage reports; never required.
209
+ connect_timeout: Seconds allowed to open a conversation, from the connection to Bell's ``ready``.
210
+ answer_timeout: Seconds after the words it answers within which a guess is still used. A later guess is
211
+ dropped.
212
+ user: An id you choose for the person on the call, sent in the hello: 1 to 128 letters, digits, ``.``,
213
+ ``_``, ``:`` or ``-``. It must never be a name, a number or an address. Bell does not use it yet.
214
+ Defaults to None (not sent).
215
+ report: True (the default) tells the Rabel API at each turn's end whether Bell's guess was kept or
216
+ dropped, with the head start of a kept one, so your agent's status can show them. No words are
217
+ added. False leaves it out.
218
+ match_policy: Decides whether the committed transcript matches an early reply's words, Bell's and the
219
+ speech-to-text's alike. Defaults to Pipecat's ``NormalizedMatch``.
220
+ speculation_timeout: Seconds an early reply may go unresolved before it is withdrawn, Bell's and the
221
+ speech-to-text's alike.
222
+ **kwargs: Passed to Pipecat's ``EagerUserTurnStopStrategy``.
223
+
224
+ Raises:
225
+ ValueError: If ``agent`` is not a valid agent name, ``user`` is not in its form, or ``report`` is not
226
+ True or False.
227
+ """
228
+ super().__init__(match_policy=match_policy, speculation_timeout=speculation_timeout, **kwargs)
229
+ if not _AGENT_NAME.match(agent):
230
+ raise ValueError(
231
+ f"agent must be 1 to 64 lower-case letters, digits, '-' or '_', not {agent!r}"
232
+ )
233
+ if user is not None and (not isinstance(user, str) or not _USER.fullmatch(user)):
234
+ # the error does not repeat the value: it may be a name or an address
235
+ raise ValueError(
236
+ "user must be 1 to 128 letters, digits, '.', '_', ':' or '-' (an id you choose, never a name, a number "
237
+ "or an address)"
238
+ )
239
+ if not isinstance(report, bool):
240
+ raise ValueError(f"report must be True or False (got {report!r})")
241
+ lo, hi = MIN_CHANCE_RANGE
242
+ if not lo <= min_chance <= hi:
243
+ logger.warning(f"{self}: min_chance {min_chance} is outside {lo} to {hi}; clamped")
244
+ min_chance = min(max(min_chance, lo), hi)
245
+
246
+ self._api_key = api_key if api_key is not None else os.environ.get("RABEL_API_KEY", "")
247
+ self._agent = agent
248
+ self._min_chance = min_chance
249
+ self._learn = learn
250
+ self._url = _ws_url(url if url is not None else os.environ.get("RABEL_API_URL") or RABEL_API_URL)
251
+ self._vendor = vendor
252
+ self._connect_timeout = connect_timeout
253
+ self._answer_timeout = answer_timeout
254
+ self._user = user
255
+ self._report = report
256
+ self._bell_speculation_timeout = speculation_timeout
257
+
258
+ self._conv: _Conversation | None = None
259
+ self._connection_task: asyncio.Task | None = None
260
+ self._sender_task: asyncio.Task | None = None
261
+ self._outbox: asyncio.Queue | None = None
262
+ self._stopped = False
263
+
264
+ # The turn as Bell's API counts it: from its first words to its final words.
265
+ self._in_turn = False
266
+ self._turn_conv: _Conversation | None = None # the conversation this turn's words go to, if any
267
+ self._heard = ""
268
+ self._heard_at: dict[str, float] = {} # words sent as heard -> when
269
+ self._guesses: list[str] = []
270
+ self._unused: list[str] = [] # guesses taken in this turn and not yet started, counted dropped if never started
271
+ self._pushed_guess: str | None = None # the guess started in this turn
272
+
273
+ # Pipecat's turn and its one early reply.
274
+ self._pipecat_turn_open = False
275
+ self._live_text: str | None = None # the words of the early reply under way, Bell's or the speech-to-text's
276
+ self._bell: UserTurnSpeculation | None = None # Bell's early reply, while it is the one under way
277
+ self._bell_at: float | None = None # when it was started (the report's head start)
278
+ self._bell_timer: asyncio.Task | None = None
279
+ self._bell_parts: list[str] = [] # transcripts committed since it was started, which it is checked against
280
+ self._bell_confirmed: UserTurnSpeculation | None = None # the one this turn's end kept
281
+ self._withdrawing_for_eager = False # while Bell's reply is withdrawn for the speech-to-text's early reply
282
+
283
+ self.stats = BellStats()
284
+ # what this call's guesses did for the host, for the summary logged when the call ends (numbers only)
285
+ self.summary: dict[str, int] = {"turns": 0, "guesses": 0, "kept": 0, "dropped": 0, "head_start_ms": 0}
286
+ self._summary_logged = False
287
+ self.ready = asyncio.Event()
288
+ """Set while a conversation with Bell is open and ready for words."""
289
+
290
+ self._register_event_handler("on_ready")
291
+ self._register_event_handler("on_guess")
292
+ self._register_event_handler("on_turn_end")
293
+
294
+ @property
295
+ def agent(self) -> str:
296
+ """The name of the agent this strategy talks to Bell for."""
297
+ return self._agent
298
+
299
+ @property
300
+ def min_chance(self) -> float:
301
+ """How sure Bell must be before it guesses."""
302
+ return self._min_chance
303
+
304
+ @property
305
+ def hold_line(self) -> float | None:
306
+ """The API's ``hold_line`` from the open conversation's ``ready``, or None.
307
+
308
+ For an app to log what the API sent; this strategy does not apply it.
309
+ """
310
+ return self._conv.hold_line if self._conv else None
311
+
312
+ @property
313
+ def hold_always(self) -> bool | None:
314
+ """The API's ``hold_always`` from the open conversation's ``ready`` (true or false), or None.
315
+
316
+ For an app to log what the API sent; this strategy does not apply it, like ``hold_line``.
317
+ """
318
+ return self._conv.hold_always if self._conv else None
319
+
320
+ @property
321
+ def hold_updates(self) -> int | None:
322
+ """The API's ``hold_updates`` from the open conversation's ``ready`` (1 or 2), or None.
323
+
324
+ For an app to log what the API sent; this strategy does not apply it, like ``hold_line``.
325
+ """
326
+ return self._conv.hold_updates if self._conv else None
327
+
328
+ # ------------------------------------------------------------------ the strategy's life
329
+
330
+ async def setup(self, setup: FrameProcessorSetup):
331
+ """Set up the strategy and open Bell's conversation in the background.
332
+
333
+ Pipecat sets a strategy up again after cleaning it up when a service's recommended strategies are merged in;
334
+ the conversation is then opened again.
335
+ """
336
+ await super().setup(setup)
337
+ self._start()
338
+
339
+ async def cleanup(self):
340
+ """Stop Bell's tasks and close its conversation at the pipeline's teardown."""
341
+ await super().cleanup()
342
+ await self._stop(polite=False, final=False)
343
+ await self._take_bell()
344
+
345
+ # ------------------------------------------------------------------ frames
346
+
347
+ async def process_frame(self, frame: Frame):
348
+ """Send the words to Bell, then let Pipecat's eager strategy see the frame.
349
+
350
+ Args:
351
+ frame: The frame to be analyzed.
352
+ """
353
+ if isinstance(frame, (EndFrame, CancelFrame)):
354
+ await super().process_frame(frame)
355
+ # An ended call sends its last turn's words to Bell before the conversation closes: Bell learns from a call
356
+ # when it closes. The frame is already on its way; this waits at most about 2 seconds, and only when the
357
+ # API is slow.
358
+ await self._stop(polite=isinstance(frame, EndFrame), final=True)
359
+ return
360
+
361
+ if isinstance(frame, UserTurnResponseCancelFrame):
362
+ # The early reply under way was withdrawn (the speech-to-text's resumed turn, a timeout, or a withdrawal of
363
+ # this strategy's own, which Pipecat feeds back to every strategy): none is under way.
364
+ await self._take_bell()
365
+ self._live_text = None
366
+ if self._withdrawing_for_eager:
367
+ # This strategy's own withdrawal of Bell's reply, made in start_user_turn_speculation just before the
368
+ # speech-to-text's early reply starts. Pipecat's eager strategy has already recorded that reply and
369
+ # would forget it on this frame, so the frame goes no further.
370
+ return
371
+ elif isinstance(frame, (VADUserStartedSpeakingFrame, UserStartedSpeakingFrame, ProposedUserStartedSpeakingFrame)):
372
+ # Speech voids the turn's answer, and with it the confirmation of the guess that gave it.
373
+ self._bell_confirmed = None
374
+ if isinstance(frame, VADUserStartedSpeakingFrame) and self._bell is not None:
375
+ # The caller went on after the VAD heard them stop. Pipecat resumes the turn and voids the early reply
376
+ # under way (the user aggregator interrupts it or withdraws it downstream, and tells no strategy), so
377
+ # Bell's no longer runs: the speech-to-text's early end of turn on its words is not held back, and words
378
+ # that reach the guess start Bell's again.
379
+ await self._take_bell()
380
+ self._live_text = None
381
+ elif isinstance(frame, TranscriptionFrame) and frame.text:
382
+ # Committed before Pipecat's strategy sees it, which may end the turn on it.
383
+ self._bell_parts.append(frame.text)
384
+ try:
385
+ await self._on_final(frame)
386
+ except Exception as e: # noqa: BLE001 - Bell must never stop the turn
387
+ self._failure("internal", f"Bell's strategy hit an error ({e!r}); the turn goes on")
388
+
389
+ await super().process_frame(frame)
390
+
391
+ if isinstance(frame, InterimTranscriptionFrame) and frame.text:
392
+ reached = None
393
+ try:
394
+ reached = self._on_heard(frame)
395
+ except Exception as e: # noqa: BLE001
396
+ self._failure("internal", f"Bell's strategy hit an error ({e!r}); the turn goes on")
397
+ if reached is not None:
398
+ # The words have reached a guess Bell made earlier in the turn: start the reply on it.
399
+ await self._start_bell(reached)
400
+
401
+ async def handle_user_turn_started(self):
402
+ """Ready the strategy for the turn now starting."""
403
+ await super().handle_user_turn_started()
404
+ unresolved = await self._take_bell()
405
+ self._bell_confirmed = None
406
+ self._bell_parts = []
407
+ self._pipecat_turn_open = True
408
+ if unresolved is not None:
409
+ await self.cancel_user_turn_speculation()
410
+
411
+ async def handle_user_turn_stopped(self):
412
+ """Clear the turn's state; withdraw Bell's early reply if the turn ended without resolving it."""
413
+ unresolved = await self._take_bell()
414
+ self._bell_confirmed = None
415
+ self._bell_parts = []
416
+ self._live_text = None
417
+ self._pipecat_turn_open = False
418
+ await super().handle_user_turn_stopped()
419
+ if unresolved is not None:
420
+ # The turn ended without the check (the turn controller's stop timeout, an interruption, the call's end).
421
+ logger.debug(f"{self}: turn ended unresolved, discarding the reply started on Bell's guess")
422
+ await self.cancel_user_turn_speculation()
423
+
424
+ async def report_user_turn_stopped(
425
+ self,
426
+ *,
427
+ enable_user_speaking_frames: bool | None = None,
428
+ confirms_speculation: bool = False,
429
+ ):
430
+ """Report that the user is done, keeping the reply started on Bell's guess only if the turn matches it.
431
+
432
+ Without a reply of Bell's under way, Pipecat's eager strategy decides, on its own early reply if it has one.
433
+
434
+ Args:
435
+ enable_user_speaking_frames: Whether to emit the ``UserStoppedSpeakingFrame`` for this turn.
436
+ confirms_speculation: Whether a reply generated ahead of this turn ending already answers it. Decided here
437
+ for Bell's own reply.
438
+ """
439
+ bell = await self._take_bell() or self._bell_confirmed
440
+ if bell is None:
441
+ await super().report_user_turn_stopped(
442
+ enable_user_speaking_frames=enable_user_speaking_frames,
443
+ confirms_speculation=confirms_speculation,
444
+ )
445
+ return
446
+
447
+ if self.match_policy.matches(bell.text, " ".join(self._bell_parts)):
448
+ self._bell_confirmed = bell
449
+ # The reply already runs on Bell's guess. The turn's end releases it, and the flag stops a second inference
450
+ # answering the same turn.
451
+ await super().report_user_turn_stopped(
452
+ enable_user_speaking_frames=enable_user_speaking_frames,
453
+ confirms_speculation=True,
454
+ )
455
+ return
456
+
457
+ self._bell_confirmed = None
458
+ await self.cancel_user_turn_speculation()
459
+ # The committed transcript gets an inference of its own, which the turn controller runs for this decision.
460
+ await super().report_user_turn_stopped(enable_user_speaking_frames=enable_user_speaking_frames)
461
+
462
+ async def start_user_turn_speculation(self, speculation: UserTurnSpeculation):
463
+ """Start the speech-to-text's own early reply, unless Bell's on the same words is under way.
464
+
465
+ Pipecat's eager strategy calls this on the speech-to-text's eager end of turn. Bell's own replies are started
466
+ through the base class and do not pass here.
467
+
468
+ This override relies on a detail Pipecat's docs do not promise: ``EagerUserTurnStopStrategy`` starts its
469
+ own early reply by calling ``self.start_user_turn_speculation()`` (Pipecat 1.16.0,
470
+ ``eager_user_turn_stop_strategy.py`` line 216, in ``_speculate``), so the call reaches this method. If a later
471
+ Pipecat started it another way, the speech-to-text's early end of turn on the words of Bell's reply under way
472
+ would start instead of being held back, Bell's reply would not be withdrawn first, and ``stats.eager_held_back``
473
+ would stay at 0. ``test_pipecats_eager_strategy_starts_its_early_reply_through_this_method`` fails if that
474
+ happens, and the nightly workflow runs it against Pipecat's main branch.
475
+
476
+ Withdrawing Bell's reply here relies on another detail: Pipecat feeds the withdrawal back to every strategy as a
477
+ ``UserTurnResponseCancelFrame`` before this call returns, and its eager strategy would forget the early reply it
478
+ has just recorded. :meth:`process_frame` keeps that frame from it while this method withdraws Bell's reply.
479
+
480
+ Args:
481
+ speculation: The speech-to-text's early end of turn.
482
+ """
483
+ if self._bell is not None and self._same(self._live_text, speculation.text):
484
+ # Starting it would replace the reply under way on Bell's guess with an identical one started later.
485
+ self.stats.eager_held_back += 1
486
+ logger.debug(f"{self}: the speech-to-text's early end of turn has the words of Bell's, under way; not started")
487
+ return
488
+ if await self._take_bell() is not None:
489
+ # Bell's reply on other words is under way. Pipecat withdraws nothing when an early reply starts, so it is
490
+ # withdrawn here first: left running, it would hold the LLM and pass the gate at the turn's end.
491
+ self._withdrawing_for_eager = True
492
+ try:
493
+ await self.cancel_user_turn_speculation()
494
+ finally:
495
+ self._withdrawing_for_eager = False
496
+ self._live_text = speculation.text
497
+ await super().start_user_turn_speculation(speculation)
498
+
499
+ # ------------------------------------------------------------------ Bell's early reply
500
+
501
+ async def _start_bell(self, text: str, chance: float | None = None):
502
+ """Withdraw the early reply under way, if any, and start one on this guess."""
503
+ if not self._pipecat_turn_open:
504
+ return # Pipecat starts no early reply outside its turn; the guess waits for the words to reach it
505
+ self._unused = [g for g in self._unused if g != text]
506
+ previous = await self._take_bell()
507
+ if previous is not None or self._live_text is not None:
508
+ await self.cancel_user_turn_speculation()
509
+ speculation = UserTurnSpeculation(text=text)
510
+ self._bell = speculation
511
+ self._bell_at = time.monotonic()
512
+ self._bell_parts = []
513
+ self._bell_confirmed = None
514
+ self._live_text = text
515
+ self._pushed_guess = text
516
+ self.stats.guesses_pushed += 1
517
+ self._bell_timer = self.create_task(self._bell_timeout(speculation), "bell_speculation_timeout")
518
+ logger.debug(f"{self}: starting an early reply on Bell's guess")
519
+ # The base class's call, not this class's override, which handles the speech-to-text's early end of turn.
520
+ await super().start_user_turn_speculation(speculation)
521
+ await self._call_event_handler("on_guess", text, chance)
522
+
523
+ async def _bell_timeout(self, speculation: UserTurnSpeculation):
524
+ """Withdraw a reply on Bell's guess that the turn never resolved."""
525
+ await asyncio.sleep(self._bell_speculation_timeout)
526
+ self._bell_timer = None
527
+ if self._bell is not speculation:
528
+ return
529
+ logger.debug(f"{self}: Bell's guess unresolved after {self._bell_speculation_timeout}s, discarding the reply")
530
+ self._bell = None
531
+ await self.cancel_user_turn_speculation()
532
+
533
+ async def _take_bell(self) -> UserTurnSpeculation | None:
534
+ """Take Bell's early reply under way, if any, stopping its clock."""
535
+ speculation, self._bell = self._bell, None
536
+ if self._bell_timer is not None:
537
+ task, self._bell_timer = self._bell_timer, None
538
+ if task is not asyncio.current_task():
539
+ await self.cancel_task(task)
540
+ return speculation
541
+
542
+ def _same(self, a: str | None, b: str | None) -> bool:
543
+ """Whether two transcripts are the same words, as the match policy compares them."""
544
+ return bool(a) and bool(b) and self.match_policy.matches(a, b)
545
+
546
+ # ------------------------------------------------------------------ Bell's turn
547
+
548
+ def _on_heard(self, frame: InterimTranscriptionFrame) -> str | None:
549
+ """Sends the words to Bell; returns an earlier guess the words have reached, to start the reply on."""
550
+ if not self._in_turn:
551
+ self._begin_turn()
552
+ self._heard = frame.text
553
+ if self._turn_conv is not None:
554
+ self._heard_at.setdefault(frame.text, time.monotonic())
555
+ self._send(self._turn_conv, {"type": "heard", "text": frame.text})
556
+ earlier = next((g for g in self._guesses if self._same(g, self._heard)), None)
557
+ if earlier and not self._same(earlier, self._live_text):
558
+ return earlier
559
+ return None
560
+
561
+ async def _on_final(self, frame: TranscriptionFrame):
562
+ final_at = time.monotonic()
563
+ conv, guess = self._turn_conv, self._pushed_guess
564
+ report, head_start_ms = self._report_of(frame.text, final_at)
565
+ self._count(report, head_start_ms)
566
+ self._drop_unused()
567
+ if conv is not None:
568
+ message: dict[str, Any] = {"type": "end_of_turn", "text": frame.text}
569
+ if self._report:
570
+ message["guess"] = report
571
+ if report == "kept" and head_start_ms is not None:
572
+ message["head_start_ms"] = head_start_ms
573
+ self._send(conv, message)
574
+ right = self._same(guess, frame.text)
575
+ self.stats.guesses_right += int(right)
576
+ await self._call_event_handler("on_turn_end", frame.text, guess, right)
577
+ self._in_turn = False
578
+ self._turn_conv = None
579
+ self._live_text = None # the turn's end settles the early reply, through the check
580
+
581
+ def _report_of(self, final: str, final_at: float) -> tuple[str, int | None]:
582
+ """What happened to Bell's guess in the turn: "kept" with its head start when the reply started on it is the
583
+ one under way and the transcript committed since it matches it, "dropped" when one was started and not kept or
584
+ when a guess taken in the turn was never started (it came before Pipecat's turn opened and the words never
585
+ reached it), "none" otherwise. This is the check :meth:`report_user_turn_stopped` makes when the turn ends on
586
+ these final words.
587
+ """
588
+ if not self._in_turn:
589
+ return "none", None
590
+ if self._pushed_guess is None:
591
+ return ("dropped" if self._unused else "none"), None
592
+ if self._bell is not None and self.match_policy.matches(self._bell.text, " ".join(self._bell_parts)):
593
+ return "kept", None if self._bell_at is None else _ms(final_at - self._bell_at)
594
+ return "dropped", None
595
+
596
+ def _drop_unused(self):
597
+ """Count as dropped the guesses taken in the turn that ending it leaves unused (never started)."""
598
+ if self._in_turn:
599
+ self.stats.guesses_dropped += len(self._unused)
600
+ self._unused = []
601
+
602
+ def _count(self, report: str, head_start_ms: int | None):
603
+ """The call's totals for the summary, and the line for a kept guess (numbers only, no word of the call)."""
604
+ s = self.summary
605
+ s["turns"] += 1
606
+ if report == "none":
607
+ return
608
+ s["guesses"] += 1
609
+ s[report] += 1
610
+ if report == "kept":
611
+ s["head_start_ms"] += head_start_ms or 0
612
+ # in the form and at the level of Pipecat's own line for an early reply kept (EagerUserTurnStopStrategy:
613
+ # "eager end of turn held, keeping the speculative response", DEBUG)
614
+ logger.bind(head_start_ms=head_start_ms).debug(
615
+ f"{self}: Bell's guess held, keeping the speculative response ({head_start_ms} ms head start)"
616
+ )
617
+
618
+ def _log_summary(self):
619
+ """One line when the call ends: numbers only, no word of the call."""
620
+ if self._summary_logged:
621
+ return
622
+ self._summary_logged = True
623
+ s = self.summary
624
+ try:
625
+ logger.bind(
626
+ turns=s["turns"], guesses=s["guesses"], kept=s["kept"], dropped=s["dropped"],
627
+ head_start_ms_total=s["head_start_ms"],
628
+ ).info(
629
+ f"{self}: Bell: {s['turns']} turns, {s['guesses']} guesses, {s['kept']} kept, {s['dropped']} dropped, "
630
+ f"{s['head_start_ms']} ms head start in all"
631
+ )
632
+ except Exception: # noqa: BLE001 - a fault here never reaches the pipeline
633
+ pass
634
+
635
+ def _begin_turn(self):
636
+ self._in_turn = True
637
+ self._heard = ""
638
+ self._heard_at = {}
639
+ self._guesses = []
640
+ self._unused = []
641
+ self._pushed_guess = None
642
+ # A turn goes to Bell only if its first words do: a conversation opened mid-turn waits for the next turn.
643
+ conv = self._conv
644
+ self._turn_conv = conv if conv is not None and self.ready.is_set() else None
645
+ if self._turn_conv is not None:
646
+ self.stats.turns_sent += 1
647
+
648
+ async def _on_guess(self, conv: _Conversation, m: dict):
649
+ """A guess from Bell: check it, then start the early reply on it or drop it."""
650
+ self.stats.guesses_received += 1
651
+ text, heard, chance = m.get("text"), m.get("heard"), m.get("chance")
652
+ if (
653
+ not isinstance(text, str)
654
+ or not text.strip()
655
+ or (heard is not None and not isinstance(heard, str))
656
+ or (chance is not None and (isinstance(chance, bool) or not isinstance(chance, (int, float))))
657
+ or (chance is not None and not 0.0 <= chance <= 1.0)
658
+ ):
659
+ self.stats.guesses_dropped += 1
660
+ self._failure("wrong_data", f"Bell sent a guess this strategy cannot read ({_short(m)}); not used")
661
+ return
662
+ if chance is not None and chance < self._min_chance:
663
+ self.stats.guesses_dropped += 1
664
+ self._failure(
665
+ "wrong_data", f"Bell sent a guess at chance {chance}, under min_chance {self._min_chance}; not used"
666
+ )
667
+ return
668
+ if not self._in_turn or self._turn_conv is not conv:
669
+ self.stats.guesses_dropped += 1 # the turn it answers is over
670
+ return
671
+ sent_at = self._heard_at.get(heard) if heard is not None else None
672
+ if heard is not None and sent_at is None:
673
+ sent_at = next((t for h, t in self._heard_at.items() if self._same(h, heard)), None)
674
+ if sent_at is None:
675
+ self.stats.guesses_dropped += 1
676
+ self._failure("wrong_data", "Bell sent a guess made from words this call did not send; not used")
677
+ return
678
+ if sent_at is not None:
679
+ late = time.monotonic() - sent_at
680
+ if late > self._answer_timeout:
681
+ self.stats.guesses_dropped += 1
682
+ self._failure(
683
+ "slow_answer",
684
+ f"Bell's guess came {late * 1000:.0f} ms after its words, over answer_timeout "
685
+ f"{self._answer_timeout * 1000:.0f} ms; not used",
686
+ )
687
+ return
688
+
689
+ self._guesses.append(text)
690
+ self._unused.append(text)
691
+ # An early reply under way on the words heard so far stays; otherwise the newest guess replaces it.
692
+ if self._live_text is not None and self._same(self._live_text, self._heard):
693
+ return
694
+ await self._start_bell(text, chance)
695
+
696
+ # ------------------------------------------------------------- connection
697
+
698
+ def _start(self):
699
+ if self._connection_task is not None:
700
+ return
701
+ self._stopped = False
702
+ if not self._api_key:
703
+ self._failure("no_key", "no Rabel API key (RABEL_API_KEY); Bell is off for this call")
704
+ return
705
+ self._outbox = asyncio.Queue()
706
+ self._sender_task = self.create_task(self._sender(), "bell_sender")
707
+ self._connection_task = self.create_task(self._run_connection(), "bell_connection")
708
+
709
+ async def _stop(self, polite: bool, final: bool):
710
+ """Close Bell's conversation. ``final`` when the call itself has ended (its end or cancel frame)."""
711
+ bell_was_on = self._connection_task is not None
712
+ if final:
713
+ self._drop_unused() # the call ended inside a turn: its guesses never started are not used
714
+ if bell_was_on and (final or self.summary["turns"] > 0):
715
+ self._log_summary()
716
+ self._stopped = True
717
+ connection, self._connection_task = self._connection_task, None
718
+ if connection is not None:
719
+ await self.cancel_task(connection)
720
+ sender, self._sender_task = self._sender_task, None
721
+ if sender is not None:
722
+ if polite and self._outbox is not None and self._conv is not None:
723
+ # The last turn's words, then a clean close: Bell learns from a call when it closes.
724
+ try:
725
+ await asyncio.wait_for(self._outbox.join(), 1.0)
726
+ except (asyncio.TimeoutError, TimeoutError):
727
+ pass
728
+ await self.cancel_task(sender)
729
+ conv, self._conv = self._conv, None
730
+ self.ready.clear()
731
+ if conv is not None:
732
+ try:
733
+ await asyncio.wait_for(conv.ws.close(), 1.0)
734
+ except Exception: # noqa: BLE001 - already gone, or slow to close; the call goes on either way
735
+ pass
736
+
737
+ def _send(self, conv: _Conversation, message: dict):
738
+ if self._outbox is not None:
739
+ self._outbox.put_nowait((conv, message))
740
+
741
+ async def _sender(self):
742
+ """Sends queued messages, so the pipeline never waits on the network."""
743
+ assert self._outbox is not None
744
+ outbox = self._outbox
745
+ while True:
746
+ conv, message = await outbox.get()
747
+ try:
748
+ if conv is self._conv:
749
+ await asyncio.wait_for(conv.ws.send(json.dumps(message)), self._connect_timeout)
750
+ except Exception: # noqa: BLE001 - the receiver sees the close and reopens
751
+ if conv is self._conv:
752
+ self._conv = None
753
+ self.ready.clear()
754
+ self._failure("closed", "the Rabel API connection failed while sending; going on without Bell")
755
+ try:
756
+ await asyncio.wait_for(conv.ws.close(), 0.5)
757
+ except Exception: # noqa: BLE001
758
+ pass
759
+ finally:
760
+ outbox.task_done()
761
+
762
+ def _hello(self) -> dict:
763
+ hello = {
764
+ "type": "hello",
765
+ "v": 2,
766
+ "agent": self._agent,
767
+ "min_chance": self._min_chance,
768
+ "learn": self._learn,
769
+ "host": "pipecat",
770
+ "host_version": _pipecat_version(),
771
+ "hookup": __version__,
772
+ }
773
+ if self._vendor:
774
+ hello["vendor"] = self._vendor
775
+ if self._user is not None:
776
+ hello["user"] = self._user
777
+ return hello
778
+
779
+ async def _run_connection(self):
780
+ """Opens conversations with the API for as long as the call lasts, by the contract's rules."""
781
+ attempt = 0
782
+ while not self._stopped:
783
+ delay: float | None
784
+ try:
785
+ conv = await asyncio.wait_for(self._open(), self._connect_timeout)
786
+ except _Refused as r:
787
+ delay = self._on_refusal(r.message, attempt)
788
+ except (asyncio.TimeoutError, TimeoutError):
789
+ self._failure(
790
+ "connect_timeout",
791
+ f"the Rabel API did not answer within connect_timeout {self._connect_timeout} s; "
792
+ "going on without Bell and retrying",
793
+ )
794
+ delay = _backoff(attempt)
795
+ except _WrongData as w:
796
+ self._failure("wrong_data", f"the Rabel API's first answer was not ready ({w}); retrying")
797
+ delay = _backoff(attempt)
798
+ except Exception as e: # noqa: BLE001 - down, refused at the socket, a bad address
799
+ self._failure("down", f"could not reach the Rabel API ({type(e).__name__}); going on without Bell")
800
+ delay = _backoff(attempt)
801
+ else:
802
+ attempt = 0
803
+ self.stats.conversations += 1
804
+ self._conv = conv
805
+ self.ready.set()
806
+ await self._call_event_handler("on_ready", {"hold_line": conv.hold_line, "calls_heard": conv.calls_heard})
807
+ await self._receive(conv)
808
+ if self._conv is conv:
809
+ self._conv = None
810
+ self.ready.clear()
811
+ if self._stopped:
812
+ return
813
+ if conv.refusal is not None:
814
+ delay = self._on_refusal(conv.refusal, attempt)
815
+ else:
816
+ lasted = time.monotonic() - conv.opened_at
817
+ code = getattr(conv.ws, "close_code", None)
818
+ if lasted >= _LONG_CONVERSATION_S and code == 1000:
819
+ logger.debug(f"{self}: the Rabel API closed the conversation after {lasted:.0f} s; reopening")
820
+ delay = 0.0
821
+ else:
822
+ self._failure(
823
+ "closed",
824
+ f"the Rabel API closed the conversation mid-call (code {code}); going on without Bell "
825
+ "and reopening",
826
+ )
827
+ delay = _backoff(attempt)
828
+ if delay is None:
829
+ return
830
+ attempt += 1
831
+ await asyncio.sleep(delay)
832
+
833
+ async def _open(self) -> _Conversation:
834
+ try:
835
+ ws = await websockets.connect(
836
+ self._url,
837
+ additional_headers={"Authorization": f"Bearer {self._api_key}"},
838
+ open_timeout=None,
839
+ max_size=2**20,
840
+ user_agent_header=f"pipecat-rabel/{__version__}",
841
+ )
842
+ except InvalidStatus as e:
843
+ status = e.response.status_code
844
+ body = _parse(e.response.body) if e.response.body else None
845
+ message = body if isinstance(body, dict) else {}
846
+ raise _Refused({"status": status, **{k: v for k, v in message.items() if k != "status"}}) from None
847
+ try:
848
+ await ws.send(json.dumps(self._hello()))
849
+ m = _parse(await ws.recv())
850
+ if isinstance(m, dict) and m.get("type") == "error":
851
+ raise _Refused(m)
852
+ if not isinstance(m, dict) or m.get("type") != "ready":
853
+ raise _WrongData(_short(m))
854
+ hold_line = m.get("hold_line")
855
+ hold_always = m.get("hold_always")
856
+ hold_updates = m.get("hold_updates")
857
+ calls_heard = m.get("calls_heard")
858
+ return _Conversation(
859
+ ws=ws,
860
+ opened_at=time.monotonic(),
861
+ hold_line=float(hold_line) if isinstance(hold_line, (int, float)) else None,
862
+ hold_always=hold_always if isinstance(hold_always, bool) else None,
863
+ hold_updates=int(hold_updates)
864
+ if isinstance(hold_updates, (int, float)) and not isinstance(hold_updates, bool) and hold_updates in (1, 2)
865
+ else None,
866
+ calls_heard=calls_heard if isinstance(calls_heard, int) else None,
867
+ )
868
+ except BaseException:
869
+ try:
870
+ await asyncio.wait_for(ws.close(), 0.5)
871
+ except Exception: # noqa: BLE001
872
+ pass
873
+ raise
874
+
875
+ async def _receive(self, conv: _Conversation):
876
+ try:
877
+ async for raw in conv.ws:
878
+ if self._conv is not conv:
879
+ return
880
+ m = _parse(raw)
881
+ kind = m.get("type") if isinstance(m, dict) else None
882
+ if kind == "guess":
883
+ try:
884
+ await self._on_guess(conv, m)
885
+ except Exception as e: # noqa: BLE001
886
+ self._failure("internal", f"Bell's strategy hit an error on a guess ({e!r}); not used")
887
+ elif kind == "end_of_turn":
888
+ pass # Bell's own record of the turn; the match policy already decided
889
+ elif kind == "error":
890
+ conv.refusal = m
891
+ elif kind is None or kind == "ready":
892
+ self._failure("wrong_data", f"the Rabel API sent a message this strategy cannot read ({_short(m)})")
893
+ # Message types this version does not know are ignored, as the contract asks.
894
+ except websockets.ConnectionClosed:
895
+ pass
896
+ except Exception as e: # noqa: BLE001
897
+ self._failure("closed", f"the Rabel API connection failed ({type(e).__name__}); going on without Bell")
898
+
899
+ def _on_refusal(self, m: dict, attempt: int) -> float | None:
900
+ """Logs a refusal; returns the wait before the next attempt, or None to stay off for the call."""
901
+ status = m.get("status")
902
+ name = m.get("error") or ""
903
+ if status in _STOP_STATUSES:
904
+ self._failure(
905
+ f"refused_{status}",
906
+ f"the Rabel API refused the conversation ({status} {name}); Bell is off for this call",
907
+ )
908
+ return None
909
+ self._failure(
910
+ f"refused_{status}",
911
+ f"the Rabel API refused the conversation ({status} {name}); going on without Bell and retrying",
912
+ )
913
+ retry_after = m.get("retry_after_s")
914
+ wait = _backoff(attempt)
915
+ if isinstance(retry_after, (int, float)) and not isinstance(retry_after, bool) and retry_after > wait:
916
+ wait = min(float(retry_after), 300.0)
917
+ return wait
918
+
919
+ def _failure(self, kind: str, line: str):
920
+ """One logged line per kind of failure a call; repeats go to DEBUG."""
921
+ n = self.stats.failures.get(kind, 0)
922
+ self.stats.failures[kind] = n + 1
923
+ if n == 0:
924
+ logger.warning(f"{self}: {line}")
925
+ else:
926
+ logger.debug(f"{self}: {line} (again, {n + 1} times)")
927
+
928
+
929
+ @dataclass
930
+ class RabelBellUserTurnStrategies(ExternalUserTurnStrategies):
931
+ """Turn strategies for a speech-to-text with its own turn detection, with Bell's early reply added.
932
+
933
+ Built on Pipecat's ``ExternalUserTurnStrategies``, as ``EagerUserTurnStrategies`` is, with
934
+ :class:`RabelBellUserTurnStopStrategy` (a subclass of ``EagerUserTurnStopStrategy``) as its stop strategy: the
935
+ service (Deepgram Flux, for one) still starts and ends the turn, its own eager end of turn still answers early when
936
+ it is switched on, and Bell's guess at the caller's words starts the reply earlier still. Pass it as the user
937
+ aggregator's ``user_turn_strategies``. The strategy is :attr:`bell`, for its events and its counts.
938
+
939
+ Parameters:
940
+ api_key: The Rabel API key; defaults to ``RABEL_API_KEY``. Not shown in this object's repr.
941
+ agent: Your agent's name, which Bell learns for.
942
+ min_chance: How sure Bell must be before it guesses, 0.67 to 0.99.
943
+ learn: False means this call teaches Bell nothing.
944
+ url: The conversation endpoint or the API's base address; defaults to ``RABEL_API_URL``, then Rabel's API.
945
+ vendor: The speech-to-text in front of the aggregator, for the API's usage reports.
946
+ connect_timeout: Seconds allowed to open a conversation.
947
+ answer_timeout: Seconds after its words within which a guess is still used.
948
+ user: An id you choose for the person on the call; never a name, a number or an address.
949
+ report: Whether each turn's end tells the API if Bell's guess was kept or dropped.
950
+ match_policy: Decides whether the committed transcript matches an early reply. Defaults to ``NormalizedMatch``.
951
+ speculation_timeout: Seconds an early reply may go unresolved before it is withdrawn.
952
+
953
+ Example::
954
+
955
+ user_aggregator, assistant_aggregator = LLMContextAggregatorPair(
956
+ context,
957
+ user_params=LLMUserAggregatorParams(
958
+ user_turn_strategies=RabelBellUserTurnStrategies(agent="front-desk"),
959
+ ),
960
+ )
961
+ """
962
+
963
+ api_key: str | None = field(default=None, repr=False)
964
+ agent: str = DEFAULT_AGENT
965
+ min_chance: float = DEFAULT_MIN_CHANCE
966
+ learn: bool = True
967
+ url: str | None = None
968
+ vendor: str | None = None
969
+ connect_timeout: float = 2.0
970
+ answer_timeout: float = 0.5
971
+ user: str | None = field(default=None, repr=False)
972
+ report: bool = True
973
+ match_policy: EagerMatchPolicy | None = None
974
+ speculation_timeout: float = 5.0
975
+
976
+ def __post_init__(self):
977
+ super().__post_init__()
978
+ self.stop = [
979
+ RabelBellUserTurnStopStrategy(
980
+ api_key=self.api_key,
981
+ agent=self.agent,
982
+ min_chance=self.min_chance,
983
+ learn=self.learn,
984
+ url=self.url,
985
+ vendor=self.vendor,
986
+ connect_timeout=self.connect_timeout,
987
+ answer_timeout=self.answer_timeout,
988
+ user=self.user,
989
+ report=self.report,
990
+ match_policy=self.match_policy,
991
+ speculation_timeout=self.speculation_timeout,
992
+ )
993
+ ]
994
+
995
+ @property
996
+ def bell(self) -> RabelBellUserTurnStopStrategy:
997
+ """Bell's stop strategy in this bundle."""
998
+ return self.stop[0]
999
+
1000
+
1001
+ class _Refused(Exception):
1002
+ def __init__(self, message: dict):
1003
+ super().__init__(message.get("status"))
1004
+ self.message = message
1005
+
1006
+
1007
+ class _WrongData(Exception):
1008
+ pass
1009
+
1010
+
1011
+ def _backoff(attempt: int) -> float:
1012
+ return _BACKOFF[min(attempt, len(_BACKOFF) - 1)]
1013
+
1014
+
1015
+ def _parse(raw: Any) -> Any:
1016
+ try:
1017
+ return json.loads(raw)
1018
+ except (TypeError, ValueError):
1019
+ return None
1020
+
1021
+
1022
+ def _short(m: Any) -> str:
1023
+ s = repr(m)
1024
+ return s if len(s) <= 80 else s[:77] + "..."
1025
+
1026
+
1027
+ def _ms(seconds: float) -> int:
1028
+ """A head start in whole ms, from 0 to the contract's limit."""
1029
+ return max(0, min(round(seconds * 1000), _MAX_HEAD_START_MS))
@@ -0,0 +1,205 @@
1
+ Metadata-Version: 2.5
2
+ Name: pipecat-rabel
3
+ Version: 0.3.0
4
+ Summary: Pipecat user turn strategy for Rabel Bell: an early start for your agent's reply, beside Deepgram Flux's eager end of turn
5
+ Project-URL: Homepage, https://rabellabs.com
6
+ Project-URL: Source, https://github.com/rabellabs/pipecat-rabel
7
+ Project-URL: Issues, https://github.com/rabellabs/pipecat-rabel/issues
8
+ Project-URL: Documentation, https://rabellabs.com/docs
9
+ Author: Rabel Labs
10
+ License-Expression: BSD-2-Clause
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: pipecat-ai<2,>=1.16.0
25
+ Requires-Dist: websockets>=15
26
+ Provides-Extra: example
27
+ Requires-Dist: pipecat-ai[anthropic,deepgram,runner,webrtc]<2,>=1.16.0; extra == 'example'
28
+ Provides-Extra: test
29
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
30
+ Requires-Dist: pytest>=8; extra == 'test'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # Bell for Pipecat
34
+
35
+ Starts your [Pipecat](https://github.com/pipecat-ai/pipecat) voice agent's reply on Bell's guess at the caller's words,
36
+ before the caller finishes.
37
+
38
+ Bell is a hosted model from Rabel Labs that learns each of your agents' callers from that agent's own calls. It is in
39
+ beta. It works best on agents whose callers come for the same few things, like a bank's phone line or a booking desk.
40
+ Where callers talk freely, Bell has little to guess and mostly stays quiet, and the call runs as it would without it.
41
+
42
+ As your speech-to-text hears a turn, Bell may guess the whole turn.
43
+ `RabelBellUserTurnStopStrategy`, a user turn stop strategy, starts Pipecat's early reply on that guess. At the end of the
44
+ turn Pipecat keeps the reply only if the final words match the guess; otherwise it discards the reply unheard and answers
45
+ the final words. The package adds nothing to your pipeline, sends no frame and replaces no service.
46
+
47
+ Bell runs on Rabel's servers: there is nothing to host and no GPU. The API's docs:
48
+ [rabellabs.com/docs](https://rabellabs.com/docs). Tested with Pipecat 1.16.0. The numbers here come from recorded,
49
+ scripted calls to one bank, in English, on Deepgram Flux's words; the rest is under [Limits](#limits).
50
+
51
+ **What Rabel keeps.** Bell never receives audio. It takes nothing but the words from your
52
+ speech-to-text and holds a call's words only while that call is open. When the call closes, Bell learns from them for
53
+ your agent and drops them. What it learns stays with your agent and is never filed under a call or under a caller's name
54
+ or number. Part of it is kept as codes that Rabel holds the key to, and the rest is short phrases kept in words. A phrase
55
+ can be a name or a number your callers say. You can list your agent's phrases at any time and delete any of them.
56
+ Deleting an agent erases what Bell learned for it. Rabel's notice says it in full:
57
+ [rabellabs.com/api-privacy](https://rabellabs.com/api-privacy).
58
+
59
+ This is a community integration, built and maintained by Rabel Labs, which runs Bell. Rabel Labs is not affiliated with,
60
+ endorsed by or sponsored by LiveKit, Pipecat (Daily) or Deepgram; they are named only to say what the package works with.
61
+
62
+ ## Installation
63
+
64
+ ```bash
65
+ uv add pipecat-rabel
66
+ ```
67
+
68
+ It needs Pipecat 1.16.0 or later (below 2) and Python 3.11 or later, and a Rabel API key in `RABEL_API_KEY`
69
+ ([sign up](https://rabellabs.com/signup); the first 10,000 minutes are free).
70
+
71
+ ## Usage with a Pipecat pipeline
72
+
73
+ Give Bell's turn strategies to your user aggregator. Nothing goes in the pipeline.
74
+
75
+ ```python
76
+ import os
77
+
78
+ from pipecat.pipeline.pipeline import Pipeline
79
+ from pipecat.processors.aggregators.llm_context import LLMContext
80
+ from pipecat.processors.aggregators.llm_response_universal import (
81
+ LLMContextAggregatorPair,
82
+ LLMUserAggregatorParams,
83
+ )
84
+ from pipecat.services.deepgram.flux.stt import DeepgramFluxSTTService
85
+
86
+ from pipecat_rabel import RabelBellUserTurnStrategies
87
+
88
+ stt = DeepgramFluxSTTService(api_key=os.getenv("DEEPGRAM_API_KEY"), enable_eager_end_of_turn=True)
89
+
90
+ context = LLMContext()
91
+ user_aggregator, assistant_aggregator = LLMContextAggregatorPair(
92
+ context,
93
+ user_params=LLMUserAggregatorParams(
94
+ user_turn_strategies=RabelBellUserTurnStrategies(agent="demo-bank"),
95
+ ),
96
+ )
97
+
98
+ # transport, llm and tts are your own; the pipeline is Pipecat's usual one
99
+ pipeline = Pipeline(
100
+ [transport.input(), stt, user_aggregator, llm, tts, transport.output(), assistant_aggregator]
101
+ )
102
+ ```
103
+
104
+ `RabelBellUserTurnStrategies` is built on Pipecat's `ExternalUserTurnStrategies`, as `EagerUserTurnStrategies` is,
105
+ with Bell's stop strategy, a subclass of `EagerUserTurnStopStrategy`. It uses Pipecat's documented door for answering
106
+ early: a custom stop strategy that calls `start_user_turn_speculation()`, `cancel_user_turn_speculation()` and
107
+ `report_user_turn_stopped()`. With Flux's eager end of turn on, as above, Pipecat answers early on Flux's ends of turn
108
+ and on Bell's guesses; with it off, on Bell's guesses alone.
109
+
110
+ The bundle replaces the turn strategies Flux recommends. If you set Flux's `should_interrupt=False`, pass
111
+ `RabelBellUserTurnStrategies(enable_interruptions=False)`.
112
+
113
+ `demo-bank` is a demonstration agent already trained on a bank's callers, so it guesses from the first call. Use your
114
+ own agent's name once it takes calls. A new name sends no guess until Bell has learned enough of its calls. The
115
+ conversation always holds the speech-to-text's final words, never the guess.
116
+
117
+ ## Running the example
118
+
119
+ [`examples/bank_call.py`](https://github.com/rabellabs/pipecat-rabel/blob/main/examples/bank_call.py) is a bank's phone agent: Deepgram Flux, Bell, Claude Haiku 5.5 and
120
+ Deepgram Aura-2, talking to you in the browser.
121
+
122
+ ```bash
123
+ uv add "pipecat-rabel[example]"
124
+ export RABEL_API_KEY=... DEEPGRAM_API_KEY=... ANTHROPIC_API_KEY=...
125
+ python examples/bank_call.py # then open http://localhost:7860 and talk
126
+ ```
127
+
128
+ Say "I need to reset my password". Each turn logs Bell's guess, whether it was right, and how long before the final
129
+ words the reply on it started. Its calls are from the Gridspace-Stanford Harper Valley dataset of simulated
130
+ bank calls (CC BY 4.0).
131
+
132
+ ## Settings
133
+
134
+ The bundle and the strategy take the same settings. The strategy is `strategies.bell`.
135
+
136
+ | Setting | Default | What it does |
137
+ |---|---|---|
138
+ | `api_key` | `RABEL_API_KEY` | Without a key Bell stays off, the strategy is Pipecat's eager one, and one line is logged. |
139
+ | `agent` | `"default"` | The agent Bell learns for: 1 to 64 lower-case letters, digits, `-` and `_`. Calls that share an agent name share what Bell learns. Give each voice agent you run its own name, such as `front-desk` or `billing`, and keep all of that agent's calls under it. |
140
+ | `min_chance` | `0.7` | How sure Bell must be before it guesses, 0.67 to 0.99. Higher means fewer guesses and fewer wrong ones. |
141
+ | `learn` | `True` | `False` means this call teaches Bell nothing. |
142
+ | `report` | `True` | Tells the API at each turn's end whether the guess was kept or dropped, with no words, so the agent's status can show it. |
143
+ | `user` | `None` | An id you choose for the person on the call. Bell does not use it yet. Never a name, a number or an address. |
144
+ | `vendor` | `None` | Your speech-to-text, for example `"deepgram/flux-general-en"`, for usage reports. |
145
+ | `connect_timeout` | `2.0` | Seconds allowed to open a conversation with the API. |
146
+ | `answer_timeout` | `0.5` | Seconds after the words it answers within which a guess is still used. |
147
+ | `match_policy` | `NormalizedMatch()` | Pipecat's check of an early reply's words against the final words. |
148
+ | `speculation_timeout` | `5.0` | Seconds an early reply may go unresolved before it is withdrawn. |
149
+ | `url` | `RABEL_API_URL`, then Rabel's API | The API's address. |
150
+
151
+ Events on the strategy: `on_ready(strategy, ready)`, `on_guess(strategy, text, chance)` and
152
+ `on_turn_end(strategy, final, guess, right)`. `strategy.stats` counts turns, guesses received, started, dropped and right,
153
+ and failures by kind.
154
+
155
+ ## What was measured
156
+
157
+ On recorded, scripted calls to one bank (Harper Valley), in English, on Deepgram Flux's words. Bell learned from 1,070
158
+ calls by 27 callers and was measured on 376 calls by 28 callers it had never heard (95% intervals, by whole calls).
159
+
160
+ - On Pipecat 1.16.0 with Flux deciding the end of the turn, Bell started the reply 170 ms a turn sooner [159, 182] than
161
+ with no early start, at 0.07 more LLM calls a turn. That is when the LLM starts. Pipecat holds an early reply until the
162
+ turn ends, so the caller hears less of it: in one reading with Claude Haiku 5.5 and Deepgram Aura-2, the first audio came
163
+ 133 ms a turn sooner [125, 142]. The package ran as `RabelBellUserTurnStrategies` on the user aggregator, with Flux's
164
+ eager end of turn off and no local VAD.
165
+ - Under LiveKit's default (its own turn detector with preemptive generation, on LiveKit Agents 1.8.13 on our own
166
+ machines), Bell started the reply 118 ms a turn sooner [108, 128], at 0.11 more LLM calls a turn. In one reading the
167
+ first audio came 115 ms a turn sooner [105, 125].
168
+
169
+ The method, the other rows, the script and its data are in [Rabel's benchmark](https://github.com/rabellabs/bell-benchmark).
170
+
171
+ ## Limits
172
+
173
+ - **The numbers come from one kind of call:** scripted calls to one bank, in English, on Flux's words. On freer speech we
174
+ have only looked informally, and Bell mostly stayed quiet. No live deployment's callers and no other language have been
175
+ measured.
176
+ - **A wrong guess costs one LLM call** and nothing the caller hears, when these turn strategies end the turn. If your app,
177
+ or a turn processor ahead of the aggregator such as `UserTurnProcessor`, pushes `UserStoppedSpeakingFrame` itself,
178
+ Pipecat releases the early reply before the words are checked and the caller can hear both replies.
179
+ - **It takes the place of Smart Turn.** Like Pipecat's eager strategies, it leaves the end of the turn to the
180
+ speech-to-text, so the speech-to-text must end turns and send interim transcriptions, as Flux does.
181
+ - **A local VAD can withdraw an early start** when the caller pauses and speaks again. That start costs one LLM call and
182
+ gains nothing; the reply starts early again when the words reach Bell's guess or Flux's eager end of turn comes.
183
+ - **A reply started on a guess never runs a tool call.** Pipecat withdraws it and the reply to the final words runs it.
184
+ - **It fails open.** While the API is unreachable, slow, refusing or sending what the strategy cannot read, Bell starts no
185
+ early reply, the turn goes exactly as with Pipecat's eager strategy, and one line is logged for each kind of failure.
186
+ The pipeline never waits for the API. After a busy, slow or unreachable API it tries again on its own; after a refused
187
+ key, no minutes left or an unknown agent, Bell stays off for the rest of the call.
188
+ - **The stats and the turn's report count a refused guess differently.** A guess the strategy refuses as unreadable,
189
+ under `min_chance`, late or for other words counts as dropped in `strategy.stats` and shows as "none" in the turn's
190
+ report.
191
+
192
+ ## Tests
193
+
194
+ ```bash
195
+ uv run --extra test pytest
196
+ ```
197
+
198
+ 112 tests, with no key and no network, against a local stand-in for the API, with the strategy in Pipecat's own user
199
+ aggregator. A [workflow](https://github.com/rabellabs/pipecat-rabel/blob/main/.github/workflows/nightly.yml) also runs them every night against Pipecat's main branch.
200
+
201
+ Tested with Pipecat 1.16.0 on Python 3.11, 3.12 and 3.13.
202
+
203
+ ## License
204
+
205
+ BSD 2-Clause. See [LICENSE](https://github.com/rabellabs/pipecat-rabel/blob/main/LICENSE).
@@ -0,0 +1,6 @@
1
+ pipecat_rabel/__init__.py,sha256=Laasd-in8O778k0PNzLI5ztYaCBwSjCY6MkcftaISW4,523
2
+ pipecat_rabel/strategy.py,sha256=vWKIBTt_cLP3hOmi9Tm9i85BrU5F14_mPiwjTPreU-Y,50873
3
+ pipecat_rabel-0.3.0.dist-info/METADATA,sha256=4nUilMeegC4dTXMnPpKrpx7L8p94sKgDYoJoizapMMk,11978
4
+ pipecat_rabel-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ pipecat_rabel-0.3.0.dist-info/licenses/LICENSE,sha256=SFc8TC4-FjFjuWK0lnYdxzcMrXUJv2EwOz43vzHq-QY,1304
6
+ pipecat_rabel-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,24 @@
1
+ BSD 2-Clause License
2
+
3
+ Copyright (c) 2026, Rabel Labs Inc.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.