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): make the configured model and temperature reach every provider

Ruben Lütke5ee8c2889cf5
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index f3d3c0f782..71841da4bb 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -504,6 +504,22 @@ class STTConfig(BaseModel):
# ignores it because an initial-prompt on silent audio used to
# hallucinate the prompt itself as the transcript.
bias_prompt: str = ""
+ # Which model each CLOUD recognizer uses, keyed by provider id
+ # (``{"openrouter-stt": "openai/gpt-4o-transcribe"}``). A per-provider slot
+ # rather than one global value, because ``model`` above is a
+ # faster-whisper checkpoint name and a checkpoint name is meaningless to a
+ # hosted API — forwarding one global string to whichever provider happened
+ # to be selected is how a picked cloud model reached no provider at all
+ # and a fresh install would have posted ``large-v3-turbo`` to Groq.
+ # Unset (the default) means "the plugin's own default model", which is the
+ # behaviour every install had before this key existed.
+ models: dict[str, str] = Field(default_factory=dict)
+ # Sampling temperature for transcription. ``0.0`` on purpose and by
+ # default: transcription is a measurement, so the same recording has to
+ # come back the same way twice. Forwarded only to providers whose model
+ # accepts the field (``jarvis.plugins.stt.capabilities``), so a backend
+ # that rejects it keeps working.
+ temperature: float = Field(default=0.0, ge=0.0, le=1.0)
class TTSConfig(BaseModel):
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index 89dbd0f8d2..142fdcd1ee 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -507,6 +507,66 @@ def set_stt_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
log.warning("Could not sync %s to the User environment: %s", _STT_MODEL_ENV, exc)
+def set_stt_provider_model(
+ provider: str, model: str, *, path: Path = DEFAULT_CONFIG_FILE
+) -> dict[str, str]:
+ """Pin ONE provider's transcription model (``[stt.models].<provider>``).
+
+ Returns the full mapping after the write, so a caller can update the live
+ config object without re-reading the file.
+
+ Why per provider rather than the single ``[stt] model``: that key holds a
+ faster-whisper CHECKPOINT name, which means nothing to a hosted API. One
+ global value therefore could not be forwarded to a cloud recognizer without
+ a fresh install posting ``large-v3-turbo`` to Groq — so the picker's choice
+ reached no provider at all and the dropdown changed nothing (AP-31).
+
+ Two layers, not three: the mapping is a TOML sub-table, and the ENV
+ override this repo uses for single-word keys (``JARVIS__STT__MODEL``) has
+ no shape that could carry it. The ``config-soll`` sync is what keeps the # i18n-allow
+ drift guard from reverting the pin, which is the layer that actually
+ mattered for the single-word keys anyway.
+
+ An empty ``model`` REMOVES the pin, which is how a user goes back to the
+ provider's own default without hand-editing anything.
+ """
+ key = str(provider or "").strip()
+ if not key:
+ raise ValueError("A provider id is required to pin an STT model.")
+ value = str(model or "").strip()
+ path = _ensure_writable_config_path(path)
+
+ with _WRITE_LOCK:
+ raw = path.read_text(encoding="utf-8")
+ had_bom = raw.startswith(_BOM)
+ if had_bom:
+ raw = raw[len(_BOM) :]
+ doc: TOMLDocument = tomlkit.parse(raw)
+ section = doc.get("stt")
+ if section is None:
+ section = tomlkit.table()
+ doc["stt"] = section
+ models = section.get("models")
+ if models is None:
+ models = tomlkit.table()
+ section["models"] = models
+ if value:
+ models[key] = value
+ else:
+ models.pop(key, None)
+ merged = {str(k): str(v) for k, v in models.items()}
+ out = tomlkit.dumps(doc)
+ if had_bom:
+ out = _BOM + out
+ _atomic_write(path, out)
+
+ try:
+ _update_config_soll_section("stt", {"models": merged}) # i18n-allow
+ except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
+ log.warning("Could not sync stt.models to config-soll.json: %s", exc) # i18n-allow
+ return merged
+
+
def set_stt_language(language: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set the STT recognition language (``[stt] language``).
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index 9e738a0549..d785de357a 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -64,7 +64,46 @@ _STT_CROSS_FAMILY_ORDER: tuple[str, ...] = (
# with every one of them dropped rather than falling all the way through to the
# local engine a base install does not ship. Anything NOT listed here (the
# language, the team-proxy endpoint/key) is load-bearing and never dropped.
-_OPTIONAL_PROVIDER_KWARGS: tuple[str, ...] = ("prompt", "timeout_s")
+_OPTIONAL_PROVIDER_KWARGS: tuple[str, ...] = (
+ "prompt", "timeout_s", "model", "temperature",
+)
+
+
+def resolve_stt_model(stt_cfg: Any, provider_name: str) -> str:
+ """The model id to hand ``provider_name``; ``""`` for "your own default".
+
+ ``[stt].model`` is a faster-whisper CHECKPOINT name (``large-v3-turbo``),
+ and a checkpoint name means nothing to a hosted API. One global value
+ forwarded to whichever provider is selected would therefore post
+ ``large-v3-turbo`` to Groq on a fresh install — so the cloud pick lives in
+ its own per-provider slot, ``[stt].models.<provider id>``, written by the
+ model picker and read here.
+
+ Precedence:
+
+ 1. **The per-provider pin**, when this install has one.
+ 2. **``""``** otherwise: the plugin's own default, i.e. exactly what every
+ install did before per-provider pins existed.
+
+ ``[stt].model`` is deliberately NOT a fallback here. It reaches the local
+ engine through :func:`_build_local_fallback`, which is the one consumer a
+ checkpoint name is the right kind of string for; letting it leak into this
+ answer would hand ``large-v3-turbo`` to a hosted API or to the on-device
+ Nemotron recognizer, neither of which has ever heard of it.
+
+ Never raises: a config object that carries none of this (a test double, a
+ stale install) answers ``""``, which is a working value everywhere.
+ """
+ name = (provider_name or "").strip()
+ if not name:
+ return ""
+ try:
+ pins = getattr(stt_cfg, "models", None) or {}
+ pinned = str(pins.get(name, "") or "").strip() if hasattr(pins, "get") else ""
+ except Exception as exc: # noqa: BLE001 — a malformed pin is not worth a build
+ logger.debug("STT per-provider model pin unreadable ({}); using defaults.", exc)
+ pinned = ""
+ return pinned
def _stt_has_credential(provider_name: str, kwargs: dict[str, Any]) -> bool:
@@ -375,6 +414,25 @@ def build_stt_from_config(stt_cfg: Any) -> Any:
kwargs["language"] = language
if bias_prompt:
kwargs["prompt"] = bias_prompt
+ # The model the USER picked. Until this line existed, the STT model
+ # picker wrote a value nothing read: every cloud plugin transcribed on
+ # its own hardcoded default, so choosing a genuinely multilingual model
+ # in the app changed exactly nothing (AP-31).
+ chosen_model = resolve_stt_model(stt_cfg, provider_name)
+ if chosen_model:
+ kwargs["model"] = chosen_model
+ # Reproducibility. A transcription is a measurement, so the same audio
+ # must come back the same way twice; the providers whose model rejects
+ # the field drop it themselves (jarvis.plugins.stt.capabilities).
+ temperature = getattr(stt_cfg, "temperature", None)
+ try:
+ if temperature is not None:
+ kwargs["temperature"] = float(temperature)
+ except (TypeError, ValueError):
+ logger.debug(
+ "STT temperature {!r} is not a number; using the provider default.",
+ temperature,
+ )
# Per-request timeout. Forwarded only when the config actually carries
# one, so every provider keeps its own documented default otherwise. It
# matters most for Gemini: google-genai FORCES ``timeout=None`` on its
@@ -414,7 +472,12 @@ def build_stt_from_config(stt_cfg: Any) -> Any:
# (AP-21). The user's STT dictionary still applies to these providers
# through its post-transcription corrections.
if provider_runs_on_device(provider_name):
- for cloud_only in ("prompt", "timeout_s"):
+ # ``temperature`` joins the cloud-only set for the same reason:
+ # the on-device recognizers this repo ships configure their own
+ # decoding, and offering it only earns the misleading "this plugin
+ # is out of date" warning from the TypeError retry below. A model
+ # PIN is not stripped — that is an explicit per-provider choice.
+ for cloud_only in ("prompt", "timeout_s", "temperature"):
kwargs.pop(cloud_only, None)
if not _stt_has_credential(provider_name, kwargs):
logger.warning(
@@ -427,9 +490,12 @@ def build_stt_from_config(stt_cfg: Any) -> Any:
try:
instance = cls(**kwargs) if kwargs else cls()
logger.info(
- "STT provider resolved via entry-point: {} (class {}, bias_prompt={} chars)",
+ "STT provider resolved via entry-point: {} (class {}, model={}, "
+ "temperature={}, bias_prompt={} chars)",
provider_name,
cls.__name__,
+ kwargs.get("model") or "<provider default>",
+ kwargs.get("temperature", "<provider default>"),
len(bias_prompt),
)
return instance
@@ -1160,6 +1226,7 @@ __all__ = [
"mark_wake_gpu_bad",
"provider_runs_on_device",
"resolve_keyed_stt_fallback",
+ "resolve_stt_model",
"start_wake_model_prefetch",
"stt_family_id",
"wake_gpu_probe_cached",
diff --git a/jarvis/plugins/stt/capabilities.py b/jarvis/plugins/stt/capabilities.py
new file mode 100644
index 0000000000..2007f6c4d1
--- /dev/null
+++ b/jarvis/plugins/stt/capabilities.py
@@ -0,0 +1,291 @@
+"""Which fields ONE transcription request may carry — asked of the MODEL.
+
+Why this is not a per-provider constant
+---------------------------------------
+Every hosted transcription endpoint in this repo speaks the same OpenAI-shaped
+dialect, and yet they do not accept the same request. ``whisper-1`` answers
+``response_format = "verbose_json"`` with per-segment timings and log
+probabilities; ``gpt-4o-transcribe`` — the newer, genuinely multilingual model
+this lane wants — rejects that value outright with HTTP 400 and transcribes
+nothing. The same split runs through ``temperature`` and the bias ``prompt`` on
+the ten-odd backends the OpenRouter gateway fronts.
+
+So the shape of a request is a property of the MODEL, not of the vendor whose
+URL it is posted to, and a plugin that hardcodes one shape can only ever be
+correct for the models that existed when it was written. That is the failure
+this module removes: sending a field the model does not support turns the whole
+utterance into an error, and the user hears nothing back with no way to tell
+that ONE optional field was the cause.
+
+Two layers, and the second is the one that survives a model we have never seen
+-----------------------------------------------------------------------------
+1. **A declared default** (:func:`declared_shape`) keyed on markers in the model
+ id — not on a provider name (AP-21). Whisper-family checkpoints get the full
+ shape; anything else starts on the universal subset, because ``json`` is the
+ one response format every transcription endpoint has ever accepted.
+2. **A rejection is evidence** (:func:`shape_after_rejection`). When the service
+ answers 400 and names a field, that field is dropped and the call retried —
+ once per field — and the narrowed shape is remembered for the rest of the
+ process (:func:`remember_shape`). A model released tomorrow therefore costs
+ at most one wasted round trip on its first use instead of bricking the lane
+ until somebody edits a table here.
+
+The memory is deliberately process-local. A capability verdict written to disk
+is a verdict nobody re-probes (AP-25's sticky-cache trap in miniature): a
+provider having a bad minute would otherwise pin a model to a degraded shape
+across every future restart with nothing in the log explaining why.
+
+Import-clean by construction: no ``jarvis.*`` import at any level, so every STT
+plugin — including the one held to a total import ban — can use it.
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+from dataclasses import dataclass, replace
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+#: How many times ONE upload may be re-shaped before the error is surfaced.
+#: There are four optional fields plus the model substitution, and a service
+#: that objects to every one of them is not going to transcribe anything —
+#: reporting that is more useful than a fifth attempt.
+MAX_REQUEST_DOWNGRADES = 5
+
+#: The response format every transcription endpoint accepts. Anything richer is
+#: a capability, never an assumption.
+UNIVERSAL_RESPONSE_FORMAT = "json"
+
+#: The format that additionally carries per-segment timings and ``avg_logprob``
+#: (which is where the confidence figure comes from).
+RICH_RESPONSE_FORMAT = "verbose_json"
+
+
+@dataclass(frozen=True, slots=True)
+class RequestShape:
+ """What one transcription request is allowed to contain.
+
+ Every field is a permission, never an instruction: a ``True`` says the
+ model would accept the field, and the caller still decides whether it has
+ anything to put in it.
+ """
+
+ #: May carry a ``language`` field (a pinned recognition language).
+ language: bool = True
+ #: May carry a bias ``prompt`` (vocabulary priming).
+ prompt: bool = True
+ #: May carry a ``temperature``.
+ temperature: bool = True
+ #: May ask for ``verbose_json`` — segments, timings, ``avg_logprob``.
+ verbose_json: bool = True
+
+ @property
+ def response_format(self) -> str:
+ """The ``response_format`` value this model actually accepts."""
+ return RICH_RESPONSE_FORMAT if self.verbose_json else UNIVERSAL_RESPONSE_FORMAT
+
+
+#: The full shape — everything the OpenAI audio API has ever offered.
+FULL_SHAPE = RequestShape()
+
+#: The subset every transcription endpoint accepts. Used for a model whose id
+#: tells us nothing, so an unknown model degrades to "works" rather than to a
+#: 400 nobody can read.
+UNIVERSAL_SHAPE = RequestShape(verbose_json=False)
+
+
+#: Model-id markers that identify a Whisper-family checkpoint. Whisper is the
+#: only transcription family that has always accepted the rich response format,
+#: and its id says so on every vendor that hosts it (``whisper-1``,
+#: ``whisper-large-v3``, ``openai/whisper-large-v3-turbo``, …).
+_WHISPER_MARKERS: tuple[str, ...] = ("whisper",)
+
+
+def declared_shape(model: str | None) -> RequestShape:
+ """The shape to START a model on, before any service has objected.
+
+ Whisper-family ids get the full shape (that is what their consumers have
+ relied on for years — segment timings feed the confidence figure). Every
+ other id, known or not, starts on :data:`UNIVERSAL_SHAPE`: plain ``json``
+ plus the optional fields, which is what ``gpt-4o-transcribe`` and the
+ gateway-hosted models accept. Being wrong in this direction costs a
+ confidence number; being wrong in the other direction costs the utterance.
+ """
+ name = str(model or "").strip().lower()
+ if not name:
+ return UNIVERSAL_SHAPE
+ if any(marker in name for marker in _WHISPER_MARKERS):
+ return FULL_SHAPE
+ return UNIVERSAL_SHAPE
+
+
+#: Field name → the words a service uses when it refuses that field. Ordered:
+#: the response format is checked first because a message about
+#: ``verbose_json`` also contains the word ``response_format`` and nothing
+#: else, while a message about ``temperature`` names only itself.
+_REJECTION_MARKERS: tuple[tuple[str, tuple[str, ...]], ...] = (
+ ("verbose_json", ("verbose_json", "response_format", "response format")),
+ ("temperature", ("temperature",)),
+ ("prompt", ("prompt",)),
+ ("language", ("language",)),
+)
+
+
+def shape_after_rejection(shape: RequestShape, message: str) -> RequestShape | None:
+ """``shape`` minus the field ``message`` complained about, or ``None``.
+
+ ``None`` means the refusal was not about an optional field — a dead key, a
+ missing model, an audio format the endpoint will not take — and the caller
+ must surface it instead of quietly retrying. That distinction is the whole
+ safety of this mechanism: a retry ladder that treats every 400 as "drop
+ something and try again" would strip a request down to nothing and report
+ the last, least informative error.
+
+ Only fields currently ENABLED can be dropped, so a repeated complaint about
+ a field we already removed cannot spin the caller in a loop.
+ """
+ text = str(message or "").lower()
+ if not text:
+ return None
+ for field_name, markers in _REJECTION_MARKERS:
+ if not getattr(shape, field_name, False):
+ continue
+ if any(marker in text for marker in markers):
+ return replace(shape, **{field_name: False})
+ return None
+
+
+# ---------------------------------------------------------------------------
+# What this process has LEARNED about a model, from the services themselves
+# ---------------------------------------------------------------------------
+
+_lock = threading.Lock()
+_learned: dict[tuple[str, str], RequestShape] = {}
+
+
+def _key(vendor: str, model: str | None) -> tuple[str, str]:
+ return (str(vendor or "").strip().lower(), str(model or "").strip().lower())
+
+
+def remember_shape(vendor: str, model: str | None, shape: RequestShape) -> None:
+ """Record that ``vendor``/``model`` accepts at most ``shape``.
+
+ Narrowing only: two concurrent calls that each learn a different rejection
+ must end with BOTH fields dropped, not with whichever call finished last.
+ """
+ key = _key(vendor, model)
+ with _lock:
+ known = _learned.get(key)
+ if known is None:
+ _learned[key] = shape
+ return
+ _learned[key] = RequestShape(
+ language=known.language and shape.language,
+ prompt=known.prompt and shape.prompt,
+ temperature=known.temperature and shape.temperature,
+ verbose_json=known.verbose_json and shape.verbose_json,
+ )
+
+
+def resolve_shape(vendor: str, model: str | None) -> RequestShape:
+ """The shape to send right now — what we learned, else what we declared."""
+ with _lock:
+ known = _learned.get(_key(vendor, model))
+ return known if known is not None else declared_shape(model)
+
+
+def reset_learned_shapes() -> None:
+ """Forget every learned narrowing. Test-isolation hook."""
+ with _lock:
+ _learned.clear()
+
+
+# ---------------------------------------------------------------------------
+# The model itself was refused
+# ---------------------------------------------------------------------------
+
+#: What a service says when the MODEL — not a field — is the problem. A user
+#: who pinned a model their account cannot call must still be able to dictate,
+#: so the caller falls back to its own default model once and says so out loud.
+#: Deliberately narrow: a phrase that also appears in an unrelated 400 would
+#: hide a real configuration error behind a silent substitution.
+_MODEL_REJECTION_MARKERS: tuple[str, ...] = (
+ "model_not_found",
+ "model not found",
+ "does not exist",
+ "no such model",
+ "unknown model",
+ "invalid model",
+ "unsupported model",
+ "is not a valid model",
+ "not available",
+)
+
+
+def is_model_rejection(message: str, model: str | None = None) -> bool:
+ """Whether ``message`` says the requested MODEL is unusable here.
+
+ ``model`` is accepted so a caller can be sure the complaint is about the id
+ it sent; when the id does not appear in the message the markers alone
+ decide, because several services report the model error without echoing it.
+ """
+ text = str(message or "").lower()
+ if not text:
+ return False
+ return any(marker in text for marker in _MODEL_REJECTION_MARKERS)
+
+
+def error_text(response: Any) -> str:
+ """The service's own words for a failed request, as a plain string.
+
+ Duck-typed rather than typed against ``httpx``: this module is imported by
+ the one plugin held to a total ``jarvis.*``-and-nothing-heavy contract, and
+ reading two attributes needs no HTTP library. An unreadable body answers
+ ``""``, which every caller treats as "no evidence, do not retry".
+ """
+ try:
+ text = getattr(response, "text", "") or ""
+ except Exception: # noqa: BLE001 — a body we cannot read is simply no evidence
+ return ""
+ return str(text)[:2000]
+
+
+def log_model_fallback(
+ vendor: str, requested: str, fallback: str, detail: str = ""
+) -> None:
+ """Say out loud that a pinned model was refused and what ran instead.
+
+ A silent substitution is the failure this repo calls AP-31 from the other
+ side: the model picker would keep showing a choice that no request has used
+ for weeks. One WARNING per occurrence, naming both ids and the service's
+ own reason, is what makes that visible in a log somebody can read.
+ """
+ log.warning(
+ "%s refused the configured transcription model %r (%s); this request "
+ "used %r instead so dictation keeps working. Pick a model your account "
+ "can call in the app's provider view to stop the substitution.",
+ vendor,
+ requested,
+ (detail or "no detail").strip()[:200],
+ fallback,
+ )
+
+
+__all__ = [
+ "FULL_SHAPE",
+ "MAX_REQUEST_DOWNGRADES",
+ "RICH_RESPONSE_FORMAT",
+ "UNIVERSAL_RESPONSE_FORMAT",
+ "UNIVERSAL_SHAPE",
+ "RequestShape",
+ "declared_shape",
+ "error_text",
+ "is_model_rejection",
+ "log_model_fallback",
+ "remember_shape",
+ "reset_learned_shapes",
+ "resolve_shape",
+ "shape_after_rejection",
+]
diff --git a/jarvis/plugins/stt/gemini_api.py b/jarvis/plugins/stt/gemini_api.py
index 063bd176c2..b8740e3c59 100644
--- a/jarvis/plugins/stt/gemini_api.py
+++ b/jarvis/plugins/stt/gemini_api.py
@@ -318,23 +318,48 @@ class GeminiSTT:
# ``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:
+
+ async def _generate(model: str) -> Any:
# 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(
+ return await asyncio.to_thread(
client.models.generate_content,
- model=self._model,
+ model=model,
contents=contents,
config=config,
)
+
+ model = self._model
+ try:
+ response = await _generate(model)
except Exception as exc: # noqa: BLE001 — degrade honestly (AP-22)
# Imported here, not at module top, to keep the plugin
# ``jarvis.*``-free at import time (the entry-point purity contract)
# — the same lazy seam the credential lookup uses. This runs only on
# an already-failed request.
+ from jarvis.plugins.stt.capabilities import (
+ is_model_rejection,
+ log_model_fallback,
+ )
from jarvis.plugins.stt.errors import STTHTTPError, status_from_exception
- message = f"Gemini STT request failed: {exc}"
+ failure: BaseException = exc
+ # A model this account cannot call is a CONFIGURATION problem, not a
+ # reason to lose the utterance: fall back to the default model once
+ # and say so, exactly like the OpenAI-shaped plugins. A failure of
+ # the FALLBACK is reported through the same classification path
+ # below — a raw SDK error escaping here would cost the caller the
+ # status code its retry ladder runs on.
+ if model != DEFAULT_MODEL and is_model_rejection(str(exc), model):
+ log_model_fallback("Gemini", model, DEFAULT_MODEL, str(exc))
+ try:
+ return _response_to_transcript(
+ await _generate(DEFAULT_MODEL), language
+ )
+ except Exception as retry_exc: # noqa: BLE001 — classify, never leak
+ failure = retry_exc
+
+ message = f"Gemini STT request failed: {failure}"
# The SDK raises its own ``APIError``, which carries the HTTP status
# as ``.code``. Flattening that into a bare RuntimeError threw away
# the one fact the caller needs to tell a retryable 429 from a
@@ -343,14 +368,14 @@ class GeminiSTT:
# type (google-genai is absent on a base install), hence the
# duck-typed lookup. A transport error / timeout has no status and
# stays a plain RuntimeError: inventing one would be a lie.
- status = status_from_exception(exc)
+ status = status_from_exception(failure)
if status is None:
- raise RuntimeError(message) from exc
+ raise RuntimeError(message) from failure
raise STTHTTPError(
message,
status=status,
- headers=getattr(getattr(exc, "response", None), "headers", None),
- ) from exc
+ headers=getattr(getattr(failure, "response", None), "headers", None),
+ ) from failure
return _response_to_transcript(response, language)
diff --git a/jarvis/plugins/stt/groq_api.py b/jarvis/plugins/stt/groq_api.py
index 92af27859a..b37c56f578 100644
--- a/jarvis/plugins/stt/groq_api.py
+++ b/jarvis/plugins/stt/groq_api.py
@@ -235,38 +235,75 @@ class GroqWhisperAPI:
# `.opus` must not be announced as `audio.wav`.
upload_name = _upload_name(filename)
mime = "audio/wav" if upload_name.endswith(".wav") else "application/octet-stream"
- files = {"file": (upload_name, wav_bytes, mime)}
- data: dict[str, str] = {
- "model": self._model,
- "response_format": "verbose_json",
- "temperature": str(self._temperature),
- }
- # Omitted entirely when None — that is what asks Whisper to detect the
- # spoken language instead of decoding it as a pinned one.
- if language:
- data["language"] = language
- if self._prompt:
- data["prompt"] = self._prompt
-
headers = {"Authorization": f"Bearer {self._api_key}"}
client = self._get_client()
- response = await client.post(
- self._endpoint, headers=headers, data=data, files=files
+
+ from jarvis.plugins.stt.capabilities import (
+ MAX_REQUEST_DOWNGRADES,
+ error_text,
+ is_model_rejection,
+ log_model_fallback,
+ remember_shape,
+ resolve_shape,
+ shape_after_rejection,
)
- # ``httpx.HTTPStatusError`` carries the status on ``.response.status_code``
- # and the ``Retry-After`` header on ``.response.headers`` — which is
- # exactly why the pipeline's transient-error retry ladder worked for THIS
- # provider and for no other one, and what the shared
- # ``jarvis.plugins.stt.errors.STTHTTPError`` reproduces for the plugins
- # that used to flatten every status into a bare RuntimeError. This plugin
- # deliberately does NOT raise that shared type: it is the one STT plugin
- # held to a total ``jarvis.*``-import ban (CLAUDE.md §5, pinned by
- # tests/contract/test_stt_protocol.py), even for a lazy import inside a
- # method. It already emits the classifiable shape, so there is nothing to
- # gain and a purity contract to lose. Do not "unify" this line.
+
+ model = self._model
+ shape = resolve_shape(self.name, model)
+ for _attempt in range(MAX_REQUEST_DOWNGRADES):
+ # A fresh file tuple per attempt: httpx consumes the buffer it is
+ # handed, so a retry with the same object would upload nothing.
+ files = {"file": (upload_name, wav_bytes, mime)}
+ data: dict[str, str] = {
+ "model": model,
+ "response_format": shape.response_format,
+ }
+ if shape.temperature:
+ data["temperature"] = str(self._temperature)
+ # Omitted entirely when None — that is what asks Whisper to detect
+ # the spoken language instead of decoding it as a pinned one.
+ if language and shape.language:
+ data["language"] = language
+ if self._prompt and shape.prompt:
+ data["prompt"] = self._prompt
+
+ response = await client.post(
+ self._endpoint, headers=headers, data=data, files=files
+ )
+ if response.status_code == 400:
+ # A refusal that names an optional field is EVIDENCE about the
+ # model, not a failure: drop that field and ask again, so a
+ # transcription model with a narrower contract than Whisper's
+ # still transcribes instead of losing the utterance.
+ detail = error_text(response)
+ narrowed = shape_after_rejection(shape, detail)
+ if narrowed is not None:
+ remember_shape(self.name, model, narrowed)
+ shape = narrowed
+ continue
+ if model != DEFAULT_MODEL and is_model_rejection(detail, model):
+ log_model_fallback("Groq", model, DEFAULT_MODEL, detail)
+ model = DEFAULT_MODEL
+ shape = resolve_shape(self.name, model)
+ continue
+ # ``httpx.HTTPStatusError`` carries the status on
+ # ``.response.status_code`` and the ``Retry-After`` header on
+ # ``.response.headers`` — which is exactly why the pipeline's
+ # transient-error retry ladder worked for THIS provider and for no
+ # other one, and what the shared
+ # ``jarvis.plugins.stt.errors.STTHTTPError`` reproduces for the
+ # plugins that used to flatten every status into a bare
+ # RuntimeError. This plugin deliberately does NOT raise that shared
+ # type: it is the one STT plugin held to a total ``jarvis.*``-import
+ # ban outside its own plugin package (CLAUDE.md §5, pinned by
+ # tests/contract/test_stt_protocol.py). It already emits the
+ # classifiable shape, so there is nothing to gain and a purity
+ # contract to lose. Do not "unify" this line.
+ response.raise_for_status()
+ return _payload_to_transcript(response.json())
+
response.raise_for_status()
- payload = response.json()
- return _payload_to_transcript(payload)
+ return _payload_to_transcript(response.json())
# ----------------------------------------------------------------------
diff --git a/jarvis/plugins/stt/openai_api.py b/jarvis/plugins/stt/openai_api.py
index acb22dbd37..4a285131e5 100644
--- a/jarvis/plugins/stt/openai_api.py
+++ b/jarvis/plugins/stt/openai_api.py
@@ -10,14 +10,21 @@ shipped no plugin, so an OpenAI-only user dead-ended on the local
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``.
+ * multipart fields: ``file`` (an in-memory WAV), ``model``, ``response_format``,
+ optional ``language`` / ``prompt`` / ``temperature``.
+
+The wire contract is NOT the same for every model, which is why the request is
+built from a per-model capability shape (:mod:`jarvis.plugins.stt.capabilities`)
+rather than from constants: ``whisper-1`` answers ``verbose_json`` with segment
+timings and log probabilities, while ``gpt-4o-transcribe`` rejects that value
+with HTTP 400 and transcribes nothing. A 400 that names an optional field
+narrows the shape and retries; a 400 that names the MODEL falls back to the
+default model once, loudly.
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.
+field and the request adapts itself to that model's contract.
Plugin contract: structurally compatible with
``jarvis.core.protocols.STTProvider`` WITHOUT importing ``jarvis.*`` at import
@@ -311,40 +318,87 @@ class OpenAIWhisperAPI:
filename: str = "audio.wav",
language: str | None = None,
) -> Transcript:
+ """POST one upload, adapting the request to what the MODEL accepts.
+
+ ``whisper-1`` answers ``verbose_json``; ``gpt-4o-transcribe`` — the
+ newer multilingual model — rejects that value with HTTP 400 and
+ transcribes nothing. The request is therefore built from a per-model
+ capability shape, and a 400 that names an optional field narrows that
+ shape and retries instead of losing the utterance
+ (:mod:`jarvis.plugins.stt.capabilities`).
+ """
url = self._ensure_endpoint()
# The NAME is how the service identifies the container, so an imported
# `.opus` must not be announced as `audio.wav`. The content type stays
# generic: the extension is the signal these APIs actually read.
upload_name = _upload_name(filename)
mime = "audio/wav" if upload_name.endswith(".wav") else "application/octet-stream"
- files = {"file": (upload_name, wav_bytes, mime)}
- data: dict[str, str] = {
- "model": self._model,
- "response_format": "verbose_json",
- "temperature": str(self._temperature),
- }
- # Omitted entirely when None — that is what asks Whisper to detect the
- # spoken language instead of decoding it as a pinned one.
- if language:
- data["language"] = 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:
+ from jarvis.plugins.stt.capabilities import (
+ MAX_REQUEST_DOWNGRADES,
+ error_text,
+ is_model_rejection,
+ log_model_fallback,
+ remember_shape,
+ resolve_shape,
+ shape_after_rejection,
+ )
+
+ model = self._model
+ shape = resolve_shape(self.name, model)
+ # One attempt per optional field that could still be dropped, plus one
+ # for the model substitution below. Bounded so a service answering 400
+ # to everything ends in an honest error rather than a retry loop.
+ for _attempt in range(MAX_REQUEST_DOWNGRADES):
+ # A fresh file tuple per attempt: httpx consumes the buffer it is
+ # handed, so a retry with the same object uploads zero bytes.
+ files = {"file": (upload_name, wav_bytes, mime)}
+ data: dict[str, str] = {
+ "model": model,
+ "response_format": shape.response_format,
+ }
+ if shape.temperature:
+ data["temperature"] = str(self._temperature)
+ # Omitted entirely when None — that is what asks Whisper to detect
+ # the spoken language instead of decoding it as a pinned one.
+ if language and shape.language:
+ data["language"] = language
+ if self._prompt and shape.prompt:
+ data["prompt"] = self._prompt
+
+ 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:
+ return _payload_to_transcript(response.json())
+ if response.status_code != 400:
+ raise _http_error_to_runtime(response)
+
+ detail = error_text(response)
+ narrowed = shape_after_rejection(shape, detail)
+ if narrowed is not None:
+ remember_shape(self.name, model, narrowed)
+ shape = narrowed
+ continue
+ if model != DEFAULT_MODEL and is_model_rejection(detail, model):
+ # The pinned model is not one this account can call. Falling
+ # back to the universally-available one keeps the user
+ # dictating; the warning is what tells them to fix the pin.
+ log_model_fallback("OpenAI", model, DEFAULT_MODEL, detail)
+ model = DEFAULT_MODEL
+ shape = resolve_shape(self.name, model)
+ continue
raise _http_error_to_runtime(response)
- payload = response.json()
- return _payload_to_transcript(payload)
+
+ raise _http_error_to_runtime(response)
# ----------------------------------------------------------------------
diff --git a/jarvis/plugins/stt/openrouter_stt.py b/jarvis/plugins/stt/openrouter_stt.py
index 8108a7d57c..55f6962d49 100644
--- a/jarvis/plugins/stt/openrouter_stt.py
+++ b/jarvis/plugins/stt/openrouter_stt.py
@@ -13,7 +13,10 @@ Endpoint (verified live 2026-07-02):
headers the brain adapter also sends).
* JSON body: ``{"model": "<id>", "input_audio": {"data": "<base64 RAW audio
bytes, NOT a data-URI>", "format": "wav"}, "language": "<ISO-639-1>"?,
- "temperature": <0-1>?}``.
+ "temperature": <0-1>?}``. Which of the optional fields a given model
+ accepts is a per-MODEL question the gateway answers with 400, so the body
+ is shaped by :mod:`jarvis.plugins.stt.capabilities` and narrowed on a
+ refusal rather than pinned to a lowest common denominator.
* JSON response: ``{"text": "...", "usage": {"seconds": ..., "cost": ...,
"total_tokens": ...?}}`` with an ``X-Generation-Id`` response header. No
streaming — a single final ``Transcript`` is returned.
@@ -141,7 +144,14 @@ class OpenRouterSTT:
base_url: str | None = None,
language: str | None = None,
prompt: str | None = None,
- temperature: float | None = None,
+ # 0.0 by DEFAULT, not "omit unless configured". Transcription is a
+ # measurement, and the same recording has to come back the same way
+ # twice — a gateway default that samples turns an unchanged dictation
+ # into a different sentence on every retry, which is exactly the kind of
+ # variance a user reads as "it got worse". The field is dropped
+ # automatically for a model that refuses it (see ``_post_transcription``),
+ # so the reproducibility costs no portability.
+ temperature: float | None = 0.0,
timeout_s: float = 30.0,
http_client: httpx.AsyncClient | None = None,
) -> None:
@@ -288,43 +298,78 @@ class OpenRouterSTT:
async def _post_transcription(
self, wav_bytes: bytes, *, language: str | None = None
) -> Transcript:
+ """POST one upload, adapting the body to what the MODEL accepts.
+
+ The gateway fronts ~10 transcription backends whose contracts differ,
+ so the body is built from a per-model capability shape
+ (:mod:`jarvis.plugins.stt.capabilities`) and a 400 that names a field
+ narrows that shape and retries. That is what lets this plugin send a
+ temperature by DEFAULT: the field used to be omitted unless configured,
+ purely because one unsupported field would have cost the whole
+ utterance — and the cost of omitting it was a transcription that came
+ back differently every time the same audio was sent.
+ """
import base64
url = self._ensure_endpoint()
- body: dict[str, Any] = {
- "model": self._model,
- "input_audio": {
- "data": base64.b64encode(wav_bytes).decode("ascii"),
- "format": "wav",
- },
- }
- # Omitted entirely when None — that is what asks the model to detect the
- # spoken language instead of decoding it as a pinned one.
- if language:
- body["language"] = language
- # Temperature is omitted unless explicitly configured: keeping the body
- # minimal maximises portability across the ~10 transcription backends the
- # gateway fronts (some reject unexpected fields).
- if self._temperature is not None:
- body["temperature"] = float(self._temperature)
-
+ encoded = base64.b64encode(wav_bytes).decode("ascii")
headers = {
"Authorization": f"Bearer {self._api_key}",
"Content-Type": "application/json",
**_ATTRIBUTION_HEADERS,
}
client = self._get_client()
- try:
- response = await client.post(url, headers=headers, json=body)
- except httpx.HTTPError as exc:
- raise RuntimeError(
- f"OpenRouter STT request failed (network/unreachable): {exc}"
- ) from exc
- if response.status_code >= 400:
+ from jarvis.plugins.stt.capabilities import (
+ MAX_REQUEST_DOWNGRADES,
+ error_text,
+ is_model_rejection,
+ log_model_fallback,
+ remember_shape,
+ resolve_shape,
+ shape_after_rejection,
+ )
+
+ model = self._model
+ shape = resolve_shape(self.name, model)
+ for _attempt in range(MAX_REQUEST_DOWNGRADES):
+ body: dict[str, Any] = {
+ "model": model,
+ "input_audio": {"data": encoded, "format": "wav"},
+ }
+ # Omitted entirely when None — that is what asks the model to detect
+ # the spoken language instead of decoding it as a pinned one.
+ if language and shape.language:
+ body["language"] = language
+ if self._temperature is not None and shape.temperature:
+ body["temperature"] = float(self._temperature)
+
+ try:
+ response = await client.post(url, headers=headers, json=body)
+ except httpx.HTTPError as exc:
+ raise RuntimeError(
+ f"OpenRouter STT request failed (network/unreachable): {exc}"
+ ) from exc
+
+ if response.status_code < 400:
+ return _payload_to_transcript(response.json())
+ if response.status_code != 400:
+ raise _http_error_to_runtime(response)
+
+ detail = error_text(response)
+ narrowed = shape_after_rejection(shape, detail)
+ if narrowed is not None:
+ remember_shape(self.name, model, narrowed)
+ shape = narrowed
+ continue
+ if model != DEFAULT_MODEL and is_model_rejection(detail, model):
+ log_model_fallback("OpenRouter", model, DEFAULT_MODEL, detail)
+ model = DEFAULT_MODEL
+ shape = resolve_shape(self.name, model)
+ continue
raise _http_error_to_runtime(response)
- payload = response.json()
- return _payload_to_transcript(payload)
+
+ raise _http_error_to_runtime(response)
# ----------------------------------------------------------------------
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index f9bebce392..19173c7e1f 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -1786,7 +1786,9 @@ def _current_selection(cfg: Any, provider_id: str, cat: Any) -> str:
"""The value currently in effect for ``provider_id``'s picker (tier-aware).
Brain → the per-provider model; TTS → the global voice (``voice_de``) or model;
- Cartesia → its own ``[tts.cartesia].model_id``; STT → the global ``stt.model``.
+ Cartesia → its own ``[tts.cartesia].model_id``; STT → its per-provider pin in
+ ``[stt.models]``, falling back to the global ``[stt] model`` (which is the
+ on-device checkpoint name, so it is only ever the right answer there).
"""
if cat.tier == "brain":
return _current_brain_model(cfg, provider_id)
@@ -1798,7 +1800,14 @@ def _current_selection(cfg: Any, provider_id: str, cat: Any) -> str:
return _cartesia_model(tts) or "sonic-3.5"
return getattr(tts, "model", "") or ""
if cat.tier == "stt":
- return getattr(getattr(cfg, "stt", None), "model", "") or ""
+ stt = getattr(cfg, "stt", None)
+ pins = getattr(stt, "models", None) or {}
+ pinned = ""
+ if hasattr(pins, "get"):
+ pinned = str(pins.get(provider_id, "") or "")
+ if pinned:
+ return pinned
+ return getattr(stt, "model", "") or ""
return ""
@@ -1987,13 +1996,32 @@ def _apply_tts_selection(
def _apply_stt_model(
provider_id: str, value: str, body: BrainModelBody, request: Request
) -> BrainModelSaveResponse:
- """Persist a STT model (global ``[stt] model``). Takes effect on voice restart."""
+ """Persist a STT model for ``provider_id``. Takes effect on voice restart.
+
+ Written to ``[stt.models].<provider id>`` — the slot the STT factory reads
+ (``jarvis.plugins.stt.resolve_stt_model``). The global ``[stt] model`` is
+ kept in step ONLY for an on-device recognizer, because that key holds a
+ faster-whisper checkpoint name and the local engine is its one consumer;
+ writing a cloud model id there would leave the local path pointing at a
+ checkpoint that does not exist.
+ """
+ on_device = False
+ try:
+ from jarvis.plugins.stt import provider_runs_on_device
+
+ on_device = provider_runs_on_device(provider_id)
+ except Exception as exc: # noqa: BLE001 — an unknown provider is treated as cloud
+ log.debug("STT on-device probe failed for %s (%s); treating as cloud.",
+ provider_id, exc)
+
persisted = False
if body.persist:
try:
- from jarvis.core.config_writer import set_stt_model
+ from jarvis.core.config_writer import set_stt_model, set_stt_provider_model
- set_stt_model(value)
+ set_stt_provider_model(provider_id, value)
+ if on_device:
+ set_stt_model(value)
persisted = True
except FileNotFoundError as exc:
raise HTTPException(status_code=500, detail=str(exc)) from exc
@@ -2005,7 +2033,14 @@ def _apply_stt_model(
cfg = _resolve_cfg(request)
if cfg is not None and getattr(cfg, "stt", None) is not None:
try:
- cfg.stt.model = value # type: ignore[attr-defined]
+ pins = dict(getattr(cfg.stt, "models", None) or {}) # type: ignore[attr-defined]
+ if value:
+ pins[provider_id] = value
+ else:
+ pins.pop(provider_id, None)
+ cfg.stt.models = pins # type: ignore[attr-defined]
+ if on_device:
+ cfg.stt.model = value # type: ignore[attr-defined]
except Exception as exc: # noqa: BLE001
log.debug("In-memory stt model update skipped: %s", exc)
diff --git a/tests/unit/plugins/stt/test_openrouter_stt.py b/tests/unit/plugins/stt/test_openrouter_stt.py
index 46cb01fff7..fa92e09c97 100644
--- a/tests/unit/plugins/stt/test_openrouter_stt.py
+++ b/tests/unit/plugins/stt/test_openrouter_stt.py
@@ -113,7 +113,16 @@ async def test_language_is_sent_when_set_and_omitted_when_auto() -> None:
@pytest.mark.asyncio
-async def test_temperature_omitted_by_default_and_sent_when_configured() -> None:
+async def test_temperature_is_pinned_to_zero_by_default() -> None:
+ """A transcription is a measurement, so it has to repeat.
+
+ The field used to be omitted unless configured, on portability grounds —
+ one backend that rejected it would have cost the whole utterance. That
+ reasoning is gone now the body is narrowed on a 400 (see
+ ``test_a_rejected_field_is_dropped_and_the_call_retried``), and what the
+ omission actually bought was a gateway default that samples: the same
+ recording came back as a different sentence on a retry.
+ """
captured: dict[str, dict] = {}
async def handler(request: httpx.Request) -> httpx.Response:
@@ -125,16 +134,18 @@ async def test_temperature_omitted_by_default_and_sent_when_configured() -> None
await stt.transcribe_pcm(_silent_pcm())
finally:
await stt.aclose()
- assert "temperature" not in captured["body"]
+ assert captured["body"]["temperature"] == 0.0
+ # An explicit None is still "say nothing about it" — the escape hatch for a
+ # deployment that wants the backend's own default.
stt2 = OpenRouterSTT(
- api_key="k", temperature=0.0, http_client=_mock_client(handler)
+ api_key="k", temperature=None, http_client=_mock_client(handler)
)
try:
await stt2.transcribe_pcm(_silent_pcm())
finally:
await stt2.aclose()
- assert captured["body"]["temperature"] == 0.0
+ assert "temperature" not in captured["body"]
@pytest.mark.asyncio
diff --git a/tests/unit/plugins/stt/test_request_capabilities.py b/tests/unit/plugins/stt/test_request_capabilities.py
new file mode 100644
index 0000000000..f4c0ffcab2
--- /dev/null
+++ b/tests/unit/plugins/stt/test_request_capabilities.py
@@ -0,0 +1,372 @@
+"""What ONE transcription request may contain, and what a 400 teaches us.
+
+The defect these lock: every hosted transcription plugin here posted the SAME
+body regardless of model. ``whisper-1`` answers ``response_format =
+"verbose_json"``; ``gpt-4o-transcribe`` — the newer, genuinely multilingual
+model a user would pick to fix mixed-language dictation — rejects that value
+with HTTP 400 and transcribes nothing. Picking the better model therefore made
+speech recognition stop working, with an error nobody could act on.
+
+Two mechanisms, tested here end to end: a per-model declared shape, and a
+refusal treated as EVIDENCE rather than as a failure.
+"""
+
+from __future__ import annotations
+
+import json
+
+import httpx
+import pytest
+
+from jarvis.plugins.stt.capabilities import (
+ FULL_SHAPE,
+ UNIVERSAL_SHAPE,
+ RequestShape,
+ declared_shape,
+ is_model_rejection,
+ remember_shape,
+ reset_learned_shapes,
+ resolve_shape,
+ shape_after_rejection,
+)
+from jarvis.plugins.stt.groq_api import GroqWhisperAPI
+from jarvis.plugins.stt.openai_api import OpenAIWhisperAPI
+from jarvis.plugins.stt.openrouter_stt import OpenRouterSTT
+
+
[email protected](autouse=True)
+def _forget_learned_shapes():
+ """Each test starts from what is DECLARED, never from a sibling's lesson."""
+ reset_learned_shapes()
+ yield
+ reset_learned_shapes()
+
+
+def _silent_pcm(seconds: float = 0.2) -> bytes:
+ return b"\x00\x00" * int(16_000 * seconds)
+
+
+def _mock_client(handler) -> httpx.AsyncClient:
+ return httpx.AsyncClient(transport=httpx.MockTransport(handler))
+
+
+# ---------------------------------------------------------------------------
+# The declared shape
+# ---------------------------------------------------------------------------
+
+
+class TestWhatAModelIsAssumedToAccept:
+ def test_a_whisper_checkpoint_keeps_the_rich_response_format(self):
+ """Segment timings feed the confidence figure; Whisper has always
+ answered them, on every vendor that hosts it."""
+ for model in (
+ "whisper-1",
+ "whisper-large-v3",
+ "openai/whisper-large-v3-turbo",
+ "distil-whisper-large-v3-en",
+ ):
+ assert declared_shape(model).verbose_json is True, model
+ assert declared_shape(model).response_format == "verbose_json"
+
+ def test_a_newer_transcription_model_starts_on_the_universal_subset(self):
+ """The whole bug: ``verbose_json`` is not universal, and assuming it
+ costs the utterance instead of a confidence number."""
+ for model in (
+ "gpt-4o-transcribe",
+ "gpt-4o-mini-transcribe",
+ "openai/gpt-4o-transcribe",
+ "google/chirp-3",
+ "mistralai/voxtral-mini-transcribe",
+ ):
+ assert declared_shape(model).verbose_json is False, model
+ assert declared_shape(model).response_format == "json"
+
+ def test_an_unknown_model_is_never_assumed_to_accept_more(self):
+ """A model released tomorrow must degrade to "works", not to a 400."""
+ assert declared_shape("some-vendor/model-nobody-has-seen") == UNIVERSAL_SHAPE
+ assert declared_shape("") == UNIVERSAL_SHAPE
+ assert declared_shape(None) == UNIVERSAL_SHAPE
+
+ def test_the_optional_fields_start_permitted_everywhere(self):
+ """Only the response format is genuinely divisive; language, prompt and
+ temperature are accepted far more widely, and a refusal narrows them."""
+ shape = declared_shape("gpt-4o-transcribe")
+ assert shape.language and shape.prompt and shape.temperature
+
+
+# ---------------------------------------------------------------------------
+# A refusal is evidence
+# ---------------------------------------------------------------------------
+
+
+class TestLearningFromARefusal:
+ def test_a_response_format_complaint_drops_exactly_that_field(self):
+ narrowed = shape_after_rejection(
+ FULL_SHAPE,
+ "Invalid value: 'verbose_json'. Supported values are: 'json' and 'text'.",
+ )
+ assert narrowed == RequestShape(verbose_json=False)
+
+ def test_each_optional_field_can_be_named_and_dropped(self):
+ assert shape_after_rejection(
+ FULL_SHAPE, "Unrecognized request argument supplied: temperature"
+ ) == RequestShape(temperature=False)
+ assert shape_after_rejection(
+ FULL_SHAPE, "prompt is not supported with this model"
+ ) == RequestShape(prompt=False)
+ assert shape_after_rejection(
+ FULL_SHAPE, "language is not supported by this endpoint"
+ ) == RequestShape(language=False)
+
+ def test_an_unrelated_refusal_teaches_nothing(self):
+ """The safety of the whole mechanism: a retry ladder that stripped a
+ field off every 400 would reduce the request to nothing and report the
+ least informative error it could find."""
+ for message in (
+ "Incorrect API key provided",
+ "Audio file is too short",
+ "You exceeded your current quota",
+ "",
+ ):
+ assert shape_after_rejection(FULL_SHAPE, message) is None, message
+
+ def test_a_field_already_dropped_cannot_be_dropped_again(self):
+ """Otherwise a service repeating its complaint spins the caller."""
+ once = shape_after_rejection(FULL_SHAPE, "response_format is invalid")
+ assert once is not None
+ assert shape_after_rejection(once, "response_format is invalid") is None
+
+ def test_what_was_learned_survives_for_the_process(self):
+ remember_shape("openai-api", "gpt-4o-transcribe", RequestShape(verbose_json=False))
+ assert resolve_shape("openai-api", "gpt-4o-transcribe").verbose_json is False
+ # Another model on the same vendor is untouched — the lesson is about
+ # the MODEL, which is where the difference actually lives.
+ assert resolve_shape("openai-api", "whisper-1").verbose_json is True
+
+ def test_two_lessons_narrow_rather_than_overwrite(self):
+ """Concurrent calls each learning a different rejection must end with
+ BOTH fields dropped, not with whichever finished last."""
+ remember_shape("x", "m", RequestShape(verbose_json=False))
+ remember_shape("x", "m", RequestShape(temperature=False))
+ shape = resolve_shape("x", "m")
+ assert shape.verbose_json is False
+ assert shape.temperature is False
+
+ def test_the_lesson_is_never_written_to_disk(self):
+ """A capability verdict nobody re-probes is AP-25's sticky cache in
+ miniature: one bad minute would pin a model across every restart."""
+ reset_learned_shapes()
+ assert resolve_shape("openai-api", "gpt-4o-transcribe") == UNIVERSAL_SHAPE
+
+
+class TestRecognisingAModelRefusal:
+ def test_the_usual_wordings_are_recognised(self):
+ for message in (
+ "The model `gpt-4o-transcribe` does not exist",
+ '{"error":{"code":"model_not_found"}}',
+ "Unknown model: whisper-9",
+ "invalid model id",
+ ):
+ assert is_model_rejection(message), message
+
+ def test_an_ordinary_failure_is_not_a_model_refusal(self):
+ for message in ("Incorrect API key provided", "rate limit reached", ""):
+ assert not is_model_rejection(message), message
+
+
+# ---------------------------------------------------------------------------
+# The plugins actually do it
+# ---------------------------------------------------------------------------
+
+
+_OK_VERBOSE = {"text": "hallo welt", "language": "de", "segments": []}
+_OK_PLAIN = {"text": "hallo welt"}
+
+
+class TestTheOpenAIShapedPluginsAdapt:
+ @pytest.mark.asyncio
+ async def test_a_rejected_response_format_is_retried_as_plain_json(self):
+ """The reported failure, end to end: picking gpt-4o-transcribe used to
+ make dictation return nothing at all."""
+ seen: list[dict[str, str]] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ fields = _multipart_fields(request)
+ seen.append(fields)
+ if fields.get("response_format") == "verbose_json":
+ return httpx.Response(
+ 400,
+ json={"error": {"message": "Invalid value: 'verbose_json'"}},
+ )
+ return httpx.Response(200, json=_OK_PLAIN)
+
+ # Declared shape says json already, so force the rich one to prove the
+ # retry: a whisper id on a service that has stopped accepting it.
+ stt = OpenAIWhisperAPI(
+ api_key="k", model="whisper-1", http_client=_mock_client(handler)
+ )
+ try:
+ result = await stt.transcribe_pcm(_silent_pcm())
+ finally:
+ await stt.aclose()
+
+ assert result.text == "hallo welt"
+ assert [f["response_format"] for f in seen] == ["verbose_json", "json"]
+
+ @pytest.mark.asyncio
+ async def test_the_retry_uploads_the_audio_again(self):
+ """httpx consumes the buffer it is handed, so a retry that reuses the
+ same file tuple posts zero bytes — a silent, total data loss."""
+ sizes: list[int] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ fields = _multipart_fields(request)
+ sizes.append(len(request.content))
+ if fields.get("response_format") == "verbose_json":
+ return httpx.Response(400, json={"error": {"message": "response_format"}})
+ return httpx.Response(200, json=_OK_PLAIN)
+
+ stt = OpenAIWhisperAPI(
+ api_key="k", model="whisper-1", http_client=_mock_client(handler)
+ )
+ try:
+ await stt.transcribe_pcm(_silent_pcm())
+ finally:
+ await stt.aclose()
+
+ assert len(sizes) == 2
+ # The retry is within a few header bytes of the first attempt.
+ assert abs(sizes[0] - sizes[1]) < 200
+
+ @pytest.mark.asyncio
+ async def test_a_refused_model_falls_back_to_the_default_one(self):
+ """A pin the account cannot call is a configuration problem, not a
+ reason to leave the user unable to dictate."""
+ models: list[str] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ fields = _multipart_fields(request)
+ models.append(fields["model"])
+ if fields["model"] != "whisper-1":
+ return httpx.Response(
+ 400, json={"error": {"code": "model_not_found"}}
+ )
+ return httpx.Response(200, json=_OK_PLAIN)
+
+ stt = OpenAIWhisperAPI(
+ api_key="k",
+ model="gpt-4o-transcribe-preview-nobody-has",
+ http_client=_mock_client(handler),
+ )
+ try:
+ result = await stt.transcribe_pcm(_silent_pcm())
+ finally:
+ await stt.aclose()
+
+ assert result.text == "hallo welt"
+ assert models[-1] == "whisper-1"
+
+ @pytest.mark.asyncio
+ async def test_an_unrelated_400_is_still_an_error(self):
+ async def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(400, json={"error": {"message": "Audio too short"}})
+
+ stt = OpenAIWhisperAPI(api_key="k", http_client=_mock_client(handler))
+ try:
+ with pytest.raises(RuntimeError):
+ await stt.transcribe_pcm(_silent_pcm())
+ finally:
+ await stt.aclose()
+
+ @pytest.mark.asyncio
+ async def test_groq_adapts_the_same_way(self):
+ seen: list[dict[str, str]] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ fields = _multipart_fields(request)
+ seen.append(fields)
+ if "temperature" in fields:
+ return httpx.Response(
+ 400, json={"error": {"message": "Unrecognized argument: temperature"}}
+ )
+ return httpx.Response(200, json=_OK_VERBOSE)
+
+ stt = GroqWhisperAPI(api_key="k", http_client=_mock_client(handler))
+ try:
+ result = await stt.transcribe_pcm(_silent_pcm())
+ finally:
+ await stt.aclose()
+
+ assert result.text == "hallo welt"
+ assert "temperature" in seen[0]
+ assert "temperature" not in seen[-1]
+
+
+class TestTheGatewayPluginAdapts:
+ @pytest.mark.asyncio
+ async def test_a_rejected_temperature_is_dropped_and_the_call_retried(self):
+ bodies: list[dict] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content)
+ bodies.append(body)
+ if "temperature" in body:
+ return httpx.Response(
+ 400, json={"error": {"message": "temperature is not supported"}}
+ )
+ return httpx.Response(200, json={"text": "hola mundo"})
+
+ stt = OpenRouterSTT(
+ api_key="k", model="google/chirp-3", http_client=_mock_client(handler)
+ )
+ try:
+ result = await stt.transcribe_pcm(_silent_pcm())
+ finally:
+ await stt.aclose()
+
+ assert result.text == "hola mundo"
+ assert "temperature" in bodies[0]
+ assert "temperature" not in bodies[-1]
+
+ @pytest.mark.asyncio
+ async def test_the_audio_survives_every_retry(self):
+ """The gateway takes base64 in the body, so the same class of bug is
+ possible here: a retry must carry the recording, not an empty string."""
+ bodies: list[dict] = []
+
+ async def handler(request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content)
+ bodies.append(body)
+ if "temperature" in body:
+ return httpx.Response(400, json={"error": {"message": "temperature"}})
+ return httpx.Response(200, json={"text": "ok"})
+
+ stt = OpenRouterSTT(api_key="k", http_client=_mock_client(handler))
+ try:
+ await stt.transcribe_pcm(_silent_pcm())
+ finally:
+ await stt.aclose()
+
+ assert len(bodies) == 2
+ assert bodies[0]["input_audio"]["data"] == bodies[1]["input_audio"]["data"]
+ assert bodies[1]["input_audio"]["data"]
+
+
+def _multipart_fields(request: httpx.Request) -> dict[str, str]:
+ """The non-file multipart fields of a transcription upload, as strings.
+
+ Parsed rather than mocked so the tests fail if the plugin stops sending a
+ field it is supposed to send.
+ """
+ raw = request.content
+ fields: dict[str, str] = {}
+ for part in raw.split(b"\r\n--"):
+ if b'name="' not in part or b'filename="' in part:
+ continue
+ name = part.split(b'name="', 1)[1].split(b'"', 1)[0].decode()
+ try:
+ value = part.split(b"\r\n\r\n", 1)[1].rsplit(b"\r\n", 1)[0]
+ except IndexError: # pragma: no cover — malformed part
+ continue
+ fields[name] = value.decode(errors="replace")
+ return fields
diff --git a/tests/unit/plugins/stt/test_stt_model_wiring.py b/tests/unit/plugins/stt/test_stt_model_wiring.py
new file mode 100644
index 0000000000..279a5082f9
--- /dev/null
+++ b/tests/unit/plugins/stt/test_stt_model_wiring.py
@@ -0,0 +1,177 @@
+"""The model the user picked has to reach the provider that transcribes.
+
+The defect: the STT model picker wrote ``[stt] model`` and the factory never
+forwarded it, so every cloud recognizer ran on its own hardcoded default. A
+user who selected a genuinely multilingual model to fix mixed-language
+dictation changed nothing at all — the classic AP-31 shape, a switch whose
+value is ignored.
+
+The repair is a per-provider slot rather than one global string, because
+``[stt] model`` holds a faster-whisper CHECKPOINT name: forwarding that one
+value to whichever provider happened to be selected would have posted
+``large-v3-turbo`` to Groq on a fresh install and broken speech recognition for
+everyone who never touched the picker.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import jarvis.core.config as cfg
+import jarvis.plugins.stt as stt_pkg
+from jarvis.core.config import STTConfig
+
+
+class _FakeCloud:
+ """A cloud provider that records exactly what it was constructed with."""
+
+ name = "openrouter-stt"
+ last_kwargs: dict[str, Any] = {}
+
+ def __init__(self, **kwargs: Any) -> None:
+ _FakeCloud.last_kwargs = kwargs
+
+
+class _FakeOnDevice:
+ name = "nemotron-local"
+ runs_on_device = True
+ last_kwargs: dict[str, Any] = {}
+
+ def __init__(self, **kwargs: Any) -> None:
+ _FakeOnDevice.last_kwargs = kwargs
+
+
+def _keyed(monkeypatch) -> None:
+ """Pretend every credential slot resolves, so the key-aware factory keeps
+ the configured provider instead of crossing families (AP-22)."""
+ monkeypatch.setattr(cfg, "get_secret_any", lambda candidates: "key")
+
+
+def _build(monkeypatch, stt_cfg: STTConfig, cls: type) -> None:
+ _keyed(monkeypatch)
+ monkeypatch.setattr(stt_pkg, "_load_provider_class", lambda name: cls)
+ stt_pkg.build_stt_from_config(stt_cfg)
+
+
+# ---------------------------------------------------------------------------
+# resolve_stt_model — the precedence, on its own
+# ---------------------------------------------------------------------------
+
+
+class TestWhichModelAProviderIsGiven:
+ def test_a_per_provider_pin_is_what_gets_sent(self):
+ conf = STTConfig(
+ provider="openrouter-stt",
+ models={"openrouter-stt": "openai/gpt-4o-transcribe"},
+ )
+ assert (
+ stt_pkg.resolve_stt_model(conf, "openrouter-stt")
+ == "openai/gpt-4o-transcribe"
+ )
+
+ def test_the_local_checkpoint_name_never_leaks_to_a_hosted_api(self):
+ """The trap this design exists to avoid: ``[stt] model`` defaults to a
+ faster-whisper checkpoint, and Groq has never heard of it."""
+ conf = STTConfig(provider="groq-api", model="large-v3-turbo")
+ assert stt_pkg.resolve_stt_model(conf, "groq-api") == ""
+ assert stt_pkg.resolve_stt_model(conf, "openai-api") == ""
+
+ def test_a_pin_for_another_provider_is_not_borrowed(self):
+ conf = STTConfig(
+ provider="groq-api", models={"openai-api": "gpt-4o-transcribe"}
+ )
+ assert stt_pkg.resolve_stt_model(conf, "groq-api") == ""
+
+ def test_an_unusable_config_answers_the_working_value(self):
+ """A test double or a stale install must never break the build."""
+
+ class _Bare:
+ provider = "groq-api"
+
+ assert stt_pkg.resolve_stt_model(_Bare(), "groq-api") == ""
+ assert stt_pkg.resolve_stt_model(STTConfig(), "") == ""
+
+
+# ---------------------------------------------------------------------------
+# The factory forwards it
+# ---------------------------------------------------------------------------
+
+
+class TestTheFactoryForwardsThePick:
+ def test_a_pinned_cloud_model_reaches_the_provider(self, monkeypatch):
+ _build(
+ monkeypatch,
+ STTConfig(
+ provider="openrouter-stt",
+ models={"openrouter-stt": "openai/gpt-4o-transcribe"},
+ ),
+ _FakeCloud,
+ )
+ assert _FakeCloud.last_kwargs["model"] == "openai/gpt-4o-transcribe"
+
+ def test_without_a_pin_the_provider_keeps_its_own_default(self, monkeypatch):
+ """No pin must mean "your default", never an empty model id."""
+ _build(monkeypatch, STTConfig(provider="openrouter-stt"), _FakeCloud)
+ assert "model" not in _FakeCloud.last_kwargs
+
+ def test_temperature_zero_is_forwarded_by_default(self, monkeypatch):
+ """A transcription is a measurement: the same audio has to come back
+ the same way twice."""
+ _build(monkeypatch, STTConfig(provider="openrouter-stt"), _FakeCloud)
+ assert _FakeCloud.last_kwargs["temperature"] == 0.0
+
+ def test_a_configured_temperature_is_honoured(self, monkeypatch):
+ _build(
+ monkeypatch, STTConfig(provider="openrouter-stt", temperature=0.2), _FakeCloud
+ )
+ assert _FakeCloud.last_kwargs["temperature"] == 0.2
+
+ def test_an_on_device_recognizer_is_not_handed_cloud_options(self, monkeypatch):
+ """It configures its own decoding; offering it these only earns a
+ misleading "this plugin is out of date" warning."""
+ _build(
+ monkeypatch,
+ STTConfig(provider="nemotron-local", bias_prompt="Ruben"),
+ _FakeOnDevice,
+ )
+ for cloud_only in ("temperature", "prompt", "timeout_s"):
+ assert cloud_only not in _FakeOnDevice.last_kwargs
+
+ def test_a_provider_that_predates_the_kwargs_still_builds(self, monkeypatch):
+ """A third-party plugin written before these existed must not fall all
+ the way through to a local engine a base install does not ship."""
+
+ class _Old:
+ name = "openrouter-stt"
+ last_kwargs: dict[str, Any] = {}
+
+ def __init__(self, *, language: str | None = None, **rest: Any) -> None:
+ if rest:
+ raise TypeError(f"unexpected keyword arguments: {sorted(rest)}")
+ _Old.last_kwargs = {"language": language}
+
+ _build(
+ monkeypatch,
+ STTConfig(
+ provider="openrouter-stt",
+ language="de",
+ models={"openrouter-stt": "openai/gpt-4o-transcribe"},
+ ),
+ _Old,
+ )
+ assert _Old.last_kwargs == {"language": "de"}
+
+ def test_a_fallback_provider_is_built_with_its_own_pin(self, monkeypatch):
+ """A cross-family fallback that silently dropped the user's model would
+ transcribe their words differently the moment it took over."""
+ _keyed(monkeypatch)
+ monkeypatch.setattr(stt_pkg, "_load_provider_class", lambda name: _FakeCloud)
+ conf = STTConfig(
+ provider="groq-api",
+ models={
+ "groq-api": "whisper-large-v3",
+ "openai-api": "gpt-4o-transcribe",
+ },
+ )
+ stt_pkg.build_named_stt_provider("openai-api", conf)
+ assert _FakeCloud.last_kwargs["model"] == "gpt-4o-transcribe"