Skip to content

The agent that grows with you

feat(plugins): add pre_transcription hook and STT prompt threading

Hans52eb8eb5332c
diff --git a/agent/transcription_provider.py b/agent/transcription_provider.py
index 2586b8cc43a..a0f9597d3ce 100644
--- a/agent/transcription_provider.py
+++ b/agent/transcription_provider.py
@@ -190,4 +190,9 @@ class TranscriptionProvider(abc.ABC):
ignore this argument.
**extra: Forward-compat parameters future schema versions
may expose. Implementations should ignore unknown keys.
+ The dispatcher currently forwards ``prompt`` here when a
+ transcription prompt is set (via the ``stt.prompt`` config
+ key or a ``pre_transcription`` hook) — prompt-capable
+ providers may use it as a vocabulary/context hint; others
+ should ignore it.
"""
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index dd83df01575..fb36868ce83 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -1233,6 +1233,29 @@ stt:
# cloud_trim_silence: true # set false to always upload the original audio
# cloud_trim_threshold_db: -40 # audio quieter than this counts as silence
# cloud_trim_keep_ms: 300 # how much of each pause survives (keeps natural pacing)
+ # Optional static transcription prompt: vocabulary/context hints for
+ # prompt-capable backends. Composition is deterministic: this config value
+ # is the base, then `pre_transcription` hooks run in registration order with
+ # last-writer-wins semantics per field.
+ #
+ # Privacy: the final prompt is sent to the configured STT provider alongside
+ # the audio. Do not include secrets or session context you would not send to
+ # that provider.
+ #
+ # Length / truncation contract: Whisper-family backends (local, openai,
+ # groq, deepinfra) only use the final ~224 prompt tokens, so Hermes
+ # truncates longer prompts client-side (keeping the tail) with a WARNING
+ # log — never an error. Other backends own their own validation.
+ #
+ # Provider behavior:
+ # local (faster-whisper) -> `initial_prompt`, forwarded unchanged
+ # openai / groq -> `prompt`, forwarded unchanged
+ # mistral -> `prompt`, forwarded unchanged
+ # deepinfra -> OpenAI-compatible `prompt`, unchanged
+ # local_command/xai/
+ # elevenlabs -> unsupported; DEBUG log, then continue
+ # plugin providers -> `prompt` in `**extra`; plugin owns limits
+ # prompt: "Hermes, Teknium, Nous Research, kanban"
local:
model: "base" # tiny | base | small | medium | large-v3 | turbo
# language: "" # auto-detect; set to "en", "es", "fr", etc. to force
diff --git a/gateway/run.py b/gateway/run.py
index 00b2ec60dc1..09d2352134f 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -22761,7 +22761,9 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
for path in audio_paths:
try:
logger.debug("Transcribing user voice: %s", path)
- result = await asyncio.to_thread(transcribe_audio, path)
+ result = await asyncio.to_thread(
+ transcribe_audio, path, None, "gateway",
+ )
if not result.get("success"):
fallback = await asyncio.to_thread(
transcribe_audio_local_fallback,
diff --git a/hermes_cli/hooks.py b/hermes_cli/hooks.py
index c71da88d5b4..5135d4a955e 100644
--- a/hermes_cli/hooks.py
+++ b/hermes_cli/hooks.py
@@ -212,6 +212,14 @@ _DEFAULT_PAYLOADS = {
"assistant_content_chars": 1200,
"assistant_tool_call_count": 0,
},
+ "pre_transcription": {
+ "file_path": "/tmp/voice-message.ogg",
+ "provider": "local",
+ "model": "base",
+ "language": "en",
+ "prompt": None,
+ "source": "gateway",
+ },
"subagent_stop": {
"parent_session_id": "parent-sess",
"child_role": None,
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index c27f02c212e..cbf551c429a 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -211,6 +211,17 @@ VALID_HOOKS: Set[str] = {
# decided_by: "aux_llm" -- only on surface="smart"
"pre_approval_request",
"post_approval_response",
+ # Pre-transcription transform hook. Fired by the STT dispatcher
+ # (tools.transcription_tools.transcribe_audio) after provider resolution
+ # and BEFORE any backend — built-in, command-type, or plugin-registered —
+ # is invoked. Callbacks receive keyword args:
+ # file_path, provider, model, language, prompt, source
+ # and may return None (unchanged) or a dict mutating any of
+ # ``prompt`` / ``language`` / ``model``. Results are applied in
+ # registration order, last-writer-wins per field. ``file_path`` is
+ # read-only — attempts to change it are logged and dropped. The static
+ # ``stt.prompt`` config value is the base; hook results mutate on top.
+ "pre_transcription",
# Kanban task lifecycle hooks. Fired by hermes_cli.kanban_db when a task
# transitions state, AFTER the change is committed to the board DB (so the
# hook always sees durable state and a slow plugin can never hold the
diff --git a/tests/tools/test_pre_transcription_hook.py b/tests/tools/test_pre_transcription_hook.py
new file mode 100644
index 00000000000..7ebede11262
--- /dev/null
+++ b/tests/tools/test_pre_transcription_hook.py
@@ -0,0 +1,631 @@
+"""Tests for the ``pre_transcription`` plugin hook and STT prompt threading
+(issue #64168) wired into ``tools.transcription_tools.transcribe_audio``.
+
+Covers:
+
+1. Fixture plugin returning a prompt → the backend call receives
+ ``initial_prompt`` (faster-whisper) / ``prompt`` (OpenAI, Groq, Mistral).
+ The API boundary is stubbed — no live model is loaded or called.
+2. Two hooks → last-writer-wins per field, in registration order.
+3. Hook returning the read-only ``file_path`` field → dropped with a log.
+4. No hook registered → invoke_hook is never called and the backend
+ dispatch kwargs are identical to a control run (no prompt/language keys
+ on the wire).
+5. ``stt.prompt`` config alone → threaded without any hook.
+6. Config + hook → hook wins (config is the base, hooks mutate on top).
+7. Unsupported backend (xAI, ElevenLabs) → DEBUG note and the call
+ proceeds without the prompt.
+8. Plugin-registered providers receive the prompt via the ABC's ``**extra``
+ kwargs — no signature change.
+
+Mirrors the ``transform_tool_result`` hook test conventions from
+``tests/test_transform_tool_result_hook.py``.
+"""
+
+from __future__ import annotations
+
+import logging
+import sys
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+import hermes_cli.plugins as plugins_mod
+from tools import transcription_tools
+
+
+PROMPT = "Hermes, Teknium, Nous Research, kanban"
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_audio(tmp_path):
+ audio = tmp_path / "voice.ogg"
+ audio.write_bytes(b"fake audio data")
+ return str(audio)
+
+
+def _fake_hooks(monkeypatch, results):
+ """Install fake has_hook/invoke_hook returning *results* and capture kwargs."""
+ captured = {}
+
+ def _invoke(hook_name, **kw):
+ captured["hook_name"] = hook_name
+ captured["kwargs"] = kw
+ return list(results)
+
+ monkeypatch.setattr("hermes_cli.plugins.has_hook", lambda name: True)
+ monkeypatch.setattr("hermes_cli.plugins.invoke_hook", _invoke)
+ return captured
+
+
+def _no_hooks(monkeypatch):
+ """No hook registered: has_hook is False and invoke_hook must not fire."""
+ def _boom(hook_name, **kw): # pragma: no cover - the assert is the point
+ raise AssertionError(
+ "invoke_hook must not be called when has_hook() is False"
+ )
+
+ monkeypatch.setattr("hermes_cli.plugins.has_hook", lambda name: False)
+ monkeypatch.setattr("hermes_cli.plugins.invoke_hook", _boom)
+
+
+def _dispatch_ctx(stt_config, provider):
+ """Patch config load + provider resolution around transcribe_audio."""
+ return (
+ patch("tools.transcription_tools._load_stt_config", return_value=stt_config),
+ patch("tools.transcription_tools._get_provider", return_value=provider),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Hook registration surface
+# ---------------------------------------------------------------------------
+
+
+def test_pre_transcription_in_valid_hooks():
+ assert "pre_transcription" in plugins_mod.VALID_HOOKS
+
+
+# ---------------------------------------------------------------------------
+# Prompt threading into backends (API boundary stubbed)
+# ---------------------------------------------------------------------------
+
+
+class TestPromptThreading:
+ def test_hook_prompt_reaches_faster_whisper_initial_prompt(
+ self, monkeypatch, tmp_path,
+ ):
+ audio = _make_audio(tmp_path)
+ _fake_hooks(monkeypatch, [{"prompt": PROMPT}])
+
+ mock_segment = MagicMock()
+ mock_segment.text = "hello"
+ mock_info = MagicMock(language="en", duration=1.0)
+ mock_model = MagicMock()
+ mock_model.transcribe.return_value = ([mock_segment], mock_info)
+
+ cfg_patch, prov_patch = _dispatch_ctx({"provider": "local"}, "local")
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._HAS_FASTER_WHISPER", True), \
+ patch("tools.transcription_tools._load_local_whisper_model",
+ return_value=mock_model), \
+ patch("tools.transcription_tools._local_model", None):
+ result = transcription_tools.transcribe_audio(audio)
+
+ assert result["success"] is True
+ _, kwargs = mock_model.transcribe.call_args
+ assert kwargs["initial_prompt"] == PROMPT
+
+ def test_hook_prompt_and_language_reach_openai(self, monkeypatch, tmp_path):
+ audio = _make_audio(tmp_path)
+ monkeypatch.setenv("VOICE_TOOLS_OPENAI_KEY", "sk-test")
+ _fake_hooks(monkeypatch, [{"prompt": PROMPT, "language": "en"}])
+
+ mock_client = MagicMock()
+ mock_client.audio.transcriptions.create.return_value = "hello"
+
+ cfg_patch, prov_patch = _dispatch_ctx({"provider": "openai"}, "openai")
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._HAS_OPENAI", True), \
+ patch("openai.OpenAI", return_value=mock_client):
+ result = transcription_tools.transcribe_audio(audio)
+
+ assert result["success"] is True
+ _, kwargs = mock_client.audio.transcriptions.create.call_args
+ assert kwargs["prompt"] == PROMPT
+ assert kwargs["language"] == "en"
+
+ def test_hook_prompt_reaches_groq(self, monkeypatch, tmp_path):
+ audio = _make_audio(tmp_path)
+ monkeypatch.setenv("GROQ_API_KEY", "gsk-test")
+ _fake_hooks(monkeypatch, [{"prompt": PROMPT}])
+
+ mock_client = MagicMock()
+ mock_client.audio.transcriptions.create.return_value = "hello"
+
+ cfg_patch, prov_patch = _dispatch_ctx({"provider": "groq"}, "groq")
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._HAS_OPENAI", True), \
+ patch("openai.OpenAI", return_value=mock_client):
+ result = transcription_tools.transcribe_audio(audio)
+
+ assert result["success"] is True
+ _, kwargs = mock_client.audio.transcriptions.create.call_args
+ assert kwargs["prompt"] == PROMPT
+
+ def test_prompt_reaches_mistral(self, monkeypatch, tmp_path):
+ """Unit-level: _transcribe_mistral forwards prompt to the SDK call."""
+ audio = _make_audio(tmp_path)
+ monkeypatch.setenv("MISTRAL_API_KEY", "mk-test")
+ # Never attempt a lazy install in tests.
+ monkeypatch.setattr("tools.lazy_deps.ensure", lambda *a, **kw: None)
+
+ mistral_cls = MagicMock()
+ mock_client = mistral_cls.return_value.__enter__.return_value
+ mock_client.audio.transcriptions.complete.return_value = SimpleNamespace(
+ text="hello",
+ )
+ fake_mistralai = SimpleNamespace(client=SimpleNamespace(Mistral=mistral_cls))
+ monkeypatch.setitem(sys.modules, "mistralai", fake_mistralai)
+ monkeypatch.setitem(sys.modules, "mistralai.client", fake_mistralai.client)
+
+ result = transcription_tools._transcribe_mistral(
+ audio, "voxtral-mini-latest", prompt=PROMPT,
+ )
+
+ assert result["success"] is True
+ _, kwargs = mock_client.audio.transcriptions.complete.call_args
+ assert kwargs["prompt"] == PROMPT
+
+
+# ---------------------------------------------------------------------------
+# Hook merge mechanics
+# ---------------------------------------------------------------------------
+
+
+class TestHookMergeMechanics:
+ def test_two_hooks_last_writer_wins_per_field(self, monkeypatch, tmp_path):
+ audio = _make_audio(tmp_path)
+ # Two hooks in registration order: the second overwrites ``prompt``
+ # but leaves ``language`` untouched — last-writer-wins PER FIELD.
+ _fake_hooks(
+ monkeypatch,
+ [{"prompt": "first", "language": "ja"}, {"prompt": "second"}],
+ )
+
+ backend = MagicMock(return_value={"success": True, "transcript": "hi"})
+ cfg_patch, prov_patch = _dispatch_ctx({"provider": "openai"}, "openai")
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._transcribe_openai", backend):
+ transcription_tools.transcribe_audio(audio)
+
+ _, kwargs = backend.call_args
+ assert kwargs["prompt"] == "second"
+ assert kwargs["language"] == "ja"
+
+ def test_hook_model_override_flows_to_backend(self, monkeypatch, tmp_path):
+ audio = _make_audio(tmp_path)
+ _fake_hooks(monkeypatch, [{"model": "gpt-4o-transcribe"}])
+
+ backend = MagicMock(return_value={"success": True, "transcript": "hi"})
+ cfg_patch, prov_patch = _dispatch_ctx({"provider": "openai"}, "openai")
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._transcribe_openai", backend):
+ transcription_tools.transcribe_audio(audio)
+
+ args, _ = backend.call_args
+ assert args[1] == "gpt-4o-transcribe"
+
+ def test_file_path_mutation_dropped_with_log(
+ self, monkeypatch, tmp_path, caplog,
+ ):
+ audio = _make_audio(tmp_path)
+ _fake_hooks(
+ monkeypatch,
+ [{"file_path": "/evil/other.ogg", "prompt": PROMPT}],
+ )
+
+ backend = MagicMock(return_value={"success": True, "transcript": "hi"})
+ cfg_patch, prov_patch = _dispatch_ctx({"provider": "openai"}, "openai")
+ with caplog.at_level(logging.WARNING, logger="tools.transcription_tools"), \
+ cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._transcribe_openai", backend):
+ transcription_tools.transcribe_audio(audio)
+
+ args, kwargs = backend.call_args
+ # Original file_path untouched, valid fields still applied.
+ assert args[0] == audio
+ assert kwargs["prompt"] == PROMPT
+ assert "read-only" in caplog.text
+
+ def test_non_string_field_values_ignored(self, monkeypatch, tmp_path):
+ audio = _make_audio(tmp_path)
+ _fake_hooks(monkeypatch, [{"prompt": 123, "language": ["en"]}])
+
+ backend = MagicMock(return_value={"success": True, "transcript": "hi"})
+ cfg_patch, prov_patch = _dispatch_ctx({"provider": "openai"}, "openai")
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._transcribe_openai", backend):
+ transcription_tools.transcribe_audio(audio)
+
+ _, kwargs = backend.call_args
+ assert kwargs["prompt"] is None
+ assert kwargs["language"] is None
+
+ def test_hook_receives_expected_kwargs(self, monkeypatch, tmp_path):
+ audio = _make_audio(tmp_path)
+ captured = _fake_hooks(monkeypatch, [])
+
+ backend = MagicMock(return_value={"success": True, "transcript": "hi"})
+ cfg_patch, prov_patch = _dispatch_ctx(
+ {"provider": "openai", "prompt": "config base"}, "openai",
+ )
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._transcribe_openai", backend):
+ transcription_tools.transcribe_audio(
+ audio, model="whisper-1", source="gateway",
+ )
+
+ assert captured["hook_name"] == "pre_transcription"
+ kw = captured["kwargs"]
+ assert kw["file_path"] == audio
+ assert kw["provider"] == "openai"
+ assert kw["model"] == "whisper-1"
+ # Config is the base — the hook sees the static stt.prompt value.
+ assert kw["prompt"] == "config base"
+ assert kw["source"] == "gateway"
+
+
+# ---------------------------------------------------------------------------
+# No-hook path stays identical
+# ---------------------------------------------------------------------------
+
+
+class TestNoHookPath:
+ def test_no_hook_dispatch_kwargs_identical_to_control(
+ self, monkeypatch, tmp_path,
+ ):
+ audio = _make_audio(tmp_path)
+ _no_hooks(monkeypatch) # invoke_hook raises if ever called
+
+ backend = MagicMock(return_value={"success": True, "transcript": "hi"})
+ cfg_patch, prov_patch = _dispatch_ctx({"provider": "openai"}, "openai")
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._transcribe_openai", backend):
+ transcription_tools.transcribe_audio(audio)
+
+ args, kwargs = backend.call_args
+ assert args == (audio, "whisper-1")
+ # No prompt/language reach the backend — same effective dispatch as
+ # a control run without the hook plumbing.
+ assert kwargs == {"language": None, "prompt": None}
+
+ def test_no_hook_openai_wire_call_has_no_prompt_or_language(
+ self, monkeypatch, tmp_path,
+ ):
+ """Wire-level control: with prompt/language unset, the OpenAI SDK
+ call carries exactly the same kwargs as before this feature."""
+ audio = _make_audio(tmp_path)
+ monkeypatch.setenv("VOICE_TOOLS_OPENAI_KEY", "sk-test")
+
+ mock_client = MagicMock()
+ mock_client.audio.transcriptions.create.return_value = "hello"
+
+ with patch("tools.transcription_tools._HAS_OPENAI", True), \
+ patch("tools.transcription_tools._resolve_stt_language",
+ return_value=None), \
+ patch("openai.OpenAI", return_value=mock_client):
+ transcription_tools._transcribe_openai(audio, "whisper-1")
+
+ _, kwargs = mock_client.audio.transcriptions.create.call_args
+ assert set(kwargs) == {"model", "file", "response_format"}
+
+
+# ---------------------------------------------------------------------------
+# stt.prompt config key
+# ---------------------------------------------------------------------------
+
+
+class TestSttPromptConfig:
+ def test_config_prompt_alone_is_threaded(self, monkeypatch, tmp_path):
+ audio = _make_audio(tmp_path)
+ _no_hooks(monkeypatch)
+
+ backend = MagicMock(return_value={"success": True, "transcript": "hi"})
+ cfg_patch, prov_patch = _dispatch_ctx(
+ {"provider": "openai", "prompt": PROMPT}, "openai",
+ )
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._transcribe_openai", backend):
+ transcription_tools.transcribe_audio(audio)
+
+ _, kwargs = backend.call_args
+ assert kwargs["prompt"] == PROMPT
+
+ def test_hook_prompt_wins_over_config_prompt(self, monkeypatch, tmp_path):
+ audio = _make_audio(tmp_path)
+ _fake_hooks(monkeypatch, [{"prompt": "hook wins"}])
+
+ backend = MagicMock(return_value={"success": True, "transcript": "hi"})
+ cfg_patch, prov_patch = _dispatch_ctx(
+ {"provider": "openai", "prompt": "config base"}, "openai",
+ )
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._transcribe_openai", backend):
+ transcription_tools.transcribe_audio(audio)
+
+ _, kwargs = backend.call_args
+ assert kwargs["prompt"] == "hook wins"
+
+ def test_whisper_family_prompt_truncated_to_tail_with_warning(
+ self, monkeypatch, tmp_path, caplog,
+ ):
+ """Whisper-family providers cap the prompt at ~224 tokens: over-long
+ prompts are truncated client-side (keeping the tail) with a warning,
+ never an error."""
+ audio = _make_audio(tmp_path)
+ long_prompt = "domain-vocabulary " * 300
+ _fake_hooks(monkeypatch, [{"prompt": long_prompt}])
+
+ backend = MagicMock(return_value={"success": True, "transcript": "hi"})
+ cfg_patch, prov_patch = _dispatch_ctx(
+ {"provider": "openai", "prompt": "config base"}, "openai",
+ )
+ with caplog.at_level(logging.WARNING, logger="tools.transcription_tools"), \
+ cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._transcribe_openai", backend):
+ result = transcription_tools.transcribe_audio(audio)
+
+ assert result["success"] is True # truncation never errors
+ _, kwargs = backend.call_args
+ max_chars = (
+ transcription_tools._WHISPER_PROMPT_TOKEN_CAP
+ * transcription_tools._PROMPT_CHARS_PER_TOKEN
+ )
+ assert len(kwargs["prompt"]) == max_chars
+ # Tail survives — whisper conditions on the final context window.
+ assert kwargs["prompt"] == long_prompt[-max_chars:]
+ assert "truncating" in caplog.text
+
+ def test_non_whisper_provider_prompt_not_truncated(
+ self, monkeypatch, tmp_path,
+ ):
+ """Providers without a known whisper prompt window (mistral) get the
+ prompt unchanged — the backend owns its own validation."""
+ audio = _make_audio(tmp_path)
+ long_prompt = "domain-vocabulary " * 300
+ _fake_hooks(monkeypatch, [{"prompt": long_prompt}])
+
+ backend = MagicMock(return_value={"success": True, "transcript": "hi"})
+ cfg_patch, prov_patch = _dispatch_ctx(
+ {"provider": "mistral", "prompt": "config base"}, "mistral",
+ )
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._transcribe_mistral", backend):
+ transcription_tools.transcribe_audio(audio)
+
+ _, kwargs = backend.call_args
+ assert kwargs["prompt"] == long_prompt
+
+ def test_short_prompt_not_truncated(self, monkeypatch, tmp_path):
+ audio = _make_audio(tmp_path)
+ _fake_hooks(monkeypatch, [{"prompt": PROMPT}])
+
+ backend = MagicMock(return_value={"success": True, "transcript": "hi"})
+ cfg_patch, prov_patch = _dispatch_ctx(
+ {"provider": "openai", "prompt": "config base"}, "openai",
+ )
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._transcribe_openai", backend):
+ transcription_tools.transcribe_audio(audio)
+
+ _, kwargs = backend.call_args
+ assert kwargs["prompt"] == PROMPT
+
+ def test_blank_config_prompt_ignored(self, monkeypatch, tmp_path):
+ audio = _make_audio(tmp_path)
+ _no_hooks(monkeypatch)
+
+ backend = MagicMock(return_value={"success": True, "transcript": "hi"})
+ cfg_patch, prov_patch = _dispatch_ctx(
+ {"provider": "openai", "prompt": " "}, "openai",
+ )
+ with cfg_patch, prov_patch, \
+ patch("tools.transcription_tools._transcribe_openai", backend):
+ transcription_tools.transcribe_audio(audio)
+
+ _, kwargs = backend.call_args
+ assert kwargs["prompt"] is None
+
+
+# ---------------------------------------------------------------------------
+# Backends without prompt support
+# ---------------------------------------------------------------------------
+
+
+class TestUnsupportedBackends:
+ def test_xai_logs_debug_and_proceeds_without_prompt(
+ self, monkeypatch, tmp_path, caplog,
+ ):
+ audio = _make_audio(tmp_path)
+ monkeypatch.setattr(
+ "tools.xai_http.resolve_xai_http_credentials",
+ lambda: {"api_key": "xk-test", "base_url": None},
+ )
+ monkeypatch.setattr(
+ "tools.xai_http.hermes_xai_user_agent", lambda: "test-ua",
+ )
+
+ response = MagicMock(status_code=200)
+ response.json.return_value = {"text": "hello", "language": "en", "duration": 1.0}
+ fake_requests = SimpleNamespace(post=MagicMock(return_value=response))
+ monkeypatch.setitem(sys.modules, "requests", fake_requests)
+
+ with caplog.at_level(logging.DEBUG, logger="tools.transcription_tools"), \
+ patch("tools.transcription_tools._load_stt_config", return_value={}):
+ result = transcription_tools._transcribe_xai(
+ audio, "grok-stt", prompt=PROMPT,
+ )
+
+ assert result["success"] is True
+ assert "does not support transcription prompts" in caplog.text
+ _, kwargs = fake_requests.post.call_args
+ assert "prompt" not in kwargs["data"]
+
+ def test_elevenlabs_logs_debug_and_proceeds_without_prompt(
+ self, monkeypatch, tmp_path, caplog,
+ ):
+ audio = _make_audio(tmp_path)
+ monkeypatch.setenv("ELEVENLABS_API_KEY", "el-test")
+
+ response = MagicMock(status_code=200)
+ response.json.return_value = {"text": "hello"}
+ fake_requests = SimpleNamespace(post=MagicMock(return_value=response))
+ monkeypatch.setitem(sys.modules, "requests", fake_requests)
+
+ with caplog.at_level(logging.DEBUG, logger="tools.transcription_tools"), \
+ patch("tools.transcription_tools._load_stt_config", return_value={}):
+ result = transcription_tools._transcribe_elevenlabs(
+ audio, "scribe_v2", prompt=PROMPT,
+ )
+
+ assert result["success"] is True
+ assert "does not support transcription prompts" in caplog.text
+ _, kwargs = fake_requests.post.call_args
+ assert "prompt" not in kwargs["data"]
+
+
+# ---------------------------------------------------------------------------
+# Plugin-registered providers (TranscriptionProvider ABC)
+# ---------------------------------------------------------------------------
+
+
+class TestPluginProviderThreading:
+ @pytest.fixture(autouse=True)
+ def _reset_registry(self):
+ from agent import transcription_registry
+ transcription_registry._reset_for_tests()
+ yield
+ transcription_registry._reset_for_tests()
+
+ def _register_fake_provider(self):
+ from agent import transcription_registry
+ from agent.transcription_provider import TranscriptionProvider
+
+ class _FakeProvider(TranscriptionProvider):
+ def __init__(self):
+ self.last_call = None
+
+ @property
+ def name(self):
+ return "openrouter"
+
+ def transcribe(self, file_path, **kw):
+ self.last_call = {"file_path": file_path, "kwargs": dict(kw)}
+ return {"success": True, "transcript": "hi", "provider": "openrouter"}
+
+ provider = _FakeProvider()
+ transcription_registry.register_provider(provider)
+ return provider
+
+ def test_plugin_provider_receives_prompt_via_extra_kwargs(
+ self, monkeypatch, tmp_path,
+ ):
+ audio = _make_audio(tmp_path)
+ provider = self._register_fake_provider()
+ _fake_hooks(monkeypatch, [{"prompt": PROMPT, "language": "en"}])
+
+ cfg_patch, prov_patch = _dispatch_ctx(
+ {"provider": "openrouter"}, "openrouter",
+ )
+ with cfg_patch, prov_patch:
+ result = transcription_tools.transcribe_audio(audio)
+
+ assert result["success"] is True
+ assert provider.last_call["kwargs"]["prompt"] == PROMPT
+ assert provider.last_call["kwargs"]["language"] == "en"
+
+ def test_plugin_provider_sees_no_prompt_key_when_unset(
+ self, monkeypatch, tmp_path,
+ ):
+ audio = _make_audio(tmp_path)
+ provider = self._register_fake_provider()
+ _no_hooks(monkeypatch)
+
+ cfg_patch, prov_patch = _dispatch_ctx(
+ {"provider": "openrouter"}, "openrouter",
+ )
+ with cfg_patch, prov_patch:
+ transcription_tools.transcribe_audio(audio)
+
+ # Byte-identical no-prompt path: the key is not even sent.
+ assert "prompt" not in provider.last_call["kwargs"]
+
+
+# ---------------------------------------------------------------------------
+# End-to-end with a real fixture plugin (real PluginManager mechanics)
+# ---------------------------------------------------------------------------
+
+
+def test_real_fixture_plugins_thread_prompt_in_registration_order(
+ monkeypatch, tmp_path,
+):
+ """Two callbacks registered by a real plugin, applied in registration
+ order with last-writer-wins — verified against the faster-whisper
+ backend stub receiving ``initial_prompt``."""
+ import os
+ from pathlib import Path
+
+ import yaml
+
+ hermes_home = Path(os.environ["HERMES_HOME"])
+ plugin_dir = hermes_home / "plugins" / "stt_vocab"
+ plugin_dir.mkdir(parents=True)
+ (plugin_dir / "plugin.yaml").write_text("name: stt_vocab\n", encoding="utf-8")
+ (plugin_dir / "__init__.py").write_text(
+ "def register(ctx):\n"
+ ' ctx.register_hook("pre_transcription", '
+ 'lambda **kw: {"prompt": "loser", "language": "en"})\n'
+ ' ctx.register_hook("pre_transcription", '
+ f'lambda **kw: {{"prompt": "{PROMPT}"}})\n',
+ encoding="utf-8",
+ )
+ cfg_path = hermes_home / "config.yaml"
+ cfg_path.write_text(
+ yaml.safe_dump({"plugins": {"enabled": ["stt_vocab"]}}),
+ encoding="utf-8",
+ )
+
+ old_manager = plugins_mod._plugin_manager
+ plugins_mod._plugin_manager = plugins_mod.PluginManager()
+ try:
+ plugins_mod.discover_plugins()
+
+ audio = _make_audio(tmp_path)
+ mock_segment = MagicMock()
+ mock_segment.text = "hello"
+ mock_info = MagicMock(language="en", duration=1.0)
+ mock_model = MagicMock()
+ mock_model.transcribe.return_value = ([mock_segment], mock_info)
+
+ with patch("tools.transcription_tools._load_stt_config",
+ return_value={"provider": "local"}), \
+ patch("tools.transcription_tools._get_provider",
+ return_value="local"), \
+ patch("tools.transcription_tools._HAS_FASTER_WHISPER", True), \
+ patch("tools.transcription_tools._load_local_whisper_model",
+ return_value=mock_model), \
+ patch("tools.transcription_tools._local_model", None):
+ result = transcription_tools.transcribe_audio(audio)
+ finally:
+ plugins_mod._plugin_manager = old_manager
+
+ assert result["success"] is True
+ _, kwargs = mock_model.transcribe.call_args
+ assert kwargs["initial_prompt"] == PROMPT # last writer won
+ assert kwargs["language"] == "en" # earlier hook's field preserved
diff --git a/tools/transcription_tools.py b/tools/transcription_tools.py
index e3112738497..c02a35a934f 100644
--- a/tools/transcription_tools.py
+++ b/tools/transcription_tools.py
@@ -876,6 +876,8 @@ def _transcribe_command_stt(
config: Dict[str, Any],
stt_config: Dict[str, Any],
model_override: Optional[str] = None,
+ language_override: Optional[str] = None,
+ prompt: Optional[str] = None,
) -> Dict[str, Any]:
"""Transcribe via a user-declared ``stt.providers.<name>: type: command``.
@@ -896,6 +898,12 @@ def _transcribe_command_stt(
Returns the standard transcribe-response envelope (``success``,
``transcript``, ``provider``, ``error``).
"""
+ if prompt:
+ logger.debug(
+ "Command STT provider '%s' does not support transcription "
+ "prompts — proceeding without the prompt.", provider_name,
+ )
+
command_template = str(config.get("command") or "").strip()
if not command_template:
return {
@@ -917,7 +925,8 @@ def _transcribe_command_stt(
timeout = _get_command_stt_timeout(config)
output_format = _get_command_stt_output_format(config)
language = (
- config.get("language")
+ language_override
+ or config.get("language")
or _resolve_stt_language(provider_name, stt_config)
or DEFAULT_COMMAND_STT_LANGUAGE
)
@@ -1170,6 +1179,7 @@ def _dispatch_to_plugin_provider(
*,
model: Optional[str] = None,
language: Optional[str] = None,
+ prompt: Optional[str] = None,
) -> Optional[Dict[str, Any]]:
"""Route the call to a plugin-registered transcription provider, or
return None.
@@ -1274,11 +1284,19 @@ def _dispatch_to_plugin_provider(
}
logger.info("Transcribing with plugin STT provider '%s'...", key)
+ # Plugin providers receive the transcription prompt via the ABC's
+ # existing ``**extra`` kwargs — no signature change needed. The key is
+ # only sent when a prompt is actually set so providers that predate it
+ # see byte-identical calls on the no-prompt path.
+ extra_kwargs: Dict[str, Any] = {}
+ if prompt is not None:
+ extra_kwargs["prompt"] = prompt
try:
result = plugin_provider.transcribe(
file_path,
model=model,
language=language,
+ **extra_kwargs,
)
except Exception as exc: # noqa: BLE001
logger.warning(
@@ -1306,6 +1324,142 @@ def _dispatch_to_plugin_provider(
return result
+# ---------------------------------------------------------------------------
+# pre_transcription plugin hook (issue #64168 — STT prompt/vocab threading)
+# ---------------------------------------------------------------------------
+
+
+# Fields a pre_transcription hook may mutate. ``file_path`` is deliberately
+# absent — it is read-only; attempts to change it are logged and dropped.
+_PRE_TRANSCRIPTION_MUTABLE_FIELDS = ("prompt", "language", "model")
+
+# Whisper-family models silently use only the final ~224 tokens of the
+# prompt/initial_prompt; longer values waste upload bytes and can trip
+# stricter OpenAI-compatible servers. Enforce the cap client-side for the
+# whisper-family backends: truncate with a warning, never error.
+# Approximation: ~4 characters per token (no tokenizer dependency).
+_WHISPER_PROMPT_TOKEN_CAP = 224
+_PROMPT_CHARS_PER_TOKEN = 4
+# Providers whose prompt parameter feeds a whisper-family model.
+_WHISPER_PROMPT_CAPPED_PROVIDERS = frozenset(
+ {"local", "openai", "groq", "deepinfra"}
+)
+
+
+def _enforce_prompt_length_limit(
+ prompt: Optional[str], provider: str
+) -> Optional[str]:
+ """Truncate *prompt* to the provider's known token cap (fail-open).
+
+ Only whisper-family backends have a documented ~224-token prompt window;
+ other providers (mistral, plugin providers) own their own validation.
+ Truncation keeps the TAIL of the prompt because whisper conditions on
+ the final context window — the most recently appended hints survive.
+ """
+ if not prompt or provider not in _WHISPER_PROMPT_CAPPED_PROVIDERS:
+ return prompt
+ max_chars = _WHISPER_PROMPT_TOKEN_CAP * _PROMPT_CHARS_PER_TOKEN
+ if len(prompt) <= max_chars:
+ return prompt
+ logger.warning(
+ "Transcription prompt is ~%d tokens; whisper-family provider '%s' "
+ "only uses the final ~%d — truncating to the last %d characters.",
+ len(prompt) // _PROMPT_CHARS_PER_TOKEN,
+ provider,
+ _WHISPER_PROMPT_TOKEN_CAP,
+ max_chars,
+ )
+ return prompt[-max_chars:]
+
+
+def _apply_pre_transcription_hook(
+ *,
+ file_path: str,
+ provider: str,
+ model: Optional[str],
+ language: Optional[str],
+ prompt: Optional[str],
+ source: Optional[str],
+) -> tuple[Optional[str], Optional[str], Optional[str]]:
+ """Fire the ``pre_transcription`` plugin hook and merge its results.
+
+ Mirrors the ``transform_*`` hook mechanics (``transform_tool_result``):
+ gated on ``has_hook`` so the no-hook dispatch path never builds hook
+ kwargs, and fail-open — any hook-plumbing error leaves the dispatch
+ untouched. ``invoke_hook`` returns results in registration order, and
+ plugin discovery scans plugin directories in sorted order, so multiple
+ plugins' hints compose deterministically (sorted by plugin id, then
+ each plugin's own registration order). Each dict result is applied
+ field-by-field on top of the previous ones, so the last hook to write
+ a field wins (last-writer-wins per field).
+
+ Model values are accepted as-is: the dispatcher has no catalog-level
+ validation today, so a hook-set model flows through the exact same
+ per-backend normalization/auto-correction (``_normalize_local_model``,
+ the Groq/OpenAI cross-corrections) a caller-supplied model would, and
+ otherwise errors at the backend as it would today.
+
+ Returns ``(model, language_override, prompt)``. ``language_override``
+ is ``None`` unless a hook explicitly set ``language`` — backends keep
+ their existing config/env language resolution when no hook overrides
+ it.
+ """
+ try:
+ from hermes_cli.plugins import has_hook, invoke_hook
+
+ # No-hook short-circuit: keep the no-plugin dispatch path
+ # byte-identical (no kwargs built, no invoke_hook call).
+ if not has_hook("pre_transcription"):
+ return model, None, prompt
+
+ hook_results = invoke_hook(
+ "pre_transcription",
+ file_path=file_path,
+ provider=provider,
+ model=model,
+ language=language,
+ prompt=prompt,
+ source=source,
+ )
+ overrides: Dict[str, Any] = {}
+ for hook_result in hook_results:
+ if not isinstance(hook_result, dict):
+ continue
+ for key, value in hook_result.items():
+ if key == "file_path":
+ # file_path is read-only for hooks — log and drop.
+ logger.warning(
+ "pre_transcription hook attempted to change "
+ "file_path (read-only) — ignoring the attempt."
+ )
+ continue
+ if key not in _PRE_TRANSCRIPTION_MUTABLE_FIELDS:
+ logger.debug(
+ "pre_transcription hook returned unsupported field "
+ "%r — ignoring.", key,
+ )
+ continue
+ if not isinstance(value, str):
+ logger.debug(
+ "pre_transcription hook returned non-string value "
+ "%r for field %r — ignoring.", value, key,
+ )
+ continue
+ overrides[key] = value
+
+ if "model" in overrides:
+ model = overrides["model"]
+ if "prompt" in overrides:
+ # Hook results win over the static ``stt.prompt`` config value —
+ # config is the base, hooks mutate on top. An empty string
+ # clears the config prompt.
+ prompt = overrides["prompt"] or None
+ return model, overrides.get("language") or None, prompt
+ except Exception as _hook_err: # noqa: BLE001 — hook plumbing is fail-open
+ logger.debug("pre_transcription hook error: %s", _hook_err)
+ return model, None, prompt
+
+
# ---------------------------------------------------------------------------
# Shared validation
# ---------------------------------------------------------------------------
@@ -1740,7 +1894,13 @@ def _join_confident_segments(segments: Any, local_cfg: Dict[str, Any]) -> str:
return " ".join(kept).strip()
-def _transcribe_local(file_path: str, model_name: str) -> Dict[str, Any]:
+def _transcribe_local(
+ file_path: str,
+ model_name: str,
+ *,
+ language: Optional[str] = None,
+ prompt: Optional[str] = None,
+) -> Dict[str, Any]:
"""Transcribe using faster-whisper (local, free)."""
global _local_model, _local_model_name
@@ -1786,6 +1946,13 @@ def _transcribe_local(file_path: str, model_name: str) -> Dict[str, Any]:
stt_config = _load_stt_config()
local_config = stt_config.get("local") or {}
transcribe_kwargs = build_local_transcribe_kwargs(stt_config)
+ # pre_transcription hook overrides win over the config-resolved
+ # values from build_local_transcribe_kwargs.
+ if language:
+ transcribe_kwargs["language"] = language
+ if prompt:
+ # faster-whisper's vocabulary/context hint parameter.
+ transcribe_kwargs["initial_prompt"] = prompt
try:
segments, info = model.transcribe(file_path, **transcribe_kwargs)
@@ -1879,8 +2046,20 @@ def _convert_caf_to_wav(file_path: str) -> Optional[str]:
return None
-def _transcribe_local_command(file_path: str, model_name: str) -> Dict[str, Any]:
+def _transcribe_local_command(
+ file_path: str,
+ model_name: str,
+ *,
+ language: Optional[str] = None,
+ prompt: Optional[str] = None,
+) -> Dict[str, Any]:
"""Run the configured local STT command template and read back a .txt transcript."""
+ if prompt:
+ logger.debug(
+ "STT provider 'local_command' does not support transcription "
+ "prompts — proceeding without the prompt."
+ )
+
command_template = _get_local_command_template()
if not command_template:
return {
@@ -1891,8 +2070,11 @@ def _transcribe_local_command(file_path: str, model_name: str) -> Dict[str, Any]
),
}
- # Language: stt.local.language > stt.language > env var > "en" default.
- language = _resolve_stt_language("local") or DEFAULT_LOCAL_STT_LANGUAGE
+ # Language: hook override > stt.local.language > stt.language > env var
+ # > "en" default.
+ language = (
+ language or _resolve_stt_language("local") or DEFAULT_LOCAL_STT_LANGUAGE
+ )
normalized_model = _normalize_local_command_model(model_name)
try:
@@ -1962,13 +2144,19 @@ def _transcribe_local_command(file_path: str, model_name: str) -> Dict[str, Any]
# ---------------------------------------------------------------------------
-def _transcribe_groq(file_path: str, model_name: str) -> Dict[str, Any]:
+def _transcribe_groq(
+ file_path: str,
+ model_name: str,
+ *,
+ language: Optional[str] = None,
+ prompt: Optional[str] = None,
+) -> Dict[str, Any]:
"""Transcribe using Groq Whisper API (free tier available).
- Honours an optional ISO-639-1 language hint resolved from
- ``stt.groq.language`` > ``stt.language`` (config.yaml) >
- ``HERMES_LOCAL_STT_LANGUAGE`` (env). When none is set, Groq
- Whisper auto-detects.
+ Honours an optional ISO-639-1 language hint resolved from a
+ ``pre_transcription`` hook override > ``stt.groq.language`` >
+ ``stt.language`` (config.yaml) > ``HERMES_LOCAL_STT_LANGUAGE`` (env).
+ When none is set, Groq Whisper auto-detects.
"""
api_key = _resolve_provider_key("GROQ_API_KEY", "groq")
if not api_key:
@@ -1982,7 +2170,8 @@ def _transcribe_groq(file_path: str, model_name: str) -> Dict[str, Any]:
logger.info("Model %s not available on Groq, using %s", model_name, DEFAULT_GROQ_STT_MODEL)
model_name = DEFAULT_GROQ_STT_MODEL
- language = _resolve_stt_language("groq")
+ # Language: hook override > stt.groq.language > stt.language > env.
+ language = language or _resolve_stt_language("groq")
try:
from openai import OpenAI, APIError, APIConnectionError, APITimeoutError
@@ -1994,6 +2183,10 @@ def _transcribe_groq(file_path: str, model_name: str) -> Dict[str, Any]:
}
if language:
create_kwargs["language"] = language
+ if prompt:
+ # Only send the prompt when set so the no-hook, no-config
+ # request stays byte-identical to today's.
+ create_kwargs["prompt"] = prompt
with open(file_path, "rb") as audio_file:
transcription = client.audio.transcriptions.create(
file=audio_file,
@@ -2034,6 +2227,8 @@ def _transcribe_openai(
api_key: Optional[str] = None,
base_url: Optional[str] = None,
provider_label: str = "openai",
+ language: Optional[str] = None,
+ prompt: Optional[str] = None,
) -> Dict[str, Any]:
"""Transcribe via the OpenAI ``audio.transcriptions.create`` SDK shape.
@@ -2050,9 +2245,10 @@ def _transcribe_openai(
return {"success": False, "transcript": "", "error": str(exc)}
base_url = base_url or fallback_base
- # Language: stt.<provider>.language > stt.language > env > auto-detect.
- # Explicit language hint improves accuracy for non-English languages.
- language = _resolve_stt_language(provider_label)
+ # Language: hook override > stt.<provider>.language > stt.language >
+ # env > auto-detect. Explicit language hint improves accuracy for
+ # non-English languages.
+ language = language or _resolve_stt_language(provider_label)
if not _HAS_OPENAI:
return {"success": False, "transcript": "", "error": "openai package not installed"}
@@ -2090,6 +2286,10 @@ def _transcribe_openai(
else:
create_kwargs["language"] = language
logger.debug("Using language hint '%s' for OpenAI STT", language)
+ if prompt:
+ # Only send the prompt when set so the no-hook, no-config
+ # request stays byte-identical to today's.
+ create_kwargs["prompt"] = prompt
return client.audio.transcriptions.create(**create_kwargs)
try:
@@ -2141,7 +2341,13 @@ def _transcribe_openai(
# ---------------------------------------------------------------------------
-def _transcribe_mistral(file_path: str, model_name: str) -> Dict[str, Any]:
+def _transcribe_mistral(
+ file_path: str,
+ model_name: str,
+ *,
+ language: Optional[str] = None,
+ prompt: Optional[str] = None,
+) -> Dict[str, Any]:
"""Transcribe using Mistral Voxtral Transcribe API.
Uses the ``mistralai`` Python SDK to call ``/v1/audio/transcriptions``.
@@ -2165,10 +2371,15 @@ def _transcribe_mistral(file_path: str, model_name: str) -> Dict[str, Any]:
"model": model_name,
"file": {"content": audio_file, "file_name": Path(file_path).name},
}
- # Language: stt.mistral.language > stt.language > env > auto.
- language = _resolve_stt_language("mistral")
+ # Language: hook override > stt.mistral.language >
+ # stt.language > env > auto.
+ language = language or _resolve_stt_language("mistral")
if language:
complete_kwargs["language"] = language
+ if prompt:
+ # Only send the prompt when set so the no-hook, no-config
+ # request stays byte-identical to today's.
+ complete_kwargs["prompt"] = prompt
result = client.audio.transcriptions.complete(**complete_kwargs)
transcript_text = _extract_transcript_text(result)
@@ -2190,7 +2401,13 @@ def _transcribe_mistral(file_path: str, model_name: str) -> Dict[str, Any]:
# ---------------------------------------------------------------------------
-def _transcribe_xai(file_path: str, model_name: str) -> Dict[str, Any]:
+def _transcribe_xai(
+ file_path: str,
+ model_name: str,
+ *,
+ language: Optional[str] = None,
+ prompt: Optional[str] = None,
+) -> Dict[str, Any]:
"""Transcribe using xAI Grok STT API.
Uses the ``POST /v1/stt`` REST endpoint with multipart/form-data.
@@ -2199,6 +2416,12 @@ def _transcribe_xai(file_path: str, model_name: str) -> Dict[str, Any]:
"""
from tools.xai_http import resolve_xai_http_credentials
+ if prompt:
+ logger.debug(
+ "STT provider 'xai' does not support transcription prompts — "
+ "proceeding without the prompt."
+ )
+
# STT is an API-billed endpoint. Prefer the explicit XAI_API_KEY over the
# general xAI OAuth/Grok-subscription credential; subscription OAuth may be
# valid for Grok while returning personal-team spending-limit errors for
@@ -2240,7 +2463,8 @@ def _transcribe_xai(file_path: str, model_name: str) -> Dict[str, Any]:
).strip().rstrip("/")
base_url = _resolve_base_url(creds)
- language = _resolve_stt_language("xai", stt_config) or ""
+ # Language: hook override > stt.xai.language > stt.language > env.
+ language = language or _resolve_stt_language("xai", stt_config) or ""
# .get("format", True) already defaults to True when the key is absent;
# is_truthy_value only normalizes truthy/falsy strings from config.
use_format = is_truthy_value(xai_config.get("format", True))
@@ -2347,8 +2571,20 @@ def _transcribe_xai(file_path: str, model_name: str) -> Dict[str, Any]:
# ---------------------------------------------------------------------------
-def _transcribe_elevenlabs(file_path: str, model_name: str) -> Dict[str, Any]:
+def _transcribe_elevenlabs(
+ file_path: str,
+ model_name: str,
+ *,
+ language: Optional[str] = None,
+ prompt: Optional[str] = None,
+) -> Dict[str, Any]:
"""Transcribe using ElevenLabs Scribe STT API."""
+ if prompt:
+ logger.debug(
+ "STT provider 'elevenlabs' does not support transcription "
+ "prompts — proceeding without the prompt."
+ )
+
api_key = _resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs")
if not api_key:
return {"success": False, "transcript": "", "error": "ELEVENLABS_API_KEY not set"}
@@ -2360,7 +2596,8 @@ def _transcribe_elevenlabs(file_path: str, model_name: str) -> Dict[str, Any]:
or get_env_value("ELEVENLABS_STT_BASE_URL")
or ELEVENLABS_STT_BASE_URL
).strip().rstrip("/")
- language_code = _resolve_stt_language(
+ # Language: hook override > stt.elevenlabs.language(_code) > stt.language.
+ language_code = language or _resolve_stt_language(
"elevenlabs", stt_config, extra_keys=("language_code",)
) or ""
tag_audio_events = is_truthy_value(elevenlabs_config.get("tag_audio_events", False))
@@ -2436,7 +2673,13 @@ def _transcribe_elevenlabs(file_path: str, model_name: str) -> Dict[str, Any]:
# ---------------------------------------------------------------------------
-def _transcribe_deepinfra(file_path: str, model_name: str) -> Dict[str, Any]:
+def _transcribe_deepinfra(
+ file_path: str,
+ model_name: str,
+ *,
+ language: Optional[str] = None,
+ prompt: Optional[str] = None,
+) -> Dict[str, Any]:
"""Resolve DeepInfra credentials/model, then delegate to the OpenAI handler.
DeepInfra's STT endpoint is OpenAI-compatible, so the actual SDK
@@ -2481,6 +2724,8 @@ def _transcribe_deepinfra(file_path: str, model_name: str) -> Dict[str, Any]:
api_key=api_key,
base_url=base_url,
provider_label="deepinfra",
+ language=language,
+ prompt=prompt,
)
@@ -2655,7 +2900,11 @@ def _trim_silence_for_cloud_stt(
# ---------------------------------------------------------------------------
-def _transcribe_prepared_audio(file_path: str, model: Optional[str] = None) -> Dict[str, Any]:
+def _transcribe_prepared_audio(
+ file_path: str,
+ model: Optional[str] = None,
+ source: Optional[str] = None,
+) -> Dict[str, Any]:
"""
Transcribe an audio file using the configured STT provider.
@@ -2666,6 +2915,9 @@ def _transcribe_prepared_audio(file_path: str, model: Optional[str] = None) -> D
Args:
file_path: Absolute path to the audio file to transcribe.
model: Override the model. If None, uses config or provider default.
+ source: Optional caller-surface label (e.g. ``"gateway"``,
+ ``"voice_mode"``) forwarded to the ``pre_transcription``
+ plugin hook for observability. Not used for dispatch.
Returns:
dict with keys:
@@ -2726,7 +2978,7 @@ def _transcribe_prepared_audio(file_path: str, model: Optional[str] = None) -> D
trim_cleanup_dir = os.path.dirname(trimmed)
try:
- return _dispatch_stt_provider(file_path, provider, stt_config, model)
+ return _dispatch_stt_provider(file_path, provider, stt_config, model, source)
finally:
if trim_cleanup_dir:
shutil.rmtree(trim_cleanup_dir, ignore_errors=True)
@@ -2737,52 +2989,97 @@ def _dispatch_stt_provider(
provider: str,
stt_config: Dict[str, Any],
model: Optional[str] = None,
+ source: Optional[str] = None,
) -> Dict[str, Any]:
"""Route *file_path* to the handler for *provider* (built-in > command > plugin)."""
+ # Optional static transcription prompt (``stt.prompt`` in config.yaml):
+ # vocabulary/context hints threaded to prompt-capable backends.
+ # Ordering: config is the base; pre_transcription hook results mutate on
+ # top, in registration order, so the last hook to set a field wins.
+ prompt = stt_config.get("prompt")
+ if not isinstance(prompt, str) or not prompt.strip():
+ prompt = None
+
+ # pre_transcription plugin hook — fires after provider resolution and
+ # BEFORE any backend (built-in, command-type, or plugin-registered) is
+ # invoked. Hooks may mutate prompt/language/model; file_path is
+ # read-only. The helper short-circuits on has_hook() so the no-hook
+ # dispatch path stays byte-identical. ``language`` stays None unless a
+ # hook overrides it — backends keep their own config/env resolution.
+ model, language, prompt = _apply_pre_transcription_hook(
+ file_path=file_path,
+ provider=provider,
+ model=model,
+ language=_get_stt_section(stt_config, provider).get("language"),
+ prompt=prompt,
+ source=source,
+ )
+
+ # Whisper-family prompt windows top out around 224 tokens — truncate
+ # (keeping the tail) with a warning rather than erroring or letting a
+ # strict server reject the request.
+ prompt = _enforce_prompt_length_limit(prompt, provider)
+
if provider == "local":
local_cfg = stt_config.get("local") or {}
model_name = _normalize_local_model(
model or local_cfg.get("model", DEFAULT_LOCAL_MODEL)
)
- return _transcribe_local(file_path, model_name)
+ return _transcribe_local(
+ file_path, model_name, language=language, prompt=prompt,
+ )
if provider == "local_command":
local_cfg = stt_config.get("local") or {}
model_name = _normalize_local_command_model(
model or local_cfg.get("model", DEFAULT_LOCAL_MODEL)
)
- return _transcribe_local_command(file_path, model_name)
+ return _transcribe_local_command(
+ file_path, model_name, language=language, prompt=prompt,
+ )
if provider == "groq":
groq_cfg = stt_config.get("groq") or {}
model_name = model or groq_cfg.get("model") or DEFAULT_GROQ_STT_MODEL
- return _transcribe_groq(file_path, model_name)
+ return _transcribe_groq(
+ file_path, model_name, language=language, prompt=prompt,
+ )
if provider == "openai":
openai_cfg = stt_config.get("openai") or {}
model_name = model or openai_cfg.get("model", DEFAULT_STT_MODEL)
- return _transcribe_openai(file_path, model_name)
+ return _transcribe_openai(
+ file_path, model_name, language=language, prompt=prompt,
+ )
if provider == "mistral":
mistral_cfg = stt_config.get("mistral") or {}
model_name = model or mistral_cfg.get("model", DEFAULT_MISTRAL_STT_MODEL)
- return _transcribe_mistral(file_path, model_name)
+ return _transcribe_mistral(
+ file_path, model_name, language=language, prompt=prompt,
+ )
if provider == "xai":
# xAI Grok STT doesn't use a model parameter — pass through for logging
model_name = model or "grok-stt"
- return _transcribe_xai(file_path, model_name)
+ return _transcribe_xai(
+ file_path, model_name, language=language, prompt=prompt,
+ )
if provider == "elevenlabs":
elevenlabs_cfg = stt_config.get("elevenlabs") or {}
model_name = model or elevenlabs_cfg.get("model_id", DEFAULT_ELEVENLABS_STT_MODEL)
- return _transcribe_elevenlabs(file_path, model_name)
+ return _transcribe_elevenlabs(
+ file_path, model_name, language=language, prompt=prompt,
+ )
if provider == "deepinfra":
di_config = stt_config.get("deepinfra") # may be None (YAML null)
di_config = di_config if isinstance(di_config, dict) else {}
model_name = model or di_config.get("model") or ""
- return _transcribe_deepinfra(file_path, model_name)
+ return _transcribe_deepinfra(
+ file_path, model_name, language=language, prompt=prompt,
+ )
# User-declared command-type provider
# (``stt.providers.<name>: type: command``). Fires after the built-in
@@ -2798,6 +3095,8 @@ def _dispatch_stt_provider(
command_provider_config,
stt_config,
model_override=model,
+ language_override=language,
+ prompt=prompt,
)
# Plugin-registered STT backend (e.g. OpenRouter, SenseAudio,
@@ -2814,7 +3113,7 @@ def _dispatch_stt_provider(
# forwards ``language`` from there. Top-level ``model`` argument
# overrides any config-set model.
plugin_cfg = stt_config.get(provider, {}) if isinstance(stt_config.get(provider), dict) else {}
- plugin_language = _resolve_stt_language(provider, stt_config)
+ plugin_language = language or _resolve_stt_language(provider, stt_config)
plugin_model = model or plugin_cfg.get("model")
plugin_result = _dispatch_to_plugin_provider(
file_path,
@@ -2822,6 +3121,7 @@ def _dispatch_stt_provider(
stt_config,
model=plugin_model,
language=plugin_language,
+ prompt=prompt,
)
if plugin_result is not None:
return plugin_result
@@ -2850,8 +3150,17 @@ def _dispatch_stt_provider(
}
-def transcribe_audio(file_path: str, model: Optional[str] = None) -> Dict[str, Any]:
- """Safely validate, preprocess supported inputs, and dispatch transcription."""
+def transcribe_audio(
+ file_path: str,
+ model: Optional[str] = None,
+ source: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Safely validate, preprocess supported inputs, and dispatch transcription.
+
+ ``source`` is an optional caller-surface label (e.g. ``"gateway"``,
+ ``"voice_mode"``) forwarded to the ``pre_transcription`` plugin hook for
+ observability. Not used for dispatch.
+ """
# Refuse to feed a credential / secret store (auth.json, .env, OAuth
# tokens, mcp-tokens/, ...) to an STT provider — before ANY validation or
# preprocessing, so the refusal names the real reason rather than a
@@ -2883,7 +3192,7 @@ def transcribe_audio(file_path: str, model: Optional[str] = None) -> Dict[str, A
prepared_error = _validate_audio_file(prepared_path, enforce_size_limit=False)
if prepared_error:
return prepared_error
- return _transcribe_prepared_audio(prepared_path, model)
+ return _transcribe_prepared_audio(prepared_path, model, source)
finally:
if cleanup_dir:
shutil.rmtree(cleanup_dir, ignore_errors=True)
diff --git a/tools/voice_mode.py b/tools/voice_mode.py
index aef09fdafcf..80652bdb0fc 100644
--- a/tools/voice_mode.py
+++ b/tools/voice_mode.py
@@ -1414,7 +1414,7 @@ def transcribe_recording(wav_path: str, model: Optional[str] = None) -> Dict[str
"""
from tools.transcription_tools import MAX_FILE_SIZE, transcribe_audio
- result = transcribe_audio(wav_path, model=model)
+ result = transcribe_audio(wav_path, model=model, source="voice_mode")
# Only chunk when the provider itself reports "File too large" —
# local providers (faster-whisper, whisper.cpp, etc.) have no upload
@@ -1473,7 +1473,7 @@ def _transcribe_wav_in_chunks(
logger.info("Transcribing oversized WAV in %d chunks: %s", len(chunk_paths), wav_path)
for index, chunk_path in enumerate(chunk_paths, start=1):
- result = transcribe_audio(chunk_path, model=model)
+ result = transcribe_audio(chunk_path, model=model, source="voice_mode")
if not result.get("success"):
error = result.get("error", "Unknown transcription error")
return {
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index 18635f79857..6a5a36dd83b 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -1908,6 +1908,7 @@ stt:
cloud_trim_silence: true # trim long pauses with ffmpeg before uploading to a cloud provider (default: true)
cloud_trim_threshold_db: -40 # audio quieter than this counts as silence
cloud_trim_keep_ms: 300 # how much of each pause survives the trim (keeps natural pacing)
+ # prompt: "Hermes, Teknium, Nous Research, kanban" # Static vocabulary hint (see below)
local:
model: "base" # tiny, base, small, medium, large-v3
language: "" # per-provider override of stt.language
@@ -1948,6 +1949,39 @@ GROQ_BASE_URL=https://api.groq.com/openai/v1
STT_OPENAI_BASE_URL=https://api.openai.com/v1
```
+### Transcription prompt (vocabulary hints)
+
+`stt.prompt` is an optional static hint passed to prompt-capable STT backends. Use it for proper nouns, product names, and jargon that Whisper-family models otherwise mis-hear:
+
+```yaml
+stt:
+ provider: "local"
+ prompt: "Hermes, Teknium, Nous Research, kanban, Ollama"
+```
+
+**Composition.** The config value is the base. Plugins that register the [`pre_transcription`](/user-guide/features/hooks#pre_transcription) hook mutate on top of it, last-writer-wins per field. Multiple plugins' hints compose deterministically: plugin discovery loads plugins in sorted order by plugin id, and each plugin's callbacks run in its own registration order, so the same set of plugins always produces the same final prompt. A hook returning an empty string for `prompt` clears the config prompt for that request. Hooks may also override `language` and `model`; `file_path` is read-only and any attempt to change it is logged and dropped. With no hook registered and no `stt.prompt` set, the outgoing request is identical to previous releases.
+
+**Provider support.**
+
+| Provider | Prompt parameter | Behavior |
+|----------|-----------------|----------|
+| `local` (faster-whisper) | `initial_prompt` | Forwarded unchanged to the local model |
+| `openai` | `prompt` | Forwarded unchanged in the transcription request |
+| `groq` | `prompt` | Forwarded unchanged in the transcription request |
+| `mistral` | `prompt` | Forwarded unchanged in the transcription request |
+| `deepinfra` | `prompt` | OpenAI-compatible path, forwarded unchanged |
+| `xai` | not supported | Logged at DEBUG, the request proceeds without the prompt |
+| `elevenlabs` | not supported | Logged at DEBUG, the request proceeds without the prompt |
+| `local_command` | not supported | Logged at DEBUG, the request proceeds without the prompt |
+| `stt.providers.<name>` with `type: command` | not supported | Logged at DEBUG, the request proceeds without the prompt |
+| Plugin-registered providers | `prompt` in the `transcribe(**extra)` kwargs | Only sent when a prompt is set, so providers that predate this key see unchanged calls |
+
+**Length.** Whisper-family models only condition on the final ~224 prompt tokens. For the whisper-family backends (`local`, `openai`, `groq`, `deepinfra`) Hermes enforces that cap client-side: an over-long final prompt is truncated to its tail with a logged warning — the request never errors because of prompt length. Other backends (`mistral`, plugin providers) receive the prompt unchanged and own their own validation. Keep hints short and specific either way.
+
+:::warning Prompts are uploaded with your audio
+The final prompt is sent to the configured STT provider alongside the audio file. Keep secrets and session-derived context out of `stt.prompt` and out of anything a `pre_transcription` hook returns, especially when the provider is a hosted API rather than local `faster-whisper`.
+:::
+
## Voice Mode (CLI)
```yaml
diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.md
index c8e5b278199..82d654fc273 100644
--- a/website/docs/user-guide/features/hooks.md
+++ b/website/docs/user-guide/features/hooks.md
@@ -441,6 +441,7 @@ Payload fields below are the exact event-specific fields supplied by each call s
| `post_tool_call` | Observer | After blocked, error, or successful result; return ignored. | `tool_name`, `args`, `result`, `task_id`, `session_id`, `tool_call_id`, `turn_id`, `api_request_id`, `duration_ms`, `status`, `error_type`, `error_message`, `middleware_trace` | Result/error text may contain arbitrary tool or user content and secrets. |
| `transform_tool_result` | Transform | After `post_tool_call`, before conversation append; first string replaces the result. | `tool_name`, `args`, `result`, `task_id`, `session_id`, `tool_call_id`, `turn_id`, `api_request_id`, `duration_ms`, `status`, `error_type`, `error_message` | Exposes the full model-bound result and arguments. |
| `transform_terminal_output` | Transform | After bounded foreground process capture, before final output limiting; first string replaces output. | `command`, `output`, `returncode`, `task_id`, `env_type` | Command/output may contain credentials. |
+| `pre_transcription` | Transform | Fired by the STT dispatcher after provider resolution and before any backend (built-in, command-type, or plugin-registered) is invoked; dict results are applied in registration order, last-writer-wins per field (`prompt`, `language`, `model`; `file_path` is read-only). | `file_path`, `provider`, `model`, `language`, `prompt`, `source` | The final prompt is uploaded to the configured STT provider with the audio — keep secrets out of hook returns. |
| `pre_llm_call` | Directive/control | Once per turn before the loop; all valid string/`{"context": ...}` returns are joined and injected into the user message. | `session_id`, `task_id`, `turn_id`, `user_message`, `conversation_history`, `is_first_turn`, `model`, `platform`, `parent_session_id`, `sender_id` | Full user message and conversation history. |
| `post_llm_call` | Observer | Successful, non-interrupted turn finalization; return ignored. | `session_id`, `task_id`, `turn_id`, `user_message`, `assistant_response`, `conversation_history`, `model`, `platform` | Full prompt, response, and history. |
| `transform_llm_output` | Transform | Before `post_llm_call` and final delivery; first non-empty string replaces the response. | `response_text`, `session_id`, `model`, `platform` | Full final assistant text. |
@@ -1302,6 +1303,53 @@ def register(ctx):
---
+### `pre_transcription`
+
+Fires inside the STT dispatcher (`tools.transcription_tools.transcribe_audio`) **after** the provider has been resolved and **before** any backend is invoked, whether that backend is built-in, a `type: command` provider, or a plugin-registered provider. Lets a plugin steer the transcription request itself instead of only observing the transcript afterwards.
+
+**Callback signature:**
+
+```python
+def my_callback(
+ file_path: str,
+ provider: str,
+ model: str | None,
+ language: str | None,
+ prompt: str | None,
+ source: str | None,
+ **kwargs,
+) -> dict | None:
+```
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `file_path` | `str` | Absolute path to the audio file about to be transcribed. Read-only. |
+| `provider` | `str` | Resolved STT provider (`local`, `groq`, `openai`, `mistral`, `xai`, `elevenlabs`, `deepinfra`, `local_command`, a command provider name, or a plugin provider name). |
+| `model` | `str \| None` | Model resolved so far, or `None` when the backend default applies. |
+| `language` | `str \| None` | Language from the provider's config section, or `None`. |
+| `prompt` | `str \| None` | The static [`stt.prompt`](/user-guide/configuration#transcription-prompt-vocabulary-hints) value, or `None`. |
+| `source` | `str \| None` | Caller surface label (`gateway`, `voice_mode`, …). Observability only, not used for dispatch. |
+
+**Return value:** a `dict` with any of `"prompt"`, `"language"`, `"model"` mapped to strings, or `None` to leave the request unchanged. Non-string values, unknown keys, and `file_path` are ignored (`file_path` attempts are logged as a warning). Results are applied in **registration order, last-writer-wins per field**, on top of the `stt.prompt` config value. Returning `""` for `prompt` clears the configured prompt for that request.
+
+**Use cases:** Inject a per-user or per-chat vocabulary list before the audio is uploaded, force `language` from the caller's locale, downgrade `model` for long recordings, route noisy sources to a different model.
+
+```python
+VOCAB = "Hermes, Teknium, Nous Research, kanban"
+
+def add_vocab(provider, prompt, source, **kwargs):
+ if source != "gateway":
+ return None
+ return {"prompt": f"{prompt}. {VOCAB}" if prompt else VOCAB}
+
+def register(ctx):
+ ctx.register_hook("pre_transcription", add_vocab)
+```
+
+Not every backend accepts a prompt. `local` maps it to faster-whisper's `initial_prompt`; `openai`, `groq`, `mistral`, and `deepinfra` send it as `prompt`; `xai`, `elevenlabs`, `local_command`, and `type: command` providers log at DEBUG and transcribe without it. See the [provider support table](/user-guide/configuration#transcription-prompt-vocabulary-hints) for the full matrix and the privacy boundary. Hook-plumbing errors are fail-open: the dispatch continues with the unmodified request.
+
+---
+
### `transform_tool_result`
Fires **after** a tool returns and **before** the result is appended to the conversation. Lets a plugin rewrite ANY tool's result string — not just terminal output — before the model sees it.
diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.md
index 185a096ba17..438831ac4d9 100644
--- a/website/docs/user-guide/features/plugins.md
+++ b/website/docs/user-guide/features/plugins.md
@@ -259,12 +259,12 @@ When you upgrade to a version of Hermes that has opt-in plugins (config schema v
## Available hooks
-Plugins can register the 24 lifecycle events currently accepted by `hermes_cli.plugins.VALID_HOOKS`. The **[Event Hooks catalog](/user-guide/features/hooks#shipped-plugin-hook-catalog)** is canonical for exact timing, return handling, payload fields, and privacy notes.
+Plugins can register the 25 lifecycle events currently accepted by `hermes_cli.plugins.VALID_HOOKS`. The **[Event Hooks catalog](/user-guide/features/hooks#shipped-plugin-hook-catalog)** is canonical for exact timing, return handling, payload fields, and privacy notes.
| Descriptive category | Shipped hooks |
|---|---|
| **Directive/control** | `pre_tool_call`, `pre_llm_call`, `pre_verify`, `pre_gateway_dispatch` |
-| **Transform** | `transform_tool_result`, `transform_terminal_output`, `transform_llm_output` |
+| **Transform** | `transform_tool_result`, `transform_terminal_output`, `transform_llm_output`, `pre_transcription` |
| **Observer** | `post_tool_call`, `post_llm_call`, `pre_api_request`, `post_api_request`, `api_request_error`, `on_stream_start`, `on_stream_delta`, `on_stream_end`, `on_interim_message`, `on_session_start`, `on_session_end`, `on_session_finalize`, `on_session_reset`, `on_skill_lifecycle`, `subagent_start`, `subagent_stop`, `pre_approval_request`, `post_approval_response`, `kanban_task_claimed`, `kanban_task_completed`, `kanban_task_blocked` |
These categories describe current behavior rather than defining future naming rules. Plugin middleware remains a separate registry/surface.