Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(stt): a Deepgram provider on the existing plugin contract

rubenluetke10-beep26654442afe5
diff --git a/docs/deepgram-stt-research-2026-05-20.md b/docs/deepgram-stt-research-2026-05-20.md
index bd4705088b..1beb01c774 100644
--- a/docs/deepgram-stt-research-2026-05-20.md
+++ b/docs/deepgram-stt-research-2026-05-20.md
@@ -1,6 +1,12 @@
# Deepgram STT — Research Dossier (2026-05-20)
-**Status:** Research-only. No code written, no plugins built, no tests run.
+**Status:** Research-only when written. **Item 1 of the implementation list
+was built on 2026-08-23** — `jarvis/plugins/stt/deepgram_api.py`, batch REST
+against Nova-3, registered as the `deepgram-api` entry point and wired into the
+STT credential table and cross-family takeover order. Items 2-4 (a separate
+Nova-3 module, the Flux WebSocket plugin, and the pipeline rewiring that
+streaming would need to be worth anything) are still open, and item 4 is the
+one that gates the other two.
**Trigger:** User wants Deepgram STT brought to the same level as the Groq integration. Two explicit research questions:
1. Is Deepgram's **token / auth flow** different from Groq's simple static API key?
2. Is Deepgram **agent-friendly** — does it deliver transcript tokens *while* the user is speaking (streaming / interim), not only after the utterance finishes?
diff --git a/jarvis/brain/app_control.py b/jarvis/brain/app_control.py
index e25bfee92f..89b21918ac 100644
--- a/jarvis/brain/app_control.py
+++ b/jarvis/brain/app_control.py
@@ -92,6 +92,8 @@ AUTH_PROVIDER_ALIASES: dict[str, str] = {
"openrouter": "openrouter",
"groq": "groq",
"groq-api": "groq",
+ # Dedicated slot — Deepgram shares its key with nothing else.
+ "deepgram-api": "deepgram",
"gemini": "gemini",
"gemini-flash-tts": "gemini",
"gemini-live": "gemini-live",
diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.py
index b54bb49fb9..4a9229f673 100644
--- a/jarvis/brain/model_catalog.py
+++ b/jarvis/brain/model_catalog.py
@@ -646,7 +646,9 @@ STT_CATALOG: dict[str, list[ModelInfo]] = {
"whisper-1",
]
),
- "deepgram": _ids(["nova-3", "nova-2", "nova-2-general", "enhanced", "base"]),
+ # Keyed by the ENTRY-POINT id. It read "deepgram" while the plugin did not
+ # exist, so the picker offered models for a provider nothing could build.
+ "deepgram-api": _ids(["nova-3", "nova-2", "nova-2-general", "enhanced", "base"]),
# OpenRouter STT — the model picker offers ONLY transcription models. This
# curated snapshot mirrors the live `?output_modalities=transcription` list
# (verified 2026-07-02); audio-in chat models are excluded. The default
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index 5e9f4e3c10..ee9a683c1f 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -28,6 +28,10 @@ ENTRY_POINT_GROUP = "jarvis.stt"
# left untouched (unknown / third-party entry-points cannot be probed).
_STT_SECRET_CANDIDATES: dict[str, tuple[tuple[str, str], ...]] = {
"groq-api": (("groq_api_key", "GROQ_API_KEY"),),
+ # Deepgram is the one entry here with a DEDICATED key: nothing else reads
+ # deepgram_api_key, so its presence means someone deliberately set up
+ # speech-to-text rather than configuring a brain that happens to transcribe.
+ "deepgram-api": (("deepgram_api_key", "DEEPGRAM_API_KEY"),),
# OpenRouter STT reuses the SAME key slot as the OpenRouter brain, so a user
# who configured OpenRouter for chat gets cloud STT for free. The id is
# ``openrouter-stt`` (distinct from the ``openrouter`` brain id) to avoid a
@@ -90,6 +94,11 @@ def _stt_keyless_credential(provider_name: str) -> bool:
# a host that set Vertex up has a paid Cloud project rather than a free-tier key,
# so it is the better takeover of the two Google entries.
_STT_CROSS_FAMILY_ORDER: tuple[str, ...] = (
+ # Deepgram leads because its key is the only unambiguous one. Every other
+ # slot here is shared with a brain or a TTS tier, so finding a key there
+ # means "this person configured a provider", not "this person chose a
+ # recognizer" — deepgram_api_key can only have been set for speech input.
+ "deepgram-api",
"openrouter-stt", "openai-api", "vertex-stt", "gemini-api", "groq-api",
)
diff --git a/jarvis/plugins/stt/deepgram_api.py b/jarvis/plugins/stt/deepgram_api.py
new file mode 100644
index 0000000000..f5e1ec9b96
--- /dev/null
+++ b/jarvis/plugins/stt/deepgram_api.py
@@ -0,0 +1,405 @@
+"""Deepgram STT plugin (batch REST, Nova-3).
+
+Cloud speech-to-text through Deepgram's ``/v1/listen`` endpoint. Deepgram is a
+useful third cloud lane because its free tier is generous and its Nova-3 model
+has a dedicated German recognizer plus a multilingual variant that handles
+German/English code-switching in one stream — the two languages this app is
+used in most.
+
+Plugin contract: structurally compatible with ``jarvis.core.protocols.STTProvider``
+without importing from ``jarvis.*`` at module level. The returned object is a
+locally defined ``Transcript`` dataclass with the same field shape; consumers
+duck-type on the attributes (``text``, ``language``, ``confidence``,
+``is_partial``, ``segments``).
+
+## How this differs from the OpenAI-shaped plugins
+
+Deepgram is NOT OpenAI-compatible, and the three differences all matter:
+
+* **Auth header is ``Token``, not ``Bearer``.** A ``Bearer`` prefix is rejected
+ with 401, which reads exactly like a wrong key and sends people to rotate a
+ credential that was fine.
+* **The audio is the raw request body**, not a multipart field. The container
+ format is declared in ``Content-Type``.
+* **Options are query parameters**, not form fields, and language detection is
+ its own flag (``detect_language=true``) rather than "omit the language".
+
+## Batch, not streaming — on purpose
+
+Deepgram's real advantage is interim results over a WebSocket, and this plugin
+does not use them. Nothing in the speech pipeline consumes interim transcripts
+today: ``_handle_utterance`` hands over one complete VAD-segmented utterance
+and expects one final transcript. Shipping a streaming plugin into a batch-only
+pipeline would add a socket and deliver no lower latency. ``stream_transcribe``
+therefore yields a single final transcript, exactly like the other cloud
+plugins, and the streaming path stays a separate piece of work that has to
+change the pipeline to be worth anything.
+
+API key resolution order (same convention as every other plugin here):
+ 1. constructor argument
+ 2. ``DEEPGRAM_API_KEY`` env var
+ 3. OS credential manager via ``keyring`` (service ``personal-jarvis``,
+ username ``deepgram_api_key``) — the name the setup wizard already writes.
+
+Never accept a key from voice/chat input (AP-2).
+"""
+from __future__ import annotations
+
+import io
+import os
+import wave
+from collections.abc import AsyncIterator
+from dataclasses import dataclass, field
+from typing import Any
+
+import httpx
+
+DEFAULT_ENDPOINT = "https://api.deepgram.com/v1/listen"
+DEFAULT_MODEL = "nova-3"
+
+#: The per-call ``language`` value that REQUESTS detection instead of a pinned
+#: language. Spelled out per plugin because plugins may not import ``jarvis.*``.
+AUTO_LANGUAGE = "auto"
+
+#: Container extensions Deepgram accepts. Anything else is sent as WAV, which
+#: is what the live microphone path always produces.
+_CONTENT_TYPES: dict[str, str] = {
+ ".wav": "audio/wav",
+ ".mp3": "audio/mpeg",
+ ".mp4": "audio/mp4",
+ ".m4a": "audio/mp4",
+ ".ogg": "audio/ogg",
+ ".oga": "audio/ogg",
+ ".opus": "audio/opus",
+ ".flac": "audio/flac",
+ ".webm": "audio/webm",
+}
+
+
+def _detect_or(language: str | None, configured: str | None) -> str | None:
+ """The language for ONE call. ``None`` means "let the service detect".
+
+ Mirrors the helper in the other cloud plugins, including the case that
+ matters: an explicit ``"auto"`` must CLEAR a configured pin for this call.
+ Treating it as "no argument given" is what once let dictation's auto mode
+ inherit ``[stt].language`` and transcribe German speech as English.
+ """
+ if language is None or not str(language).strip():
+ return configured
+ return None if str(language).strip().lower() == AUTO_LANGUAGE else str(language)
+
+
+@dataclass(frozen=True, slots=True)
+class Transcript:
+ """Local Transcript shape, mirrors ``jarvis.core.protocols.Transcript``.
+
+ Plugin code must not import from ``jarvis.*``; structural compatibility is
+ sufficient because ``STTProvider`` is a ``runtime_checkable`` Protocol and
+ consumers access fields by name.
+ """
+
+ text: str
+ language: str
+ confidence: float
+ is_partial: bool = False
+ segments: tuple[dict[str, Any], ...] = field(default_factory=tuple)
+ #: What the vendor returned BEFORE the cleanup filter ran. Read by the two
+ #: callers that must not get an edited string — the dictation lane (which
+ #: owns the user's filler switch) and wake verification.
+ raw_text: str = ""
+
+
+class DeepgramSTT:
+ """Deepgram-hosted Nova-3 STT (cloud, batch)."""
+
+ name = "deepgram-api"
+ supports_streaming = False
+ #: Concurrent ``transcribe_pcm`` calls are safe: each is one HTTP request
+ #: on a shared async client with no native engine behind it, so AP-24's
+ #: single-caller rule for in-process inference engines does not apply.
+ supports_concurrent_requests = True
+
+ def __init__(
+ self,
+ *,
+ api_key: str | None = None,
+ model: str = DEFAULT_MODEL,
+ endpoint: str = DEFAULT_ENDPOINT,
+ language: str | None = None,
+ smart_format: bool = True,
+ timeout_s: float = 30.0,
+ http_client: httpx.AsyncClient | None = None,
+ ) -> None:
+ self._api_key = (
+ api_key
+ or os.environ.get("DEEPGRAM_API_KEY", "")
+ or _read_keyring_secret("personal-jarvis", "deepgram_api_key")
+ )
+ self._model = model
+ self._last_used_model = ""
+ self._endpoint = endpoint
+ self._language = language if language and language != AUTO_LANGUAGE else None
+ # Punctuation, casing and number formatting. On by default because
+ # every consumer downstream reads the text as prose, and un-formatted
+ # Deepgram output is a lowercase unpunctuated run-on.
+ self._smart_format = smart_format
+ self._timeout_s = timeout_s
+ self._client = http_client
+ self._owns_client = http_client is None
+
+ # ------------------------------------------------------------------
+ # Public API (STTProvider contract)
+ # ------------------------------------------------------------------
+
+ @property
+ def last_used_model(self) -> str:
+ """Effective model that produced the latest successful transcript."""
+ return self._last_used_model
+
+ async def transcribe(self, audio: AsyncIterator[Any]) -> Transcript:
+ """Collect audio chunks, upload once, return a final Transcript."""
+ pcm_pieces: list[bytes] = []
+ sample_rate = 16_000
+ channels = 1
+ async for chunk in audio:
+ pcm_pieces.append(bytes(chunk.pcm))
+ sample_rate = int(getattr(chunk, "sample_rate", sample_rate))
+ channels = int(getattr(chunk, "channels", channels))
+
+ if not pcm_pieces:
+ return Transcript(text="", language="unknown", confidence=0.0)
+
+ wav_bytes = _wrap_pcm_as_wav(
+ b"".join(pcm_pieces), sample_rate=sample_rate, channels=channels
+ )
+ return await self._post_transcription(wav_bytes, language=self._language)
+
+ async def stream_transcribe(
+ self, audio: AsyncIterator[Any]
+ ) -> AsyncIterator[Transcript]:
+ """One final Transcript.
+
+ Deepgram does stream, over a WebSocket; see the module docstring for
+ why this plugin deliberately does not, and what would have to change
+ first for it to be worth doing.
+ """
+ final = await self.transcribe(audio)
+ yield final
+
+ async def transcribe_pcm(
+ self,
+ pcm_bytes: bytes,
+ sample_rate: int = 16_000,
+ language: str | None = None,
+ ) -> Transcript:
+ """The path the live microphone actually takes.
+
+ ``jarvis.speech.pipeline._handle_utterance`` delivers one complete
+ VAD-segmented utterance as raw int16 PCM. ``language="auto"`` forces
+ per-utterance detection for THIS call even when a language is
+ configured — see :func:`_detect_or`.
+ """
+ if not pcm_bytes:
+ return Transcript(text="", language="unknown", confidence=0.0)
+ wav_bytes = _wrap_pcm_as_wav(pcm_bytes, sample_rate=sample_rate, channels=1)
+ return await self._post_transcription(
+ wav_bytes, language=_detect_or(language, self._language)
+ )
+
+ async def transcribe_container(
+ self, data: bytes, *, filename: str = "recording", language: str | None = None
+ ) -> Transcript:
+ """Transcribe an ENCODED audio file (m4a, opus, mp3, mp4, wav, …).
+
+ The optional capability the UltraWiki enrichment stage looks for. The
+ live path delivers raw PCM, which everything else here wraps in a WAV
+ container; an imported voice note is already encoded, so it is passed
+ through untouched — re-wrapping it would corrupt it — with the real
+ container announced in ``Content-Type``.
+ """
+ if not data:
+ return Transcript(text="", language="unknown", confidence=0.0)
+ return await self._post_transcription(
+ data,
+ content_type=_content_type_for(filename),
+ language=_detect_or(language, self._language),
+ )
+
+ def _ensure_model(self) -> None:
+ """No-op compat shim — cloud STT has nothing to warm up.
+
+ ``jarvis.speech.pipeline._warmup`` calls this to pre-download local
+ Whisper weights. Here the first request is the warm-up.
+ """
+ return None
+
+ async def aclose(self) -> None:
+ """Close the owned HTTP client (no-op when one was injected)."""
+ if self._owns_client and self._client is not None:
+ await self._client.aclose()
+ self._client = None
+
+ # ------------------------------------------------------------------
+ # Internals
+ # ------------------------------------------------------------------
+
+ def _get_client(self) -> httpx.AsyncClient:
+ if self._client is None:
+ self._client = httpx.AsyncClient(timeout=self._timeout_s)
+ return self._client
+
+ def _query_params(self, language: str | None) -> dict[str, str]:
+ """Deepgram takes its options as query parameters, not form fields."""
+ params: dict[str, str] = {"model": self._model}
+ if self._smart_format:
+ params["smart_format"] = "true"
+ if language:
+ params["language"] = language
+ else:
+ # Deepgram needs an explicit request to detect. Omitting the
+ # language does NOT mean "detect" the way it does for Whisper — it
+ # means "use the model default", which is English.
+ params["detect_language"] = "true"
+ return params
+
+ async def _post_transcription(
+ self,
+ audio_bytes: bytes,
+ *,
+ content_type: str = "audio/wav",
+ language: str | None = None,
+ ) -> Transcript:
+ if not self._api_key:
+ raise RuntimeError(
+ "DEEPGRAM_API_KEY missing; provide api_key=… , set the env var, "
+ "or store it in the credential manager via the setup wizard."
+ )
+
+ headers = {
+ # Deepgram's scheme keyword is "Token". A "Bearer" prefix is
+ # rejected with 401, which looks exactly like a bad key and sends
+ # people off to rotate a credential that was never the problem.
+ "Authorization": f"Token {self._api_key}",
+ "Content-Type": content_type,
+ }
+ response = await self._get_client().post(
+ self._endpoint,
+ headers=headers,
+ params=self._query_params(language),
+ content=audio_bytes,
+ )
+ # Raise the httpx error rather than flattening it: it carries the
+ # status on ``.response.status_code`` and ``Retry-After`` on
+ # ``.response.headers``, which is what lets the pipeline's transient
+ # retry ladder tell a rate limit apart from a bad key.
+ response.raise_for_status()
+ transcript = _payload_to_transcript(response.json(), fallback_language=language)
+ self._last_used_model = self._model
+ return transcript
+
+
+# ----------------------------------------------------------------------
+# Helpers (module-private)
+# ----------------------------------------------------------------------
+
+def _read_keyring_secret(service: str, username: str) -> str:
+ """Best-effort credential-manager lookup. Returns ``""`` on any failure."""
+ # No jarvis.* import here (plugin purity contract): the host's plugin
+ # loader installs the process-wide keyring backend — on macOS the
+ # single-vault-item wrapper (BUG-103) — before this module is imported, so
+ # this direct read is served from the bundled vault rather than a per-item
+ # Keychain entry with its own permission dialog. Standalone use degrades to
+ # the plain OS keyring.
+ try:
+ import keyring # type: ignore[import-not-found]
+ except ImportError:
+ # keyring is a soft dependency; a base install without it simply has no
+ # vault to read, which is "no key" and is already reported honestly by
+ # the caller. Logging it on every lookup would be noise, not a finding.
+ return ""
+ try:
+ return keyring.get_password(service, username) or ""
+ except Exception: # noqa: BLE001 — a locked or absent vault is "no key",
+ # which the caller already reports honestly; re-raising here would turn
+ # a missing optional credential into a crash.
+ return ""
+
+
+def _content_type_for(filename: str) -> str:
+ """Announce the real container, defaulting to WAV for anything unknown."""
+ from pathlib import PurePosixPath # noqa: PLC0415 — tiny, local
+
+ suffix = PurePosixPath(str(filename or "")).suffix.lower()
+ return _CONTENT_TYPES.get(suffix, "audio/wav")
+
+
+def _wrap_pcm_as_wav(pcm: bytes, *, sample_rate: int, channels: int) -> bytes:
+ """Wrap int16 little-endian PCM in a minimal WAV header (in memory)."""
+ buf = io.BytesIO()
+ with wave.open(buf, "wb") as wav:
+ wav.setnchannels(max(1, channels))
+ wav.setsampwidth(2) # int16
+ wav.setframerate(sample_rate)
+ wav.writeframes(pcm)
+ return buf.getvalue()
+
+
+def _payload_to_transcript(
+ payload: dict[str, Any], *, fallback_language: str | None = None
+) -> Transcript:
+ """Parse Deepgram's ``/v1/listen`` response into a Transcript.
+
+ The response nests the result under
+ ``results.channels[0].alternatives[0]``. Every level is read defensively
+ because a request that produced no speech returns the same envelope with an
+ empty alternative rather than a distinct shape.
+
+ The text is filtered on the way in (``clean_stt_text``), which is the last
+ point where recognizer artifacts can be removed before every consumer
+ downstream reads the string. The untouched text stays on ``raw_text``.
+ """
+ results = payload.get("results") or {}
+ channels = results.get("channels") or []
+ channel = channels[0] if channels else {}
+ alternatives = channel.get("alternatives") or []
+ alternative = alternatives[0] if alternatives else {}
+
+ raw = str(alternative.get("transcript", "")).strip()
+ # Deepgram reports a real 0..1 confidence per alternative, so unlike the
+ # Whisper plugins there is no log-probability to exponentiate. A response
+ # with text but no confidence field is treated as certain rather than as
+ # silence.
+ confidence = float(alternative.get("confidence", 1.0 if raw else 0.0))
+
+ language = str(
+ channel.get("detected_language") or fallback_language or "unknown"
+ )
+
+ # Utterances are the closest thing to Whisper's segments and carry the
+ # timings the flight recorder reads. They are only present when the
+ # request asked for them, so an empty tuple is the normal case here.
+ seg_tuple: tuple[dict[str, Any], ...] = tuple(
+ {
+ "start": float(u.get("start", 0.0)),
+ "end": float(u.get("end", 0.0)),
+ "text": str(u.get("transcript", "")),
+ "avg_logprob": 0.0,
+ }
+ for u in (results.get("utterances") or ())
+ )
+
+ # Local import, like the credential lookup: the module top stays
+ # ``jarvis.*``-free (entry-point purity).
+ from jarvis.plugins.stt.transcript_filter import clean_stt_text
+
+ return Transcript(
+ text=clean_stt_text(raw, language=language),
+ language=language,
+ confidence=min(1.0, max(0.0, confidence)),
+ is_partial=False,
+ segments=seg_tuple,
+ raw_text=raw,
+ )
+
+
+__all__ = ["DeepgramSTT", "Transcript"]
diff --git a/pyproject.toml b/pyproject.toml
index ad257fed16..b1fc428a97 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -531,6 +531,11 @@ openai-api = "jarvis.plugins.stt.openai_api:OpenAIWhisperAPI"
# Gemini AI-Studio key; the Gemini-only downloader gets voice input with no
# second credential.
gemini-api = "jarvis.plugins.stt.gemini_api:GeminiSTT"
+# Deepgram Nova-3 cloud transcription. Batch REST, not the WebSocket streaming
+# lane: nothing in the speech pipeline consumes interim transcripts yet, so a
+# socket would add complexity and deliver no lower latency. Uses its own
+# deepgram_api_key, which the setup wizard already knows how to store.
+deepgram-api = "jarvis.plugins.stt.deepgram_api:DeepgramSTT"
# Same recognizer on Google Cloud Vertex AI — reuses the shared Vertex
# credential, so setting Vertex up once serves brain, voice input and voice out.
vertex-stt = "jarvis.plugins.stt.gemini_api:VertexSTT"
diff --git a/tests/contract/test_cloud_stt_plugins_contract.py b/tests/contract/test_cloud_stt_plugins_contract.py
index 251262416f..f9c8d8db23 100644
--- a/tests/contract/test_cloud_stt_plugins_contract.py
+++ b/tests/contract/test_cloud_stt_plugins_contract.py
@@ -1,4 +1,4 @@
-"""Contract tests for the OpenAI + Gemini cloud STT plugins.
+"""Contract tests for the OpenAI, Gemini and Deepgram cloud STT plugins.
New STT providers MUST pass ``tests/contract/``. These assert the two plugins
added to close the single-key STT gap (an OpenAI-only or Gemini-only downloader
@@ -25,12 +25,14 @@ from pathlib import Path
import pytest
from jarvis.core.protocols import STTProvider
+from jarvis.plugins.stt.deepgram_api import DeepgramSTT
from jarvis.plugins.stt.gemini_api import GeminiSTT
from jarvis.plugins.stt.openai_api import OpenAIWhisperAPI
_CASES = [
("openai-api", OpenAIWhisperAPI, "jarvis.plugins.stt.openai_api"),
("gemini-api", GeminiSTT, "jarvis.plugins.stt.gemini_api"),
+ ("deepgram-api", DeepgramSTT, "jarvis.plugins.stt.deepgram_api"),
]
@@ -55,6 +57,10 @@ def test_gemini_instance_is_stt_provider() -> None:
assert isinstance(GeminiSTT(api_key="dummy"), STTProvider)
+def test_deepgram_instance_is_stt_provider() -> None:
+ assert isinstance(DeepgramSTT(api_key="dummy"), STTProvider)
+
+
@pytest.mark.parametrize("name,_cls,mod_name", _CASES)
def test_plugin_module_has_no_top_level_jarvis_import(name, _cls, mod_name) -> None:
"""No ``jarvis.*`` import at MODULE level (column 0). A lazy import inside a
diff --git a/tests/unit/stt/test_deepgram_api.py b/tests/unit/stt/test_deepgram_api.py
new file mode 100644
index 0000000000..54a950925e
--- /dev/null
+++ b/tests/unit/stt/test_deepgram_api.py
@@ -0,0 +1,234 @@
+"""Functional tests for the Deepgram STT plugin, over a fake transport.
+
+Deepgram is not OpenAI-shaped, and each of the three differences is a real bug
+if it is got wrong — a `Bearer` prefix reads as a bad key, multipart audio is
+rejected, and an omitted language silently transcribes German as English. So
+the request itself is what is asserted here, not just the parsed result.
+
+No network: httpx's MockTransport answers the request and hands the recorded
+request object back to the test.
+"""
+from __future__ import annotations
+
+import json
+import wave
+from io import BytesIO
+
+import httpx
+import pytest
+
+from jarvis.plugins.stt.deepgram_api import (
+ DEFAULT_MODEL,
+ DeepgramSTT,
+ _payload_to_transcript,
+ _wrap_pcm_as_wav,
+)
+
+PCM = b"\x00\x01" * 1600 # 0.1 s of int16 at 16 kHz
+
+
+def _payload(
+ transcript: str = "hallo welt",
+ confidence: float = 0.97,
+ detected: str | None = "de",
+) -> dict:
+ channel: dict = {
+ "alternatives": [{"transcript": transcript, "confidence": confidence}]
+ }
+ if detected is not None:
+ channel["detected_language"] = detected
+ return {"results": {"channels": [channel]}}
+
+
+def _client(payload: dict, record: list[httpx.Request], status: int = 200):
+ def handler(request: httpx.Request) -> httpx.Response:
+ record.append(request)
+ return httpx.Response(status, json=payload)
+
+ return httpx.AsyncClient(transport=httpx.MockTransport(handler))
+
+
+def _provider(record: list[httpx.Request], payload: dict | None = None, **kwargs):
+ return DeepgramSTT(
+ api_key="k", http_client=_client(payload or _payload(), record), **kwargs
+ )
+
+
+# ---------------------------------------------------------------- the request
+
+
+async def test_authorization_uses_token_not_bearer():
+ record: list[httpx.Request] = []
+ await _provider(record).transcribe_pcm(PCM)
+ # A Bearer prefix here is rejected with 401, which is indistinguishable
+ # from a wrong key and sends people to rotate a working credential.
+ assert record[0].headers["authorization"] == "Token k"
+
+
+async def test_audio_is_the_request_body_not_a_multipart_field():
+ record: list[httpx.Request] = []
+ await _provider(record).transcribe_pcm(PCM)
+ body = record[0].content
+ assert body.startswith(b"RIFF")
+ assert b"Content-Disposition" not in body
+ assert record[0].headers["content-type"] == "audio/wav"
+
+
+async def test_a_configured_language_is_sent_and_detection_is_not_requested():
+ record: list[httpx.Request] = []
+ await _provider(record, language="de").transcribe_pcm(PCM)
+ params = record[0].url.params
+ assert params["language"] == "de"
+ assert "detect_language" not in params
+
+
+async def test_no_language_asks_deepgram_to_detect_explicitly():
+ record: list[httpx.Request] = []
+ await _provider(record).transcribe_pcm(PCM)
+ # Omitting the language does NOT mean "detect" for Deepgram the way it does
+ # for Whisper — it falls back to English, so the flag must be explicit.
+ assert record[0].url.params["detect_language"] == "true"
+
+
+async def test_auto_clears_a_configured_language_for_that_call_only():
+ record: list[httpx.Request] = []
+ provider = _provider(record, language="de")
+ await provider.transcribe_pcm(PCM, language="auto")
+ assert "language" not in record[0].url.params
+ assert record[0].url.params["detect_language"] == "true"
+ # The configured pin survives for the next call.
+ await provider.transcribe_pcm(PCM)
+ assert record[1].url.params["language"] == "de"
+
+
+async def test_model_and_smart_format_reach_the_query_string():
+ record: list[httpx.Request] = []
+ await _provider(record).transcribe_pcm(PCM)
+ assert record[0].url.params["model"] == DEFAULT_MODEL
+ assert record[0].url.params["smart_format"] == "true"
+
+
+async def test_an_encoded_container_is_passed_through_with_its_real_type():
+ record: list[httpx.Request] = []
+ await _provider(record).transcribe_container(b"OggS-fake", filename="note.opus")
+ # Re-wrapping an already-encoded file would corrupt it.
+ assert record[0].content == b"OggS-fake"
+ assert record[0].headers["content-type"] == "audio/opus"
+
+
+# ---------------------------------------------------------------- the response
+
+
+async def test_transcript_carries_text_language_and_confidence():
+ record: list[httpx.Request] = []
+ result = await _provider(record).transcribe_pcm(PCM)
+ assert result.text == "hallo welt"
+ assert result.language == "de"
+ assert result.confidence == pytest.approx(0.97)
+ assert result.is_partial is False
+
+
+async def test_empty_audio_never_reaches_the_network():
+ record: list[httpx.Request] = []
+ result = await _provider(record).transcribe_pcm(b"")
+ assert record == []
+ assert result.text == ""
+ assert result.confidence == 0.0
+
+
+async def test_a_missing_key_says_so_instead_of_sending_an_unauthorized_request():
+ record: list[httpx.Request] = []
+ provider = DeepgramSTT(api_key="", http_client=_client(_payload(), record))
+ provider._api_key = "" # defeat any ambient env/keyring value on this box
+ with pytest.raises(RuntimeError, match="DEEPGRAM_API_KEY"):
+ await provider.transcribe_pcm(PCM)
+ assert record == []
+
+
+async def test_an_http_error_keeps_its_status_for_the_retry_ladder():
+ record: list[httpx.Request] = []
+ provider = DeepgramSTT(
+ api_key="k", http_client=_client(_payload(), record, status=429)
+ )
+ with pytest.raises(httpx.HTTPStatusError) as excinfo:
+ await provider.transcribe_pcm(PCM)
+ # Flattening this into a bare RuntimeError is what stops the pipeline from
+ # telling a rate limit apart from a bad key.
+ assert excinfo.value.response.status_code == 429
+
+
+async def test_stream_transcribe_yields_exactly_one_final_transcript():
+ record: list[httpx.Request] = []
+
+ async def chunks():
+ class Chunk:
+ pcm = PCM
+ sample_rate = 16_000
+ channels = 1
+
+ yield Chunk()
+
+ out = [t async for t in _provider(record).stream_transcribe(chunks())]
+ assert len(out) == 1
+ assert out[0].is_partial is False
+ assert out[0].text == "hallo welt"
+
+
+# ---------------------------------------------------------------- parsing
+
+
+def test_a_response_with_no_speech_parses_as_empty_rather_than_raising():
+ result = _payload_to_transcript({"results": {"channels": []}})
+ assert result.text == ""
+ assert result.confidence == 0.0
+ assert result.language == "unknown"
+
+
+def test_the_requested_language_is_used_when_deepgram_reports_none():
+ result = _payload_to_transcript(_payload(detected=None), fallback_language="de")
+ assert result.language == "de"
+
+
+def test_utterances_become_segments_when_present():
+ payload = _payload()
+ payload["results"]["utterances"] = [
+ {"start": 0.2, "end": 1.1, "transcript": "hallo"},
+ ]
+ result = _payload_to_transcript(payload)
+ assert result.segments[0]["start"] == pytest.approx(0.2)
+ assert result.segments[0]["text"] == "hallo"
+
+
+def test_raw_text_keeps_what_the_vendor_actually_returned():
+ result = _payload_to_transcript(_payload(transcript=" hallo welt "))
+ assert result.raw_text == "hallo welt"
+
+
+# ---------------------------------------------------------------- wav wrapper
+
+
+def test_pcm_is_wrapped_as_16_bit_mono_wav_at_the_given_rate():
+ data = _wrap_pcm_as_wav(PCM, sample_rate=16_000, channels=1)
+ with wave.open(BytesIO(data), "rb") as wav:
+ assert wav.getnchannels() == 1
+ assert wav.getsampwidth() == 2
+ assert wav.getframerate() == 16_000
+ assert wav.readframes(wav.getnframes()) == PCM
+
+
+def test_the_payload_shape_matches_deepgrams_documented_envelope():
+ # Guards the nesting the parser walks: results -> channels -> alternatives.
+ envelope = json.loads(json.dumps(_payload()))
+ assert envelope["results"]["channels"][0]["alternatives"][0]["transcript"]