Files
livekit-agents/python/tests/test_plugin_elevenlabs_stt.py
T

690 lines
25 KiB
Python

"""Unit tests for ElevenLabs STT plugin configuration."""
from __future__ import annotations
import asyncio
import base64
import dataclasses
import json
import time
from collections.abc import Callable
from types import SimpleNamespace
from typing import Any, cast
import pytest
from aiohttp import web
from aiohttp.test_utils import TestServer
from yarl import URL
from livekit import rtc
from livekit.agents import DEFAULT_API_CONNECT_OPTIONS, APIStatusError, LanguageCode, http, stt
from livekit.agents.types import NOT_GIVEN
from livekit.plugins.elevenlabs import stt as elevenlabs_stt
from tests.utils.attempts import observed_attempts
pytestmark = pytest.mark.plugin("elevenlabs")
class _EventSink:
def __init__(self) -> None:
self.events: list[stt.SpeechEvent] = []
def send_nowait(self, event: stt.SpeechEvent) -> None:
self.events.append(event)
def _new_stream(
*,
server_vad=NOT_GIVEN,
language: str | None = "en",
include_timestamps: bool = False,
include_language_detection=NOT_GIVEN,
secondary_languages: list[str] | Any = NOT_GIVEN,
) -> elevenlabs_stt.SpeechStream:
# mirrors what STT.__init__ stores: both language options are normalized on the way in
opts = elevenlabs_stt.STTOptions(
model_id="scribe_v2_realtime",
api_key="test-key",
base_url=elevenlabs_stt.API_BASE_URL_V1,
language_code=None,
secondary_languages=[LanguageCode(code) for code in secondary_languages]
if secondary_languages is not NOT_GIVEN
else NOT_GIVEN,
include_language_detection=include_language_detection,
tag_audio_events=True,
include_timestamps=include_timestamps,
sample_rate=16000,
server_vad=server_vad,
keyterms=NOT_GIVEN,
no_verbatim=False,
enable_logging=True,
previous_text=None,
)
# These parser tests do not run the stream lifecycle or own tasks. Initialize its provider
# state and retry counter without replacing the scheduler; the attempt loop reads the running
# loop's clock, so every caller is an async test.
stream = object.__new__(elevenlabs_stt.SpeechStream)
stream._stt = elevenlabs_stt.STT(api_key="test-key", model="scribe_v2_realtime")
stream._opts = opts
stream._conn_options = DEFAULT_API_CONNECT_OPTIONS
stream._language = LanguageCode(language) if language else None
stream._speaking = False
stream._last_partial_text = ""
stream._start_time_offset = 0.0
stream._core_attempts = observed_attempts("stt_stream", DEFAULT_API_CONNECT_OPTIONS)
stream._event_ch = _EventSink()
return stream
def _committed_transcript(
text: str,
*,
with_timestamps: bool = False,
language_code: str | None = None,
) -> dict:
message: dict = {
"message_type": "committed_transcript_with_timestamps"
if with_timestamps
else "committed_transcript",
"text": text,
"words": [
{"text": text, "start": 0.1, "end": 0.4},
]
if text
else [],
}
# the server only carries the detected language on the delayed copy, and only when
# language detection is enabled
if language_code is not None:
message["language_code"] = language_code
return message
def _partial_transcript(text: str) -> dict:
return {"message_type": "partial_transcript", "text": text, "words": []}
def _interim_texts(stream: elevenlabs_stt.SpeechStream) -> list[str]:
return [
event.alternatives[0].text
for event in stream._event_ch.events
if event.type == stt.SpeechEventType.INTERIM_TRANSCRIPT
]
async def test_advancing_partial_transcripts_are_forwarded() -> None:
stream = _new_stream(server_vad={"vad_silence_threshold_secs": 0.5})
stream._process_stream_event(_partial_transcript("yeah"))
stream._process_stream_event(_partial_transcript("yeah please"))
assert _interim_texts(stream) == ["yeah", "yeah please"]
async def test_re_sent_partial_transcript_is_dropped() -> None:
stream = _new_stream(server_vad={"vad_silence_threshold_secs": 0.5})
for _ in range(5):
stream._process_stream_event(_partial_transcript("yeah please"))
assert _interim_texts(stream) == ["yeah please"]
assert [event.type for event in stream._event_ch.events] == [
stt.SpeechEventType.START_OF_SPEECH,
stt.SpeechEventType.INTERIM_TRANSCRIPT,
]
async def test_the_same_words_after_a_commit_are_forwarded_again() -> None:
stream = _new_stream(server_vad={"vad_silence_threshold_secs": 0.5})
stream._process_stream_event(_partial_transcript("right"))
stream._process_stream_event(_committed_transcript("right"))
stream._process_stream_event(_partial_transcript("right"))
assert _interim_texts(stream) == ["right", "right"]
async def test_the_same_words_after_an_empty_commit_are_forwarded_again() -> None:
stream = _new_stream(server_vad=None)
stream._process_stream_event(_partial_transcript("right"))
stream._process_stream_event(_committed_transcript(""))
stream._process_stream_event(_partial_transcript("right"))
assert _interim_texts(stream) == ["right", "right"]
async def test_server_vad_commit_emits_end_of_speech() -> None:
stream = _new_stream(server_vad={"vad_silence_threshold_secs": 0.5})
stream._process_stream_event(_committed_transcript("hello"))
assert [event.type for event in stream._event_ch.events] == [
stt.SpeechEventType.START_OF_SPEECH,
stt.SpeechEventType.FINAL_TRANSCRIPT,
stt.SpeechEventType.END_OF_SPEECH,
]
assert stream._event_ch.events[1].alternatives[0].text == "hello"
assert stream._speaking is False
async def test_manual_commit_still_waits_for_empty_commit() -> None:
stream = _new_stream(server_vad=None)
stream._process_stream_event(_committed_transcript("hello"))
assert [event.type for event in stream._event_ch.events] == [
stt.SpeechEventType.START_OF_SPEECH,
stt.SpeechEventType.FINAL_TRANSCRIPT,
]
assert stream._speaking is True
stream._process_stream_event(_committed_transcript(""))
assert stream._event_ch.events[-1].type == stt.SpeechEventType.END_OF_SPEECH
assert stream._speaking is False
def _stt(**kwargs: object) -> elevenlabs_stt.STT:
return elevenlabs_stt.STT(api_key="test-key", model="scribe_v2_realtime", **kwargs)
def test_update_options_forwards_no_verbatim_to_active_streams() -> None:
# no_verbatim is a WebSocket query param applied at connect time, so a live
# realtime stream must be told to reconnect. Verify STT.update_options
# forwards it to active streams (which trigger a reconnect).
instance = _stt()
captured: dict[str, object] = {}
class _FakeStream:
def update_options(self, **kwargs: object) -> None:
captured.update(kwargs)
fake = _FakeStream()
instance._streams.add(fake)
instance.update_options(no_verbatim=True)
assert captured.get("no_verbatim") is True
def test_previous_text_is_ignored_for_non_realtime_model(caplog: pytest.LogCaptureFixture) -> None:
with caplog.at_level("WARNING"):
instance = elevenlabs_stt.STT(
api_key="test-key",
model="scribe_v2",
previous_text="prior context",
)
assert instance._opts.previous_text is None
assert any("previous_text" in record.message for record in caplog.records)
@pytest.mark.parametrize(("enable_logging", "expected"), [(True, "true"), (False, "false")])
async def test_connect_ws_includes_enable_logging(enable_logging: bool, expected: str) -> None:
# enable_logging is a WebSocket query param. Verify it is forwarded to the
# realtime connect URL with the expected lowercase boolean string.
stream = _new_stream()
stream._opts.enable_logging = enable_logging
url = await _connect_ws_url(stream)
assert f"enable_logging={expected}" in url
async def _connect_ws_url(stream: elevenlabs_stt.SpeechStream) -> str:
"""Capture the URL from a real local WebSocket handshake."""
captured: list[str] = []
async def connect(request: web.Request) -> web.WebSocketResponse:
captured.append(request.raw_path)
socket = web.WebSocketResponse()
await socket.prepare(request)
async for _ in socket:
pass
return socket
app = web.Application()
app.router.add_get("/{path:.*}", connect)
async with TestServer(app) as server, http.open() as session:
stream._opts.base_url = str(server.make_url("/")).rstrip("/")
stream._session = session
socket = await stream._connect_ws()
await socket.close()
return captured[0]
async def test_connect_ws_includes_keyterms() -> None:
# keyterms bias the realtime model and are sent as repeated query params on
# the connect URL.
stream = _new_stream()
stream._opts.keyterms = ["nginx", "Grafana Loki", "Ærø"]
url = await _connect_ws_url(stream)
assert "keyterms=nginx" in url
assert "keyterms=Grafana%20Loki" in url
assert "keyterms=%C3%86r%C3%B8" in url
async def test_connect_ws_escapes_query_delimiters_in_keyterms() -> None:
# Keyterms are free-form text. Unescaped, "&" would split the term and inject
# a bogus query param and "#" would truncate it, so both must be encoded and
# must survive a round trip through the URL parser the transport uses.
stream = _new_stream()
stream._opts.keyterms = ["Smith & Sons", "C#"]
url = await _connect_ws_url(stream)
assert "keyterms=Smith%20%26%20Sons" in url
assert "keyterms=C%23" in url
assert URL(url).query.getall("keyterms") == ["Smith & Sons", "C#"]
async def test_stream_update_options_sets_keyterms_and_requests_reconnect() -> None:
stream = _new_stream()
stream._reconnect_event = asyncio.Event()
stream.update_options(keyterms=["nginx"])
assert stream._opts.keyterms == ["nginx"]
assert stream._reconnect_event.is_set()
async def test_connect_ws_normalizes_the_primary_language() -> None:
# LanguageCode keeps the region ("en-US") but the realtime API rejects it, so the primary
# language goes on the wire through the same normalization the secondary ones get
stream = _new_stream(language="en_US", secondary_languages=["ru-RU"])
url = await _connect_ws_url(stream)
assert URL(url).query.getall("language_code") == ["en"]
assert URL(url).query.getall("secondary_languages") == ["ru"]
async def test_connect_ws_normalizes_secondary_languages() -> None:
# the realtime API takes ISO-639-1/3 and rejects anything else, including the region-tagged
# tags LanguageCode produces, so names and regions are mapped before the connect URL
stream = _new_stream(language="en", secondary_languages=["ru_RU", "french", "spa"])
url = await _connect_ws_url(stream)
assert URL(url).query.getall("secondary_languages") == ["ru", "fr", "es"]
def test_secondary_languages_ignored_for_batch_model(caplog: pytest.LogCaptureFixture) -> None:
with caplog.at_level("WARNING"):
instance = elevenlabs_stt.STT(
api_key="test-key", model="scribe_v2", secondary_languages=["ru"]
)
assert instance._opts.secondary_languages is NOT_GIVEN
assert "only supported for Scribe v2 realtime" in caplog.text
async def test_connect_ws_requests_language_detection_when_no_language_is_pinned() -> None:
url = await _connect_ws_url(_new_stream(language=None))
assert "include_language_detection=true" in url
async def test_connect_ws_omits_language_detection_when_language_is_pinned() -> None:
url = await _connect_ws_url(_new_stream(language="en"))
assert "include_language_detection" not in url
async def test_connect_ws_requests_language_detection_when_explicitly_enabled() -> None:
stream = _new_stream(language="en", include_language_detection=True)
url = await _connect_ws_url(stream)
assert "include_language_detection=true" in url
async def test_connect_ws_omits_language_detection_when_explicitly_disabled() -> None:
url = await _connect_ws_url(_new_stream(language=None, include_language_detection=False))
assert "include_language_detection" not in url
async def test_final_transcript_reports_the_detected_language() -> None:
# with detection on, the detected language only reaches the delayed copy of the
# commit, so that copy has to be the final one or every transcript is labelled
# with the pinned language (or "en" when nothing is pinned).
stream = _new_stream(
server_vad={"vad_silence_threshold_secs": 0.5},
language="en",
include_language_detection=True,
secondary_languages=["ru"],
)
stream._process_stream_event(_committed_transcript("привет"))
stream._process_stream_event(
_committed_transcript("привет", with_timestamps=True, language_code="ru")
)
finals = [
event
for event in stream._event_ch.events
if event.type is stt.SpeechEventType.FINAL_TRANSCRIPT
]
assert len(finals) == 1
assert finals[0].alternatives[0].language == "ru"
async def test_autodetected_language_reaches_the_final_transcript() -> None:
# without a pinned language the plugin asks the server to detect one; that language
# only rides on the delayed copy, so dropping it labelled every transcript "en"
stream = _new_stream(server_vad={"vad_silence_threshold_secs": 0.5}, language=None)
stream._process_stream_event(
_committed_transcript("привет", with_timestamps=True, language_code="ru")
)
stream._process_stream_event(_committed_transcript("привет"))
finals = [
event
for event in stream._event_ch.events
if event.type is stt.SpeechEventType.FINAL_TRANSCRIPT
]
assert len(finals) == 1
assert finals[0].alternatives[0].language == "ru"
# reading the timestamped copy must not start handing out word timings the caller
# never asked for
assert finals[0].alternatives[0].words is None
async def test_final_transcript_keeps_the_plain_copy_without_detection() -> None:
stream = _new_stream(server_vad={"vad_silence_threshold_secs": 0.5}, language="es")
stream._process_stream_event(_committed_transcript("hola"))
stream._process_stream_event(_committed_transcript("hola", with_timestamps=True))
finals = [
event
for event in stream._event_ch.events
if event.type is stt.SpeechEventType.FINAL_TRANSCRIPT
]
assert len(finals) == 1
assert finals[0].alternatives[0].language == "es"
@pytest.mark.parametrize(
"message_type",
["partial_transcript", "committed_transcript", "committed_transcript_with_timestamps"],
)
@pytest.mark.parametrize(
("language", "language_data", "expected_language"),
[
("es", {}, "es"),
("es", {"language_code": None}, "es"),
("es", {"language_code": ""}, "es"),
("es", {"language_code": "fra"}, "fr"),
(None, {}, "en"),
(None, {"language_code": None}, "en"),
(None, {"language_code": ""}, "en"),
(None, {"language_code": "fra"}, "fr"),
],
)
async def test_transcript_language_falls_back_to_configured_language(
message_type: str,
language: str | None,
language_data: dict[str, str | None],
expected_language: str,
) -> None:
stream = _new_stream(
language=language,
include_timestamps=message_type == "committed_transcript_with_timestamps",
include_language_detection=False,
)
stream._process_stream_event({"message_type": message_type, "text": "hola", **language_data})
transcript = stream._event_ch.events[-1]
assert transcript.type == (
stt.SpeechEventType.INTERIM_TRANSCRIPT
if message_type == "partial_transcript"
else stt.SpeechEventType.FINAL_TRANSCRIPT
)
assert transcript.alternatives[0].language == expected_language
class _FakeWS:
"""Records outgoing messages. receive() parks so recv_task stays alive."""
def __init__(self) -> None:
self.sent: list[dict] = []
self._closed = asyncio.Event()
async def send_str(self, data: str) -> None:
self.sent.append(json.loads(data))
async def receive(self) -> Any:
await self._closed.wait()
raise AssertionError("the test should never let recv_task resume")
async def close(self) -> None:
self._closed.set()
def _live_stream(ws: _FakeWS, **kwargs: Any) -> elevenlabs_stt.SpeechStream:
"""A real SpeechStream running its real _run loop against a fake socket."""
instance = elevenlabs_stt.STT(api_key="test-key", model="scribe_v2_realtime", **kwargs)
opts = dataclasses.replace(instance._opts)
stream = elevenlabs_stt.SpeechStream(
stt=instance,
opts=opts,
conn_options=DEFAULT_API_CONNECT_OPTIONS,
language=None,
http_session=cast(Any, SimpleNamespace(closed=False)),
)
async def _fake_connect() -> Any:
return ws
# patched before the _run task gets its first tick, so no real socket is opened
stream._connect_ws = _fake_connect # type: ignore[method-assign]
return stream
def _frame(ms: int, sample_rate: int = 16000) -> rtc.AudioFrame:
samples = sample_rate * ms // 1000
return rtc.AudioFrame(
data=b"\x00\x00" * samples,
sample_rate=sample_rate,
num_channels=1,
samples_per_channel=samples,
)
async def _wait_until(predicate: Callable[[], bool], *, timeout: float = 5.0) -> None:
deadline = time.monotonic() + timeout
while not predicate():
assert time.monotonic() < deadline, "timed out waiting for the stream to send"
await asyncio.sleep(0.01)
async def test_flush_commits_the_turn_when_no_audio_is_left_to_send() -> None:
# 50ms is exactly one repack chunk, so AudioByteStream.flush() returns no frames.
# The commit must still go out: Scribe v2 does not finalize a turn without one, and
# gating it on the per-frame loop dropped it here (roughly 1 flush in 5).
ws = _FakeWS()
stream = _live_stream(ws)
try:
stream.push_frame(_frame(50))
await _wait_until(lambda: len(ws.sent) == 1)
stream.flush()
await _wait_until(lambda: len(ws.sent) == 2)
assert [msg["commit"] for msg in ws.sent] == [False, True]
assert ws.sent[-1]["audio_base_64"] == ""
finally:
await stream.aclose()
async def test_flush_commits_after_the_buffered_audio() -> None:
# a partial chunk is still pending: it has to reach the server before the commit,
# otherwise the tail of the turn is transcribed against the next one
ws = _FakeWS()
stream = _live_stream(ws)
try:
stream.push_frame(_frame(30))
stream.flush()
await _wait_until(lambda: len(ws.sent) == 2)
assert [msg["commit"] for msg in ws.sent] == [False, True]
assert ws.sent[0]["audio_base_64"] != ""
finally:
await stream.aclose()
def test_speech_confidence_from_word_logprobs() -> None:
# confident transcription: word logprobs near 0 -> confidence near 1 (spacing tokens ignored)
words = [
{"type": "word", "logprob": -0.01},
{"type": "spacing", "logprob": -2.0},
{"type": "word", "logprob": -0.05},
]
assert 0.9 < elevenlabs_stt._speech_confidence(words) <= 1.0
def test_speech_confidence_flags_low_quality_transcription() -> None:
# uncertain transcription (very negative logprobs) -> low confidence
words = [{"type": "word", "logprob": -2.5}, {"type": "word", "logprob": -3.0}]
assert elevenlabs_stt._speech_confidence(words) < 0.2
def test_speech_confidence_defaults_to_zero_without_logprobs() -> None:
# no words, or words without logprobs (e.g. non-timestamped commit) -> default 0.0
assert elevenlabs_stt._speech_confidence(None) == 0.0
assert elevenlabs_stt._speech_confidence([{"text": "hi", "start": 0.1, "end": 0.4}]) == 0.0
async def test_committed_transcript_sets_confidence() -> None:
stream = _new_stream(server_vad={"vad_silence_threshold_secs": 0.5})
stream._process_stream_event(
{
"message_type": "committed_transcript",
"text": "hello",
"words": [
{"text": "hello", "start": 0.1, "end": 0.4, "type": "word", "logprob": -0.02}
],
}
)
final = stream._event_ch.events[1]
assert final.type == stt.SpeechEventType.FINAL_TRANSCRIPT
assert final.alternatives[0].confidence > 0.9
@pytest.mark.parametrize("duration", [0, -1, 0.5, 100.0, True, False, None, "100"])
def test_invalid_audio_chunk_duration_is_rejected(duration: Any) -> None:
with pytest.raises(ValueError, match="audio_chunk_duration_ms must be a positive integer"):
_stt(audio_chunk_duration_ms=duration)
@pytest.mark.parametrize("sample_rate", [8000, 16000, 48000])
@pytest.mark.parametrize("duration", [1, 50, 75, 100, 200])
@pytest.mark.parametrize("tail_ms", [0, 1])
async def test_configured_audio_chunks_preserve_audio_and_commit(
sample_rate: int, duration: int, tail_ms: int
) -> None:
ws = _FakeWS()
stream = _live_stream(ws, sample_rate=sample_rate, audio_chunk_duration_ms=duration)
# Distinct PCM bytes reveal drops, duplication and reordering across input frames.
total_samples = sample_rate * (duration * 2 + tail_ms) // 1000
audio = bytes(i % 251 for i in range(total_samples * 2))
input_frame_bytes = sample_rate * 20 // 1000 * 2
chunk_bytes = sample_rate * duration // 1000 * 2
expected_chunks = [audio[i : i + chunk_bytes] for i in range(0, len(audio), chunk_bytes)]
try:
for offset in range(0, len(audio), input_frame_bytes):
data = audio[offset : offset + input_frame_bytes]
stream.push_frame(
rtc.AudioFrame(
data=data,
sample_rate=sample_rate,
num_channels=1,
samples_per_channel=len(data) // 2,
)
)
# Complete chunks must be released before the caller flushes.
await _wait_until(lambda: len(ws.sent) >= len(audio) // chunk_bytes)
stream.flush()
await _wait_until(lambda: len(ws.sent) >= len(expected_chunks) + 1)
assert [base64.b64decode(msg["audio_base_64"]) for msg in ws.sent[:-1]] == expected_chunks
assert [msg["commit"] for msg in ws.sent] == [False] * len(expected_chunks) + [True]
assert all(msg["sample_rate"] == sample_rate for msg in ws.sent)
assert ws.sent[-1]["audio_base_64"] == ""
finally:
await stream.aclose()
_INVALID_KEY = {"detail": {"code": "invalid_api_key", "message": "Invalid API key"}}
@pytest.mark.parametrize(
("body", "message", "parsed"),
[
(json.dumps(_INVALID_KEY), "Invalid API key", _INVALID_KEY),
("", "Unknown ElevenLabs error", ""),
("{not json", "{not json", "{not json"),
],
)
async def test_recognize_does_not_retry_a_client_error(
body: str, message: str, parsed: Any
) -> None:
requests = 0
async def handler(request: web.Request) -> web.Response:
nonlocal requests
requests += 1
return web.Response(status=401, text=body, content_type="application/json")
app = web.Application()
app.router.add_post("/speech-to-text", handler)
async with TestServer(app) as server, http.open() as session:
url = str(server.make_url(""))
batch_stt = elevenlabs_stt.STT(api_key="bad-key", base_url=url, http_session=session)
with pytest.raises(APIStatusError) as exc_info:
await batch_stt.recognize([_frame(100)])
assert exc_info.value.status_code == 401
assert exc_info.value.message == message
assert exc_info.value.body == parsed
assert requests == 1
async def test_batch_recognition_rejects_nontext_transcript() -> None:
from aiohttp import web
from aiohttp.test_utils import TestServer
from pydantic import ValidationError
from livekit import rtc
from livekit.agents import APIConnectionError, APIConnectOptions
from livekit.plugins import elevenlabs
async def recognize(request: web.Request) -> web.Response:
await request.read()
return web.json_response({"text": 42, "language_code": "en", "words": []})
app = web.Application()
app.router.add_post("/{path:.*}", recognize)
async with TestServer(app) as server, http.open() as session:
model = elevenlabs.STT(
api_key="test", base_url=str(server.make_url("/")), http_session=session
)
try:
frame = rtc.AudioFrame.create(
sample_rate=16000, num_channels=1, samples_per_channel=160
)
with pytest.raises(APIConnectionError) as failure:
await model.recognize(frame, conn_options=APIConnectOptions(max_retry=0))
assert isinstance(failure.value.__cause__, ValidationError)
assert any(error["loc"][-1] == "text" for error in failure.value.__cause__.errors())
finally:
await model.aclose()