Skip to content

The agent that grows with you

feat(tts): let the agent pick ElevenLabs voices (voice_id + paginated tts_voices search)

Tekniumc975831fbcee
diff --git a/acp_adapter/tools.py b/acp_adapter/tools.py
index 794eedc2cfa..01a7e7a90fd 100644
--- a/acp_adapter/tools.py
+++ b/acp_adapter/tools.py
@@ -24,7 +24,7 @@ TOOL_KIND_MAP: dict[str, ToolKind] = {
"search": ("search_files",),
"execute": ("terminal", "process", "execute_code", "browser_click", "browser_type", "browser_scroll",
"browser_press", "browser_back", "delegate_task", "image_generate", "text_to_speech"),
- "fetch": ("web_search", "web_extract", "browser_navigate"),
+ "fetch": ("web_search", "web_extract", "browser_navigate", "tts_voices"),
"other": ("todo",),
"think": ("_thinking",),
}.items()
diff --git a/agent/display.py b/agent/display.py
index 14cb2ffff50..7519e871da3 100644
--- a/agent/display.py
+++ b/agent/display.py
@@ -353,7 +353,7 @@ def _browser_exec_step_label(args: dict, max_chars: int = 80) -> str | None:
_PRIMARY_ARGS = {
"terminal": "command", "web_search": "query", "web_extract": "urls", "read_file": "path",
"write_file": "path", "patch": "path", "search_files": "pattern", "browser_navigate": "url",
- "browser_click": "ref", "browser_type": "text", "image_generate": "prompt", "text_to_speech": "text",
+ "browser_click": "ref", "browser_type": "text", "image_generate": "prompt", "text_to_speech": "text", "tts_voices": "query",
"vision_analyze": "question", "skill_view": "name", "skills_list": "category", "cronjob_manage": "action",
"execute_code": "code", "browser_exec": "code", "delegate_task": "goal",
"skill_manage": "name",
@@ -1265,6 +1265,7 @@ _CUTE_LINES = {
"skill_view": _cute_skill_view,
"image_generate": lambda a, r: _cute_row("🎨", "create", _cute_trunc(a.get("prompt", ""))),
"text_to_speech": lambda a, r: _cute_row("πŸ”Š", "speak", _cute_trunc(a.get("text", ""))),
+ "tts_voices": lambda a, r: _cute_row("πŸ—£οΈ ", "voices", _cute_trunc(a.get("query") or a.get("source") or "account")),
"vision_analyze": lambda a, r: _cute_row("πŸ‘οΈ ", "vision", _cute_trunc(a.get("question", ""))),
"send_message": lambda a, r: _cute_row("πŸ“¨", "send", f"{a.get('target', '?')}: \"{_cute_trunc(a.get('message', ''))}\""),
"cronjob_manage": _cute_cronjob,
diff --git a/model_tools.py b/model_tools.py
index 97f2987a7b9..56262b9b2be 100644
--- a/model_tools.py
+++ b/model_tools.py
@@ -183,7 +183,7 @@ _LEGACY_TOOLSET_MAP = {
"skills_tools": ["skills_list", "skill_view", "skill_manage"],
"cronjob_tools": ["cronjob_manage"],
"file_tools": ["read_file", "write_file", "patch", "search_files"],
- "tts_tools": ["text_to_speech"],
+ "tts_tools": ["text_to_speech", "tts_voices"],
}
diff --git a/tests/fixtures/prompt_surface/surfaces.json b/tests/fixtures/prompt_surface/surfaces.json
index 04c38c12ebd..24e9c733f54 100644
--- a/tests/fixtures/prompt_surface/surfaces.json
+++ b/tests/fixtures/prompt_surface/surfaces.json
@@ -5,7 +5,7 @@
"stable": 1829,
"volatile": 1528
},
- "tool_tokens": 11242,
+ "tool_tokens": 11549,
"tools": [
"browser_cdp",
"browser_dialog",
@@ -26,6 +26,7 @@
"tool_call",
"tool_describe",
"tool_search",
+ "tts_voices",
"vision_analyze",
"web_extract",
"web_search",
@@ -38,7 +39,7 @@
"stable": 1225,
"volatile": 1528
},
- "tool_tokens": 11242,
+ "tool_tokens": 11549,
"tools": [
"browser_cdp",
"browser_dialog",
@@ -59,6 +60,7 @@
"tool_call",
"tool_describe",
"tool_search",
+ "tts_voices",
"vision_analyze",
"web_extract",
"web_search",
@@ -71,7 +73,7 @@
"stable": 1646,
"volatile": 1527
},
- "tool_tokens": 11242,
+ "tool_tokens": 11549,
"tools": [
"browser_cdp",
"browser_dialog",
@@ -92,6 +94,7 @@
"tool_call",
"tool_describe",
"tool_search",
+ "tts_voices",
"vision_analyze",
"web_extract",
"web_search",
@@ -104,7 +107,7 @@
"stable": 2420,
"volatile": 1524
},
- "tool_tokens": 11398,
+ "tool_tokens": 11705,
"tools": [
"browser_cdp",
"browser_dialog",
@@ -125,6 +128,7 @@
"tool_call",
"tool_describe",
"tool_search",
+ "tts_voices",
"vision_analyze",
"web_extract",
"web_search",
@@ -137,7 +141,7 @@
"stable": 1225,
"volatile": 1528
},
- "tool_tokens": 11242,
+ "tool_tokens": 11549,
"tools": [
"browser_cdp",
"browser_dialog",
@@ -158,6 +162,7 @@
"tool_call",
"tool_describe",
"tool_search",
+ "tts_voices",
"vision_analyze",
"web_extract",
"web_search",
@@ -170,7 +175,7 @@
"stable": 1211,
"volatile": 1528
},
- "tool_tokens": 11242,
+ "tool_tokens": 11549,
"tools": [
"browser_cdp",
"browser_dialog",
@@ -191,6 +196,7 @@
"tool_call",
"tool_describe",
"tool_search",
+ "tts_voices",
"vision_analyze",
"web_extract",
"web_search",
@@ -203,7 +209,7 @@
"stable": 1473,
"volatile": 1529
},
- "tool_tokens": 11898,
+ "tool_tokens": 12205,
"tools": [
"browser_cdp",
"browser_dialog",
@@ -225,6 +231,7 @@
"tool_call",
"tool_describe",
"tool_search",
+ "tts_voices",
"vision_analyze",
"web_extract",
"web_search",
@@ -237,7 +244,7 @@
"stable": 1244,
"volatile": 1529
},
- "tool_tokens": 11242,
+ "tool_tokens": 11549,
"tools": [
"browser_cdp",
"browser_dialog",
@@ -258,6 +265,7 @@
"tool_call",
"tool_describe",
"tool_search",
+ "tts_voices",
"vision_analyze",
"web_extract",
"web_search",
@@ -270,7 +278,7 @@
"stable": 1276,
"volatile": 1529
},
- "tool_tokens": 11242,
+ "tool_tokens": 11549,
"tools": [
"browser_cdp",
"browser_dialog",
@@ -291,6 +299,7 @@
"tool_call",
"tool_describe",
"tool_search",
+ "tts_voices",
"vision_analyze",
"web_extract",
"web_search",
diff --git a/tests/fixtures/prompt_surface/tools/tts_voices.json b/tests/fixtures/prompt_surface/tools/tts_voices.json
new file mode 100644
index 00000000000..0d2242c0e58
--- /dev/null
+++ b/tests/fixtures/prompt_surface/tools/tts_voices.json
@@ -0,0 +1,46 @@
+{
+ "description": "Search ElevenLabs voices to pick a voice_id for text_to_speech. source 'account' = the user's voices (premade, saved, cloned, designed); 'library' = the public Voice Library (thousands of community voices; paid plans only). Paginated: pass next_page back as page. You can't hear voices, so choose from the labels and description, and offer the user preview_url links when the pick matters.",
+ "name": "tts_voices",
+ "parameters": {
+ "properties": {
+ "accent": {
+ "description": "Filter, e.g. british, american, scottish.",
+ "type": "string"
+ },
+ "age": {
+ "description": "Filter, e.g. young, middle_aged, old.",
+ "type": "string"
+ },
+ "gender": {
+ "description": "Filter, e.g. male, female, neutral.",
+ "type": "string"
+ },
+ "language": {
+ "description": "Filter by ISO 639-1 code, e.g. en.",
+ "type": "string"
+ },
+ "page": {
+ "description": "next_page from the previous result.",
+ "type": "string"
+ },
+ "page_size": {
+ "description": "1-100, default 20.",
+ "type": "integer"
+ },
+ "query": {
+ "description": "Free-text search over names, descriptions and labels, e.g. 'gruff old dwarf'.",
+ "type": "string"
+ },
+ "source": {
+ "description": "Default account.",
+ "enum": [
+ "account",
+ "library"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [],
+ "type": "object"
+ }
+}
diff --git a/tests/tools/test_tts_voice_selection.py b/tests/tools/test_tts_voice_selection.py
new file mode 100644
index 00000000000..0e0b50f1bb0
--- /dev/null
+++ b/tests/tools/test_tts_voice_selection.py
@@ -0,0 +1,103 @@
+"""Model-selected ElevenLabs voices: the ``voice_id`` field on ``text_to_speech`` and the
+``tts_voices`` browse/search tool exist only while ElevenLabs is the configured provider."""
+
+import json
+from unittest.mock import patch
+
+import httpx
+import pytest
+
+from tools import tts_tool, tts_voices_tool
+
+_EL_CONFIG = {"provider": "elevenlabs", "elevenlabs": {"voice_id": "configuredVoice001"}}
+
+
[email protected]("config, exposed", [
+ (_EL_CONFIG, True), ({"provider": "edge"}, False), ({"provider": "openai"}, False)])
+def test_voice_selection_surface_follows_provider(config, exposed):
+ with patch("tools.tts_tool._load_tts_config", return_value=config), \
+ patch("tools.tts_tool._resolve_provider_key", return_value="el-test-key"):
+ schema = tts_tool._tts_schema_overrides()
+ assert ("voice_id" in schema["parameters"]["properties"]) is exposed
+ assert ("tts_voices" in schema.get("description", "")) is exposed
+ assert tts_voices_tool.check_tts_voices_requirements() is exposed
+ with patch("tools.tts_tool._load_tts_config", return_value=_EL_CONFIG), \
+ patch("tools.tts_tool._resolve_provider_key", return_value=""):
+ assert tts_voices_tool.check_tts_voices_requirements() is False
+
+
+def test_voice_id_reaches_elevenlabs_and_is_ignored_elsewhere(tmp_path):
+ seen = []
+
+ class _FakeElevenLabs: # the SDK client: records the voice the real generator sends
+ def __init__(self, **_kwargs):
+ self.text_to_speech = self
+
+ def convert(self, *, voice_id, **_kwargs):
+ seen.append(voice_id)
+ return [b"ID3\x03\x00\x00\x00\x00\x00\x00"]
+
+ with patch("tools.tts_tool._import_elevenlabs", return_value=_FakeElevenLabs), \
+ patch("tools.tts_tool._resolve_provider_key", return_value="el-test-key"), \
+ patch("tools.tts_tool._load_tts_config", return_value=_EL_CONFIG):
+ ok = json.loads(tts_tool.text_to_speech_tool(
+ "Hail, traveler.", output_path=str(tmp_path / "a.mp3"), voice_id="pickedVoice0042"))
+ default = json.loads(tts_tool.text_to_speech_tool(
+ "Hail, traveler.", output_path=str(tmp_path / "b.mp3")))
+ bad = json.loads(tts_tool.text_to_speech_tool(
+ "Hail.", output_path=str(tmp_path / "c.mp3"), voice_id="../v1/user"))
+ assert ok["success"] and default["success"] and not bad["success"]
+ assert seen == ["pickedVoice0042", "configuredVoice001"]
+ assert _EL_CONFIG["elevenlabs"]["voice_id"] == "configuredVoice001" # cached config untouched
+
+ with patch("tools.tts_tool._load_tts_config", return_value={"provider": "edge"}):
+ config, error = tts_tool._apply_voice_override({"provider": "edge"}, "edge", "pickedVoice0042")
+ assert error is None and "elevenlabs" not in config
+
+
[email protected]("source, path, first_page, cursor_param, body, next_page", [
+ ("account", "/v2/voices", "", "next_page_token",
+ {"voices": [{"voice_id": "acct1", "name": "Bram", "category": "premade",
+ "labels": {"gender": "male", "age": "old", "accent": "scottish",
+ "use case": "characters"},
+ "preview_url": "https://example.test/bram.mp3"}],
+ "has_more": True, "next_page_token": "tok-2"}, "tok-2"),
+ ("library", "/v1/shared-voices", "3", "page",
+ {"voices": [{"voice_id": "lib1", "name": "Gruff", "gender": "male", "age": "old",
+ "accent": "scottish", "descriptive": "gruff", "use_case": "characters",
+ "category": "professional", "description": "x" * 400}],
+ "has_more": True, "total_count": 812}, "4"),
+])
+def test_tts_voices_pages_both_sources(source, path, first_page, cursor_param, body, next_page):
+ calls = []
+
+ def fake_get(url, params=None, headers=None, timeout=None):
+ calls.append((url, dict(params or {}), headers))
+ return httpx.Response(200, json=body)
+
+ with patch("tools.tts_tool._load_tts_config", return_value=_EL_CONFIG), \
+ patch("tools.tts_tool._resolve_provider_key", return_value="el-test-key"), \
+ patch("tools.tts_voices_tool.httpx.get", side_effect=fake_get):
+ result = json.loads(tts_voices_tool.tts_voices_tool(
+ query="gruff dwarf", source=source, gender="Male", page=first_page, page_size=500))
+ url, params, headers = calls[0]
+ assert url == "https://api.elevenlabs.io" + path
+ assert headers["xi-api-key"] == "el-test-key"
+ assert params["search"] == "gruff dwarf" and params["gender"] == "male"
+ assert params["page_size"] == 100
+ if first_page:
+ assert str(params[cursor_param]) == first_page
+ row = result["voices"][0]
+ assert result["success"] and result["next_page"] == next_page
+ assert row["gender"] == "male" and row["accent"] == "scottish" and row["use_case"] == "characters"
+ assert result["configured_voice_id"] == "configuredVoice001"
+ if source == "library":
+ assert result["total"] == 812 and len(row["description"]) == 240
+
+
+def test_tts_voices_rejects_a_non_numeric_library_page():
+ with patch("tools.tts_tool._load_tts_config", return_value=_EL_CONFIG), \
+ patch("tools.tts_tool._resolve_provider_key", return_value="el-test-key"), \
+ patch("tools.tts_voices_tool.httpx.get") as get:
+ result = json.loads(tts_voices_tool.tts_voices_tool(source="library", page="tok-2"))
+ assert not result["success"] and get.call_count == 0
diff --git a/tools/tts_tool.py b/tools/tts_tool.py
index b60cdf372f3..fb27e285295 100644
--- a/tools/tts_tool.py
+++ b/tools/tts_tool.py
@@ -305,6 +305,37 @@ def _apply_call_overrides(tts_config: dict[str, Any], speed: Optional[float], pr
return tts_config, configured_provider
+# ElevenLabs voice ids are short alphanumeric tokens; anything else never reaches the URL path.
+_ELEVENLABS_VOICE_ID_RE = re.compile(r"^[A-Za-z0-9]{8,64}$")
+
+
+def elevenlabs_voice_selection_active(tts_config: Optional[dict[str, Any]] = None) -> bool:
+ """Whether the model may pick voices: built-in ElevenLabs is the configured provider (gates
+ the ``voice_id`` schema field and the ``tts_voices`` tool, so other providers see neither)."""
+ tts_config = _load_tts_config() if tts_config is None else tts_config
+ return (_get_provider(tts_config) == "elevenlabs"
+ and _resolve_command_provider_config("elevenlabs", tts_config) is None)
+
+
+def _apply_voice_override(tts_config: dict[str, Any], provider: str, voice_id: Optional[str]):
+ """Per-call ElevenLabs ``voice_id`` on a copy of the config -> ``(tts_config, error_json)``.
+ Ignored (logged) on any other provider: a schema cached before a provider switch may still
+ send it, and it must not fail the speech."""
+ voice_id = (voice_id or "").strip()
+ if not voice_id:
+ return tts_config, None
+ if provider != "elevenlabs" or not elevenlabs_voice_selection_active(tts_config):
+ logger.warning("Ignoring per-call TTS voice_id; tts.provider is %r", provider)
+ return tts_config, None
+ if not _ELEVENLABS_VOICE_ID_RE.match(voice_id):
+ return tts_config, tool_error(
+ f"Invalid ElevenLabs voice_id {voice_id!r}: use a voice_id returned by tts_voices.",
+ success=False)
+ section = dict(tts_config.get("elevenlabs") or {})
+ section["voice_id"] = voice_id
+ return {**tts_config, "elevenlabs": section}, None
+
+
def _session_platform() -> tuple:
"""``(platform, wants_opus)`` β€” platforms delivering voice bubbles only as Ogg/Opus want Opus."""
from gateway.session_context import get_session_env
@@ -456,7 +487,8 @@ def _synthesize_chunks(chunks: list[str], base_path: Path, generated_artifacts:
def text_to_speech_tool(
text: str, output_path: Optional[str] = None, speed: Optional[float] = None,
- instructions: Optional[str] = None, provider: Optional[str] = None) -> str:
+ instructions: Optional[str] = None, provider: Optional[str] = None,
+ voice_id: Optional[str] = None) -> str:
"""Convert text to speech with long-form chunking; returns the JSON result envelope.
Text is normalized, split into provider-safe chunks (never silently truncated), synthesized
@@ -472,6 +504,9 @@ def text_to_speech_tool(
if not text:
return tool_error("Text is empty after TTS cleanup", success=False)
tts_config, provider = _apply_call_overrides(_load_tts_config(), speed, provider)
+ tts_config, error = _apply_voice_override(tts_config, provider, voice_id)
+ if error:
+ return error
command_provider_config = _resolve_command_provider_config(provider, tts_config)
max_len = _resolve_max_text_length(provider, tts_config)
chunks = _split_text_for_tts(text, max_len)
@@ -635,12 +670,22 @@ def _tts_schema_overrides() -> dict:
would name the launch profile's home for everyone else (#95685)."""
params = copy.deepcopy(TTS_SCHEMA["parameters"])
params["properties"]["output_path"]["description"] = _output_path_description(display_hermes_home())
- return {"parameters": params}
+ if not elevenlabs_voice_selection_active():
+ return {"parameters": params}
+ params["properties"]["voice_id"] = {
+ "type": "string",
+ "description": ("ElevenLabs voice for this audio (a voice_id from tts_voices). "
+ "Omit to use the user's configured voice.")}
+ return {"parameters": params, "description": TTS_SCHEMA["description"].replace(
+ _CONFIGURED_VOICE_SENTENCE, _ELEVENLABS_VOICE_SENTENCE)}
+
+_CONFIGURED_VOICE_SENTENCE = "Voice and provider are user-configured (built-in providers like edge/openai or custom command providers under tts.providers.<name>), not model-selected."
+_ELEVENLABS_VOICE_SENTENCE = "The provider is user-configured (ElevenLabs); pick a voice per call with voice_id, found via tts_voices."
TTS_SCHEMA = {
"name": "text_to_speech",
- "description": "Convert text to speech audio. Returns a MEDIA: path that the platform delivers as native audio. Compatible providers render as a voice bubble on Telegram; otherwise audio is sent as a regular attachment. In CLI mode, saves to ~/voice-memos/. Voice and provider are user-configured (built-in providers like edge/openai or custom command providers under tts.providers.<name>), not model-selected.",
+ "description": "Convert text to speech audio. Returns a MEDIA: path that the platform delivers as native audio. Compatible providers render as a voice bubble on Telegram; otherwise audio is sent as a regular attachment. In CLI mode, saves to ~/voice-memos/. " + _CONFIGURED_VOICE_SENTENCE,
"parameters": {
"type": "object",
"properties": {
@@ -676,7 +721,7 @@ registry.register(
schema=TTS_SCHEMA,
handler=lambda args, **kw: text_to_speech_tool(
text=args.get("text", ""),
- **{k: args.get(k) for k in ("output_path", "speed", "instructions")}),
+ **{k: args.get(k) for k in ("output_path", "speed", "instructions", "voice_id")}),
check_fn=check_tts_requirements,
emoji="πŸ”Š",
dynamic_schema_overrides=_tts_schema_overrides)
diff --git a/tools/tts_voices_tool.py b/tools/tts_voices_tool.py
new file mode 100644
index 00000000000..ec0994d25a9
--- /dev/null
+++ b/tools/tts_voices_tool.py
@@ -0,0 +1,177 @@
+"""``tts_voices``: browse and search ElevenLabs voices so the agent can pick one per
+``text_to_speech`` call (``voice_id``).
+
+Registered in the ``tts`` toolset but only exposed while ``tts.provider`` is ElevenLabs with a
+key, the same gate as the ``voice_id`` schema field. Two sources share one paginated shape:
+``account`` (``GET /v2/voices``: premade + the user's saved, cloned and designed voices) and
+``library`` (``GET /v1/shared-voices``: the public Voice Library). ``next_page`` is opaque to the
+model: a cursor token for the account and a page number for the library.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any, Optional
+
+import httpx
+
+from tools.registry import registry, tool_error
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_ELEVENLABS_BASE_URL = "https://api.elevenlabs.io"
+_SOURCES = ("account", "library")
+_DEFAULT_PAGE_SIZE = 20
+_MAX_PAGE_SIZE = 100
+_DESCRIPTION_MAX_CHARS = 240
+_TIMEOUT_SECONDS = 20.0
+_FILTERS = ("gender", "age", "accent", "language")
+
+
+def check_tts_voices_requirements() -> bool:
+ """Exposed only when ElevenLabs is the configured TTS provider and its key resolves."""
+ from tools import tts_tool
+ try:
+ return (tts_tool.elevenlabs_voice_selection_active()
+ and bool(tts_tool._resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs")))
+ except Exception:
+ return False
+
+
+def _clip(text: Any) -> str:
+ text = " ".join(str(text or "").split())
+ return text if len(text) <= _DESCRIPTION_MAX_CHARS else text[: _DESCRIPTION_MAX_CHARS - 1] + "…"
+
+
+def _voice_row(voice: dict[str, Any]) -> dict[str, Any]:
+ """One compact voice: library rows carry the traits at top level, account rows under ``labels``."""
+ raw_labels = voice.get("labels")
+ labels: dict[str, Any] = raw_labels if isinstance(raw_labels, dict) else {}
+ row = {"voice_id": voice.get("voice_id"), "name": voice.get("name")}
+ for key in ("gender", "age", "accent", "language", "descriptive", "use_case"):
+ value = voice.get(key) or labels.get(key) or labels.get(key.replace("_", " "))
+ if value:
+ row[key] = value
+ if voice.get("category"):
+ row["category"] = voice["category"]
+ if voice.get("description"):
+ row["description"] = _clip(voice["description"])
+ if voice.get("preview_url"):
+ row["preview_url"] = voice["preview_url"]
+ return row
+
+
+def _request_params(source: str, query: str, filters: dict[str, str], page: str,
+ page_size: int) -> tuple[str, dict[str, Any]]:
+ """``(path, params)`` for one source; raises ValueError on a cursor of the wrong kind."""
+ params: dict[str, Any] = {"page_size": page_size, **filters}
+ if query:
+ params["search"] = query
+ if source == "account":
+ params["include_total_count"] = "false"
+ if page:
+ params["next_page_token"] = page
+ return "/v2/voices", params
+ if page and not page.isdigit():
+ raise ValueError(f"Invalid library page {page!r}: pass next_page from the previous result.")
+ params["page"] = int(page or 0)
+ return "/v1/shared-voices", params
+
+
+def _next_page(source: str, body: dict[str, Any], page: str) -> Optional[str]:
+ if not body.get("has_more"):
+ return None
+ if source == "account":
+ return body.get("next_page_token") or None
+ return str(int(page or 0) + 1)
+
+
+def tts_voices_tool(query: str = "", source: str = "account", gender: str = "", age: str = "",
+ accent: str = "", language: str = "", page: str = "",
+ page_size: Optional[int] = None) -> str:
+ """Search one ElevenLabs voice source and return a compact, paginated JSON page."""
+ from tools import tts_tool
+ source = (source or "account").strip().lower()
+ if source not in _SOURCES:
+ return tool_error(f"source must be one of {', '.join(_SOURCES)}", success=False)
+ tts_config = tts_tool._load_tts_config()
+ if not tts_tool.elevenlabs_voice_selection_active(tts_config):
+ return tool_error("tts_voices needs tts.provider: elevenlabs", success=False)
+ api_key = tts_tool._resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs")
+ if not api_key:
+ return tool_error("ELEVENLABS_API_KEY not set. Get one at https://elevenlabs.io/", success=False)
+ try:
+ size = max(1, min(_MAX_PAGE_SIZE, int(page_size or _DEFAULT_PAGE_SIZE)))
+ except (TypeError, ValueError):
+ size = _DEFAULT_PAGE_SIZE
+ filters = {}
+ for name, value in zip(_FILTERS, (gender, age, accent, language)):
+ if str(value or "").strip():
+ filters[name] = str(value).strip().lower()
+ page = str(page or "").strip()
+ try:
+ path, params = _request_params(source, str(query or "").strip(), filters, page, size)
+ except ValueError as exc:
+ return tool_error(str(exc), success=False)
+ el_config = tts_config.get("elevenlabs") or {}
+ base_url = (el_config.get("base_url") or DEFAULT_ELEVENLABS_BASE_URL).rstrip("/")
+ try:
+ response = httpx.get(base_url + path, params=params, timeout=_TIMEOUT_SECONDS,
+ headers={"xi-api-key": api_key, "accept": "application/json"})
+ except httpx.HTTPError as exc:
+ return tool_error(f"ElevenLabs voice search failed: {exc}", success=False)
+ if response.status_code != 200:
+ detail = response.text[:300]
+ logger.warning("ElevenLabs %s returned HTTP %s", path, response.status_code)
+ return tool_error(f"ElevenLabs voice search failed (HTTP {response.status_code}): {detail}",
+ success=False)
+ try:
+ body = response.json()
+ except ValueError:
+ return tool_error("ElevenLabs voice search returned a non-JSON body", success=False)
+ voices = [_voice_row(v) for v in body.get("voices") or [] if isinstance(v, dict)]
+ result: dict[str, Any] = {
+ "success": True, "source": source, "count": len(voices), "voices": voices,
+ "next_page": _next_page(source, body, page),
+ "configured_voice_id": el_config.get("voice_id") or None,
+ }
+ if source == "library" and body.get("total_count"):
+ result["total"] = body["total_count"]
+ return json.dumps(result, ensure_ascii=False)
+
+
+TTS_VOICES_SCHEMA = {
+ "name": "tts_voices",
+ "description": (
+ "Search ElevenLabs voices to pick a voice_id for text_to_speech. source 'account' = the "
+ "user's voices (premade, saved, cloned, designed); 'library' = the public Voice Library "
+ "(thousands of community voices; paid plans only). Paginated: pass next_page back as page. "
+ "You can't hear voices, so choose from the labels and description, and offer the user "
+ "preview_url links when the pick matters."),
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string",
+ "description": "Free-text search over names, descriptions and labels, e.g. 'gruff old dwarf'."},
+ "source": {"type": "string", "enum": list(_SOURCES), "description": "Default account."},
+ "gender": {"type": "string", "description": "Filter, e.g. male, female, neutral."},
+ "age": {"type": "string", "description": "Filter, e.g. young, middle_aged, old."},
+ "accent": {"type": "string", "description": "Filter, e.g. british, american, scottish."},
+ "language": {"type": "string", "description": "Filter by ISO 639-1 code, e.g. en."},
+ "page": {"type": "string", "description": "next_page from the previous result."},
+ "page_size": {"type": "integer", "description": "1-100, default 20."},
+ },
+ "required": [],
+ },
+}
+
+registry.register(
+ name="tts_voices",
+ toolset="tts",
+ schema=TTS_VOICES_SCHEMA,
+ handler=lambda args, **kw: tts_voices_tool(
+ **{k: args.get(k) for k in ("query", "source", "gender", "age", "accent", "language",
+ "page", "page_size") if args.get(k) is not None}),
+ check_fn=check_tts_voices_requirements,
+ emoji="πŸ—£οΈ")
diff --git a/toolsets.py b/toolsets.py
index a4f73e29c05..1360bb750e1 100644
--- a/toolsets.py
+++ b/toolsets.py
@@ -17,7 +17,7 @@ _HERMES_CORE_TOOLS = [
"browser_exec", # THE browser: Python over CDP (browser-harness)
"browser_cdp", "browser_dialog",
"browser_vault", # rides with the browser; deferred by default (tools.tool_search.defer)
- "text_to_speech",
+ "text_to_speech", "tts_voices", # tts_voices: check_fn-gated to the ElevenLabs provider
"todo_list", "memory",
"session_search",
"clarify",
@@ -61,7 +61,7 @@ def _core_without(*excluded, kanban=True):
# Coding posture: everything you reach for while pairing on code; drops messaging,
# tts, image_gen, cron, kanban and computer-use.
-_CODING_TOOLS = _core_without("image_generate", "text_to_speech", "cronjob_manage", "computer_use", kanban=False)
+_CODING_TOOLS = _core_without("image_generate", "text_to_speech", "tts_voices", "cronjob_manage", "computer_use", kanban=False)
# Toolsets a CLIENT adds to its own sessions (tui_gateway/server.py::_gui_surface_toolsets), never
# config: another surface lacking them made no configuration choice.
@@ -121,7 +121,7 @@ TOOLSETS = {
"search (content + files)",
["read_file", "write_file", "patch", "search_files"],
),
- "tts": _ts("Text-to-speech: convert text to audio with Edge TTS (free), ElevenLabs, OpenAI, or xAI", ["text_to_speech"]),
+ "tts": _ts("Text-to-speech: convert text to audio with Edge TTS (free), ElevenLabs, OpenAI, or xAI", ["text_to_speech", "tts_voices"]),
"todo": _ts("Task planning and tracking for multi-step work", ["todo_list"]),
"memory": _ts("Persistent memory across sessions (personal notes + user profile)", ["memory"]),
"context_engine": _ts("Runtime tools exposed by the active context engine"),
@@ -193,7 +193,7 @@ TOOLSETS = {
"hermes-api-server": _ts(
"OpenAI-compatible API server β€” full agent tools accessible via HTTP (no "
"interactive UI tools like clarify or send_message)",
- _core_without("text_to_speech", "clarify", "computer_use", kanban=False),
+ _core_without("text_to_speech", "tts_voices", "clarify", "computer_use", kanban=False),
),
"hermes-cli": _bundle("Full interactive CLI toolset - all default tools plus cronjob management"),
diff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.md
index 27f14469f6e..89f7335c5ef 100644
--- a/website/docs/reference/tools-reference.md
+++ b/website/docs/reference/tools-reference.md
@@ -344,6 +344,7 @@ The single `video_generate` tool covers both modalities β€” pass `image_url` to
| Tool | Description | Requires environment |
|------|-------------|----------------------|
| `text_to_speech` | Convert text to speech audio. Returns a MEDIA: path that the platform delivers as a voice message. On Telegram it plays as a voice bubble, on Discord/WhatsApp as an audio attachment. In CLI mode, saves to ~/voice-memos/. Voice and provider… | β€” |
+| `tts_voices` | Search ElevenLabs voices (your account or the public Voice Library, paginated) to pick a `voice_id` for `text_to_speech`. Only exposed while `tts.provider` is `elevenlabs`. | ELEVENLABS_API_KEY |
## `discord` toolset
diff --git a/website/docs/reference/toolsets-reference.md b/website/docs/reference/toolsets-reference.md
index 4173fd7ec6f..fe712dfc42a 100644
--- a/website/docs/reference/toolsets-reference.md
+++ b/website/docs/reference/toolsets-reference.md
@@ -80,7 +80,7 @@ Or in-session:
| `skills` | `skill_manage`, `skill_view`, `skills_list` | Skill CRUD and browsing. |
| `terminal` | `process_manage`, `terminal` | Shell command execution and background process management. |
| `todo` | `todo_list` | Task list management within a session. |
-| `tts` | `text_to_speech` | Text-to-speech audio generation. |
+| `tts` | `text_to_speech`, `tts_voices` | Text-to-speech audio generation; `tts_voices` (voice search) only appears with the ElevenLabs provider. |
| `vision` | `vision_analyze` | Image analysis via vision-capable models. |
| `video` | `video_analyze` | Video analysis and understanding tools (opt-in, not in the default toolset β€” add explicitly via `--toolsets`). |
| `web` | `web_extract`, `web_search` | Web search and page content extraction. |
diff --git a/website/docs/user-guide/features/tts.md b/website/docs/user-guide/features/tts.md
index 3c62222592a..ee22af1e81a 100644
--- a/website/docs/user-guide/features/tts.md
+++ b/website/docs/user-guide/features/tts.md
@@ -228,6 +228,18 @@ Without ffmpeg, Edge TTS, MiniMax TTS, NeuTTS, KittenTTS, and Piper audio are se
If you want voice bubbles without installing ffmpeg, switch to the OpenAI, ElevenLabs, or Mistral provider.
:::
+### ElevenLabs: agent-selected voices
+
+With `tts.provider: elevenlabs` and `ELEVENLABS_API_KEY` set, the agent can pick a different voice for each `text_to_speech` call, for example one voice per character in a script. Two things appear only for ElevenLabs (other providers keep the configured voice and see neither):
+
+- `text_to_speech` gains an optional `voice_id`. Leaving it out uses `tts.elevenlabs.voice_id`; the config is never rewritten.
+- The `tts_voices` tool searches voices, 20 per page by default (up to 100), with `next_page` for the following page:
+ - `source: account` (default) lists the voices on your account: premade ones plus anything you saved, cloned or designed.
+ - `source: library` searches the public Voice Library (thousands of community voices). ElevenLabs only allows library voices over the API on paid plans.
+ - Filters: free-text `query` (name, description, labels), `gender`, `age`, `accent`, `language` (ISO code like `en`).
+
+The agent can't listen to voices. It chooses from each voice's labels and description, and every result carries a `preview_url` you can open to hear the voice before committing to it.
+
### xAI Custom Voices (voice cloning)
xAI supports cloning your voice and using it with TTS. Create a custom voice in the [xAI Console](https://console.x.ai/team/default/voice/voice-library), then set the resulting `voice_id` in your config: