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): add OpenAI Whisper and Gemini cloud STT plugins for single-key downloaders

Ruben Lütkec597ab3a507d
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index d6b7d472c1..955fc5c0e0 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -1,4 +1,4 @@
-"""STT provider plugins (faster-whisper, OpenAI, Groq, Deepgram).
+"""STT provider plugins (faster-whisper, Groq, OpenRouter, OpenAI, Gemini).
This package exposes a single ``build_stt_from_config`` factory that turns an
``STTConfig`` into the configured ``STTProvider``-conformant instance via the
@@ -32,22 +32,30 @@ _STT_SECRET_CANDIDATES: dict[str, tuple[tuple[str, str], ...]] = {
# ``openrouter-stt`` (distinct from the ``openrouter`` brain id) to avoid a
# collision in the shared model-catalog / provider-spec namespaces.
"openrouter-stt": (("openrouter_api_key", "OPENROUTER_API_KEY"),),
+ # OpenAI Whisper STT reuses the SAME openai_api_key slot as the OpenAI brain.
"openai-api": (("openai_api_key", "OPENAI_API_KEY"),),
- "deepgram": (("deepgram_api_key", "DEEPGRAM_API_KEY"),),
- "deepgram-flux": (("deepgram_api_key", "DEEPGRAM_API_KEY"),),
- "deepgram-nova3": (("deepgram_api_key", "DEEPGRAM_API_KEY"),),
+ # Gemini STT reuses the SAME AI-Studio key slots as the Gemini brain/TTS, so
+ # the Gemini-only downloader (the recommended-default persona) gets cloud
+ # voice input with no second credential.
+ "gemini-api": (
+ ("gemini_api_key", "GEMINI_API_KEY"),
+ ("google_aistudio_api_key", "GOOGLE_AIStudio_API_KEY"),
+ ("google_api_key", "GOOGLE_API_KEY"),
+ ),
}
# Cross-family probe order when the configured cloud STT has no usable key: the
# family the maintainer ships first, then the common BYO-key alternatives. Only a
# family that BOTH has a key AND is registered as a `jarvis.stt` entry-point is
-# ever chosen (unregistered names — e.g. openai/deepgram today — are skipped, so
-# we never promise an STT we cannot build). This mirrors the TTS factory's
-# `_TTS_CROSS_FAMILY_ORDER`; it is what lets a fresh downloader whose only key is
-# an OpenRouter key (a gateway shared with the brain) get working voice input
-# instead of dead-ending on local faster-whisper the base install never shipped.
+# ever chosen (a keyed-but-unregistered name is skipped, so we never promise an
+# STT we cannot build). Every entry here now HAS a plugin (groq-api, openrouter-
+# stt, openai-api, gemini-api); the dead `deepgram*` names were removed so the
+# resolver can never cross to a non-existent provider. This mirrors the TTS
+# factory's `_TTS_CROSS_FAMILY_ORDER`; it is what lets a fresh downloader whose
+# only key is (say) an OpenAI or Gemini key get working voice input instead of
+# dead-ending on local faster-whisper the base install never shipped.
_STT_CROSS_FAMILY_ORDER: tuple[str, ...] = (
- "groq-api", "openrouter-stt", "openai-api", "deepgram",
+ "groq-api", "openrouter-stt", "openai-api", "gemini-api",
)
@@ -251,11 +259,71 @@ def build_stt_from_config(stt_cfg: Any) -> Any:
return _build_local_fallback(stt_cfg, language)
+# One-time gate so the "no working STT" hint is logged at most once per process
+# (the STT provider is rebuilt whenever a key changes; the hint must not repeat).
+_NO_STT_HINT_EMITTED = False
+
+
+def _faster_whisper_installed() -> bool:
+ """True iff the local ``faster_whisper`` engine is importable on this host.
+
+ A cheap spec probe (no heavy import): ``fwhisper`` imports ``faster_whisper``
+ lazily, so a base/headless install builds a ``FasterWhisperProvider`` fine and
+ only fails on the FIRST transcription. This lets the hint below detect the
+ genuine dead-end (no cloud key AND no local engine) before that happens.
+ """
+ import importlib.util
+
+ return importlib.util.find_spec("faster_whisper") is not None
+
+
+def _any_cloud_stt_key() -> bool:
+ """True iff the host has a usable key for ANY known cloud STT family."""
+ return any(_stt_family_has_key(name) for name in _STT_CROSS_FAMILY_ORDER)
+
+
+def _maybe_hint_no_working_stt() -> None:
+ """Log a one-time, actionable English hint when NO STT can work here.
+
+ Fires only when BOTH are true: no cloud STT key resolves (Groq / OpenRouter /
+ OpenAI / Gemini) AND the local ``faster-whisper`` engine is not installed — the
+ genuine dead-end where voice input silently cannot work. Log-only: it never
+ changes the graceful local-fallback behaviour, and a host that has either a
+ cloud key or the local engine (the maintainer, a keyed downloader) never sees
+ it. The probe is wrapped defensively so a config hiccup can never break the
+ STT build.
+ """
+ global _NO_STT_HINT_EMITTED
+ if _NO_STT_HINT_EMITTED:
+ return
+ try:
+ if _any_cloud_stt_key() or _faster_whisper_installed():
+ return
+ except Exception as exc: # noqa: BLE001 — a hint probe must never break STT build
+ logger.debug("STT self-recovery hint probe failed ({}); skipping hint.", exc)
+ return
+ _NO_STT_HINT_EMITTED = True
+ logger.warning(
+ "No speech-to-text is available on this host: no cloud STT key is "
+ "configured (Groq / OpenRouter / OpenAI / Gemini) and the local "
+ "faster-whisper engine is not installed, so voice input cannot work. "
+ "To fix it in-app: add a Groq, OpenRouter, OpenAI, or Gemini key in the "
+ "API-Keys view. Or install the local engine via the '[full]' or "
+ "'[local-voice]' extra (e.g. pip install 'personal-jarvis[full]')."
+ )
+
+
def _build_local_fallback(stt_cfg: Any, language: str | None) -> Any:
"""Construct the key-free local faster-whisper provider (the universal floor)."""
from jarvis.core.device import resolve_device
from jarvis.plugins.stt.fwhisper import FasterWhisperProvider
+ # Honest self-recovery hint (log-only, does not change the fallback): when
+ # this host has neither a cloud STT key nor the local engine, voice input
+ # cannot work — tell the user exactly how to fix it in-app instead of only
+ # the generic spoken apology later.
+ _maybe_hint_no_working_stt()
+
# Central CPU-first device resolution (ADR-0024). The utterance provider is
# latency-tolerant, so its capability verdict is left unverified (None): an
# explicit ``device = "cuda"`` in jarvis.toml is the user's opt-in and is
diff --git a/jarvis/plugins/stt/gemini_api.py b/jarvis/plugins/stt/gemini_api.py
new file mode 100644
index 0000000000..94e7299fb9
--- /dev/null
+++ b/jarvis/plugins/stt/gemini_api.py
@@ -0,0 +1,325 @@
+"""Gemini STT plugin — cloud transcription via google-genai inline audio.
+
+The Gemini-only downloader is the recommended-default persona, yet the STT
+cross-family table named ``gemini-api`` with no plugin behind it — so a user
+whose ONLY key is a Google AI-Studio (Gemini) key got NO cloud speech-to-text
+and dead-ended on the local ``faster-whisper`` engine the base install never
+bundles. This plugin closes that gap by transcribing through the SAME Gemini
+credential the brain and TTS already use — no second key.
+
+How it works (and its honest limits): Gemini has no dedicated transcription
+endpoint. Instead this uses the model's multimodal audio understanding —
+``generate_content`` with the utterance as an inline ``audio/wav`` part and a
+tight instruction to emit the verbatim transcript only. That is GENERATIVE
+transcription, so it is best-effort: it is fed a full VAD-segmented utterance
+(real speech that already passed voice-activity detection), returns free-form
+text with no per-segment timings or confidence, and can add stray preamble that
+the light output cleanup below trims. It is a working cloud STT for a Gemini-only
+user, not a drop-in equal of a dedicated ASR model.
+
+Model default: the same widely-served Gemini flash model the brain defaults to.
+Gate on the capability, never a fancier model id (AP-21) — any audio-capable
+Gemini model works; a user can set another in the STT model field.
+
+Plugin contract: structurally compatible with
+``jarvis.core.protocols.STTProvider`` WITHOUT importing ``jarvis.*`` at import
+time (entry-point plugins stay import-clean). The credential lookup imports
+``jarvis.core.config`` lazily inside a method, mirroring the Gemini brain. The
+returned object is a locally defined ``Transcript`` dataclass with the identical
+field shape; consumers duck-type on ``text`` / ``language`` / ``confidence`` /
+``is_partial`` / ``segments``.
+
+Audio I/O contract (compatible with the Jarvis VAD output):
+ * ``transcribe`` consumes chunks exposing ``.pcm`` (int16 little-endian
+ bytes), ``.sample_rate`` (Hz) and optionally ``.channels`` (default 1).
+ * ``transcribe_pcm`` receives a full VAD-segmented utterance as raw int16 PCM
+ at 16 kHz mono (the pipeline default) — the drop-in shim the speech
+ pipeline actually calls.
+ * All PCM is wrapped in an in-memory WAV container before the inline upload.
+
+Credential resolution reuses ``jarvis.core.config.resolve_provider_endpoint``
+(keyring -> ENV -> .env -> local-file fallback), exactly like the Gemini brain.
+A missing key, an unavailable ``google-genai`` package, or an API error raises a
+clear English error so the STT factory degrades to the key-free local
+``faster-whisper`` floor instead of bricking voice input for a single-provider
+user (AP-22). Never accept a key from voice/chat input (AP-2).
+"""
+from __future__ import annotations
+
+import asyncio
+import base64
+from collections.abc import AsyncIterator
+from dataclasses import dataclass, field
+from typing import Any
+
+# Widely-served Gemini flash model with audio understanding. NOT pinned to a
+# preview/pro id (AP-21): any audio-capable Gemini model transcribes; a user can
+# override it in the STT model field. Kept in step with the Gemini brain default.
+DEFAULT_MODEL = "gemini-3-flash-preview"
+
+# The transcription directive. Tight on purpose: a generative model must be told
+# to emit ONLY the verbatim words, or it wraps the transcript in commentary. The
+# output cleanup below is a light safety net, not a content filter (AP-27): it
+# never inspects the transcript for a wake word or rewrites recognized speech.
+_TRANSCRIBE_INSTRUCTION = (
+ "Transcribe the speech in this audio verbatim. Output ONLY the exact words "
+ "spoken, with no preamble, no explanation, no speaker labels, and no "
+ "quotation marks around the text. If the audio contains no discernible "
+ "speech, output nothing at all."
+)
+
+
+@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 the fields by name.
+ """
+
+ text: str
+ language: str
+ confidence: float
+ is_partial: bool = False
+ segments: tuple[dict[str, Any], ...] = field(default_factory=tuple)
+
+
+class GeminiSTT:
+ """Google Gemini cloud STT (non-streaming, generative audio understanding).
+
+ The provider id is ``gemini-api`` (NOT ``gemini``) on purpose: the Gemini
+ *brain* already owns the ``gemini`` id in the shared model-catalog and
+ provider-spec namespaces, so the STT variant takes a distinct id — mirroring
+ the repo's own ``openrouter`` (brain) vs ``openrouter-stt`` (STT) split. The
+ underlying credential is still SHARED with the brain/TTS, so no second key is
+ needed.
+ """
+
+ name = "gemini-api"
+ supports_streaming = False
+
+ def __init__(
+ self,
+ *,
+ api_key: str | None = None,
+ model: str = DEFAULT_MODEL,
+ language: str | None = None,
+ prompt: str | None = None,
+ temperature: float = 0.0,
+ timeout_s: float = 30.0,
+ client: Any | None = None,
+ ) -> None:
+ # An explicitly injected ``api_key`` / ``client`` wins (tests, team
+ # setups). Otherwise the key is resolved lazily on the first request via
+ # ``resolve_provider_endpoint`` so construction stays cheap and never
+ # triggers a config load on the boot critical path (AP-26).
+ self._api_key = (api_key or "").strip() or None
+ self._model = model or DEFAULT_MODEL
+ self._language = language if language and language != "auto" else None
+ # A bias/vocabulary hint (proper nouns). Appended to the instruction so
+ # the model favours those spellings; never treated as required content.
+ self._prompt = (prompt or "").strip() or None
+ self._temperature = temperature
+ self._timeout_s = timeout_s
+ self._client = client
+
+ # ------------------------------------------------------------------
+ # Public API (STTProvider contract + pipeline compat shims)
+ # ------------------------------------------------------------------
+
+ 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)
+
+ async def stream_transcribe(
+ self, audio: AsyncIterator[Any]
+ ) -> AsyncIterator[Transcript]:
+ """Gemini STT is non-streaming — yield a single final Transcript."""
+ 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:
+ """Drop-in compat shim mirroring ``FasterWhisperProvider.transcribe_pcm``.
+
+ The speech pipeline delivers a full VAD-segmented utterance as raw int16
+ PCM (mono, 16 kHz by default). We wrap it in a WAV container and send it
+ as a single inline-audio request.
+ """
+ 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)
+ if language and language != "auto":
+ previous = self._language
+ self._language = language
+ try:
+ return await self._post_transcription(wav_bytes)
+ finally:
+ self._language = previous
+ return await self._post_transcription(wav_bytes)
+
+ def _ensure_model(self) -> None:
+ """No-op compat shim — cloud STT has nothing to warm up.
+
+ ``jarvis.speech.pipeline`` calls ``_ensure_model`` to pre-download local
+ Whisper weights. For a cloud provider the first request is the warm-up.
+ """
+ return None
+
+ async def aclose(self) -> None:
+ """No owned network client to close (the genai client is stateless)."""
+ return None
+
+ # ------------------------------------------------------------------
+ # Internals
+ # ------------------------------------------------------------------
+
+ def _ensure_client(self) -> Any:
+ """Return the google-genai client, building it lazily from the key.
+
+ An injected client (tests / team setups) wins and skips the SDK import
+ entirely. Raises a clear English error when no Gemini key is configured
+ or ``google-genai`` is not installed, so the STT factory degrades to the
+ local floor rather than bricking voice input (AP-22).
+ """
+ if self._client is not None:
+ return self._client
+
+ key = self._api_key
+ if not key:
+ # Lazy import keeps the plugin ``jarvis.*``-free at import time.
+ from jarvis.core import config as _cfg
+
+ ep = _cfg.resolve_provider_endpoint("gemini")
+ key = ep.credential or None
+ if not key:
+ raise RuntimeError(
+ "No Gemini API key found (gemini_api_key / GEMINI_API_KEY / "
+ "GOOGLE_AIStudio_API_KEY). Add it in the app's API-Keys view; the "
+ "key is shared with the Gemini brain and TTS."
+ )
+ try:
+ from google import genai
+ except ImportError as exc:
+ raise RuntimeError(
+ "Gemini STT needs the 'google-genai' package (installed with the "
+ "'[full]' extra). Install it, or use a different STT provider."
+ ) from exc
+ self._client = genai.Client(api_key=key)
+ return self._client
+
+ def _build_contents(self, wav_bytes: bytes) -> list[dict[str, Any]]:
+ """Build the raw-dict ``contents`` payload (no google-genai types import).
+
+ The SDK accepts a plain dict with an ``inline_data`` part whose ``data``
+ is a base64 string — the exact shape the Gemini brain uses for images —
+ so building it here keeps the module import-clean and unit-testable with
+ a fake client.
+ """
+ instruction = _TRANSCRIBE_INSTRUCTION
+ if self._language:
+ instruction += f" The spoken language is '{self._language}'."
+ if self._prompt:
+ instruction += (
+ f" Expected vocabulary and proper nouns (favour these spellings): "
+ f"{self._prompt}."
+ )
+ audio_part = {
+ "inline_data": {
+ "mime_type": "audio/wav",
+ "data": base64.b64encode(wav_bytes).decode("ascii"),
+ }
+ }
+ return [{"role": "user", "parts": [audio_part, {"text": instruction}]}]
+
+ async def _post_transcription(self, wav_bytes: bytes) -> Transcript:
+ client = self._ensure_client()
+ contents = self._build_contents(wav_bytes)
+ # ``config`` as a plain dict is accepted by google-genai; temperature 0.0
+ # keeps the transcription as deterministic as a generative model allows.
+ config = {"temperature": self._temperature}
+ try:
+ # google-genai's ``generate_content`` is synchronous, so run it off
+ # the event loop (same pattern as the Gemini Flash TTS plugin).
+ response = await asyncio.to_thread(
+ client.models.generate_content,
+ model=self._model,
+ contents=contents,
+ config=config,
+ )
+ except Exception as exc: # noqa: BLE001 — degrade honestly (AP-22)
+ raise RuntimeError(f"Gemini STT request failed: {exc}") from exc
+ return _response_to_transcript(response, self._language)
+
+
+# ----------------------------------------------------------------------
+# Helpers (module-private)
+# ----------------------------------------------------------------------
+
+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)."""
+ import io
+ import wave
+
+ 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 _clean_transcript(text: str) -> str:
+ """Light cleanup of generative preamble artifacts — never a content filter.
+
+ A generative model occasionally wraps the transcript in matched quotes even
+ when told not to. Strip ONE matched pair of surrounding quotes. This is
+ word-agnostic and never inspects the transcript for any specific phrase
+ (AP-27): it only removes an outer quote pair, so recognized speech is
+ preserved verbatim.
+ """
+ cleaned = text.strip()
+ if len(cleaned) >= 2 and cleaned[0] == cleaned[-1] and cleaned[0] in {'"', "'"}:
+ cleaned = cleaned[1:-1].strip()
+ return cleaned
+
+
+def _response_to_transcript(response: Any, language: str | None) -> Transcript:
+ """Parse a google-genai response into a Transcript.
+
+ Uses the SDK's ``.text`` convenience accessor. Gemini returns no per-segment
+ timings or confidence, so confidence is a plain presence signal (1.0 for
+ non-empty text, else 0.0) and segments stay empty — the same convention the
+ OpenRouter plugin uses when segments are absent.
+ """
+ text = _clean_transcript(str(getattr(response, "text", None) or ""))
+ return Transcript(
+ text=text,
+ language=language or "unknown",
+ confidence=1.0 if text else 0.0,
+ is_partial=False,
+ segments=(),
+ )
+
+
+__all__ = ["GeminiSTT", "Transcript"]
diff --git a/jarvis/plugins/stt/openai_api.py b/jarvis/plugins/stt/openai_api.py
new file mode 100644
index 0000000000..100fb980b5
--- /dev/null
+++ b/jarvis/plugins/stt/openai_api.py
@@ -0,0 +1,381 @@
+"""OpenAI Whisper STT plugin — cloud transcription via the OpenAI audio API.
+
+One OpenAI API key — the SAME ``openai_api_key`` slot the OpenAI *brain* already
+uses — unlocks cloud speech-to-text, so a downloader whose only credential is an
+OpenAI key gets working voice input with no second key. This closes the single
+biggest single-key STT gap: the cross-family table named ``openai-api`` but
+shipped no plugin, so an OpenAI-only user dead-ended on the local
+``faster-whisper`` engine the base install never bundles.
+
+Endpoint (OpenAI-compatible audio API, identical wire shape to the Groq plugin):
+ * ``POST {base_url}/audio/transcriptions`` (multipart upload),
+ * Headers: ``Authorization: Bearer <key>``,
+ * multipart fields: ``file`` (an in-memory WAV), ``model``, ``response_format``
+ (``verbose_json`` for segment timings + confidence), optional ``language`` /
+ ``prompt`` / ``temperature``.
+
+Model default: ``whisper-1`` — the universally-available transcription model
+every OpenAI account can call. Gate on the capability, never a fancier model id
+(AP-21); a user who wants a newer transcription model sets it in the STT model
+field and the wire contract is unchanged.
+
+Plugin contract: structurally compatible with
+``jarvis.core.protocols.STTProvider`` WITHOUT importing ``jarvis.*`` at import
+time (entry-point plugins stay import-clean). The credential lookup imports
+``jarvis.core.config`` lazily inside a method, mirroring the OpenRouter STT
+plugin. The returned object is a locally defined ``Transcript`` dataclass with
+the identical field shape; consumers duck-type on ``text`` / ``language`` /
+``confidence`` / ``is_partial`` / ``segments``.
+
+Audio I/O contract (compatible with the Jarvis VAD output):
+ * ``transcribe`` consumes chunks exposing ``.pcm`` (int16 little-endian
+ bytes), ``.sample_rate`` (Hz) and optionally ``.channels`` (default 1).
+ * ``transcribe_pcm`` receives a full VAD-segmented utterance as raw int16 PCM
+ at 16 kHz mono (the pipeline default) — the drop-in shim the speech
+ pipeline actually calls.
+ * All PCM is wrapped in an in-memory WAV container before multipart upload.
+
+Credential resolution reuses ``jarvis.core.config.resolve_provider_endpoint``
+(keyring -> ENV -> .env -> local-file fallback), exactly like the OpenAI brain.
+A missing / dead (401) / out-of-credit (402) / rate-limited (429) / unreachable
+key raises a clear English error so the STT factory degrades to the key-free
+local ``faster-whisper`` floor instead of bricking voice input for a single-
+provider user (AP-22). Never accept a key from voice/chat input (AP-2).
+"""
+from __future__ import annotations
+
+import io
+import math
+import wave
+from collections.abc import AsyncIterator
+from dataclasses import dataclass, field
+from typing import Any
+
+import httpx
+
+# Vendor default; the effective base URL may be overridden per install via
+# ``[brain.providers.openai].base_url`` (resolved in ``_ensure_endpoint``), and
+# a team proxy re-points it transparently.
+DEFAULT_BASE_URL = "https://api.openai.com/v1"
+
+# The universally-available OpenAI transcription model. Deliberately NOT a
+# newer/fancier id (AP-21): ``whisper-1`` is the default every account can call,
+# so a model-less construction never bricks for a downloader whose account has
+# not been granted a preview transcription model.
+DEFAULT_MODEL = "whisper-1"
+
+# Whisper accepts up to 224 prompt tokens; ~1000 chars is a safe cap that stays
+# under that even for token-dense compounds (avg ~4 chars/token). Going over
+# makes the API reject the whole turn with HTTP 400 and the user experiences
+# total silence — never worth saving a few extra words.
+_MAX_PROMPT_CHARS = 1024
+
+
+@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 the fields by name.
+ """
+
+ text: str
+ language: str
+ confidence: float
+ is_partial: bool = False
+ segments: tuple[dict[str, Any], ...] = field(default_factory=tuple)
+
+
+class OpenAIWhisperAPI:
+ """OpenAI-hosted cloud STT (non-streaming, multipart transcription API).
+
+ The provider id is ``openai-api`` (NOT ``openai``) on purpose: the OpenAI
+ *brain* already owns the ``openai`` id in the shared model-catalog and
+ provider-spec namespaces, so the STT variant takes a distinct id — mirroring
+ the repo's own ``openrouter`` (brain) vs ``openrouter-stt`` (STT) split. The
+ underlying credential (``openai_api_key``) is still SHARED with the brain, so
+ no second key is needed.
+ """
+
+ name = "openai-api"
+ supports_streaming = False
+
+ def __init__(
+ self,
+ *,
+ api_key: str | None = None,
+ model: str = DEFAULT_MODEL,
+ base_url: str | None = None,
+ language: str | None = None,
+ prompt: str | None = None,
+ temperature: float = 0.0,
+ timeout_s: float = 30.0,
+ http_client: httpx.AsyncClient | None = None,
+ ) -> None:
+ # ``api_key`` / ``base_url`` may be injected (team proxy / tests). When
+ # left None they are resolved lazily on the first request via
+ # ``resolve_provider_endpoint`` so construction stays cheap and never
+ # triggers a config load on the boot critical path (AP-26).
+ self._api_key = api_key or None
+ self._api_key_is_explicit = bool(api_key)
+ self._model = model or DEFAULT_MODEL
+ self._base_url = base_url or None
+ self._language = language if language and language != "auto" else None
+ # Whisper ``prompt`` biases the token distribution toward the words in
+ # this string — the standard trick to keep proper nouns and domain
+ # vocabulary stable. Strip + cap so a whitespace-only config value
+ # behaves like "unset", and an oversized one cannot crash the API with
+ # HTTP 400 ("prompt too long").
+ cleaned = (prompt or "").strip()
+ self._prompt = cleaned[:_MAX_PROMPT_CHARS] if cleaned else None
+ self._temperature = temperature
+ self._timeout_s = timeout_s
+ self._client = http_client
+ self._owns_client = http_client is None
+ self._endpoint_url: str | None = None
+ self._resolved_secret_revision = -1
+
+ # ------------------------------------------------------------------
+ # Public API (STTProvider contract + pipeline compat shims)
+ # ------------------------------------------------------------------
+
+ 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)
+
+ async def stream_transcribe(
+ self, audio: AsyncIterator[Any]
+ ) -> AsyncIterator[Transcript]:
+ """OpenAI has no streaming STT here — yield a single final Transcript."""
+ 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:
+ """Drop-in compat shim mirroring ``FasterWhisperProvider.transcribe_pcm``.
+
+ The speech pipeline delivers a full VAD-segmented utterance as raw int16
+ PCM (mono, 16 kHz by default). We wrap it in a WAV container and POST it
+ as a single multipart request.
+ """
+ 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)
+ # Optional per-call language override (restore afterwards).
+ if language and language != "auto":
+ previous = self._language
+ self._language = language
+ try:
+ return await self._post_transcription(wav_bytes)
+ finally:
+ self._language = previous
+ return await self._post_transcription(wav_bytes)
+
+ def _ensure_model(self) -> None:
+ """No-op compat shim — cloud STT has nothing to warm up.
+
+ ``jarvis.speech.pipeline`` calls ``_ensure_model`` to pre-download local
+ Whisper weights. For a cloud provider the first request is the warm-up.
+ """
+ return None
+
+ async def aclose(self) -> None:
+ """Close the owned HTTP client (no-op when injected externally)."""
+ 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 _ensure_endpoint(self) -> str:
+ """Resolve the current credential + transcription URL.
+
+ Lazy so construction never loads config; keeps the boot path clean and
+ lets the STT factory build the instance before the key is probed. A
+ config-resolved key is refreshed at each transcription boundary so one
+ replacement in the API-Keys view applies to brain, TTS, and STT without
+ rebuilding this instance. Explicitly injected credentials remain pinned
+ (team proxy / test contract). Raises a clear English error when no OpenAI
+ credential is configured, so the factory / pipeline can fall back to the
+ local floor (AP-22).
+ """
+ if (
+ self._api_key_is_explicit
+ and self._endpoint_url is not None
+ and self._api_key
+ ):
+ return self._endpoint_url
+
+ base = self._base_url or DEFAULT_BASE_URL
+ if not self._api_key_is_explicit:
+ # Import here (not at module top) to keep the plugin ``jarvis.*``-free
+ # at import time; the entry-point loader tolerates a lazy internal use.
+ from jarvis.core import config as _cfg
+
+ current_revision = _cfg.secret_revision("openai_api_key")
+ if (
+ self._endpoint_url is not None
+ and self._api_key
+ and self._resolved_secret_revision == current_revision
+ ):
+ return self._endpoint_url
+ ep = _cfg.resolve_provider_endpoint(
+ "openai", vendor_default_base_url=DEFAULT_BASE_URL
+ )
+ self._api_key = ep.credential or None
+ base = ep.base_url or DEFAULT_BASE_URL
+ self._resolved_secret_revision = current_revision
+
+ if not self._api_key:
+ raise RuntimeError(
+ "No OpenAI API key found (openai_api_key / OPENAI_API_KEY). Add "
+ "it in the app's API-Keys view; the key is shared with the OpenAI "
+ "brain."
+ )
+ self._endpoint_url = base.rstrip("/") + "/audio/transcriptions"
+ return self._endpoint_url
+
+ async def _post_transcription(self, wav_bytes: bytes) -> Transcript:
+ url = self._ensure_endpoint()
+ files = {"file": ("audio.wav", wav_bytes, "audio/wav")}
+ data: dict[str, str] = {
+ "model": self._model,
+ "response_format": "verbose_json",
+ "temperature": str(self._temperature),
+ }
+ if self._language:
+ data["language"] = self._language
+ if self._prompt:
+ data["prompt"] = self._prompt
+
+ headers = {"Authorization": f"Bearer {self._api_key}"}
+ client = self._get_client()
+ try:
+ response = await client.post(
+ url, headers=headers, data=data, files=files
+ )
+ except httpx.HTTPError as exc:
+ raise RuntimeError(
+ f"OpenAI STT request failed (network/unreachable): {exc}"
+ ) from exc
+
+ if response.status_code >= 400:
+ raise _http_error_to_runtime(response)
+ payload = response.json()
+ return _payload_to_transcript(payload)
+
+
+# ----------------------------------------------------------------------
+# Helpers (module-private)
+# ----------------------------------------------------------------------
+
+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 _http_error_to_runtime(response: httpx.Response) -> RuntimeError:
+ """Map an HTTP error status to a clear English RuntimeError.
+
+ 401 (bad/dead key), 402 (out of credit), 429 (rate limited) and any other
+ 4xx/5xx all become a RuntimeError so the caller degrades honestly to the
+ local floor rather than bricking the STT tier (AP-22).
+ """
+ status = response.status_code
+ detail = ""
+ try:
+ payload = response.json()
+ if isinstance(payload, dict):
+ err = payload.get("error")
+ if isinstance(err, dict):
+ detail = str(err.get("message", "")).strip()
+ elif isinstance(err, str):
+ detail = err.strip()
+ except Exception: # noqa: BLE001 — body may not be JSON
+ detail = (response.text or "").strip()[:200]
+
+ reason = {
+ 401: "invalid or missing OpenAI API key",
+ 402: "OpenAI account out of credit",
+ 429: "OpenAI rate limit / quota exceeded",
+ }.get(status, f"OpenAI STT HTTP {status}")
+ msg = f"OpenAI STT failed: {reason}"
+ if detail:
+ msg = f"{msg} ({detail})"
+ return RuntimeError(msg)
+
+
+def _payload_to_transcript(payload: dict[str, Any]) -> Transcript:
+ """Parse OpenAI's OpenAI-shaped verbose_json response into a Transcript.
+
+ Shape: ``{"text": ..., "language": ..., "segments": [{"start","end","text",
+ "avg_logprob"}, ...]}``. When segments are present the confidence is derived
+ from the mean segment ``avg_logprob`` (``exp`` of the average); otherwise it
+ is a plain presence signal (1.0 for non-empty text, else 0.0) — the same
+ convention the Groq plugin uses.
+ """
+ text = str(payload.get("text", "")).strip()
+ language = str(payload.get("language", "unknown")) or "unknown"
+ segments_raw = payload.get("segments") or ()
+
+ seg_tuple: tuple[dict[str, Any], ...] = tuple(
+ {
+ "start": float(s.get("start", 0.0)),
+ "end": float(s.get("end", 0.0)),
+ "text": str(s.get("text", "")),
+ "avg_logprob": float(s.get("avg_logprob", 0.0)),
+ }
+ for s in segments_raw
+ )
+
+ if seg_tuple:
+ avg = sum(s["avg_logprob"] for s in seg_tuple) / len(seg_tuple)
+ try:
+ confidence = float(math.exp(avg))
+ except OverflowError:
+ confidence = 0.0
+ else:
+ confidence = 1.0 if text else 0.0
+
+ return Transcript(
+ text=text,
+ language=language,
+ confidence=min(1.0, max(0.0, confidence)),
+ is_partial=False,
+ segments=seg_tuple,
+ )
+
+
+__all__ = ["OpenAIWhisperAPI", "Transcript"]
diff --git a/pyproject.toml b/pyproject.toml
index 94fb3b5ec7..09e77bb80f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -358,6 +358,12 @@ openwakeword = "jarvis.plugins.wake.openwakeword_provider:OpenWakeWordProvider"
groq-api = "jarvis.plugins.stt.groq_api:GroqWhisperAPI"
# OpenRouter cloud transcription — reuses the shared openrouter_api_key.
openrouter-stt = "jarvis.plugins.stt.openrouter_stt:OpenRouterSTT"
+# OpenAI Whisper cloud transcription — reuses the shared openai_api_key.
+openai-api = "jarvis.plugins.stt.openai_api:OpenAIWhisperAPI"
+# Gemini cloud transcription (google-genai inline audio) — reuses the shared
+# Gemini AI-Studio key; the Gemini-only downloader gets voice input with no
+# second credential.
+gemini-api = "jarvis.plugins.stt.gemini_api:GeminiSTT"
[project.entry-points."jarvis.tts"]
inworld = "jarvis.plugins.tts.inworld_tts:InworldTTS"
diff --git a/tests/contract/test_cloud_stt_plugins_contract.py b/tests/contract/test_cloud_stt_plugins_contract.py
new file mode 100644
index 0000000000..251262416f
--- /dev/null
+++ b/tests/contract/test_cloud_stt_plugins_contract.py
@@ -0,0 +1,74 @@
+"""Contract tests for the OpenAI + Gemini 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
+had no cloud speech-to-text) satisfy the ``STTProvider`` structural contract:
+
+ * ``name`` matches the ``jarvis.stt`` entry-point id,
+ * ``supports_streaming`` exists and ``transcribe`` / ``stream_transcribe`` /
+ ``transcribe_pcm`` have the right async shapes,
+ * a constructed instance is a runtime ``STTProvider``,
+ * the plugin module imports NO ``jarvis.*`` at module load time (entry-point
+ plugins stay import-clean; the credential lookup may import lazily inside a
+ method, mirroring the OpenRouter STT plugin).
+
+The classes are imported directly (not via entry-point discovery) so the file is
+green regardless of whether ``pip install -e .`` has re-registered the new
+entry-points yet.
+"""
+from __future__ import annotations
+
+import importlib
+import inspect
+from pathlib import Path
+
+import pytest
+
+from jarvis.core.protocols import STTProvider
+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"),
+]
+
+
[email protected]("name,cls,_mod", _CASES)
+def test_class_name_matches_entry_point(name, cls, _mod) -> None:
+ assert cls.name == name, f"{cls.__name__}.name = {cls.name!r}, expected {name!r}"
+
+
[email protected]("name,cls,_mod", _CASES)
+def test_provider_has_required_shapes(name, cls, _mod) -> None:
+ assert hasattr(cls, "supports_streaming")
+ assert inspect.iscoroutinefunction(cls.transcribe)
+ assert inspect.isasyncgenfunction(cls.stream_transcribe)
+ assert inspect.iscoroutinefunction(cls.transcribe_pcm)
+
+
+def test_openai_instance_is_stt_provider() -> None:
+ assert isinstance(OpenAIWhisperAPI(api_key="dummy"), STTProvider)
+
+
+def test_gemini_instance_is_stt_provider() -> None:
+ assert isinstance(GeminiSTT(api_key="dummy"), STTProvider)
+
+
[email protected]("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
+ method is allowed — the OpenRouter STT plugin does the same for its
+ credential lookup."""
+ mod = importlib.import_module(mod_name)
+ source = Path(mod.__file__).read_text(encoding="utf-8")
+ offending = [
+ ln
+ for ln in source.splitlines()
+ # Only flag top-level (unindented) import statements.
+ if ln[:1] not in (" ", "\t")
+ and ln.startswith(("from jarvis", "import jarvis"))
+ ]
+ assert not offending, (
+ f"top-level jarvis.* imports leaked into {mod_name}: " + "; ".join(offending)
+ )
diff --git a/tests/unit/plugins/stt/test_gemini_stt.py b/tests/unit/plugins/stt/test_gemini_stt.py
new file mode 100644
index 0000000000..63102ddf5a
--- /dev/null
+++ b/tests/unit/plugins/stt/test_gemini_stt.py
@@ -0,0 +1,149 @@
+"""Unit tests for the Gemini STT plugin.
+
+Gemini has no HTTP wire we can mock at the transport layer — it transcribes via
+the ``google-genai`` client's ``generate_content``. So these inject a hand-rolled
+FAKE client (NOT ``unittest.mock``): a tiny object exposing
+``models.generate_content(...)`` that returns a fake response with ``.text``. No
+network, no SDK install, no ``jarvis.*`` monkeypatching needed for the happy path.
+"""
+from __future__ import annotations
+
+import asyncio
+import base64
+import io
+import wave
+from dataclasses import dataclass
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.plugins.stt.gemini_api import GeminiSTT, Transcript
+
+# ---------------------------------------------------------------------------
+# Fake google-genai client (records the outgoing call, returns a canned reply)
+# ---------------------------------------------------------------------------
+
+@dataclass
+class _FakeResponse:
+ text: str
+
+
+class _FakeModels:
+ def __init__(self, response: _FakeResponse, captured: dict) -> None:
+ self._response = response
+ self._captured = captured
+
+ def generate_content(self, *, model, contents, config): # noqa: ANN001
+ self._captured["model"] = model
+ self._captured["contents"] = contents
+ self._captured["config"] = config
+ return self._response
+
+
+class _FakeClient:
+ def __init__(self, text: str, captured: dict) -> None:
+ self.models = _FakeModels(_FakeResponse(text), captured)
+
+
+@dataclass
+class _FakeChunk:
+ pcm: bytes
+ sample_rate: int = 16_000
+ channels: int = 1
+ timestamp_ns: int = 0
+
+
+async def _async_iter(items):
+ for item in items:
+ yield item
+
+
+def _fake_pcm(seconds: float = 0.25, sample_rate: int = 16_000) -> bytes:
+ return b"\x00\x00" * int(sample_rate * seconds)
+
+
+def test_provider_identity_is_distinct_from_brain() -> None:
+ """The STT id must be ``gemini-api`` (the brain owns ``gemini``)."""
+ assert GeminiSTT.name == "gemini-api"
+ assert GeminiSTT.supports_streaming is False
+
+
+def test_transcribe_returns_text_and_sends_inline_wav_audio() -> None:
+ captured: dict = {}
+ pcm = _fake_pcm(0.4)
+ stt = GeminiSTT(client=_FakeClient("hello there", captured))
+
+ result = asyncio.run(stt.transcribe(_async_iter([_FakeChunk(pcm=pcm)])))
+
+ assert isinstance(result, Transcript)
+ assert result.text == "hello there"
+ assert result.confidence == 1.0
+ assert result.is_partial is False
+ assert result.segments == ()
+
+ # The audio rode as a base64 WAV inline_data part, and an instruction text
+ # part was included.
+ parts = captured["contents"][0]["parts"]
+ inline = parts[0]["inline_data"]
+ assert inline["mime_type"] == "audio/wav"
+ wav_bytes = base64.b64decode(inline["data"])
+ with wave.open(io.BytesIO(wav_bytes), "rb") as wav:
+ assert wav.getnchannels() == 1
+ assert wav.getsampwidth() == 2
+ assert wav.readframes(wav.getnframes()) == pcm
+ assert any("text" in p for p in parts[1:])
+
+
+def test_empty_pcm_returns_empty_transcript_without_calling_client() -> None:
+ captured: dict = {}
+ stt = GeminiSTT(client=_FakeClient("should not be used", captured))
+ result = asyncio.run(stt.transcribe_pcm(b""))
+ assert result.text == ""
+ assert result.confidence == 0.0
+ assert captured == {} # generate_content was never invoked
+
+
+def test_surrounding_quotes_are_stripped() -> None:
+ captured: dict = {}
+ stt = GeminiSTT(client=_FakeClient('"turn on the lights"', captured))
+ result = asyncio.run(stt.transcribe_pcm(_fake_pcm(0.2)))
+ assert result.text == "turn on the lights"
+
+
+def test_language_override_is_threaded_into_the_instruction() -> None:
+ captured: dict = {}
+ stt = GeminiSTT(client=_FakeClient("hello", captured))
+ asyncio.run(stt.transcribe_pcm(_fake_pcm(0.2), language="de"))
+ instruction = captured["contents"][0]["parts"][1]["text"]
+ assert "de" in instruction
+
+
+def test_stream_transcribe_yields_single_final() -> None:
+ captured: dict = {}
+ stt = GeminiSTT(client=_FakeClient("Test", captured))
+
+ async def drive():
+ out = []
+ async for t in stt.stream_transcribe(_async_iter([_FakeChunk(pcm=_fake_pcm(0.2))])):
+ out.append(t)
+ return out
+
+ results = asyncio.run(drive())
+ assert len(results) == 1
+ assert results[0].text == "Test"
+
+
+def test_missing_key_raises_clear_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ """No injected client / key AND no configured Gemini credential → a clear
+ English error so the STT factory degrades to the local floor (AP-22)."""
+ from jarvis.core import config as cfg
+
+ monkeypatch.setattr(
+ cfg,
+ "resolve_provider_endpoint",
+ lambda *a, **k: SimpleNamespace(credential="", base_url=None, via_proxy=False),
+ )
+
+ stt = GeminiSTT() # no client, no api_key
+ with pytest.raises(RuntimeError, match="Gemini API key"):
+ asyncio.run(stt.transcribe_pcm(_fake_pcm(0.2)))
diff --git a/tests/unit/plugins/stt/test_openai_stt.py b/tests/unit/plugins/stt/test_openai_stt.py
new file mode 100644
index 0000000000..f1fb967610
--- /dev/null
+++ b/tests/unit/plugins/stt/test_openai_stt.py
@@ -0,0 +1,197 @@
+"""Unit tests for the OpenAI Whisper STT plugin.
+
+Covers the wire contract (WAV multipart upload, Bearer auth, model + language
+fields), response parsing, and the missing-key / HTTP-error fallbacks that let
+the STT factory degrade to the local floor (AP-22).
+
+These use ``httpx.MockTransport`` (a fake transport, not ``unittest.mock``) so no
+real network call is made and the exact outgoing request can be asserted.
+"""
+from __future__ import annotations
+
+import asyncio
+import io
+import wave
+from dataclasses import dataclass
+from types import SimpleNamespace
+
+import httpx
+import pytest
+
+from jarvis.plugins.stt.openai_api import (
+ DEFAULT_MODEL,
+ OpenAIWhisperAPI,
+ Transcript,
+)
+
+
+@dataclass
+class _FakeChunk:
+ """Minimal AudioChunk duck-type for STT input."""
+
+ pcm: bytes
+ sample_rate: int = 16_000
+ channels: int = 1
+ timestamp_ns: int = 0
+
+
+async def _async_iter(items):
+ for item in items:
+ yield item
+
+
+def _fake_pcm(seconds: float = 0.25, sample_rate: int = 16_000) -> bytes:
+ return b"\x00\x00" * int(sample_rate * seconds)
+
+
+def _mock_client(handler) -> httpx.AsyncClient:
+ return httpx.AsyncClient(transport=httpx.MockTransport(handler))
+
+
+def test_provider_identity_is_distinct_from_brain() -> None:
+ """The STT id must be ``openai-api`` (the brain owns ``openai``) and be
+ non-streaming."""
+ assert OpenAIWhisperAPI.name == "openai-api"
+ assert OpenAIWhisperAPI.supports_streaming is False
+
+
+def test_transcribe_uploads_wav_and_parses_response() -> None:
+ captured: dict[str, object] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["url"] = str(request.url)
+ captured["auth"] = request.headers.get("authorization")
+ captured["body"] = request.content
+ body = {
+ "text": "hello world",
+ "language": "en",
+ "segments": [
+ {"start": 0.0, "end": 0.7, "text": "hello world", "avg_logprob": -0.2},
+ ],
+ }
+ return httpx.Response(200, json=body)
+
+ provider = OpenAIWhisperAPI(api_key="test-key-xxx", http_client=_mock_client(handler))
+ chunks = [_FakeChunk(pcm=_fake_pcm(0.5))]
+ result = asyncio.run(provider.transcribe(_async_iter(chunks)))
+
+ assert isinstance(result, Transcript)
+ assert result.text == "hello world"
+ assert result.language == "en"
+ assert 0.0 < result.confidence <= 1.0
+ assert result.is_partial is False
+ assert len(result.segments) == 1
+
+ assert captured["auth"] == "Bearer test-key-xxx"
+ assert str(captured["url"]).endswith("/audio/transcriptions")
+ assert "api.openai.com" in str(captured["url"])
+ # The multipart body must contain a real WAV and the whisper-1 model field.
+ assert b"RIFF" in captured["body"]
+ assert b"WAVE" in captured["body"]
+ assert DEFAULT_MODEL.encode() in captured["body"]
+
+
+def test_empty_audio_returns_empty_transcript_without_http() -> None:
+ calls = {"n": 0}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls["n"] += 1
+ return httpx.Response(500, text="should not be called")
+
+ provider = OpenAIWhisperAPI(api_key="k", http_client=_mock_client(handler))
+ result = asyncio.run(provider.transcribe(_async_iter([])))
+ assert result.text == ""
+ assert result.confidence == 0.0
+ assert calls["n"] == 0
+
+
+def test_language_is_sent_when_set_and_omitted_when_auto() -> None:
+ captured: dict[str, bytes] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = request.content
+ return httpx.Response(200, json={"text": "ok", "language": "de", "segments": []})
+
+ prov = OpenAIWhisperAPI(api_key="k", language="de", http_client=_mock_client(handler))
+ asyncio.run(prov.transcribe_pcm(_fake_pcm(0.2)))
+ assert b'name="language"' in captured["body"] # language field present
+
+ prov2 = OpenAIWhisperAPI(api_key="k", language="auto", http_client=_mock_client(handler))
+ asyncio.run(prov2.transcribe_pcm(_fake_pcm(0.2)))
+ # "auto" is treated as unset — no language multipart field named "language".
+ assert b'name="language"' not in captured["body"]
+
+
+def test_stream_transcribe_yields_single_final() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json={"text": "Test", "language": "en", "segments": []})
+
+ provider = OpenAIWhisperAPI(api_key="k", http_client=_mock_client(handler))
+ chunks = [_FakeChunk(pcm=_fake_pcm(0.3))]
+
+ async def drive():
+ out = []
+ async for t in provider.stream_transcribe(_async_iter(chunks)):
+ out.append(t)
+ return out
+
+ results = asyncio.run(drive())
+ assert len(results) == 1
+ assert results[0].text == "Test"
+
+
+def test_missing_key_raises_clear_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ """With no injected key AND no configured credential, a clear English error
+ is raised so the STT factory degrades to the local floor (AP-22)."""
+ from jarvis.core import config as cfg
+
+ monkeypatch.setattr(
+ cfg,
+ "resolve_provider_endpoint",
+ lambda *a, **k: SimpleNamespace(
+ credential="", base_url="https://api.openai.com/v1", via_proxy=False
+ ),
+ )
+ monkeypatch.setattr(cfg, "secret_revision", lambda _key: 0)
+
+ provider = OpenAIWhisperAPI() # no api_key injected
+ with pytest.raises(RuntimeError, match="OpenAI API key"):
+ asyncio.run(provider.transcribe_pcm(_fake_pcm(0.2)))
+
+
+ "status,needle",
+ [
+ (401, "invalid or missing"),
+ (402, "out of credit"),
+ (429, "rate limit"),
+ ],
+)
+def test_http_errors_raise_clear_runtime_error(status: int, needle: str) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(status, json={"error": {"message": "boom"}})
+
+ provider = OpenAIWhisperAPI(api_key="k", http_client=_mock_client(handler))
+ with pytest.raises(RuntimeError) as excinfo:
+ asyncio.run(provider.transcribe_pcm(_fake_pcm(0.2)))
+ assert needle in str(excinfo.value)
+
+
+def test_wraps_pcm_into_valid_wav_container() -> None:
+ captured: dict[str, bytes] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = request.content
+ return httpx.Response(200, json={"text": "ok", "language": "de", "segments": []})
+
+ provider = OpenAIWhisperAPI(api_key="k", http_client=_mock_client(handler))
+ asyncio.run(provider.transcribe_pcm(_fake_pcm(0.4)))
+
+ body = captured["body"]
+ riff_idx = body.find(b"RIFF")
+ assert riff_idx >= 0, "no RIFF header in upload body"
+ with wave.open(io.BytesIO(body[riff_idx:]), "rb") as wav:
+ assert wav.getnchannels() == 1
+ assert wav.getsampwidth() == 2
+ assert wav.getframerate() == 16_000
+ assert wav.getnframes() > 0