Skip to content

The open-source AI voice studio. Clone, dictate, create.

feat(api): map OpenAI speech fields onto profiles/engines, add formats, speed, errors, tests, docs

jamiepined6231c48f524
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 62a149b7..4837f671 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,9 @@
### Dictation and agents
- **Bring your own LLM for refinement and personalities.** Settings → Captures → Refinement gains a *Custom LLM endpoint (advanced)* section: point it at any server that speaks OpenAI's `/v1/chat/completions` (llama.cpp, vLLM, LM Studio, LocalAI, Ollama's OpenAI shim, OpenRouter, or OpenAI itself) with a model name and an optional API key, and dictation refinement and personality compose/rewrite go there instead of the bundled Qwen3. Leave the endpoint blank and nothing changes. The key is write-only: the settings API reports only whether one is stored. The dictation readiness checklist treats a configured endpoint as ready, the Models page keeps managing the on-device Qwen regardless, and a failing endpoint surfaces as a clear error naming the URL and status. — @ext-sakamoro ([#947](https://github.com/jamiepine/voicebox/pull/947))
+### API
+
+- **OpenAI-compatible text-to-speech API.** `POST /v1/audio/speech` and `GET /v1/models` accept OpenAI's request shape, so the official `openai` SDKs, Open WebUI, Home Assistant and any other OpenAI TTS client become a local, offline TTS by changing only the base URL. `voice` is a Voicebox profile (name or id, falling back to the per-client binding and default voice like `/speak`); `model` is a Voicebox engine or model variant, with `tts-1`, `tts-1-hd` and `gpt-4o-mini-tts` accepted as aliases for the profile's configured engine; `response_format` supports `wav`, `mp3`, `flac`, `opus`, `pcm` and (with ffmpeg) `aac`; `speed` is a pitch-preserving time stretch; `instructions` feeds the engine's instruct prompt. Errors use OpenAI's `{"error": {...}}` body, and the endpoint is documented on the MCP Server page. — @neuron-tech-ai (from [#656](https://github.com/jamiepine/voicebox/pull/656); fixes [#10](https://github.com/jamiepine/voicebox/issues/10))
## [0.6.0] - 2026-10-04
diff --git a/backend/routes/openai_compat.py b/backend/routes/openai_compat.py
index 59fdd1f8..449fbbb2 100644
--- a/backend/routes/openai_compat.py
+++ b/backend/routes/openai_compat.py
@@ -1,212 +1,406 @@
-"""
-OpenAI-compatible TTS API endpoints.
-
-Implements a subset of the OpenAI Audio API so that clients using the
-official openai Python SDK (or any OpenAI-compatible caller) can point at
-voicebox without code changes.
-
-Supported endpoints
--------------------
-POST /v1/audio/speech
- Accept an OpenAI ``speech`` request body, map the model and voice to an
- internal engine / voice-prompt, and return raw WAV bytes.
-
-GET /v1/models
- Stub that returns the three model IDs understood by this server.
-
-Model mapping
--------------
-tts-1 → Kokoro (fast, CPU-friendly)
-tts-1-hd → Qwen3-TTS 1.7B
-gpt-4o-mini-tts → Qwen3-TTS 0.6B
-
-Voice mapping (when no matching profile is found by name)
----------------------------------------------------------
-alloy → af_alloy
-echo → am_echo
-fable → bm_fable
-onyx → am_onyx
-nova → af_nova
-shimmer → af_sky
-
-Limitations
------------
-- ``response_format`` is always treated as WAV; other formats (mp3, opus,
- aac, flac, pcm) are not yet supported. Pass ``response_format="wav"``
- or omit it to avoid surprises.
-- ``speed`` is accepted in the schema for API compatibility but is not yet
- forwarded to the TTS backends. Non-default speed values are silently
- ignored.
+"""OpenAI-compatible audio API: ``POST /v1/audio/speech`` and ``GET /v1/models``.
+
+Any client built against OpenAI's text-to-speech API (the official ``openai``
+SDKs, Open WebUI, Home Assistant, SillyTavern, shell scripts...) can point at
+a local Voicebox by changing only the base URL. Voicebox has no API keys, so
+the ``Authorization`` header is accepted and ignored.
+
+Request field mapping
+---------------------
+``voice``
+ A Voicebox voice profile, by name (case-insensitive) or id. When omitted
+ or empty, the per-client MCP binding (``X-Voicebox-Client-Id``) and then
+ the global default playback voice are tried, exactly like ``POST /speak``.
+``model``
+ A Voicebox TTS engine (``qwen``, ``chatterbox``, ``kokoro``...) or a
+ model variant from ``/v1/models`` (``qwen-tts-0.6B``). OpenAI's own ids
+ (``tts-1``, ``tts-1-hd``, ``gpt-4o-mini-tts``) are aliases for "the
+ profile's configured engine", so unchanged client code works.
+``input``
+ The text to speak, in the profile's language.
+``response_format``
+ ``wav`` (default), ``mp3``, ``flac``, ``opus``, ``pcm`` (raw 16-bit
+ little-endian mono at the engine's sample rate), ``aac`` (needs ffmpeg).
+``speed``
+ 0.25-4.0, applied as a pitch-preserving time stretch after synthesis.
+``instructions``
+ Forwarded as the ``instruct`` prompt to engines that support it (Qwen).
+
+Errors use OpenAI's ``{"error": {"message", "type", "param", "code"}}`` body
+so SDK exceptions carry a readable message.
"""
from __future__ import annotations
import logging
-from typing import Optional
-
-from fastapi import APIRouter, Depends, HTTPException
-from fastapi.responses import Response
-from pydantic import BaseModel
+import shutil
+import subprocess
+import time
+from typing import Any
+
+import numpy as np
+import soundfile as sf
+from fastapi import APIRouter, Depends, HTTPException, Request
+from fastapi.responses import JSONResponse, Response
+from pydantic import BaseModel, Field, ValidationError
from sqlalchemy.orm import Session
-from sqlalchemy import func
from ..database import get_db
logger = logging.getLogger(__name__)
-router = APIRouter()
+router = APIRouter(tags=["openai-compatible"])
-# ---------------------------------------------------------------------------
-# Model / voice mappings
-# ---------------------------------------------------------------------------
+# OpenAI's own model ids. They carry no engine information for us, so they
+# resolve to whatever engine the voice profile is configured for.
+OPENAI_MODEL_ALIASES = ("tts-1", "tts-1-hd", "gpt-4o-mini-tts")
-_MODEL_MAP: dict[str, tuple[str, str]] = {
- # openai_model_id -> (engine, model_size)
- "tts-1": ("kokoro", "default"),
- "tts-1-hd": ("qwen", "1.7B"),
- "gpt-4o-mini-tts": ("qwen", "0.6B"),
+# response_format -> (soundfile format, soundfile subtype, media type)
+_SOUNDFILE_FORMATS: dict[str, tuple[str, str | None, str]] = {
+ "wav": ("WAV", "PCM_16", "audio/wav"),
+ "mp3": ("MP3", "MPEG_LAYER_III", "audio/mpeg"),
+ "flac": ("FLAC", None, "audio/flac"),
+ "opus": ("OGG", "OPUS", "audio/ogg"),
}
-
-_OPENAI_VOICE_TO_KOKORO: dict[str, str] = {
- "alloy": "af_alloy",
- "echo": "am_echo",
- "fable": "bm_fable",
- "onyx": "am_onyx",
- "nova": "af_nova",
- "shimmer": "af_sky",
+_FFMPEG_FORMATS: dict[str, tuple[list[str], str]] = {
+ "aac": (["-c:a", "aac", "-b:a", "128k", "-f", "adts"], "audio/aac"),
}
+RESPONSE_FORMATS = (*_SOUNDFILE_FORMATS, "pcm", *_FFMPEG_FORMATS)
+
+# Voicebox launched long after the OpenAI `created` epoch convention; a fixed
+# value keeps the field deterministic for clients that display it.
+_MODELS_CREATED = 1737763200 # 2026-01-25, the Voicebox repo's creation date
+
+
+class OpenAIError(Exception):
+ """An error rendered in OpenAI's JSON error shape."""
+
+ def __init__(
+ self,
+ status_code: int,
+ message: str,
+ *,
+ error_type: str = "invalid_request_error",
+ param: str | None = None,
+ code: str | None = None,
+ ):
+ super().__init__(message)
+ self.status_code = status_code
+ self.message = message
+ self.error_type = error_type
+ self.param = param
+ self.code = code
+
+ def response(self) -> JSONResponse:
+ return JSONResponse(
+ status_code=self.status_code,
+ content={
+ "error": {
+ "message": self.message,
+ "type": self.error_type,
+ "param": self.param,
+ "code": self.code,
+ }
+ },
+ )
-_AVAILABLE_MODELS = list(_MODEL_MAP.keys())
-
-
-# ---------------------------------------------------------------------------
-# Request schema
-# ---------------------------------------------------------------------------
class SpeechRequest(BaseModel):
- model: str
- input: str
- voice: str = "alloy"
- response_format: Optional[str] = "wav"
- speed: Optional[float] = 1.0
- # instructions / system prompt (OpenAI "instruct" equivalent)
- instructions: Optional[str] = None
+ model: str = Field(..., min_length=1)
+ input: str = Field(..., min_length=1, max_length=10000)
+ voice: str | None = None
+ response_format: str = "wav"
+ speed: float = Field(1.0, ge=0.25, le=4.0)
+ instructions: str | None = None
+
+
+def _available_formats() -> list[str]:
+ formats = [f for f in RESPONSE_FORMATS if f not in _FFMPEG_FORMATS]
+ if shutil.which("ffmpeg"):
+ formats.extend(_FFMPEG_FORMATS)
+ return formats
+
+
+def _model_entries() -> list[dict[str, Any]]:
+ """Every id ``model`` accepts, in OpenAI's model-object shape."""
+ from ..backends import TTS_ENGINES, get_tts_model_configs
+
+ entries = [
+ {
+ "id": alias,
+ "object": "model",
+ "created": _MODELS_CREATED,
+ "owned_by": "voicebox",
+ "description": "Alias: uses the engine configured on the requested voice profile.",
+ }
+ for alias in OPENAI_MODEL_ALIASES
+ ]
+ for engine, display_name in TTS_ENGINES.items():
+ entries.append(
+ {
+ "id": engine,
+ "object": "model",
+ "created": _MODELS_CREATED,
+ "owned_by": "voicebox",
+ "description": display_name,
+ }
+ )
+ for cfg in get_tts_model_configs():
+ if cfg.model_name in TTS_ENGINES:
+ continue
+ entries.append(
+ {
+ "id": cfg.model_name,
+ "object": "model",
+ "created": _MODELS_CREATED,
+ "owned_by": "voicebox",
+ "description": cfg.display_name,
+ }
+ )
+ return entries
-# ---------------------------------------------------------------------------
-# Endpoints
-# ---------------------------------------------------------------------------
+def resolve_model(model: str, profile) -> tuple[str, str | None]:
+ """Map the request's ``model`` onto ``(engine, model_size)``.
[email protected]("/v1/audio/speech")
-async def create_speech(
- request: SpeechRequest,
- db: Session = Depends(get_db),
-) -> Response:
- """Generate speech from text, returning WAV audio bytes.
-
- Always returns ``audio/wav`` regardless of ``response_format`` — this
- keeps the implementation simple while remaining correct for most callers.
+ ``model_size`` is ``None`` for engines with a single variant.
"""
- from ..backends import load_engine_model, get_tts_backend_for_engine, engine_needs_trim
- from ..utils.chunked_tts import generate_chunked
- from ..utils.audio import normalize_audio, trim_tts_output
- from ..services.tts import audio_to_wav_bytes
-
- # --- Resolve model -------------------------------------------------
- mapping = _MODEL_MAP.get(request.model)
- if mapping is None:
- raise HTTPException(
- status_code=400,
- detail=f"Unknown model '{request.model}'. Supported: {_AVAILABLE_MODELS}",
+ from ..backends import TTS_ENGINES, engine_has_model_sizes, get_tts_model_configs
+
+ if model in OPENAI_MODEL_ALIASES:
+ engine = getattr(profile, "default_engine", None) or getattr(profile, "preset_engine", None) or "qwen"
+ elif model in TTS_ENGINES:
+ engine = model
+ else:
+ cfg = next((c for c in get_tts_model_configs() if c.model_name == model), None)
+ if cfg is None:
+ known = [e["id"] for e in _model_entries()]
+ raise OpenAIError(
+ 404,
+ f"The model '{model}' does not exist. Available models: {', '.join(known)}.",
+ param="model",
+ code="model_not_found",
+ )
+ return cfg.engine, (cfg.model_size if engine_has_model_sizes(cfg.engine) else None)
+
+ if not engine_has_model_sizes(engine):
+ return engine, None
+ # Bare engine name: the first registered variant is that engine's default size.
+ default_cfg = next(c for c in get_tts_model_configs() if c.engine == engine)
+ return engine, default_cfg.model_size
+
+
+def encode_audio(audio: np.ndarray, sample_rate: int, response_format: str) -> tuple[bytes, str]:
+ """Encode float audio into the requested container; returns (bytes, media type)."""
+ import io
+
+ if response_format == "pcm":
+ pcm = np.clip(audio, -1.0, 1.0)
+ return (pcm * 32767).astype("<i2").tobytes(), "audio/pcm"
+
+ if response_format in _SOUNDFILE_FORMATS:
+ fmt, subtype, media_type = _SOUNDFILE_FORMATS[response_format]
+ if fmt not in sf.available_formats():
+ raise OpenAIError(
+ 400,
+ f"response_format '{response_format}' is not supported by this server's libsndfile build.",
+ param="response_format",
+ code="unsupported_format",
+ )
+ buffer = io.BytesIO()
+ sf.write(buffer, audio, sample_rate, format=fmt, subtype=subtype)
+ return buffer.getvalue(), media_type
+
+ ffmpeg_args, media_type = _FFMPEG_FORMATS[response_format]
+ if shutil.which("ffmpeg") is None:
+ raise OpenAIError(
+ 400,
+ f"response_format '{response_format}' requires ffmpeg, which is not installed on this server. "
+ f"Supported formats here: {', '.join(_available_formats())}.",
+ param="response_format",
+ code="unsupported_format",
+ )
+ wav = io.BytesIO()
+ sf.write(wav, audio, sample_rate, format="WAV", subtype="PCM_16")
+ try:
+ result = subprocess.run(
+ ["ffmpeg", "-hide_banner", "-loglevel", "error", "-i", "pipe:0", *ffmpeg_args, "pipe:1"],
+ input=wav.getvalue(),
+ capture_output=True,
+ timeout=120,
+ check=False,
)
- engine, model_size = mapping
+ except subprocess.TimeoutExpired as exc:
+ raise OpenAIError(500, "ffmpeg timed out while encoding.", error_type="server_error") from exc
+ if result.returncode != 0:
+ stderr = result.stderr.decode(errors="replace").strip()
+ raise OpenAIError(500, f"ffmpeg failed to encode audio: {stderr}", error_type="server_error")
+ return result.stdout, media_type
- # --- Resolve voice prompt ------------------------------------------
- voice_prompt = await _resolve_voice_prompt(request.voice, engine, db)
- # --- Load model and generate ---------------------------------------
- tts_model = get_tts_backend_for_engine(engine)
- await load_engine_model(engine, model_size)
-
- trim_fn = trim_tts_output if engine_needs_trim(engine) else None
-
- audio, sample_rate = await generate_chunked(
- tts_model,
- request.input,
- voice_prompt,
- language="en",
- seed=None,
- instruct=request.instructions,
- trim_fn=trim_fn,
- )
+def apply_speed(audio: np.ndarray, sample_rate: int, speed: float) -> np.ndarray:
+ """Time-stretch without changing pitch. ``speed`` > 1 shortens the clip."""
+ if abs(speed - 1.0) < 1e-3 or audio.size == 0:
+ return audio
+ import librosa
- audio = normalize_audio(audio)
- wav_bytes = audio_to_wav_bytes(audio, sample_rate)
-
- return Response(
- content=wav_bytes,
- media_type="audio/wav",
- headers={"Content-Disposition": "attachment; filename=speech.wav"},
- )
+ stretched = librosa.effects.time_stretch(audio.astype(np.float32), rate=speed)
+ return stretched.astype(audio.dtype, copy=False)
@router.get("/v1/models")
async def list_models():
- """Return model IDs understood by this server."""
- return {
- "object": "list",
- "data": [
- {"id": model_id, "object": "model", "owned_by": "voicebox"}
- for model_id in _AVAILABLE_MODELS
- ],
- }
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-async def _resolve_voice_prompt(voice: str, engine: str, db: Session) -> dict:
- """Return a voice_prompt dict for the requested voice name.
-
- Strategy:
- 1. Look up a VoiceProfile by name (case-insensitive). If found, delegate
- to ``profiles.create_voice_prompt_for_profile`` which handles reference
- audio encoding and caching.
- 2. If no profile matches (or the engine is kokoro), fall back to a
- static voice-id dict using the ``_OPENAI_VOICE_TO_KOKORO`` mapping.
- """
- from ..database import VoiceProfile as DBVoiceProfile
- from ..services import profiles as profiles_svc
-
- # Try profile lookup first
- profile = (
- db.query(DBVoiceProfile)
- .filter(func.lower(DBVoiceProfile.name) == voice.lower())
- .first()
+ """List every id ``POST /v1/audio/speech`` accepts as ``model``."""
+ return {"object": "list", "data": _model_entries()}
+
+
[email protected]("/v1/models/{model_id}")
+async def get_model(model_id: str):
+ for entry in _model_entries():
+ if entry["id"] == model_id:
+ return entry
+ return OpenAIError(404, f"The model '{model_id}' does not exist.", param="model", code="model_not_found").response()
+
+
[email protected]("/v1/audio/speech")
+async def create_speech(request: Request, db: Session = Depends(get_db)):
+ """Synthesize ``input`` in a Voicebox voice and return the encoded audio."""
+ try:
+ return await _create_speech(request, db)
+ except OpenAIError as e:
+ return e.response()
+ except HTTPException as e:
+ detail = e.detail if isinstance(e.detail, str) else str(e.detail)
+ return OpenAIError(e.status_code, detail).response()
+
+
+async def _create_speech(request: Request, db: Session) -> Response:
+ from ..backends import (
+ engine_needs_trim,
+ engine_retries_runaway,
+ ensure_model_cached_or_raise,
+ get_tts_backend_for_engine,
+ load_engine_model,
)
+ from ..mcp_server.resolve import resolve_profile
+ from ..services import profiles
+ from ..services.generation import release_generation_memory
+ from ..utils.chunked_tts import generate_chunked
- if profile is not None:
- try:
- return await profiles_svc.create_voice_prompt_for_profile(
- str(profile.id),
- db,
- use_cache=True,
- engine=engine,
- )
- except Exception as e:
- # Profile found but voice-prompt creation failed; fall through to
- # built-in voice. Log so the failure is not silently swallowed.
- logger.warning(
- "Failed to create voice prompt for profile '%s': %s. "
- "Falling back to built-in Kokoro voice.",
- voice,
- e,
+ try:
+ body = await request.json()
+ except ValueError as exc:
+ raise OpenAIError(400, "Request body must be valid JSON.") from exc
+ if not isinstance(body, dict):
+ raise OpenAIError(400, "Request body must be a JSON object.")
+ try:
+ data = SpeechRequest.model_validate(body)
+ except ValidationError as exc:
+ first = exc.errors()[0]
+ param = ".".join(str(p) for p in first.get("loc", ())) or None
+ raise OpenAIError(400, f"Invalid value for '{param}': {first['msg']}", param=param) from exc
+
+ if data.response_format not in RESPONSE_FORMATS:
+ raise OpenAIError(
+ 400,
+ f"Invalid response_format '{data.response_format}'. Supported: {', '.join(RESPONSE_FORMATS)}.",
+ param="response_format",
+ code="unsupported_format",
+ )
+
+ client_id = request.headers.get("X-Voicebox-Client-Id")
+ profile = resolve_profile(data.voice or None, client_id, db)
+ if profile is None:
+ if data.voice:
+ raise OpenAIError(
+ 400,
+ f"Voice '{data.voice}' is not a Voicebox voice profile. "
+ "Pass a profile name or id; GET /profiles lists them.",
+ param="voice",
+ code="voice_not_found",
)
+ raise OpenAIError(
+ 400,
+ "No voice given and no default voice configured. Pass `voice` (a profile name or id), "
+ "or set a default in Voicebox → Settings → MCP.",
+ param="voice",
+ code="voice_required",
+ )
+
+ engine, model_size = resolve_model(data.model, profile)
+ try:
+ profiles.validate_profile_engine(profile, engine)
+ except ValueError as exc:
+ raise OpenAIError(400, str(exc), param="model", code="engine_not_compatible") from exc
+
+ try:
+ await ensure_model_cached_or_raise(engine, model_size or "default")
+ except HTTPException as exc:
+ raise OpenAIError(
+ 400,
+ f"The model for '{data.model}' (engine '{engine}') is not downloaded yet. "
+ "Download it in Voicebox → Models, or POST /models/load.",
+ param="model",
+ code="model_not_downloaded",
+ ) from exc
+ await load_engine_model(engine, model_size or "default")
+ tts_model = get_tts_backend_for_engine(engine)
- # Fall back to built-in Kokoro voice id using engine-specific key names.
- kokoro_voice = _OPENAI_VOICE_TO_KOKORO.get(voice.lower(), "af_alloy")
- if engine == "kokoro":
- return {"kokoro_voice": kokoro_voice}
- # qwen_custom_voice and all other engines expect preset_voice_id
- return {"preset_voice_id": kokoro_voice}
+ voice_prompt = await profiles.create_voice_prompt_for_profile(str(profile.id), db, engine=engine)
+
+ trim_fn = None
+ runaway_detector = None
+ if engine_needs_trim(engine):
+ from ..utils.audio import trim_tts_output
+
+ trim_fn = trim_tts_output
+ if engine_retries_runaway(engine):
+ from ..utils.audio import has_tts_runaway
+
+ runaway_detector = has_tts_runaway
+
+ started = time.monotonic()
+ try:
+ audio, sample_rate = await generate_chunked(
+ tts_model,
+ data.input,
+ voice_prompt,
+ language=getattr(profile, "language", None) or "en",
+ instruct=data.instructions,
+ trim_fn=trim_fn,
+ runaway_detector=runaway_detector,
+ )
+ finally:
+ release_generation_memory(tts_model)
+
+ if profile.effects_chain:
+ import json
+
+ from ..utils.effects import apply_effects
+
+ try:
+ effects_chain = json.loads(profile.effects_chain)
+ except ValueError:
+ effects_chain = None
+ if effects_chain:
+ audio = apply_effects(audio, sample_rate, effects_chain)
+
+ from ..utils.audio import normalize_audio
+
+ audio = normalize_audio(audio)
+ audio = apply_speed(audio, sample_rate, data.speed)
+ content, media_type = encode_audio(audio, sample_rate, data.response_format)
+
+ logger.info(
+ "OpenAI-compat speech: profile=%s engine=%s format=%s %.1fs audio in %.1fs",
+ profile.name,
+ engine,
+ data.response_format,
+ len(audio) / sample_rate,
+ time.monotonic() - started,
+ )
+ return Response(
+ content=content,
+ media_type=media_type,
+ headers={"Content-Disposition": f'attachment; filename="speech.{data.response_format}"'},
+ )
diff --git a/backend/tests/test_openai_compat.py b/backend/tests/test_openai_compat.py
new file mode 100644
index 00000000..96896568
--- /dev/null
+++ b/backend/tests/test_openai_compat.py
@@ -0,0 +1,315 @@
+"""Tests for the OpenAI-compatible ``/v1/audio/speech`` and ``/v1/models`` routes.
+
+The routes are mounted on a bare FastAPI app and driven through the official
+``openai`` Python SDK over an in-process ASGI transport, so the tests prove a
+stock OpenAI client works against Voicebox with only the base URL changed.
+Synthesis is stubbed with a sine wave; model loading and cache checks are
+no-ops.
+"""
+
+import io
+import json
+
+import httpx
+import numpy as np
+import pytest
+import soundfile as sf
+from fastapi import FastAPI
+from openai import AsyncOpenAI, BadRequestError, NotFoundError
+
+import backend.backends as backends
+import backend.mcp_server.resolve as resolve_mod
+import backend.services.generation as generation_svc
+import backend.services.profiles as profiles_svc
+import backend.utils.chunked_tts as chunked_tts
+from backend.database import get_db
+from backend.routes import openai_compat
+
+SAMPLE_RATE = 24000
+DURATION_S = 1.0
+
+
+class _FakeProfile:
+ def __init__(self, name="Morgan", voice_type="cloned", default_engine=None, effects_chain=None):
+ self.id = "profile-1"
+ self.name = name
+ self.language = "en"
+ self.voice_type = voice_type
+ self.default_engine = default_engine
+ self.preset_engine = None
+ self.preset_voice_id = None
+ self.effects_chain = effects_chain
+
+
+class _FakeBackend:
+ device = "cpu"
+
+
+def app(monkeypatch):
+ """App with only the OpenAI-compatible router and a stubbed pipeline."""
+ calls = {}
+
+ def fake_resolve_profile(explicit, client_id, db):
+ calls["voice"] = explicit
+ calls["client_id"] = client_id
+ if explicit is None:
+ return _FakeProfile(name="Default") if client_id == "bound-agent" else None
+ if explicit.lower() in ("morgan", "profile-1"):
+ return _FakeProfile()
+ return None
+
+ async def fake_ensure_cached(engine, model_size="default"):
+ calls["ensure"] = (engine, model_size)
+
+ async def fake_load(engine, model_size="default"):
+ calls["load"] = (engine, model_size)
+
+ async def fake_voice_prompt(profile_id, db, use_cache=True, engine="qwen"):
+ calls["voice_prompt_engine"] = engine
+ return {"fake": True}
+
+ async def fake_generate_chunked(backend, text, voice_prompt, **kwargs):
+ calls["text"] = text
+ calls["generate_kwargs"] = kwargs
+ t = np.linspace(0, DURATION_S, int(SAMPLE_RATE * DURATION_S), endpoint=False)
+ return (0.5 * np.sin(2 * np.pi * 440 * t)).astype(np.float32), SAMPLE_RATE
+
+ monkeypatch.setattr(resolve_mod, "resolve_profile", fake_resolve_profile)
+ monkeypatch.setattr(backends, "ensure_model_cached_or_raise", fake_ensure_cached)
+ monkeypatch.setattr(backends, "load_engine_model", fake_load)
+ monkeypatch.setattr(backends, "get_tts_backend_for_engine", lambda engine: _FakeBackend())
+ monkeypatch.setattr(profiles_svc, "create_voice_prompt_for_profile", fake_voice_prompt)
+ monkeypatch.setattr(chunked_tts, "generate_chunked", fake_generate_chunked)
+ monkeypatch.setattr(generation_svc, "release_generation_memory", lambda tts_model: None)
+
+ application = FastAPI()
+ application.include_router(openai_compat.router)
+ application.dependency_overrides[get_db] = lambda: object()
+ application.state.calls = calls
+ return application
+
+
+def client(app):
+ """Official openai SDK client pointed at the in-process app."""
+ transport = httpx.ASGITransport(app=app)
+ return AsyncOpenAI(
+ base_url="http://voicebox.test/v1",
+ api_key="not-used",
+ http_client=httpx.AsyncClient(transport=transport),
+ )
+
+
+def raw_client(app):
+ return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://voicebox.test")
+
+
+# ─── /v1/models ───────────────────────────────────────────────────────────
+
+
+async def test_models_list_includes_aliases_engines_and_variants(client):
+ models = await client.models.list()
+ ids = {m.id for m in models.data}
+ assert {"tts-1", "tts-1-hd", "gpt-4o-mini-tts"} <= ids
+ assert {"qwen", "chatterbox", "kokoro"} <= ids
+ assert "qwen-tts-0.6B" in ids
+ assert all(m.object == "model" and m.owned_by == "voicebox" for m in models.data)
+
+
+async def test_models_retrieve_known_and_unknown(client):
+ model = await client.models.retrieve("qwen")
+ assert model.id == "qwen"
+ with pytest.raises(NotFoundError) as exc_info:
+ await client.models.retrieve("eleven-labs-v9")
+ assert exc_info.value.code == "model_not_found"
+
+
+# ─── /v1/audio/speech: happy paths ────────────────────────────────────────
+
+
+async def test_speech_wav_default_with_openai_alias_uses_profile_engine(client, app):
+ response = await client.audio.speech.create(model="tts-1", voice="Morgan", input="Hello there")
+ assert response.response.headers["content-type"] == "audio/wav"
+ audio, sr = sf.read(io.BytesIO(response.content))
+ assert sr == SAMPLE_RATE
+ assert abs(len(audio) / sr - DURATION_S) < 0.01
+
+ calls = app.state.calls
+ assert calls["voice"] == "Morgan"
+ assert calls["text"] == "Hello there"
+ # A cloned profile without a configured engine falls back to qwen at its default size.
+ assert calls["load"] == ("qwen", "1.7B")
+ assert calls["voice_prompt_engine"] == "qwen"
+
+
+async def test_speech_model_is_a_voicebox_engine(client, app):
+ await client.audio.speech.create(model="chatterbox", voice="Morgan", input="Hi")
+ assert app.state.calls["load"] == ("chatterbox", "default")
+
+
+async def test_speech_model_variant_selects_size(client, app):
+ await client.audio.speech.create(model="qwen-tts-0.6B", voice="Morgan", input="Hi")
+ assert app.state.calls["load"] == ("qwen", "0.6B")
+
+
+ ("response_format", "media_type", "magic"),
+ [
+ ("mp3", "audio/mpeg", None),
+ ("flac", "audio/flac", b"fLaC"),
+ ("opus", "audio/ogg", b"OggS"),
+ ],
+)
+async def test_speech_encodes_compressed_formats(client, response_format, media_type, magic):
+ response = await client.audio.speech.create(
+ model="tts-1", voice="Morgan", input="Hi", response_format=response_format
+ )
+ assert response.response.headers["content-type"] == media_type
+ assert response.response.headers["content-disposition"].endswith(f'speech.{response_format}"')
+ if magic:
+ assert response.content[:4] == magic
+ # Whatever the container, libsndfile must be able to read our output back.
+ audio, _sr = sf.read(io.BytesIO(response.content))
+ assert len(audio) > 0
+
+
+async def test_speech_pcm_is_raw_int16_mono(client):
+ response = await client.audio.speech.create(model="tts-1", voice="Morgan", input="Hi", response_format="pcm")
+ assert response.response.headers["content-type"] == "audio/pcm"
+ samples = np.frombuffer(response.content, dtype="<i2")
+ assert len(samples) == int(SAMPLE_RATE * DURATION_S)
+ assert samples.max() > 1000 # non-silent after loudness normalization
+
+
+async def test_speech_speed_time_stretches(client):
+ response = await client.audio.speech.create(model="tts-1", voice="Morgan", input="Hi", speed=2.0)
+ audio, sr = sf.read(io.BytesIO(response.content))
+ assert abs(len(audio) / sr - DURATION_S / 2) < 0.05
+
+
+async def test_speech_instructions_forwarded_as_instruct(client, app):
+ await client.audio.speech.create(
+ model="gpt-4o-mini-tts", voice="Morgan", input="Hi", instructions="Whisper, slowly."
+ )
+ assert app.state.calls["generate_kwargs"]["instruct"] == "Whisper, slowly."
+
+
+async def test_speech_without_voice_uses_client_binding(raw_client, app):
+ response = await raw_client.post(
+ "/v1/audio/speech",
+ json={"model": "tts-1", "input": "Hi"},
+ headers={"X-Voicebox-Client-Id": "bound-agent"},
+ )
+ assert response.status_code == 200
+ assert app.state.calls["voice"] is None
+ assert app.state.calls["client_id"] == "bound-agent"
+
+
+# ─── /v1/audio/speech: errors in OpenAI's shape ───────────────────────────
+
+
+async def test_unknown_voice_is_openai_error(client):
+ with pytest.raises(BadRequestError) as exc_info:
+ await client.audio.speech.create(model="tts-1", voice="alloy", input="Hi")
+ err = exc_info.value
+ assert err.code == "voice_not_found"
+ assert err.param == "voice"
+ assert "alloy" in err.message
+
+
+async def test_missing_voice_without_default_is_openai_error(raw_client):
+ response = await raw_client.post("/v1/audio/speech", json={"model": "tts-1", "input": "Hi"})
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "voice_required"
+
+
+async def test_unknown_model_is_openai_404(client):
+ with pytest.raises(NotFoundError) as exc_info:
+ await client.audio.speech.create(model="tts-9000", voice="Morgan", input="Hi")
+ assert exc_info.value.code == "model_not_found"
+ assert exc_info.value.param == "model"
+
+
+async def test_unknown_response_format_is_openai_error(raw_client):
+ response = await raw_client.post(
+ "/v1/audio/speech",
+ json={"model": "tts-1", "voice": "Morgan", "input": "Hi", "response_format": "wma"},
+ )
+ assert response.status_code == 400
+ body = response.json()["error"]
+ assert body["code"] == "unsupported_format"
+ assert body["param"] == "response_format"
+
+
+async def test_validation_errors_are_400_not_422(raw_client):
+ response = await raw_client.post("/v1/audio/speech", json={"model": "tts-1", "voice": "Morgan"})
+ assert response.status_code == 400
+ body = response.json()["error"]
+ assert body["param"] == "input"
+ assert body["type"] == "invalid_request_error"
+
+ response = await raw_client.post(
+ "/v1/audio/speech", json={"model": "tts-1", "voice": "Morgan", "input": "Hi", "speed": 9}
+ )
+ assert response.status_code == 400
+ assert response.json()["error"]["param"] == "speed"
+
+ response = await raw_client.post(
+ "/v1/audio/speech", content=b"not json", headers={"content-type": "application/json"}
+ )
+ assert response.status_code == 400
+ assert "JSON" in response.json()["error"]["message"]
+
+
+async def test_model_not_downloaded_http_exception_is_rewrapped(raw_client, monkeypatch):
+ from fastapi import HTTPException
+
+ async def not_cached(engine, model_size="default"):
+ raise HTTPException(status_code=400, detail="Model 1.7B is not downloaded yet.")
+
+ monkeypatch.setattr(backends, "ensure_model_cached_or_raise", not_cached)
+ response = await raw_client.post("/v1/audio/speech", json={"model": "tts-1", "voice": "Morgan", "input": "Hi"})
+ assert response.status_code == 400
+ body = response.json()["error"]
+ assert body["code"] == "model_not_downloaded"
+ assert "not downloaded" in body["message"]
+ assert "/models/load" in body["message"]
+
+
+async def test_preset_profile_rejects_other_engine(raw_client, monkeypatch):
+ def preset_profile(explicit, client_id, db):
+ p = _FakeProfile(name="Heart", voice_type="preset")
+ p.preset_engine = "kokoro"
+ p.preset_voice_id = "af_heart"
+ return p
+
+ monkeypatch.setattr(resolve_mod, "resolve_profile", preset_profile)
+ response = await raw_client.post("/v1/audio/speech", json={"model": "qwen", "voice": "Heart", "input": "Hi"})
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "engine_not_compatible"
+
+ # The alias picks the preset's own engine, so the same profile works with tts-1.
+ response = await raw_client.post("/v1/audio/speech", json={"model": "tts-1", "voice": "Heart", "input": "Hi"})
+ assert response.status_code == 200
+
+
+# ─── encoder unit coverage ────────────────────────────────────────────────
+
+
+def test_encode_audio_wav_roundtrip():
+ audio = np.zeros(2400, dtype=np.float32)
+ content, media_type = openai_compat.encode_audio(audio, 24000, "wav")
+ assert media_type == "audio/wav"
+ data, sr = sf.read(io.BytesIO(content))
+ assert sr == 24000
+ assert len(data) == 2400
+
+
+def test_aac_without_ffmpeg_is_unsupported(monkeypatch):
+ monkeypatch.setattr(openai_compat.shutil, "which", lambda name: None)
+ with pytest.raises(openai_compat.OpenAIError) as exc_info:
+ openai_compat.encode_audio(np.zeros(100, dtype=np.float32), 24000, "aac")
+ assert exc_info.value.code == "unsupported_format"
+ assert json.loads(exc_info.value.response().body)["error"]["param"] == "response_format"
diff --git a/docs/content/docs/overview/mcp-server.mdx b/docs/content/docs/overview/mcp-server.mdx
index e947a7a4..12d07a68 100644
--- a/docs/content/docs/overview/mcp-server.mdx
+++ b/docs/content/docs/overview/mcp-server.mdx
@@ -230,6 +230,64 @@ Body fields match the MCP tool: `text`, optional `profile`, `engine`,
`personality`, `language`. Returns a `GenerationResponse` — the same shape as
`POST /generate`.
+## OpenAI-compatible API
+
+Voicebox also answers OpenAI's text-to-speech API at `POST /v1/audio/speech`
+and `GET /v1/models`, so anything already built against OpenAI TTS (the
+official `openai` SDKs, Open WebUI, Home Assistant, SillyTavern, shell
+scripts) becomes a local, offline TTS by changing only the base URL. Voicebox
+has no API keys: pass any non-empty string, the `Authorization` header is
+ignored.
+
+```python
+from openai import OpenAI
+
+client = OpenAI(base_url="http://127.0.0.1:17493/v1", api_key="voicebox")
+
+audio = client.audio.speech.create(
+ model="tts-1", # or a Voicebox engine: "qwen", "chatterbox", "kokoro"...
+ voice="Morgan", # a Voicebox voice profile, by name or id
+ input="Build complete.",
+ response_format="mp3",
+)
+audio.write_to_file("build.mp3")
+```
+
+```bash
+curl -X POST http://127.0.0.1:17493/v1/audio/speech \
+ -H 'Content-Type: application/json' \
+ -d '{"model":"tts-1","voice":"Morgan","input":"Build complete."}' \
+ --output build.wav
+```
+
+How the OpenAI fields map onto Voicebox:
+
+| Field | Meaning in Voicebox |
+| --- | --- |
+| `voice` | A voice profile, by name (case-insensitive) or id. Omit it and the [voice resolution](#voice-resolution) chain applies: the `X-Voicebox-Client-Id` binding, then the default playback voice. There are no built-in `alloy`/`nova` voices — create a profile (a Kokoro preset profile named "Alloy" works fine). |
+| `model` | A TTS engine (`qwen`, `qwen_custom_voice`, `luxtts`, `chatterbox`, `chatterbox_turbo`, `tada`, `kokoro`) or a model variant such as `qwen-tts-0.6B`. OpenAI's own ids `tts-1`, `tts-1-hd` and `gpt-4o-mini-tts` are accepted as aliases for "the engine configured on the profile", so unchanged client code works. `GET /v1/models` lists every accepted id. The model must already be downloaded (Voicebox → Models). |
+| `input` | The text to speak, up to 10,000 characters, in the profile's language. Long text is chunked at sentence boundaries like the rest of Voicebox. |
+| `response_format` | `wav` (default), `mp3`, `flac`, `opus`, `pcm` (raw 16-bit little-endian mono at the engine's sample rate, 24 kHz for most engines) and `aac` (requires `ffmpeg` on the server's PATH). |
+| `speed` | `0.25`–`4.0`. Applied as a pitch-preserving time stretch after synthesis. |
+| `instructions` | Forwarded as the engine's instruct prompt where supported (Qwen). |
+
+The profile's effects chain is applied and the output is loudness-normalized,
+exactly as in the app. The response is the finished audio in one body (no
+chunked streaming yet); nothing is written to generation history.
+
+Errors use OpenAI's `{"error": {"message", "type", "param", "code"}}` body,
+so SDK exceptions carry the reason: `voice_not_found`, `voice_required`,
+`model_not_found`, `model_not_downloaded`, `engine_not_compatible`,
+`unsupported_format`. Validation problems come back as `400`, not FastAPI's
+`422`.
+
+<Callout type="warn">
+ The endpoint shares the rest of the API's trust boundary: no auth,
+ localhost by default. If you expose Voicebox on a network for a tool like
+ Open WebUI, see [Remote Mode](/overview/remote-mode) and keep it behind a
+ firewall or VPN.
+</Callout>
+
## Debugging
Use the MCP Inspector to poke tools directly without plumbing through an