Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: record media API traffic in the monitor and add verbose_json transcriptions (#9217)

Nilay505568a7e2c4
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index c77a48937b9..08a8ac6c48a 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -6286,6 +6286,7 @@ class ExternalProviderClient:
model: str,
language: Optional[str] = None,
response_format: str = "json",
+ timestamp_granularities: Optional[list[str]] = None,
) -> tuple[bytes, str]:
"""Post audio to an OpenAI-compatible transcription endpoint."""
data = {
@@ -6294,6 +6295,9 @@ class ExternalProviderClient:
}
if language:
data["language"] = language
+ if timestamp_granularities:
+ # Repeated field, so httpx wants the list under the bracketed name OpenAI uses.
+ data["timestamp_granularities[]"] = list(timestamp_granularities)
headers = self._auth_headers()
headers.pop("Content-Type", None)
response = await _http_client.post(
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 867ea5a0ae0..9a717d92d60 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -37,7 +37,7 @@ import contextvars
import threading
import weakref
from concurrent.futures import ThreadPoolExecutor
-from contextlib import ExitStack, contextmanager
+from contextlib import ExitStack, asynccontextmanager, contextmanager
from dataclasses import fields as dataclass_fields, replace
@@ -4967,6 +4967,69 @@ def _monitor_active_model() -> Optional[str]:
return public_model_id(backend.active_model_name) or backend.active_model_name
+@asynccontextmanager
+async def _monitored_media_request(
+ request: Request, *, model: Optional[str], prompt: str, subject: Optional[str]
+):
+ """Give the image/audio routes the API monitor row the text routes already open."""
+ monitor_id = None
+ if not getattr(request.state, "skip_api_monitor", False):
+ monitor_id = api_monitor.start(
+ endpoint = request.url.path,
+ method = request.method,
+ via_api_key = _request_used_api_key(request),
+ model = model or "",
+ prompt = prompt,
+ subject = subject,
+ )
+ try:
+ yield monitor_id
+ except asyncio.CancelledError:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
+ except HTTPException as exc:
+ # Client aborts reach these routes as a 499 from the disconnect watchers, not as a
+ # CancelledError, so without this an ordinary stop would be a red error row.
+ if getattr(exc, "status_code", None) == 499:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
+ # The route's own message ("No model loaded."), not the llama-server mapping.
+ detail = exc.detail
+ if isinstance(detail, dict):
+ # openai_error_body nests the message, but plenty of raisers pass a flat dict:
+ # .get("message") on a non-dict "error" used to raise out of this handler,
+ # skipping finish() and stranding the row at "running".
+ error = detail.get("error")
+ message = error.get("message") if isinstance(error, dict) else None
+ detail = message or str(detail)
+ api_monitor.fail(monitor_id, str(detail))
+ raise
+ except Exception as exc:
+ api_monitor.fail(monitor_id, _friendly_error(exc))
+ raise
+ except BaseException as exc:
+ # KeyboardInterrupt and SystemExit are not Exception, so without this arm the row
+ # never leaves "running". fail_open only touches a row a handler above left open.
+ api_monitor.fail_open(monitor_id, _friendly_error(exc))
+ raise
+ api_monitor.finish(monitor_id)
+
+
+def _external_transcript_preview(response: Response) -> str:
+ """The transcript out of a proxied STT response, for the monitor row's reply.
+
+ The provider echoes the requested response_format, so json carries the text under a
+ key and srt/vtt/text are already the text. A preview is never worth raising over.
+ """
+ try:
+ body = bytes(response.body or b"")
+ if "json" in (response.media_type or "").lower():
+ return str(json.loads(body.decode("utf-8", "replace")).get("text", ""))
+ return body.decode("utf-8", "replace")
+ except Exception:
+ return ""
+
+
def _validate_native_gguf_companion(
companion_path: str | None,
gguf_path: str | None,
@@ -12125,12 +12188,22 @@ async def openai_audio_speech(
messages = [{"role": "user", "content": body.input}],
max_tokens = AUDIO_GENERATION_MAX_TOKENS,
)
- wav_bytes, sample_rate, model_name, audio_type = await _generate_tts_wav(
- body.input, payload, request, current_subject
- )
- await asyncio.to_thread(
- _persist_tts_clip, wav_bytes, sample_rate, body.input, model_name, audio_type
- )
+ # model is informational and is echoed verbatim into the row, so a failure before the
+ # relabel below would strand the raw client string, possibly a host path, on a terminal
+ # row that goes out over the tunnel. Redact up front, not only on success.
+ async with _monitored_media_request(
+ request,
+ model = public_model_id(body.model) or body.model,
+ prompt = body.input,
+ subject = current_subject,
+ ) as monitor_id:
+ wav_bytes, sample_rate, model_name, audio_type = await _generate_tts_wav(
+ body.input, payload, request, current_subject
+ )
+ api_monitor.relabel(monitor_id, model_name)
+ await asyncio.to_thread(
+ _persist_tts_clip, wav_bytes, sample_rate, body.input, model_name, audio_type
+ )
return Response(content = wav_bytes, media_type = "audio/wav")
@@ -12145,6 +12218,7 @@ async def _external_stt_transcription(
response_format: str,
encrypted_api_key: Optional[str],
request: Request,
+ timestamp_granularities: Optional[list[str]] = None,
) -> Response:
provider_id = provider_id.strip()
if not provider_id:
@@ -12206,6 +12280,7 @@ async def _external_stt_transcription(
model = external_model,
language = language,
response_format = response_format,
+ timestamp_granularities = timestamp_granularities,
)
)
disconnect_watcher = asyncio.create_task(
@@ -12246,47 +12321,118 @@ async def openai_audio_transcriptions(
response_format: str = Form("json"),
provider_id: Optional[str] = Form(None),
encrypted_api_key: Optional[str] = Form(None),
+ timestamp_granularities: Optional[list[str]] = Form(None, alias = "timestamp_granularities[]"),
current_subject: str = Depends(get_current_subject),
):
"""OpenAI-compatible speech-to-text (POST /v1/audio/transcriptions).
With ``provider_id`` set, the request is proxied to that saved connection.
Otherwise ``model`` maps to a sidecar model id, with ``whisper-1`` or nothing
- selecting the default. ``response_format`` supports ``json`` and ``text``."""
+ selecting the default. ``response_format`` supports ``json``, ``text`` and
+ ``verbose_json``."""
fmt = (response_format or "json").strip().lower()
- if fmt not in ("json", "text"):
+ if fmt not in ("json", "text", "verbose_json"):
raise HTTPException(
status_code = 400,
- detail = f"Unsupported response_format '{response_format}'. Use 'json' or 'text'.",
+ detail = (
+ f"Unsupported response_format '{response_format}'. "
+ "Use 'json', 'text' or 'verbose_json'."
+ ),
)
# UploadFile spools to disk, but an unbounded read materializes the whole upload in
# memory before the shared size check. One byte past the limit is enough to reject it.
raw = await file.read(_MAX_AUDIO_RAW_BYTES + 1)
if isinstance(provider_id, str):
- return await _external_stt_transcription(
- provider_id = provider_id,
- raw = raw,
- filename = file.filename or "audio",
- content_type = file.content_type or "application/octet-stream",
- model = model,
- language = language,
- response_format = fmt,
- encrypted_api_key = encrypted_api_key,
- request = request,
+ # The proxied path is traffic through this server too, so it opens the same row;
+ # without this a saved STT connection is invisible. It never relabels, so the
+ # opening label is what the row keeps for life, hence the path-free treatment.
+ _requested = (model or "").strip()
+ async with _monitored_media_request(
+ request,
+ model = public_model_id(_requested) or _requested,
+ prompt = file.filename or "audio",
+ subject = current_subject,
+ ) as monitor_id:
+ response = await _external_stt_transcription(
+ provider_id = provider_id,
+ raw = raw,
+ filename = file.filename or "audio",
+ content_type = file.content_type or "application/octet-stream",
+ model = model,
+ language = language,
+ response_format = fmt,
+ timestamp_granularities = timestamp_granularities,
+ encrypted_api_key = encrypted_api_key,
+ request = request,
+ )
+ 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()):
+ raise HTTPException(
+ status_code = 501,
+ detail = (
+ "verbose_json reports the language of the audio and the local STT engine "
+ "does not detect one. Send the 'language' parameter, or use response_format "
+ "'json' or 'text'."
+ ),
+ )
+ if isinstance(timestamp_granularities, list) and timestamp_granularities:
+ # Accepting the parameter and returning neither words nor segments would look like
+ # the audio simply had none. The sidecar reports no per-token timing today.
+ raise HTTPException(
+ status_code = 400,
+ detail = (
+ "timestamp_granularities is not supported by the local STT engine. "
+ "Use a saved STT connection with provider_id for word or segment timings."
+ ),
)
# 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
- result = await _transcribe_audio_result(
- raw,
- sidecar_model,
- language,
- fast = False,
- engine = _stt_engine_for_model(sidecar_model),
- request = request,
- )
+ # The relabel below only lands on success; a sidecar failure would otherwise strand the
+ # raw client string, which may be a host path, on the terminal row.
+ _opening_label = sidecar_model or "whisper-1"
+ async with _monitored_media_request(
+ request,
+ model = public_model_id(_opening_label) or _opening_label,
+ 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,
+ )
+ text = str(result.get("text", ""))
+ # Same path-free treatment the image route gives its label: sidecar ids are
+ # curated or owner/model today, but the row goes out over the tunnel.
+ _served_model = str(result.get("model") or "")
+ api_monitor.relabel(monitor_id, public_model_id(_served_model) or _served_model)
+ api_monitor.set_reply(monitor_id, text)
+
if fmt == "text":
- return PlainTextResponse(content = str(result.get("text", "")))
- return JSONResponse(content = {"text": result.get("text", "")})
+ return PlainTextResponse(content = text)
+ if fmt == "verbose_json":
+ _duration = result.get("duration")
+ 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,
+ "text": text,
+ }
+ )
+ return JSONResponse(content = {"text": text})
# =====================================================================
@@ -26491,12 +26637,8 @@ async def openai_image_generations(
With media auto-switch on, ``model`` names the image model to serve on and is loaded
when it is not the resident one; with it off ``model`` stays informational."""
- from core.inference import image_gallery
- from core.inference.diffusion_engine_router import get_active_diffusion_engine
- from core.inference.diffusion_families import default_generation_params
- from core.inference.gpu_arbiter import DIFFUSION
- from core.inference.media_auto_switch import maybe_auto_switch_media_model
-
+ # Refused before the row is opened, as on /audio/speech: a request rejected before any
+ # work is not traffic worth a red error row.
if body.stream:
raise HTTPException(
status_code = 400,
@@ -26510,6 +26652,34 @@ async def openai_image_generations(
raise HTTPException(
status_code = 400, detail = openai_error_body(str(exc), status = 400, param = "size")
)
+ # The relabel below only covers a successful generation, so a load or generation failure
+ # would strand the raw client string, possibly a host path, on a tunnelled row.
+ async with _monitored_media_request(
+ request,
+ model = public_model_id(body.model) or body.model,
+ prompt = body.prompt,
+ subject = current_subject,
+ ) as monitor_id:
+ return await _generate_openai_images(
+ body, request, current_subject, hf_token, monitor_id, width, height
+ )
+
+
+# Split out so the monitor row can wrap the whole handler without reindenting it.
+async def _generate_openai_images(
+ body: ImageGenerationRequest,
+ request: Request,
+ current_subject: str,
+ hf_token: Optional[str],
+ monitor_id: Optional[str],
+ width: int,
+ height: int,
+):
+ from core.inference import image_gallery
+ from core.inference.diffusion_engine_router import get_active_diffusion_engine
+ from core.inference.diffusion_families import default_generation_params
+ from core.inference.gpu_arbiter import DIFFUSION
+ from core.inference.media_auto_switch import maybe_auto_switch_media_model
# Before the loaded check: the requested model may be the one this brings up.
await maybe_auto_switch_media_model(
@@ -26570,6 +26740,10 @@ async def openai_image_generations(
logger.error("openai_images.generate_failed: %s", exc)
raise HTTPException(status_code = 500, detail = "Image generation failed.")
+ # A local-directory load puts the host path in repo_id and the monitor row goes out over
+ # the tunnel, so the label gets the same path-free treatment as active_model.
+ _served_repo = str(result.get("repo_id") or "")
+ api_monitor.relabel(monitor_id, public_model_id(_served_repo) or _served_repo)
created = int(time.time())
want_b64 = body.response_format == "b64_json"
# Persist each image with its full recipe, like /images/generate, so url links resolve and images show in the gallery.
diff --git a/studio/backend/tests/test_audio_sampling_fill.py b/studio/backend/tests/test_audio_sampling_fill.py
index 11bb65f9e05..3113b6edbca 100644
--- a/studio/backend/tests/test_audio_sampling_fill.py
+++ b/studio/backend/tests/test_audio_sampling_fill.py
@@ -18,9 +18,28 @@ import pytest
import routes.inference as inference_route
from fastapi import HTTPException
from models.inference import AudioSpeechRequest, ChatCompletionRequest
+from starlette.requests import Request
from utils.inference import inference_config as ic
+def _request(path = "/v1/audio/speech"):
+ """/v1/audio/speech opens an API monitor row, so it needs a real request."""
+ return Request(
+ {
+ "type": "http",
+ "http_version": "1.1",
+ "method": "POST",
+ "scheme": "http",
+ "server": ("testserver", 80),
+ "path": path,
+ "raw_path": path.encode(),
+ "query_string": b"",
+ "root_path": "",
+ "headers": [],
+ }
+ )
+
+
class _FakeLlama:
# is_loaded False forces the transformers (non-GGUF) TTS branch in generate_audio.
is_loaded = False
@@ -127,7 +146,7 @@ def test_whisper_is_rejected_cleanly_by_both_tts_endpoints(monkeypatch):
speech = AudioSpeechRequest(input = "hi", model = "some/custom-tts")
for request in (
inference_route.generate_audio(payload, request = None, current_subject = "t"),
- inference_route.openai_audio_speech(speech, request = None, current_subject = "t"),
+ inference_route.openai_audio_speech(speech, request = _request(), current_subject = "t"),
):
with pytest.raises(HTTPException) as exc:
asyncio.run(request)
diff --git a/studio/backend/tests/test_openai_audio_speech_route.py b/studio/backend/tests/test_openai_audio_speech_route.py
index 85277f3bedf..8ca3b02aa2c 100644
--- a/studio/backend/tests/test_openai_audio_speech_route.py
+++ b/studio/backend/tests/test_openai_audio_speech_route.py
@@ -15,6 +15,7 @@ from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
import core.inference.audio_gallery as gallery_module
+from core.inference.api_monitor import api_monitor
import routes.inference as routes_module
from auth.authentication import get_current_subject
from routes.inference import router
@@ -310,3 +311,98 @@ def test_non_latin_prompts_are_not_billed_at_the_latin_rate():
# And CJK, which already worked, is unchanged.
assert estimate("你好世界" * 50) >= 200
+
+
+def test_speech_opens_a_monitor_row(monkeypatch):
+ cli, calls, saved = _make_client(monkeypatch)
+ api_monitor.clear()
+ assert cli.post("/v1/audio/speech", json = {"input": "hello sloth"}).status_code == 200
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["endpoint"] == "/v1/audio/speech"
+ assert rows[0]["status"] == "completed"
+ assert rows[0]["prompt_preview"] == "hello sloth"
+ # Relabelled to the loaded TTS model, not the informational body.model.
+ assert rows[0]["model"] == "unsloth/orpheus-3b-0.1-ft"
+
+
+def test_tts_failure_records_an_error_row(monkeypatch):
+ async def _boom(text):
+ raise HTTPException(status_code = 400, detail = "No model loaded.")
+
+ cli, calls, saved = _make_client(monkeypatch, generate = _boom)
+ api_monitor.clear()
+ assert cli.post("/v1/audio/speech", json = {"input": "hi"}).status_code == 400
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["status"] == "error"
+ assert rows[0]["error"] == "No model loaded."
+
+
+def test_rejected_response_format_records_nothing(monkeypatch):
+ # Refused before any work, so it is not traffic the monitor should show.
+ cli, calls, saved = _make_client(monkeypatch)
+ api_monitor.clear()
+ resp = cli.post("/v1/audio/speech", json = {"input": "hi", "response_format": "mp3"})
+ assert resp.status_code == 400
+ assert api_monitor.snapshot(include_details = False) == []
+
+
+def test_client_abort_records_a_cancelled_row(monkeypatch):
+ # The disconnect watcher turns a client abort into a 499, not a CancelledError.
+ async def _cancelled(text):
+ raise HTTPException(status_code = 499, detail = "Audio generation cancelled")
+
+ cli, calls, saved = _make_client(monkeypatch, generate = _cancelled)
+ api_monitor.clear()
+ assert cli.post("/v1/audio/speech", json = {"input": "hi"}).status_code == 499
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["status"] == "cancelled"
+ assert not rows[0]["error"]
+
+
+ "requested, expected",
+ [
+ ("/home/ana/models/orpheus-3b-0.1-ft", "orpheus-3b-0.1-ft"),
+ ("/srv/voices/Kokoro-82M-Q4_K_M.gguf", "Kokoro-82M-Q4_K_M"),
+ (r"C:\Users\ana\models\kokoro-82m.gguf", "kokoro-82m"),
+ (r"\\fileserver\share\models\orpheus-3b", "orpheus-3b"),
+ ],
+)
+def test_a_failure_before_the_relabel_does_not_leak_the_requested_path(
+ monkeypatch, requested, expected
+):
+ """body.model is informational and is echoed straight into the row, so the relabel on
+ the success path is the only thing that ever cleaned it. A failure before generation
+ (no audio model loaded) left the raw client string on a terminal row that the monitor
+ overlay polls and serves. Windows and UNC forms are covered because redacting a host
+ path is the whole point."""
+
+ async def _boom(text):
+ raise HTTPException(status_code = 400, detail = "No model loaded.")
+
+ cli, calls, saved = _make_client(monkeypatch, generate = _boom)
+ api_monitor.clear()
+ resp = cli.post("/v1/audio/speech", json = {"input": "hi", "model": requested})
+ assert resp.status_code == 400
+ row = api_monitor.snapshot(include_details = False)[0]
+ assert row["status"] == "error"
+ assert row["model"] == expected
+ assert "/" not in row["model"] and "\\" not in row["model"]
+
+
+def test_an_ordinary_model_id_is_still_recorded_verbatim(monkeypatch):
+ # The redaction must not rewrite the ids clients actually send.
+ async def _boom(text):
+ raise HTTPException(status_code = 400, detail = "No model loaded.")
+
+ cli, calls, saved = _make_client(monkeypatch, generate = _boom)
+ for requested in ("tts-1", "gpt-4o-mini-tts", "unsloth/orpheus-3b-0.1-ft"):
+ api_monitor.clear()
+ assert (
+ cli.post("/v1/audio/speech", json = {"input": "hi", "model": requested}).status_code
+ == 400
+ )
+ assert api_monitor.snapshot(include_details = False)[0]["model"] == requested
diff --git a/studio/backend/tests/test_openai_audio_transcriptions_route.py b/studio/backend/tests/test_openai_audio_transcriptions_route.py
index 1f2e4aa262f..b6681b4afcb 100644
--- a/studio/backend/tests/test_openai_audio_transcriptions_route.py
+++ b/studio/backend/tests/test_openai_audio_transcriptions_route.py
@@ -8,11 +8,14 @@ model-id mapping, response formats and error propagation without whisper or a GP
from __future__ import annotations
+import asyncio
+
import pytest
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
import routes.inference as routes_module
+from core.inference.api_monitor import api_monitor
from auth.authentication import get_current_subject
from routes.inference import router
from utils.api_errors import install_api_error_handlers
@@ -172,6 +175,245 @@ def test_the_studio_json_route_also_forwards_the_request(monkeypatch):
assert calls[0]["request"] is not None
+def test_verbose_json_carries_language_and_duration(monkeypatch):
+ cli, calls = _make_client(monkeypatch)
+ resp = _post(cli, data = {"response_format": "verbose_json", "language": "en"})
+ assert resp.status_code == 200
+ assert resp.json() == {
+ "task": "transcribe",
+ "language": "en",
+ "duration": 1.2,
+ "text": "hello sloth",
+ }
+
+
+def test_verbose_json_without_a_language_is_refused_before_any_work(monkeypatch):
+ """OpenAI types language as a required string and the sidecar only echoes back the
+ language it was given, so an auto-detect request has nothing truthful to report.
+
+ Naming a language nobody detected would label a Japanese clip "en", so this refuses.
+ It refuses before the sidecar runs, so no GPU is burnt and no row is opened."""
+ cli, calls = _make_client(monkeypatch)
+ api_monitor.clear()
+ resp = _post(cli, data = {"response_format": "verbose_json"})
+ assert resp.status_code == 501
+ assert "language" in resp.json()["error"]["message"]
+ assert calls == []
+ assert api_monitor.snapshot(include_details = False) == []
+
+
+def test_verbose_json_works_when_the_caller_supplies_a_language(monkeypatch):
+ # Echoing a language the caller named is correct, so this half of verbose_json works.
+ cli, calls = _make_client(monkeypatch)
+ resp = _post(cli, data = {"response_format": "verbose_json", "language": "en"})
+ assert resp.status_code == 200
+ assert resp.json()["language"] == "en"
+
+
+def test_verbose_json_never_emits_a_null_duration(monkeypatch):
+ """A clip that decodes to no samples has no duration; OpenAI requires a number.
+
+ Unlike the language this is not a guess: such a clip really is zero seconds."""
+
+ async def _empty(raw):
+ return {"text": "", "language": "en", "duration": None, "model": "small"}
+
+ cli, calls = _make_client(monkeypatch, transcribe = _empty)
+ resp = _post(cli, data = {"response_format": "verbose_json", "language": "en"})
+ assert resp.json()["duration"] == 0.0
+
+
+def test_timestamp_granularities_are_refused_not_dropped(monkeypatch):
+ # Returning 200 with neither words nor segments looks like the audio simply had none.
+ cli, calls = _make_client(monkeypatch)
+ resp = _post(
+ cli,
+ data = {
+ "response_format": "verbose_json",
+ "language": "en",
+ "timestamp_granularities[]": "word",
+ },
+ )
+ assert resp.status_code == 400
+ assert "timestamp_granularities" in resp.json()["error"]["message"]
+ assert calls == []
+
+
+ "result",
+ [
+ {"text": "hi", "language": "en", "duration": 1.2, "model": "small"},
+ {"text": "", "language": "en", "duration": None, "model": "small"},
+ {"text": "hi", "language": "fr", "duration": 3, "model": "small"},
+ ],
+)
+def test_verbose_json_validates_against_the_openai_client_model(monkeypatch, result):
+ """The response has to survive the schema the official client parses it with."""
+ openai_types = pytest.importorskip("openai.types.audio.transcription_verbose")
+
+ async def _result(raw):
+ return dict(result)
+
+ cli, calls = _make_client(monkeypatch, transcribe = _result)
+ resp = _post(cli, data = {"response_format": "verbose_json", "language": "en"})
+ assert resp.status_code == 200
+ openai_types.TranscriptionVerbose.model_validate(resp.json())
+
+
+def test_subtitle_formats_are_still_400(monkeypatch):
+ # srt/vtt need per-segment timing the sidecar does not report yet.
+ cli, calls = _make_client(monkeypatch)
+ for fmt in ("srt", "vtt"):
+ assert _post(cli, data = {"response_format": fmt}).status_code == 400
+
+
+def test_transcription_opens_a_monitor_row(monkeypatch):
+ cli, calls = _make_client(monkeypatch)
+ api_monitor.clear()
+ assert _post(cli, filename = "meeting.wav").status_code == 200
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["endpoint"] == "/v1/audio/transcriptions"
+ assert rows[0]["status"] == "completed"
+ assert rows[0]["prompt_preview"] == "meeting.wav"
+ assert rows[0]["reply_preview"] == "hello sloth"
+ assert rows[0]["model"] == "small"
+
+
+def test_sidecar_failure_records_an_error_row(monkeypatch):
+ async def _boom(raw):
+ raise HTTPException(status_code = 409, detail = "Model is busy.")
+
+ cli, calls = _make_client(monkeypatch, transcribe = _boom)
+ api_monitor.clear()
+ assert _post(cli).status_code == 409
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["status"] == "error"
+ assert rows[0]["error"] == "Model is busy."
+
+
+def test_client_abort_records_a_cancelled_row(monkeypatch):
+ # SttTranscriptionCancelledError surfaces as a 499, so the row is a cancellation.
+ async def _cancelled(raw):
+ raise HTTPException(status_code = 499, detail = "Transcription cancelled")
+
+ cli, calls = _make_client(monkeypatch, transcribe = _cancelled)
+ api_monitor.clear()
+ assert _post(cli).status_code == 499
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["status"] == "cancelled"
+ assert not rows[0]["error"]
+
+
+ "detail",
+ [
+ {"error": "bad"},
+ {"error": ["bad"]},
+ {"error": None},
+ {"message": "bad"},
+ {"error": {"message": "nested"}},
+ ],
+)
+def test_a_dict_detail_never_strands_the_row(monkeypatch, detail):
+ """Only openai_error_body's shape nests the message. For any other dict the handler
+ called .get() on a non-dict and raised AttributeError out of the context manager,
+ which skipped finish() and left the row at "running" forever."""
+
+ async def _boom(raw):
+ raise HTTPException(status_code = 400, detail = detail)
+
+ cli, calls = _make_client(monkeypatch, transcribe = _boom)
+ api_monitor.clear()
+ assert _post(cli).status_code == 400
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["status"] == "error"
+ assert rows[0]["error"]
+
+
[email protected]("exc", [KeyboardInterrupt, SystemExit])
+def test_a_baseexception_still_closes_the_row(monkeypatch, exc):
+ """KeyboardInterrupt and SystemExit are not Exception, so they used to fall past
+ every handler and leave the row stuck at "running" for the life of the process."""
+
+ async def _boom(raw):
+ raise exc("bang")
+
+ cli, calls = _make_client(monkeypatch, transcribe = _boom)
+ api_monitor.clear()
+ with pytest.raises(BaseException):
+ _post(cli)
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["status"] == "error"
+ assert rows[0]["error"]
+
+
+def test_a_real_cancellederror_records_a_cancelled_row(monkeypatch):
+ # The 499 arm covers the disconnect watchers; this is the plain asyncio cancel.
+ async def _cancelled(raw):
+ raise asyncio.CancelledError()
+
+ cli, calls = _make_client(monkeypatch, transcribe = _cancelled)
+ api_monitor.clear()
+ with pytest.raises(BaseException):
+ _post(cli)
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["status"] == "cancelled"
+
+
+def test_a_non_http_failure_records_a_friendly_error_row(monkeypatch):
+ # Every other error test raises HTTPException; this is the catch-all arm.
+ async def _boom(raw):
+ raise RuntimeError("sidecar exploded")
+
+ cli, calls = _make_client(monkeypatch, transcribe = _boom)
+ api_monitor.clear()
+ with pytest.raises(RuntimeError):
+ _post(cli)
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["status"] == "error"
+ assert "sidecar exploded" not in rows[0]["error"]
+
+
+def test_the_monitor_label_never_carries_a_local_path(monkeypatch):
+ # Sidecar ids are curated or owner/model today; the row still goes over the tunnel.
+ async def _pathy(raw):
+ return {
+ "text": "t",
+ "language": "en",
+ "duration": 1.0,
+ "model": "/home/me/models/whisper-large-v3",
+ }
+
+ cli, calls = _make_client(monkeypatch, transcribe = _pathy)
+ api_monitor.clear()
+ assert _post(cli).status_code == 200
+ row = api_monitor.snapshot(include_details = False)[0]
+ assert "/" not in row["model"]
+ assert row["model"] == "whisper-large-v3"
+
+
+def test_skip_api_monitor_suppresses_the_row(monkeypatch):
+ """Internal workflows set the flag; the media routes must honour it like the
+ text routes do, or an internal step shows up as user API traffic."""
+ cli, calls = _make_client(monkeypatch)
+
+ @cli.app.middleware("http")
+ async def _skip(request, call_next):
+ request.state.skip_api_monitor = True
+ return await call_next(request)
+
+ api_monitor.clear()
+ assert _post(TestClient(cli.app)).status_code == 200
+ assert api_monitor.snapshot(include_details = False) == []
+
+
def _install_external(
monkeypatch,
*,
@@ -264,6 +506,7 @@ def test_provider_id_routes_to_external_endpoint_without_loading_the_sidecar(mon
"model": "Systran/faster-distil-whisper-large-v3",
"language": "en",
"response_format": "json",
+ "timestamp_granularities": None,
}
]
assert credential_calls[0]["allow_saved_key"] is True
@@ -477,3 +720,193 @@ def test_external_client_sends_openai_compatible_multipart(monkeypatch):
"response_format": "json",
"language": "en",
}
+
+
+def test_verbose_json_is_forwarded_to_the_provider_verbatim(monkeypatch):
+ """The proxied arm returns the provider's own verbose_json, segments and all, so
+ the format has to reach it and the body must come back untouched."""
+ cli, sidecar_calls = _make_client(monkeypatch)
+ provider_body = (
+ b'{"task":"transcribe","language":"en","duration":1.5,'
+ b'"text":"remote words","segments":[{"id":0,"text":"remote words"}]}'
+ )
+
+ class _FakeClient:
+ def __init__(self, provider_type, base_url, api_key):
+ pass
+
+ async def create_transcription(self, **kwargs):
+ sidecar_calls.append(kwargs)
+ return provider_body, "application/json"
+
+ _install_external(monkeypatch)
+ monkeypatch.setattr(routes_module, "ExternalProviderClient", _FakeClient)
+ api_monitor.clear()
+ resp = _post(
+ cli,
+ data = {"provider_id": "conn-1", "model": "whisper-1", "response_format": "verbose_json"},
+ )
+ assert resp.status_code == 200
+ assert sidecar_calls[-1]["response_format"] == "verbose_json"
+ # The monitor preview reads the body without consuming it.
+ assert resp.json()["segments"] == [{"id": 0, "text": "remote words"}]
+ assert api_monitor.snapshot(include_details = False)[0]["reply_preview"] == "remote words"
+
+
+def test_external_transcription_opens_a_monitor_row(monkeypatch):
+ cli, sidecar_calls = _make_client(monkeypatch)
+ _install_external(monkeypatch)
+ api_monitor.clear()
+ resp = _post(
+ cli,
+ data = {"provider_id": "conn-1", "model": "Systran/faster-distil-whisper-large-v3"},
+ filename = "dictation.webm",
+ )
+ assert resp.status_code == 200
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["endpoint"] == "/v1/audio/transcriptions"
+ assert rows[0]["status"] == "completed"
+ assert rows[0]["model"] == "Systran/faster-distil-whisper-large-v3"
+ assert rows[0]["prompt_preview"] == "dictation.webm"
+ assert rows[0]["reply_preview"] == "remote words"
+
+
+def test_external_transcription_reply_preview_for_plain_text(monkeypatch):
+ cli, sidecar_calls = _make_client(monkeypatch)
+ _install_external(monkeypatch, media_type = "text/plain")
+ api_monitor.clear()
+ resp = _post(
+ cli,
+ data = {
+ "provider_id": "conn-1",
+ "model": "Systran/faster-distil-whisper-large-v3",
+ "response_format": "text",
+ },
+ )
+ assert resp.status_code == 200
+ assert api_monitor.snapshot(include_details = False)[0]["reply_preview"] == "remote words"
+
+
+def test_external_transcription_failure_records_an_error_row(monkeypatch):
+ # A disabled connection is rejected before the proxy call; the row still closes.
+ cli, sidecar_calls = _make_client(monkeypatch)
+ _install_external(monkeypatch, enabled = False)
+ api_monitor.clear()
+ resp = _post(
+ cli,
+ data = {"provider_id": "conn-1", "model": "Systran/faster-distil-whisper-large-v3"},
+ )
+ assert resp.status_code >= 400
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["status"] == "error"
+ assert rows[0]["error"]
+
+
+def test_external_reply_preview_handles_an_uppercase_json_media_type(monkeypatch):
+ # Content-Type is case-insensitive, so Application/JSON is still a JSON envelope and
+ # the row should show the transcript, not the whole {"text": ...} wrapper.
+ cli, sidecar_calls = _make_client(monkeypatch)
+ _install_external(monkeypatch, media_type = "Application/JSON")
+ api_monitor.clear()
+ resp = _post(
+ cli,
+ data = {"provider_id": "conn-1", "model": "Systran/faster-distil-whisper-large-v3"},
+ )
+ assert resp.status_code == 200
+ assert api_monitor.snapshot(include_details = False)[0]["reply_preview"] == "remote words"
+
+
+def test_timestamp_granularities_reach_a_capable_provider(monkeypatch):
+ # The sidecar cannot produce timings, but a saved connection may, so the proxied arm
+ # forwards the parameter instead of dropping it.
+ cli, sidecar_calls = _make_client(monkeypatch)
+ _client_args, transcription_calls, _creds = _install_external(monkeypatch)
+ resp = _post(
+ cli,
+ data = {
+ "provider_id": "conn-1",
+ "model": "whisper-1",
+ "response_format": "verbose_json",
+ "timestamp_granularities[]": ["word", "segment"],
+ },
+ )
+ assert resp.status_code == 200
+ assert transcription_calls[-1]["timestamp_granularities"] == ["word", "segment"]
+
+
+def test_the_provider_client_sends_granularities_as_a_repeated_field(monkeypatch):
+ from core.inference.external_provider import ExternalProviderClient
+
+ sent = {}
+
+ class _Resp:
+ status_code = 200
+ content = b'{"text":"x"}'
+ headers = {"content-type": "application/json"}
+
+ def raise_for_status(self):
+ return None
+
+ async def _post_capture(url, **kwargs):
+ sent.update(kwargs)
+ return _Resp()
+
+ import core.inference.external_provider as ep
+
+ monkeypatch.setattr(ep._http_client, "post", _post_capture)
+ client = ExternalProviderClient("custom", "http://stt.local/v1", "sk-test")
+ import asyncio as _asyncio
+
+ _asyncio.run(
+ client.create_transcription(
+ audio = b"x",
+ filename = "a.wav",
+ content_type = "audio/wav",
+ model = "whisper-1",
+ timestamp_granularities = ["word"],
+ )
+ )
+ assert sent["data"]["timestamp_granularities[]"] == ["word"]
+
+
+ "requested, expected",
+ [
+ ("/home/ana/models/whisper-large-v3", "whisper-large-v3"),
+ (r"C:\Users\ana\models\whisper-large-v3", "whisper-large-v3"),
+ (r"\\fileserver\share\models\whisper-large-v3", "whisper-large-v3"),
+ ],
+)
+def test_a_sidecar_failure_does_not_leak_the_requested_path(monkeypatch, requested, expected):
+ """The relabel only lands on success, so a sidecar failure kept the raw client string
+ on the terminal row. Windows and UNC forms are covered because os.path.basename alone
+ would not split either one on a Linux host."""
+
+ async def _boom(raw):
+ raise HTTPException(status_code = 409, detail = "Model is busy.")
+
+ cli, calls = _make_client(monkeypatch, transcribe = _boom)
+ api_monitor.clear()
+ assert _post(cli, data = {"model": requested}).status_code == 409
+ row = api_monitor.snapshot(include_details = False)[0]
+ assert row["status"] == "error"
+ assert row["model"] == expected
+ assert "/" not in row["model"] and "\\" not in row["model"]
+ # The redaction is for the monitor label only; the engine still gets what was asked for.
+ assert calls[0]["model"] == requested
+
+
+def test_the_proxied_row_never_carries_a_local_path(monkeypatch):
+ """The proxied arm never relabels at all, so whatever it opens with is what the row
+ keeps for its whole life, success included."""
+ cli, _sidecar_calls = _make_client(monkeypatch)
+ _client_args, transcription_calls, _creds = _install_external(monkeypatch)
+ api_monitor.clear()
+ resp = _post(cli, data = {"provider_id": "conn-1", "model": "/home/ana/models/whisper-v3"})
+ assert resp.status_code == 200
+ row = api_monitor.snapshot(include_details = False)[0]
+ assert row["model"] == "whisper-v3"
+ # Only the label is redacted; the provider is still asked for what the client sent.
+ assert transcription_calls[-1]["model"] == "/home/ana/models/whisper-v3"
diff --git a/studio/backend/tests/test_openai_audio_upload_bound.py b/studio/backend/tests/test_openai_audio_upload_bound.py
index 68de04d5e7c..2236007247d 100644
--- a/studio/backend/tests/test_openai_audio_upload_bound.py
+++ b/studio/backend/tests/test_openai_audio_upload_bound.py
@@ -5,14 +5,34 @@ import asyncio
import pytest
from fastapi import HTTPException
+from starlette.requests import Request
import routes.inference as inference_route
+def _request():
+ return Request(
+ {
+ "type": "http",
+ "http_version": "1.1",
+ "method": "POST",
+ "scheme": "http",
+ "server": ("testserver", 80),
+ "path": "/v1/audio/transcriptions",
+ "raw_path": b"/v1/audio/transcriptions",
+ "query_string": b"",
+ "root_path": "",
+ "headers": [],
+ }
+ )
+
+
def test_openai_transcription_reads_only_one_byte_past_limit(monkeypatch):
sizes = []
class _Upload:
+ filename = "clip.wav"
+
async def read(self, size = -1):
sizes.append(size)
return b"x" * size
@@ -22,7 +42,7 @@ def test_openai_transcription_reads_only_one_byte_past_limit(monkeypatch):
with pytest.raises(HTTPException) as exc:
asyncio.run(
inference_route.openai_audio_transcriptions(
- request = None,
+ request = _request(),
file = _Upload(),
model = None,
language = None,
diff --git a/studio/backend/tests/test_openai_images_generations_route.py b/studio/backend/tests/test_openai_images_generations_route.py
index 6c470469316..cd99c9994db 100644
--- a/studio/backend/tests/test_openai_images_generations_route.py
+++ b/studio/backend/tests/test_openai_images_generations_route.py
@@ -19,6 +19,7 @@ import core.inference.diffusion as diffusion_module
import core.inference.diffusion_engine_router as engine_router
import core.inference.image_gallery as gallery_module
from auth.authentication import get_current_subject
+from core.inference.api_monitor import api_monitor
from core.inference.diffusion_families import default_generation_params
from routes.inference import router, _parse_openai_image_size
from utils.api_errors import install_api_error_handlers
@@ -459,3 +460,83 @@ def test_activation_shortfall_is_an_actionable_400(monkeypatch):
assert err["param"] == "size"
# Still typed: an ordinary ValueError keeps its sanitized 500 (test above), so no other raw
# exception text rides out on the back of this.
+
+
+def test_generation_opens_a_monitor_row(client):
+ api_monitor.clear()
+ assert _post(client, {"prompt": "a sloth in space"}).status_code == 200
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["endpoint"] == "/v1/images/generations"
+ assert rows[0]["method"] == "POST"
+ assert rows[0]["status"] == "completed"
+ assert rows[0]["prompt_preview"] == "a sloth in space"
+ # Relabelled to what served, not the informational body.model.
+ assert rows[0]["model"] == "unsloth/Z-Image-Turbo-GGUF"
+
+
+def test_no_loaded_model_records_an_error_row(monkeypatch):
+ backend = _FakeBackend(loaded = False)
+ monkeypatch.setattr(diffusion_module, "get_diffusion_backend", lambda: backend)
+ cli, store, _save = _make_client(backend)
+ monkeypatch.setattr(gallery_module, "save", _save)
+ api_monitor.clear()
+ assert _post(cli, {"prompt": "a sloth"}).status_code == 503
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["status"] == "error"
+ # The route's 503 detail, not _friendly_error's generic fallback.
+ assert "image model" in rows[0]["error"]
+
+
+def test_local_directory_load_is_not_leaked_into_the_monitor(monkeypatch):
+ # A local pick puts the host directory in repo_id and the row goes out over the tunnel,
+ # so the label gets the same path-free treatment as active_model.
+ backend = _FakeBackend(repo_id = "/home/ana/models/my-flux")
+ monkeypatch.setattr(diffusion_module, "get_diffusion_backend", lambda: backend)
+ cli, store, _save = _make_client(backend)
+ monkeypatch.setattr(gallery_module, "save", _save)
+ api_monitor.clear()
+ assert (
+ cli.post("/v1/images/generations", json = {"prompt": "p", "size": "256x256"}).status_code
+ == 200
+ )
+ rows = api_monitor.snapshot(include_details = False)
+ assert len(rows) == 1
+ assert rows[0]["model"] == "my-flux"
+
+
+ "body",
+ [
+ {"prompt": "p", "size": "300x300"},
+ {"prompt": "p", "size": "abc"},
+ {"prompt": "p", "stream": True},
+ ],
+)
+def test_a_refused_request_records_nothing(client, body):
+ """size and stream were validated inside the monitor, so a request refused before any
+ work still produced a red error row. /audio/speech and /audio/transcriptions reject
+ their bad parameters before opening a row, and this route now matches them."""
+ api_monitor.clear()
+ assert _post(client, body).status_code == 400
+ assert api_monitor.snapshot(include_details = False) == []
+
+
+def test_a_failed_generation_does_not_leak_a_local_path_label(monkeypatch):
+ """The relabel only runs after a successful generation, so a failure left whatever the
+ client sent in body.model on a row that goes out over the tunnel."""
+ backend = _FakeBackend(loaded = False)
+ monkeypatch.setattr(diffusion_module, "get_diffusion_backend", lambda: backend)
+ cli, store, _save = _make_client(backend)
+ monkeypatch.setattr(gallery_module, "save", _save)
+ for sent, expected in (
+ ("/home/ana/models/my-flux", "my-flux"),
+ ("C:\\models\\my-flux", "my-flux"),
+ ("unsloth/Z-Image-Turbo-GGUF", "unsloth/Z-Image-Turbo-GGUF"),
+ ):
+ api_monitor.clear()
+ assert _post(cli, {"prompt": "a sloth", "model": sent}).status_code == 503
+ row = api_monitor.snapshot(include_details = False)[0]
+ assert row["status"] == "error"
+ assert row["model"] == expected