Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions tests/tools/test_tts_instructions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
"""Tests for the OpenAI TTS `instructions` field passthrough.

Covers #14196: forwarding the OpenAI-spec `instructions` parameter through the
`text_to_speech` tool so the agent can control tone/emotion/pacing on
gpt-4o-mini-tts and OpenAI-compatible voice-design servers.
"""

import json
from unittest.mock import MagicMock, patch

import pytest


@pytest.fixture(autouse=True)
def clean_env(monkeypatch):
for key in ("OPENAI_API_KEY", "HERMES_SESSION_PLATFORM"):
monkeypatch.delenv(key, raising=False)


# ---------------------------------------------------------------------------
# Backend-level passthrough (_generate_openai_tts)
# ---------------------------------------------------------------------------

class TestOpenaiBackendInstructions:
def _run(self, tmp_path, monkeypatch, *, tts_config=None, instructions=None):
monkeypatch.setenv("OPENAI_API_KEY", "test-key")
mock_client = MagicMock()
mock_client.audio.speech.create.return_value = MagicMock()
mock_cls = MagicMock(return_value=mock_client)

with patch("tools.tts_tool._import_openai_client", return_value=mock_cls), \
patch("tools.tts_tool._resolve_openai_audio_client_config",
return_value=("test-key", None)):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current main now unpacks three values from this helper (tools/tts_tool.py:1027, commit b53ba0e188363800447b7aca4c0a85420c39d1a8). Return ("test-key", None, False) here and in the second helper so these tests do not fail during setup.

from tools.tts_tool import _generate_openai_tts
kwargs = {}
if instructions is not None:
kwargs["instructions"] = instructions
_generate_openai_tts(
"Hello", str(tmp_path / "out.mp3"), tts_config or {}, **kwargs
)
return mock_client.audio.speech.create

def test_instructions_forwarded_when_provided(self, tmp_path, monkeypatch):
"""Tool arg `instructions` is passed to audio.speech.create as-is."""
create = self._run(tmp_path, monkeypatch, instructions="Speak cheerfully.")
assert create.call_args[1]["instructions"] == "Speak cheerfully."

def test_instructions_absent_by_default(self, tmp_path, monkeypatch):
"""No instructions arg -> key not present in create kwargs.

Preserves behavior on `tts-1`/`tts-1-hd` and strict servers that
reject unknown kwargs.
"""
create = self._run(tmp_path, monkeypatch)
assert "instructions" not in create.call_args[1]

def test_empty_string_instructions_omitted(self, tmp_path, monkeypatch):
"""Empty string is treated as absent (not forwarded)."""
create = self._run(tmp_path, monkeypatch, instructions="")
assert "instructions" not in create.call_args[1]


# ---------------------------------------------------------------------------
# Tool-level plumbing (text_to_speech_tool -> _generate_openai_tts)
# ---------------------------------------------------------------------------

class TestToolLevelInstructions:
def _invoke_tool(self, tmp_path, monkeypatch, *, instructions=None):
monkeypatch.setenv("OPENAI_API_KEY", "test-key")

mock_client = MagicMock()

def fake_stream(path):
# Mimic OpenAI SDK's stream_to_file by writing a tiny payload.
with open(path, "wb") as f:
f.write(b"ID3\x03\x00\x00\x00\x00\x00\x00")

response = MagicMock()
response.stream_to_file.side_effect = fake_stream
mock_client.audio.speech.create.return_value = response

mock_cls = MagicMock(return_value=mock_client)

with patch("tools.tts_tool._import_openai_client", return_value=mock_cls), \
patch("tools.tts_tool._resolve_openai_audio_client_config",
return_value=("test-key", None)), \
patch("tools.tts_tool._load_tts_config",
return_value={"provider": "openai"}):
from tools.tts_tool import text_to_speech_tool
kwargs = {"output_path": str(tmp_path / "out.mp3")}
if instructions is not None:
kwargs["instructions"] = instructions
result = text_to_speech_tool("Hello world", **kwargs)
return mock_client.audio.speech.create, json.loads(result)

def test_tool_threads_instructions_to_openai_create(
self, tmp_path, monkeypatch
):
create, result = self._invoke_tool(
tmp_path, monkeypatch, instructions="Whisper conspiratorially."
)
assert result.get("success") is True
assert create.call_args[1]["instructions"] == "Whisper conspiratorially."

def test_tool_omits_instructions_when_not_supplied(
self, tmp_path, monkeypatch
):
create, result = self._invoke_tool(tmp_path, monkeypatch)
assert result.get("success") is True
assert "instructions" not in create.call_args[1]


# ---------------------------------------------------------------------------
# Schema
# ---------------------------------------------------------------------------

class TestSchema:
def test_schema_exposes_instructions_parameter(self):
from tools.tts_tool import TTS_SCHEMA
props = TTS_SCHEMA["parameters"]["properties"]
assert "instructions" in props
assert props["instructions"]["type"] == "string"
# Must stay optional — current behavior must be preserved.
assert "instructions" not in TTS_SCHEMA["parameters"].get("required", [])
4 changes: 2 additions & 2 deletions tests/tools/test_tts_max_text_length.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def test_openai_truncates_at_4096_not_4000(self, tmp_path, monkeypatch, caplog):
text = "A" * 5000
captured_text = {}

def fake_openai(t, out, cfg):
def fake_openai(t, out, cfg, **_kw):
captured_text["text"] = t
with open(out, "wb") as f:
f.write(b"\x00")
Expand Down Expand Up @@ -175,7 +175,7 @@ def test_user_override_is_respected(self, tmp_path, monkeypatch):
text = "C" * 500
captured_text = {}

def fake_openai(t, out, cfg):
def fake_openai(t, out, cfg, **_kw):
captured_text["text"] = t
with open(out, "wb") as f:
f.write(b"\x00")
Expand Down
34 changes: 31 additions & 3 deletions tools/tts_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -977,14 +977,25 @@ def _generate_elevenlabs(text: str, output_path: str, tts_config: Dict[str, Any]
# ===========================================================================
# Provider: OpenAI TTS
# ===========================================================================
def _generate_openai_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:
def _generate_openai_tts(
text: str,
output_path: str,
tts_config: Dict[str, Any],
*,
instructions: Optional[str] = None,
) -> str:
"""
Generate audio using OpenAI TTS.

Args:
text: Text to convert.
output_path: Where to save the audio file.
tts_config: TTS config dict.
instructions: Optional voice-design guidance (tone, emotion, pacing,
accent, whispering). Forwarded to `audio.speech.create` when
truthy; omitted otherwise so ``tts-1``/``tts-1-hd`` and strict
OpenAI-compatible servers that reject unknown kwargs are
unaffected.

Returns:
Path to the saved audio file.
Expand Down Expand Up @@ -1015,6 +1026,8 @@ def _generate_openai_tts(text: str, output_path: str, tts_config: Dict[str, Any]
}
if speed != 1.0:
create_kwargs["speed"] = max(0.25, min(4.0, speed))
if instructions:
create_kwargs["instructions"] = instructions
response = client.audio.speech.create(**create_kwargs)

response.stream_to_file(output_path)
Expand Down Expand Up @@ -1837,6 +1850,7 @@ def _generate_kittentts(text: str, output_path: str, tts_config: Dict[str, Any])
def text_to_speech_tool(
text: str,
output_path: Optional[str] = None,
instructions: Optional[str] = None,
) -> str:
"""
Convert text to speech audio.
Expand All @@ -1851,6 +1865,10 @@ def text_to_speech_tool(
Args:
text: The text to convert to speech.
output_path: Optional custom save path. Defaults to ~/voice-memos/<timestamp>.mp3
instructions: Optional voice-design guidance (tone, emotion, pacing,
accent, whispering). Forwarded to the OpenAI backend
(gpt-4o-mini-tts and OpenAI-compatible servers). Silently
ignored by backends that don't support it.

Returns:
str: JSON result with success, file_path, and optionally MEDIA tag.
Expand Down Expand Up @@ -1976,7 +1994,7 @@ def text_to_speech_tool(
"error": "OpenAI provider selected but 'openai' package not installed."
}, ensure_ascii=False)
logger.info("Generating speech with OpenAI TTS...")
_generate_openai_tts(text, file_str, tts_config)
_generate_openai_tts(text, file_str, tts_config, instructions=instructions)

elif provider == "minimax":
logger.info("Generating speech with MiniMax TTS...")
Expand Down Expand Up @@ -2532,6 +2550,15 @@ def _check(importer, label):
"output_path": {
"type": "string",
"description": f"Optional custom file path to save the audio. Defaults to {display_hermes_home()}/audio_cache/<timestamp>.mp3"
},
"instructions": {
"type": "string",
"description": (
"Optional voice-design guidance: tone, emotion, pacing, accent, "
"whispering, impressions (e.g. 'Speak in a cheerful, excited whisper'). "
"Forwarded to the OpenAI backend (gpt-4o-mini-tts and OpenAI-compatible "
"voice-design servers). Silently ignored by backends that don't support it."
)
}
},
"required": ["text"]
Expand All @@ -2544,7 +2571,8 @@ def _check(importer, label):
schema=TTS_SCHEMA,
handler=lambda args, **kw: text_to_speech_tool(
text=args.get("text", ""),
output_path=args.get("output_path")),
output_path=args.get("output_path"),
instructions=args.get("instructions")),
check_fn=check_tts_requirements,
emoji="🔊",
)
11 changes: 11 additions & 0 deletions website/docs/user-guide/features/voice-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,11 @@ tts:
model: "gpt-4o-mini-tts"
voice: "alloy" # alloy, echo, fable, onyx, nova, shimmer
base_url: "https://api.openai.com/v1" # optional: override for self-hosted or OpenAI-compatible endpoints
# The `text_to_speech` tool accepts an optional per-call `instructions`
# argument (tone, emotion, pacing, accent, whispering) that is forwarded
# to `gpt-4o-mini-tts` and to OpenAI-compatible voice-design servers
# (e.g. Qwen3-TTS-VoiceDesign via oMLX). See OpenAI's voice-design guide:
# https://platform.openai.com/docs/guides/text-to-speech
neutts:
ref_audio: ''
ref_text: ''
Expand Down Expand Up @@ -472,6 +477,12 @@ Provider priority (automatic fallback): **local** > **groq** > **openai**

NeuTTS uses the `tts.neutts` config block above.

For `openai`, the `text_to_speech` tool accepts an optional `instructions`
argument that unlocks `gpt-4o-mini-tts`'s voice-design capability (tone,
emotion, pacing, accent, whispering). The same field also routes to
OpenAI-compatible voice-design servers mounted via `tts.openai.base_url`
(e.g. Qwen3-TTS-VoiceDesign via oMLX).

---

## Troubleshooting
Expand Down