Skip to content

Studio: complete the OpenAI-compatible audio API - #12812

Merged
danielhanchen merged 9 commits into
unslothai:mainfrom
Etherll:feat/studio-audio-api
Oct 6, 2026
Merged

danielhanchen merged 9 commits into
unslothai:mainfrom
Etherll:feat/studio-audio-api

Conversation

@Etherll

@Etherll Etherll commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

A script with an API key can now run the same audio workflows as the Audio pages through /v1. Before, /v1/audio/speech ignored voice and speed and only returned WAV, transcriptions had no timings, and /v1/audio/run always used whatever model was already loaded and could not be fed audio from a /v1 client.

/v1/audio/speech

  • voice takes a saved voice id (a string or {"id": ...}) and speaks in that voice, using its stored transcript as the reference text. A built-in speaker the loaded model lists (for example Kokoro's af_bella) goes into audio_options.voice unless the request already set one. Other names, such as OpenAI's alloy, are still ignored.
  • New reference and reference_text fields clone from an uploaded input, a history clip or a saved voice. Sending a saved voice and a reference together is a 400 with param: "reference".
  • response_format accepts wav, mp3, flac, opus, aac and pcm, re-encoded with PyAV from the generated WAV. A format whose encoder is missing from the FFmpeg build returns a 400 that lists the formats that work. pcm is bare 24 kHz 16-bit little-endian mono samples, the format OpenAI's clients play. History still keeps the WAV.
  • stream_format: "sse" returns a 400. speed now has OpenAI's 0.25 to 4.0 bounds and reaches models that support it.

/v1/audio/transcriptions

  • On audio.cpp models, verbose_json returns OpenAI segments, and words when timestamp_granularities[]=word is sent. verbose_json no longer needs language when the model reports the language itself (Qwen3-ASR does; VibeVoice-ASR does not, so send language there).
  • New diarized_json returns speaker-labelled segments for models that can tell speakers apart (MOSS-Transcribe-Diarize, VibeVoice-ASR). Other models get the same 422 message the Transcribe page shows.
  • The upload is decoded to a temporary WAV for audio.cpp and deleted afterwards, so nothing is added to inputs or transcript history. Past 30 minutes it is refused with 413, as before. Whisper and other non-audio.cpp engines behave as before.

/v1/audio/run

  • Takes a model. With model auto-switch on, a named model is loaded for any workflow. A model that cannot run the requested workflow (for example separate on a TTS model) is refused with a 400 param: "model" before the resident model is evicted. The check is a new require_audio_workflow argument to _maybe_auto_switch_model.
  • Runs and /v1/audio/generate calls now appear in the API monitor. Runs from the Audio page and chat read-aloud do not.

Audio inputs (POST, GET .../file, DELETE), saved voices (CRUD and .../file) and history clip files now also answer on /v1, and the URLs those calls and /v1/audio/run return point at /v1. /v1/audio/inputs gets the same streamed upload path and 200 MiB cap as the /api/inference route, so it bypasses the general /v1 body limit. These routes stay key-only, and the keyless route test now covers them.

/v1/audio/translations and listing audio workflows in /v1/models are left for a follow-up to keep this one reviewable.

Endpoints

Endpoint Use
POST /v1/audio/speech Text to speech. model, input, voice (saved voice id, {"id": ...} or a built-in speaker), reference + reference_text to clone, response_format (wav, mp3, flac, opus, aac, pcm), speed, instructions, language, seed, audio_options
POST /v1/audio/transcriptions Speech to text. file, model, language, response_format (json, text, verbose_json, diarized_json), timestamp_granularities[] on audio.cpp models
POST /v1/audio/run An Audio page workflow (clone, speak, edit, convert, music, separate) with model, audio named by input_id, clip_id or voice_id
POST /v1/audio/inputs?name=... Upload audio as the raw body (any container PyAV reads, up to 200 MiB); kept for 24 hours
GET /v1/audio/inputs/{id}/file, DELETE /v1/audio/inputs/{id} Fetch or remove an upload
GET, POST /v1/audio/voices; PATCH, DELETE /v1/audio/voices/{id}; GET /v1/audio/voices/{id}/file Saved voices
GET /v1/audio/gallery/{id}/file A clip a run produced
POST /v1/audio/generate Chat-shaped text to speech, as before

Compatibility

speed values outside 0.25 to 4.0 used to be accepted and ignored. They now fail validation. A voice string that matches a saved voice id or one of the loaded model's speakers now changes the output, where it was ignored before.

Testing

Live run against a Studio server started from this branch on one GPU, calling /v1 with an API key through the openai Python SDK: 22/22 checks passed.

  • Kokoro speech in every format (wav, mp3, flac, opus, aac, pcm) with the expected file signatures and content types, pcm as bare samples, and a built-in voice changing the speaker.
  • /v1/audio/inputs upload, /v1/audio/voices create, then VoxCPM2 speech in that saved voice (as an object and as a string with mp3) and a reference clone. Voice plus reference returned 400, and sse returned 400.
  • VibeVoice-ASR verbose_json with segments and diarized_json with Speaker 1. Qwen3-ASR verbose_json with no language sent returned "English". diarized_json on Whisper returned the 422.
  • /v1/audio/run separate naming Kokoro was refused while VoxCPM2 stayed loaded. Naming HTDemucs auto-loaded it and returned four stems. A saved-voice speak run returned a /v1/audio/gallery/... URL.
  • The API monitor listed rows for /v1/audio/run, /v1/audio/speech and /v1/audio/transcriptions.

Word timings on Qwen3-ASR need the aligner download and were not run live. Route tests with a faked sidecar cover them. The PyAV encoder was also checked against PyAV 12.3 (the requirement floor), 15 and 19.

Backend tests: 1435 passed, 1 skipped.

cd studio/backend
python -m pytest -q \
  tests/test_openai_audio_speech_route.py \
  tests/test_openai_audio_transcriptions_route.py \
  tests/test_audio_run_route.py \
  tests/test_audio_inputs.py \
  tests/test_audio_voices.py \
  tests/test_openai_auto_switch.py \
  tests/test_middleware.py \
  tests/test_keyless_api_access.py \
  tests/test_openai_audio_upload_bound.py \
  tests/test_account_media_isolation.py \
  tests/test_audio_cpp_separation.py \
  tests/test_transcribe_source_route.py \
  tests/test_stt_capabilities.py \
  tests/test_api_monitor.py \
  tests/test_audio_runtime_errors.py

The multi-account suite and the audio clone, convert and edit request tests also pass (1071 passed).

A script with an API key can now do what the Audio pages do, against /v1:

- /v1/audio/speech takes a saved voice (id or {"id"}), a built-in speaker
  of the model, or a reference clip to clone, and returns wav, mp3, flac,
  opus, aac or pcm. History keeps the WAV.
- /v1/audio/transcriptions gives OpenAI segments and words on audio.cpp
  models, plus diarized_json for models that tell speakers apart.
- /v1/audio/run takes a model and loads it, refusing one that cannot run
  the workflow before the resident model is evicted. API runs show in the
  API monitor.
- Audio inputs, saved voices and history clip files answer on /v1, with
  the upload streamed past the /v1 body cap. URLs returned on /v1 point
  at /v1.
@Etherll
Etherll requested a review from danielhanchen as a code owner October 6, 2026 03:14
@Etherll

Etherll commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

- A timed /v1/audio/transcriptions upload past 30 minutes is refused with
  413, like the plain one, instead of being transcribed cut short.
- pcm speech is 24 kHz mono, the format OpenAI's clients play.
- The input sweep reaps a prepared upload a crash left behind.
@Etherll

Etherll commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

A timed transcription can wait an hour on the aligner download before
audio.cpp reads its copy, so the sweep reaps a leftover copy after the
inputs' 24 h TTL, not the hour a temp file gets.
@Etherll

Etherll commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

The Repo tests (CPU, rest) failure here (audio_inputs.py:264: Path.open() in test_runtime_text_encoding.py) is a false positive in that check, not something to change in this PR: line 264 is stream.codec_context.open(), which opens a PyAV codec and takes no encoding. The check did not follow PyAV objects through a function-local import av, a with av.open(...) as dst, or dst.add_stream(). #12831 fixes the check; once it lands, a re-run should clear this.

@Etherll

Etherll commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

A client with an API key can now use the Audio pages through /v1: speech in a saved, built-in or cloned voice, returned as wav, mp3, flac, opus, aac or pcm, and transcriptions with segments, words and speaker labels on audio.cpp models, with /v1/audio/run naming the model to load. Uploads and saved voices work there too. Translations and audio workflows in /v1/models are left for a follow-up.

What changed

  • A timestamped transcription over 30 minutes was cut short yet returned as a success. It now gets 413, like a plain transcription.
  • pcm speech followed the model's sample rate and channels, so OpenAI clients played 44.1 kHz audio at the wrong speed. It is now 24 kHz mono, as OpenAI defines it.
  • A transcription copy left by a crash was never cleaned up. The input sweep now removes it after 24 hours, like other uploads, leaving room for a slow aligner download.

Audio backend tests pass on 8e91dce (1435 passed, 1 skipped). A live run on one GPU through the openai Python SDK passed 22 of 22 checks on 3c35744. The fixes came after it, each with a test that fails without it. Qwen3-ASR word timings were not run live (they need the aligner download). In CI, Repo tests (CPU, rest) fails on a text-encoding check that reads the PyAV codec open in audio_inputs.py as a file open; #12831 fixes that check, and the rest of CI is still running. Codex review was requested at 03:56 UTC on 8e91dce, no response yet.

@danielhanchen

Copy link
Copy Markdown
Member

Both red checks here are this PR's own. They pass on main 1fb38f9. test_text_io_encoding and test_runtime_text_encoding flag studio/backend/core/inference/audio_inputs.py:264, a Path.open() in text mode without an encoding. Without one, Windows and C-locale Linux use the locale codepage. Pass encoding = "utf-8", or open in binary mode if the file is bytes.

@danielhanchen danielhanchen self-assigned this Oct 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Review record for #12812, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#492.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror e54893927 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/routes/inference.py (on the mirror)

@@ -23549,7 +23655,7 @@ async def _external_tts_speech(body: AudioSpeechRequest, request: Request) -> Re
     """Proxy CreateSpeech to a saved connection, so read-aloud skips the local model slot."""
     provider_id = (body.provider_id or "").strip()
     external_model = (body.model or "").strip()
-    external_voice = (body.voice or "").strip()
+    external_voice = body.voice.strip() if isinstance(body.voice, str) else ""

P2 Badge Forward custom voice objects to external speech providers

When a request uses provider_id with the newly accepted voice: {"id": ...} form, this expression converts the AudioSpeechVoice to an empty string, so the following required-voice check returns 400 and the upstream provider is never called. Preserve the object when forwarding the request so OpenAI-compatible custom voices work through saved connections as well as through the local path.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing: a voice object with provider_id gets an explicit 400 (voice required), never wrong audio; saved connections take a voice name, as before this PR.

Round 2: reviewed mirror d6a76e33f (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/routes/inference.py (on the mirror)

@@ -22604,6 +22667,14 @@ def _audio_source_error(exc) -> HTTPException:
     return HTTPException(status_code = exc.status, detail = exc.detail)
 
 
+def _v1_url(request: Request, url: str) -> str:
+    """A Studio file URL on the mount the client called, so a /v1 client needs only that base URL."""
+    prefix = "/api/inference/"
+    if request.url.path.startswith("/v1/") and url.startswith(prefix):
+        return "/v1/" + url[len(prefix) :]

P2 Badge Preserve the ASGI root path in returned audio URLs

When Studio is exposed under a nonempty ASGI root_path—for example, uvicorn --root-path /studio behind a path-stripping proxy—this returns /v1/... rather than /studio/v1/.... The new input, voice, and run responses all use this helper, so clients following their returned file URLs escape the proxy mount and receive a 404; prefix the rewritten URL with request.scope["root_path"] and normalize that prefix when detecting the /v1 mount.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing: every audio file URL Studio returns, /api/inference included, omitted root_path before this PR too; Studio launches its own server with no root path, so this is not new to /v1.

Round 3: reviewed mirror 2d60d5cd9 (this PR's 30cbe5a63)

chatgpt-codex-connector[bot] on studio/backend/routes/inference.py (on the mirror)

@@ -23901,11 +24056,40 @@ async def openai_audio_transcriptions(
             )
             api_monitor.set_reply(monitor_id, _external_transcript_preview(response))
         return response
-    # Refused before any work, like the response_format check above: the sidecar echoes the
-    # language it was given and detects none, so an auto-detect request has nothing truthful
-    # for verbose_json's required language field, and guessing would silently label a
-    # Japanese clip "en". isinstance because a direct call passes the raw Form default.
-    if fmt == "verbose_json" and not (isinstance(language, str) and language.strip()):
+    from core.inference import audio_inputs, stt_capabilities, stt_details
+
+    # openai's whisper-1 placeholder means the default transcription model, not a sidecar id
+    sidecar_model = None if model in (None, "", "whisper-1") else model
+    engine = _stt_engine_for_model(sidecar_model)
+    # isinstance because a direct call passes the raw Form default.
+    granularities = timestamp_granularities if isinstance(timestamp_granularities, list) else []
+    if granularities and fmt != "verbose_json":
+        # OpenAI's contract; also spares an aligner download whose timings would be dropped.
+        _raise_unsupported_openai_parameter(
+            "timestamp_granularities",
+            "timestamp_granularities needs response_format 'verbose_json'.",
+        )
+    has_language = isinstance(language, str) and language.strip()
+    serving_engine = _resolve_serving_stt_engine(engine)
+    timed = serving_engine == "audiocpp" and (
+        fmt in ("verbose_json", "diarized_json") or bool(granularities)
+    )
+    if timed or fmt == "diarized_json":
+        caps = await asyncio.to_thread(
+            stt_capabilities.capabilities_for, sidecar_model, serving_engine
+        )
+        _refuse_stt_caps(
+            caps, timestamps = timed and bool(granularities), speakers = fmt == "diarized_json"

P2 Badge Reject word timing on segment-only models

When timestamp_granularities[]=word is requested from an always-timestamped model such as MOSS-Transcribe-Diarize or VibeVoice, this capability check admits the request because it only distinguishes generic timestamp support. Those families can return segments without any words, and the formatter later silently omits the requested words field. Distinguish word-level capability from segment timestamps and reject unsupported word requests before transcription.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing: these families report segments only, so there are no word timings to drop; words is optional in OpenAI's verbose_json and the segments asked for by default are returned.

chatgpt-codex-connector[bot] on studio/backend/routes/inference.py (on the mirror)

@@ -23901,11 +24056,40 @@ async def openai_audio_transcriptions(
             )
             api_monitor.set_reply(monitor_id, _external_transcript_preview(response))
         return response
-    # Refused before any work, like the response_format check above: the sidecar echoes the
-    # language it was given and detects none, so an auto-detect request has nothing truthful
-    # for verbose_json's required language field, and guessing would silently label a
-    # Japanese clip "en". isinstance because a direct call passes the raw Form default.
-    if fmt == "verbose_json" and not (isinstance(language, str) and language.strip()):
+    from core.inference import audio_inputs, stt_capabilities, stt_details
+
+    # openai's whisper-1 placeholder means the default transcription model, not a sidecar id
+    sidecar_model = None if model in (None, "", "whisper-1") else model
+    engine = _stt_engine_for_model(sidecar_model)
+    # isinstance because a direct call passes the raw Form default.
+    granularities = timestamp_granularities if isinstance(timestamp_granularities, list) else []

P2 Badge Validate timestamp granularity names

For an audio.cpp request using verbose_json, arbitrary nonempty values such as timestamp_granularities[]=words or foo pass here because only the list's truthiness is checked. On Qwen3-ASR this can even trigger the roughly 1.1 GB alignment download before returning a response with no matching field. Reject every value outside the API's word and segment enum before capability checks or transcription.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing: values outside OpenAI's word/segment enum are malformed requests; well-formed ones behave as documented.

chatgpt-codex-connector[bot] on studio/backend/routes/inference.py (on the mirror)

@@ -23952,20 +24155,54 @@ async def openai_audio_transcriptions(
 
     if fmt == "text":
         return PlainTextResponse(content = text)
-    if fmt == "verbose_json":
-        _duration = result.get("duration")
+    _duration = result.get("duration")
+    # Unlike the language, this is not a guess: duration is None only for a clip that decoded
+    # to no samples, and that clip really is zero seconds.
+    duration = float(_duration) if isinstance(_duration, (int, float)) else 0.0
+    segments = result.get("segments") or []
+    if fmt == "diarized_json":
+        labels = {s["id"]: s["label"] for s in result.get("speakers") or ()}
         return JSONResponse(
             content = {
                 "task": "transcribe",
-                # Both are required by OpenAI's schema, so a null fails validation inside
-                # the official clients. The request is refused above with no language.
-                "language": str(result.get("language") or language).strip(),
-                # Unlike the language, this is not a guess: duration is None only for a
-                # clip that decoded to no samples, and that clip really is zero seconds.
-                "duration": float(_duration) if isinstance(_duration, (int, float)) else 0.0,
+                "duration": duration,
                 "text": text,
+                "segments": [
+                    {
+                        "type": "transcript.text.segment",
+                        "id": f"seg_{index}",
+                        "start": s["start"],
+                        "end": s["end"],
+                        "text": s["text"],
+                        "speaker": labels.get(s.get("speaker"), s.get("speaker") or ""),

P2 Badge Avoid empty speaker labels in diarized output

When a diarization model returns a transcript segment that does not overlap any speaker turn—a supported VibeVoice normalization case—the segment has no speaker key and this fallback serializes "speaker": "". The resulting diarized_json segment is not actually speaker-annotated, so consumers cannot group it with a speaker despite requesting diarization. Assign a stable unknown speaker label or reject incomplete diarization instead of emitting an empty label.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing: an empty string is a valid speaker per the schema and marks a span the model attributed to no speaker; nothing is lost or misattributed.

chatgpt-codex-connector[bot] on studio/backend/routes/inference.py (on the mirror)

@@ -23935,15 +24117,36 @@ async def openai_audio_transcriptions(
         prompt = file.filename or "audio",
         subject = current_subject,
     ) as monitor_id:
-        result = await _transcribe_audio_result(
-            raw,
-            sidecar_model,
-            language,
-            fast = False,
-            engine = _stt_engine_for_model(sidecar_model),
-            request = request,
-        )
+        path = None
+        try:
+            if timed:
+                rate = stt_details.FIXED_SPAN_RATES.get(caps["family"], 16000)
+                try:
+                    path = await asyncio.to_thread(_prepared_upload, raw, rate)
+                except audio_inputs.AudioInputError as exc:
+                    raise _audio_source_error(exc) from None
+            result = await _transcribe_audio_result(
+                raw,
+                sidecar_model,
+                language,
+                fast = False,
+                engine = engine,
+                request = request,
+                source_path = path,
+                timestamps = bool(granularities),

P2 Badge Honor the default segment granularity

When an audio.cpp Qwen3-ASR request selects verbose_json but omits timestamp_granularities[], this passes timestamps=False. Qwen3-ASR is an on-request timestamp model—the sidecar only enables its aligner and returns segments when this flag is true—so the response omits segment timestamps even though the OpenAI-compatible default granularity is segment. Treat an omitted granularity as a segment request when producing verbose_json.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing, as on the earlier thread: segments is optional in verbose_json, and defaulting timings on would fetch the 1.1 GB aligner for every Qwen3-ASR verbose_json call; send timestamp_granularities[]=segment.

Round 4: reviewed mirror 2d60d5cd95 (this PR's 30cbe5a63)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 2d60d5cd95

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 2d60d5cd95 (this PR's 30cbe5a63).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 6, 2026
…#12831)

* Runtime encoding lint: follow another library's objects through with, methods and attributes

The scan exempts .open() on a name bound to another library's object, but only
for a plain assignment from that library, with the module's top-level imports.
PyAV code spells it differently: `import av` inside the function, the
container from `with av.open(...) as dst`, a stream from `dst.add_stream()`,
and `stream.codec_context.open()`, which opens a codec and takes no encoding.
That was reported as a Path.open() with no correct edit (seen on unslothai#12812).

Foreign names now come from with-bindings too, from calls on a foreign name,
using the imports visible at each call; and .open() on an attribute chain rooted
at a foreign name is exempt. A path held on self, built by pathlib, or reached
through a pathlib object's attributes is still checked.

* Narrow runtime encoding exemption to PyAV codecs

* Trim comments in runtime encoding guard

* Key the PyAV codec exemption on path and expression, not line number

---------

Co-authored-by: mahiatlinux <[email protected]>
@danielhanchen
danielhanchen merged commit 0423db5 into unslothai:main Oct 6, 2026
Etherll added a commit to Etherll/unsloth that referenced this pull request Oct 7, 2026
unslothai#12812 landed on main as a squash, so its backend files take main's
version. Keep the Use via API import and audioApiRequested beside
main's imports and requestedTab rename.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants