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: rate the API monitor Throughput tile on the decode window (#8139)

Michael Han90f2fcaa9979
diff --git a/studio/backend/core/inference/api_monitor.py b/studio/backend/core/inference/api_monitor.py
index cf08dfb9860..29e3786e1a1 100644
--- a/studio/backend/core/inference/api_monitor.py
+++ b/studio/backend/core/inference/api_monitor.py
@@ -19,6 +19,7 @@ _MAX_ENTRIES = 50
_MAX_PROMPT_CHARS = 12000
_MAX_REPLY_CHARS = 12000
_PREVIEW_CHARS = 360
+_MAX_DECODE_MS = 24 * 60 * 60 * 1000
# Far above any real context window; larger means a broken upstream payload.
_MAX_TOKEN_COUNT = 1 << 40
@@ -102,6 +103,8 @@ class ApiMonitorEntry:
first_decode_monotonic: Optional[float] = None
prompt_ms: Optional[float] = None
tok_per_sec: Optional[float] = None
+ # timings.predicted_ms; set only from engine timings, so its presence marks a rateable row.
+ decode_ms: Optional[float] = None
stop_reason: Optional[str] = None
# Every finish reason seen so far. An n > 1 stream reports each choice in its own
# chunk, so agreement can only be judged across the whole request. Not serialized.
@@ -173,6 +176,9 @@ class ApiMonitorEntry:
"progress": self.progress,
"ttft_ms": ttft_ms,
"tok_per_sec": round(tok_per_sec, 2) if tok_per_sec is not None else None,
+ # The engine's decode span, not the streamed window: an unknowable first-chunk token
+ # count and reasoning tokens both inflate a streamed rate. Absent rather than guessed.
+ "decode_ms": int(self.decode_ms) if self.decode_ms is not None else None,
"stop_reason": self.stop_reason,
}
if include_details:
@@ -387,6 +393,7 @@ class ApiMonitor:
*,
tok_per_sec: Optional[float] = None,
prompt_ms: Optional[float] = None,
+ decode_ms: Optional[float] = None,
stop_reason: Optional[str] = None,
) -> None:
if not entry_id:
@@ -395,6 +402,7 @@ class ApiMonitor:
# streaming generators) would truncate the user's response.
tok_per_sec = _finite_float_or_none(tok_per_sec)
prompt_ms = _finite_float_or_none(prompt_ms)
+ decode_ms = _finite_float_or_none(decode_ms)
with self._lock:
entry = self._find_locked(entry_id)
if entry is None:
@@ -403,6 +411,9 @@ class ApiMonitor:
entry.tok_per_sec = tok_per_sec
if prompt_ms is not None:
entry.prompt_ms = prompt_ms
+ # Past a day of decode it is a bad reading, not a slow model.
+ if decode_ms is not None and 0 <= decode_ms <= _MAX_DECODE_MS:
+ entry.decode_ms = decode_ms
if stop_reason is not None:
entry.stop_reason = str(stop_reason)
entry.updated_at = time.time()
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index fc073338fd8..7665d5a5fca 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -22,6 +22,7 @@ import json
import httpx
from loggers import get_logger
import asyncio
+import contextvars
import threading
import weakref
from concurrent.futures import ThreadPoolExecutor
@@ -3140,6 +3141,16 @@ def _monitor_prompt_from_messages(messages) -> str:
return "\n\n".join(lines)
+# A wrapper route (Responses) suppresses the inner chat handler's monitor row, dropping the
+# engine timings computed inside it: ChatCompletion has no timings field, so they cannot be read
+# back off the serialized body. The wrapper leaves a dict here for the inner call to fill. A dict
+# because a context is copied into tasks and threads: writes do not flow back up, mutations do.
+_monitor_perf_sink: contextvars.ContextVar[Optional[dict]] = contextvars.ContextVar(
+ "unsloth_monitor_perf_sink",
+ default = None,
+)
+
+
def _monitor_usage(
monitor_id: Optional[str],
usage: Optional[dict],
@@ -3148,6 +3159,11 @@ def _monitor_usage(
timings: Optional[dict] = None,
stop_reason: Optional[str] = None,
):
+ # Only a suppressed row relays: a call with its own row must not clobber the wrapper's.
+ if not monitor_id and isinstance(timings, dict) and timings:
+ sink = _monitor_perf_sink.get()
+ if sink is not None:
+ sink["timings"] = timings
# isinstance, not truthiness: a non-dict usage would raise on .get() into the
# streaming generator and abort the user's response.
if isinstance(usage, dict) and usage:
@@ -3158,15 +3174,23 @@ def _monitor_usage(
total_tokens = usage.get("total_tokens"),
context_length = context_length,
)
- tok_per_sec = prompt_ms = None
+ tok_per_sec = prompt_ms = decode_ms = None
if isinstance(timings, dict):
tok_per_sec = timings.get("predicted_per_second")
prompt_ms = timings.get("prompt_ms")
- if tok_per_sec is not None or prompt_ms is not None or stop_reason is not None:
+ # The span the tile rates on: total tokens over total time, not a mean of per-request rates.
+ decode_ms = timings.get("predicted_ms")
+ if (
+ tok_per_sec is not None
+ or prompt_ms is not None
+ or decode_ms is not None
+ or stop_reason is not None
+ ):
api_monitor.set_perf(
monitor_id,
tok_per_sec = tok_per_sec,
prompt_ms = prompt_ms,
+ decode_ms = decode_ms,
stop_reason = stop_reason,
)
@@ -14851,8 +14875,15 @@ async def _responses_non_streaming(
if request_state is not None:
request_state.skip_api_monitor = True
+ # Catches the engine timings the suppressed inner monitor would otherwise drop.
+ inner_perf: dict = {}
+
try:
- result = await openai_chat_completions(chat_req, request)
+ _sink_token = _monitor_perf_sink.set(inner_perf)
+ try:
+ result = await openai_chat_completions(chat_req, request)
+ finally:
+ _monitor_perf_sink.reset(_sink_token)
# openai_chat_completions returns a JSONResponse for non-streaming.
if isinstance(result, Response):
@@ -14922,8 +14953,12 @@ async def _responses_non_streaming(
monitor_id,
usage_data,
_monitor_context_length(),
- # Inner chat monitor is suppressed here, so perf stats must come off the body.
- timings = body.get("timings") if isinstance(body, dict) else None,
+ # Inner monitor suppressed: only the llama-server pass-through carries timings on
+ # the body; in-process paths return a ChatCompletion with no field for them.
+ timings = (
+ (body.get("timings") if isinstance(body, dict) else None)
+ or inner_perf.get("timings")
+ ),
stop_reason = (choices[0].get("finish_reason") if choices else None),
)
api_monitor.finish(monitor_id)
@@ -15191,13 +15226,13 @@ async def _responses_stream(
next_output_index += 1
return output_index
- def _apply_usage(u) -> None:
+ def _apply_usage(u, timings = None) -> None:
nonlocal input_tokens, output_tokens
- if not u:
- return
- input_tokens = u.get("prompt_tokens", input_tokens)
- output_tokens = u.get("completion_tokens", output_tokens)
- _monitor_usage(monitor_id, u, llama_backend.context_length)
+ # No early return on a falsy usage: the final chunk can carry timings alone.
+ if isinstance(u, dict):
+ input_tokens = u.get("prompt_tokens", input_tokens)
+ output_tokens = u.get("completion_tokens", output_tokens)
+ _monitor_usage(monitor_id, u, llama_backend.context_length, timings = timings)
def _ensure_reasoning_open() -> list[str]:
if reasoning_state["opened"]:
@@ -15560,7 +15595,7 @@ async def _responses_stream(
choices = chunk_data.get("choices", [])
if not choices:
- _apply_usage(chunk_data.get("usage"))
+ _apply_usage(chunk_data.get("usage"), chunk_data.get("timings"))
continue
if choices[0].get("finish_reason"):
stream_finish_reason = choices[0]["finish_reason"]
@@ -15645,7 +15680,7 @@ async def _responses_stream(
for event in _tool_call_delta_events(tc):
yield event
- _apply_usage(chunk_data.get("usage"))
+ _apply_usage(chunk_data.get("usage"), chunk_data.get("timings"))
except asyncio.CancelledError:
disconnect_event.set()
api_monitor.finish(monitor_id, "cancelled")
diff --git a/studio/backend/tests/test_api_monitor.py b/studio/backend/tests/test_api_monitor.py
index dadf9dc06fe..b761e892400 100644
--- a/studio/backend/tests/test_api_monitor.py
+++ b/studio/backend/tests/test_api_monitor.py
@@ -1524,3 +1524,86 @@ def test_direct_busy_reads_the_live_counter(monkeypatch):
assert inf._direct_llama_is_busy() is False
monkeypatch.setattr(inf, "_direct_llama_inflight", 2)
assert inf._direct_llama_is_busy() is True
+
+
+def test_the_decode_span_comes_only_from_engine_timings(monkeypatch):
+ """duration_ms carries the queue wait, which read a 50 tok/s model as 5. decode_ms must not."""
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
+ entry_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "local-model",
+ prompt = "user: hello",
+ )
+ inference_route._monitor_usage(
+ entry_id,
+ {"prompt_tokens": 11, "completion_tokens": 50},
+ 4096,
+ timings = {"prompt_ms": 9000.0, "predicted_ms": 1000.0, "predicted_per_second": 50.0},
+ )
+ monitor.finish(entry_id)
+
+ [row] = monitor.snapshot()
+ assert row["decode_ms"] == 1000
+ assert row["completion_tokens"] / (row["decode_ms"] / 1000) == 50.0
+
+
+def test_a_timings_only_final_chunk_still_sets_the_decode_span(monkeypatch):
+ """llama-server can end a stream with timings and no usage."""
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
+ entry_id = monitor.start(
+ endpoint = "/v1/completions",
+ method = "POST",
+ model = "local-model",
+ prompt = "user: hello",
+ )
+ inference_route._monitor_usage(entry_id, None, None, timings = {"predicted_ms": 1000})
+ monitor.finish(entry_id)
+
+ assert monitor.snapshot()[0]["decode_ms"] == 1000
+
+
+def test_a_streamed_reply_alone_reports_no_decode_span():
+ """Timing the stream misses the first chunk and reasoning tokens, so report nothing."""
+ monitor = ApiMonitor(max_entries = 3)
+ entry_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "local-model",
+ prompt = "user: hello",
+ )
+ monitor.append_reply(entry_id, "hi")
+ monitor.append_reply(entry_id, " there")
+ monitor.finish(entry_id)
+
+ row = monitor.snapshot()[0]
+ assert row["decode_ms"] is None
+ assert row["duration_ms"] is not None
+
+
+ # "1000" is absent on purpose: _finite_float_or_none coerces a numeric string.
+ "predicted_ms",
+ [float("inf"), float("nan"), -1, "abc", None, 1e308, 10**400, {}, []],
+)
+def test_a_bad_predicted_ms_is_dropped_rather_than_raising(monkeypatch, predicted_ms):
+ """json.loads accepts a bare Infinity; a raise in a streaming generator truncates the reply."""
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
+ entry_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "local-model",
+ prompt = "user: hello",
+ )
+ inference_route._monitor_usage(
+ entry_id,
+ {"completion_tokens": 50},
+ None,
+ timings = {"predicted_ms": predicted_ms},
+ )
+ monitor.finish(entry_id)
+
+ assert monitor.snapshot()[0]["decode_ms"] is None
diff --git a/studio/backend/tests/test_responses_tool_passthrough.py b/studio/backend/tests/test_responses_tool_passthrough.py
index af1751b39ee..d487d96c9fb 100644
--- a/studio/backend/tests/test_responses_tool_passthrough.py
+++ b/studio/backend/tests/test_responses_tool_passthrough.py
@@ -834,6 +834,94 @@ class TestResponsesNonStreamingAdapter:
assert entry["completion_tokens"] == 3
assert request.state.skip_api_monitor is False
+ @staticmethod
+ def _run_in_process_completion(monkeypatch, monitor, timings):
+ """Drive the wrapper over an in-process chat completion: its own monitor row is
+ suppressed and a ``ChatCompletion`` has no ``timings`` field to carry them out."""
+ import routes.inference as inf_mod
+ from models.inference import (
+ ChatCompletion,
+ CompletionChoice,
+ CompletionMessage,
+ CompletionUsage,
+ )
+
+ usage = {"prompt_tokens": 11, "completion_tokens": 50, "total_tokens": 61}
+
+ async def fake_chat_completions(chat_req, request):
+ assert request.state.skip_api_monitor is True
+ # monitor_id is None here: this call's own row is the suppressed one.
+ inf_mod._monitor_usage(None, usage, 4096, timings = timings)
+ return inf_mod._model_json_response(
+ ChatCompletion(
+ model = "test-model",
+ choices = [
+ CompletionChoice(
+ index = 0,
+ message = CompletionMessage(content = "answer"),
+ finish_reason = "stop",
+ )
+ ],
+ usage = CompletionUsage(**usage),
+ )
+ )
+
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "openai_chat_completions", fake_chat_completions)
+ request = SimpleNamespace(
+ state = SimpleNamespace(),
+ url = SimpleNamespace(path = "/v1/responses"),
+ method = "POST",
+ )
+
+ async def run():
+ response = await _responses_non_streaming(
+ ResponsesRequest(input = "hi"),
+ [ChatMessage(role = "user", content = "hi")],
+ request,
+ )
+ return json.loads(response.body.decode())
+
+ return asyncio.run(run())
+
+ def test_in_process_engine_timings_reach_the_monitor(self, monkeypatch):
+ """A local non-streamed /v1/responses never reached the Throughput tile: the
+ wrapper read decode_ms off the body, which a ChatCompletion cannot carry."""
+ from models.inference import ChatCompletion
+
+ # Asserted, not assumed: pydantic drops undeclared fields, so a body lookup finds nothing.
+ assert "timings" not in json.loads(
+ ChatCompletion(choices = [], timings = {"predicted_ms": 1000.0}).model_dump_json()
+ )
+
+ monitor = ApiMonitor(max_entries = 3)
+ body = self._run_in_process_completion(
+ monkeypatch,
+ monitor,
+ {"prompt_ms": 9000.0, "predicted_ms": 1000.0, "predicted_per_second": 50.0},
+ )
+
+ assert body["output"][0]["content"][0]["text"] == "answer"
+ [entry] = monitor.snapshot()
+ assert entry["completion_tokens"] == 50
+ assert entry["decode_ms"] == 1000
+ # 9s of that request was queue wait and prefill; the model generated at 50 tok/s.
+ assert entry["completion_tokens"] / (entry["decode_ms"] / 1000) == 50.0
+
+ def test_a_relayed_decode_span_does_not_outlive_its_request(self, monkeypatch):
+ """The relay is scoped to one inner call, so a timing-less request inherits nothing."""
+ monitor = ApiMonitor(max_entries = 3)
+ self._run_in_process_completion(
+ monkeypatch,
+ monitor,
+ {"predicted_ms": 1000.0},
+ )
+ self._run_in_process_completion(monkeypatch, monitor, None)
+
+ newest, previous = monitor.snapshot()
+ assert previous["decode_ms"] == 1000
+ assert newest["decode_ms"] is None
+
def test_monitor_records_tool_only_reply(self, monkeypatch):
import routes.inference as inf_mod
@@ -1175,6 +1263,44 @@ class TestResponsesStreamAdapter:
assert entry["total_tokens"] == 5
assert entry["context_length"] == 4096
+ def test_final_chunk_timings_reach_the_monitor(self, monkeypatch):
+ """Responses recorded usage but never timings, so a local request never reached
+ the Throughput tile. The final chunk can carry timings with no usage of its own."""
+ import routes.inference as inf_mod
+
+ chunks = [
+ {"choices": [{"delta": {"content": "33"}}]},
+ {"choices": [], "usage": {"prompt_tokens": 11, "completion_tokens": 50}},
+ {"choices": [], "timings": {"prompt_ms": 9000.0, "predicted_ms": 1000.0}},
+ ]
+ self._install_stream_mock(monkeypatch, chunks)
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/responses",
+ method = "POST",
+ model = "m",
+ prompt = "hi",
+ )
+ payload = ResponsesRequest(input = "hi", stream = True)
+ messages = [ChatMessage(role = "user", content = "hi")]
+
+ async def run():
+ response = await _responses_stream(
+ payload,
+ messages,
+ self._Request(),
+ monitor_id = monitor_id,
+ )
+ return await self._collect(response)
+
+ asyncio.run(run())
+
+ [entry] = monitor.snapshot()
+ assert entry["decode_ms"] == 1000
+ assert entry["completion_tokens"] == 50
+ assert entry["completion_tokens"] / (entry["decode_ms"] / 1000) == 50.0
+
def test_function_call_chunk_updates_monitor_reply(self, monkeypatch):
import routes.inference as inf_mod
diff --git a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
index 0df5b96a861..87ced4421fd 100644
--- a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
+++ b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx
@@ -455,6 +455,11 @@ function RequestDetail({
label: "First token",
value: entry.ttft_ms != null ? formatDuration(entry.ttft_ms) : "–",
},
+ // Duration minus this is the queue wait, not slow decoding.
+ {
+ label: "Generating",
+ value: entry.decode_ms != null ? formatDuration(entry.decode_ms) : "–",
+ },
{
label: "Speed",
value: formatTokPerSec(entry.tok_per_sec) ?? "–",
@@ -884,7 +889,7 @@ export function ApiMonitorPage(): ReactElement {
? "–"
: `${stats.tokensPerSecond.toFixed(1)} tok/s`
}
- hint={`${formatCount(stats.totalTokens)} tokens`}
+ hint={`${formatCount(stats.totalTokens)} tokens · generation only`}
/>
</section>
diff --git a/studio/frontend/src/features/api-monitor/stats.ts b/studio/frontend/src/features/api-monitor/stats.ts
new file mode 100644
index 00000000000..2f47a000d35
--- /dev/null
+++ b/studio/frontend/src/features/api-monitor/stats.ts
@@ -0,0 +1,113 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Split out of use-api-monitor.ts so the arithmetic runs under `node --test`: the hook
+// imports through the "@/" alias, which node cannot resolve.
+
+import type { ApiMonitorEntry } from "../chat/types/api";
+
+export interface MonitorStats {
+ active: number;
+ total: number;
+ completed: number;
+ errors: number;
+ cancelled: number;
+ /** Mean duration over finished requests, or null when none have finished. */
+ avgDurationMs: number | null;
+ /** Slowest finished request, for spotting a pathological call. */
+ maxDurationMs: number | null;
+ totalTokens: number;
+ /** Share of finished requests that failed, 0-1. Null when nothing finished. */
+ errorRate: number | null;
+ /** Mean completion tokens per second over requests that reported both. */
+ tokensPerSecond: number | null;
+}
+
+function isTerminal(entry: ApiMonitorEntry): boolean {
+ return entry.status !== "running";
+}
+
+function completionTokens(entry: ApiMonitorEntry): number | null {
+ if (entry.completion_tokens != null) {
+ return entry.completion_tokens;
+ }
+ // Some providers report only a total, so subtract the prompt to estimate generated.
+ if (entry.total_tokens != null && entry.prompt_tokens != null) {
+ return Math.max(0, entry.total_tokens - entry.prompt_tokens);
+ }
+ return null;
+}
+
+function entryTokens(entry: ApiMonitorEntry): number {
+ if (entry.total_tokens != null) {
+ return entry.total_tokens;
+ }
+ return (entry.prompt_tokens ?? 0) + (entry.completion_tokens ?? 0);
+}
+
+export function computeStats(entries: ApiMonitorEntry[]): MonitorStats {
+ let active = 0;
+ let completed = 0;
+ let errors = 0;
+ let cancelled = 0;
+ let totalTokens = 0;
+ let durationSum = 0;
+ let durationCount = 0;
+ let maxDurationMs: number | null = null;
+ // Total tokens over total time: averaging rates lets one tiny request outweigh a long one.
+ let generatedTokens = 0;
+ let generatedDurationMs = 0;
+
+ let requests = 0;
+
+ for (const entry of entries) {
+ // A load, unload or download is not an HTTP call: it reads as "running" throughout, so
+ // counting it invents an in-flight request. The backend leaves these out of active_count.
+ if (entry.kind === "lifecycle") {
+ continue;
+ }
+ requests += 1;
+ totalTokens += entryTokens(entry);
+ if (entry.status === "running") {
+ active += 1;
+ } else if (entry.status === "error") {
+ errors += 1;
+ } else if (entry.status === "cancelled") {
+ cancelled += 1;
+ } else {
+ completed += 1;
+ }
+ const duration = entry.duration_ms;
+ if (duration != null && isTerminal(entry)) {
+ durationSum += duration;
+ durationCount += 1;
+ maxDurationMs =
+ maxDurationMs == null ? duration : Math.max(maxDurationMs, duration);
+ const generated = completionTokens(entry);
+ // Rate the decode window: duration_ms carries queue wait and prefill,
+ // which read a 50 tok/s model as 5. Untimed requests are skipped.
+ const decodeMs = entry.decode_ms;
+ if (decodeMs != null && decodeMs > 0 && generated != null && generated > 0) {
+ generatedTokens += generated;
+ generatedDurationMs += decodeMs;
+ }
+ }
+ }
+
+ const finished = completed + errors + cancelled;
+ return {
+ active,
+ total: requests,
+ completed,
+ errors,
+ cancelled,
+ avgDurationMs: durationCount > 0 ? durationSum / durationCount : null,
+ maxDurationMs,
+ totalTokens,
+ errorRate: finished > 0 ? errors / finished : null,
+ tokensPerSecond:
+ generatedDurationMs > 0
+ ? generatedTokens / (generatedDurationMs / 1000)
+ : null,
+ };
+}
diff --git a/studio/frontend/src/features/api-monitor/use-api-monitor.ts b/studio/frontend/src/features/api-monitor/use-api-monitor.ts
index 45c2b6904a6..21031bca996 100644
--- a/studio/frontend/src/features/api-monitor/use-api-monitor.ts
+++ b/studio/frontend/src/features/api-monitor/use-api-monitor.ts
@@ -12,10 +12,14 @@ import type {
} from "@/features/chat/types/api";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { clearMonitor } from "./clear-monitor";
+import { type MonitorStats, computeStats } from "./stats";
/** Poll cadence while live. Matches the settings console it replaces. */
const POLL_INTERVAL_MS = 1500;
+export { computeStats };
+export type { MonitorStats };
+
export type MonitorStatusFilter =
| "all"
| "running"
@@ -23,110 +27,6 @@ export type MonitorStatusFilter =
| "error"
| "cancelled";
-export interface MonitorStats {
- active: number;
- total: number;
- completed: number;
- errors: number;
- cancelled: number;
- /** Mean duration over finished requests, or null when none have finished. */
- avgDurationMs: number | null;
- /** Slowest finished request, for spotting a pathological call. */
- maxDurationMs: number | null;
- totalTokens: number;
- /** Share of finished requests that failed, 0-1. Null when nothing finished. */
- errorRate: number | null;
- /** Mean completion tokens per second over requests that reported both. */
- tokensPerSecond: number | null;
-}
-
-function isTerminal(entry: ApiMonitorEntry): boolean {
- return entry.status !== "running";
-}
-
-function completionTokens(entry: ApiMonitorEntry): number | null {
- if (entry.completion_tokens != null) {
- return entry.completion_tokens;
- }
- // Some providers report only a total, so subtract the prompt to estimate generated.
- if (entry.total_tokens != null && entry.prompt_tokens != null) {
- return Math.max(0, entry.total_tokens - entry.prompt_tokens);
- }
- return null;
-}
-
-function entryTokens(entry: ApiMonitorEntry): number {
- if (entry.total_tokens != null) {
- return entry.total_tokens;
- }
- return (entry.prompt_tokens ?? 0) + (entry.completion_tokens ?? 0);
-}
-
-export function computeStats(entries: ApiMonitorEntry[]): MonitorStats {
- let active = 0;
- let completed = 0;
- let errors = 0;
- let cancelled = 0;
- let totalTokens = 0;
- let durationSum = 0;
- let durationCount = 0;
- let maxDurationMs: number | null = null;
- // Total tokens over total time: averaging rates lets one tiny request outweigh a long one.
- let generatedTokens = 0;
- let generatedDurationMs = 0;
-
- let requests = 0;
-
- for (const entry of entries) {
- // A load, unload or download is not an HTTP call: it reads as "running" throughout, so
- // counting it invents an in-flight request. The backend leaves these out of active_count.
- if (entry.kind === "lifecycle") {
- continue;
- }
- requests += 1;
- totalTokens += entryTokens(entry);
- if (entry.status === "running") {
- active += 1;
- } else if (entry.status === "error") {
- errors += 1;
- } else if (entry.status === "cancelled") {
- cancelled += 1;
- } else {
- completed += 1;
- }
- const duration = entry.duration_ms;
- if (duration != null && isTerminal(entry)) {
- durationSum += duration;
- durationCount += 1;
- maxDurationMs =
- maxDurationMs == null ? duration : Math.max(maxDurationMs, duration);
- const generated = completionTokens(entry);
- // A sub-millisecond duration divides into a meaningless rate.
- if (generated != null && generated > 0 && duration > 0) {
- generatedTokens += generated;
- generatedDurationMs += duration;
- }
- }
- }
-
- const finished = completed + errors + cancelled;
- return {
- active,
- total: requests,
- completed,
- errors,
- cancelled,
- avgDurationMs: durationCount > 0 ? durationSum / durationCount : null,
- maxDurationMs,
- totalTokens,
- errorRate: finished > 0 ? errors / finished : null,
- tokensPerSecond:
- generatedDurationMs > 0
- ? generatedTokens / (generatedDurationMs / 1000)
- : null,
- };
-}
-
export function filterEntries(
entries: ApiMonitorEntry[],
status: MonitorStatusFilter,
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index c2da6e3438b..ac5e94113bf 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -369,6 +369,9 @@ export interface ApiMonitorEntry {
updated_at: number;
finished_at?: number | null;
duration_ms?: number | null;
+ // duration_ms covers the whole request, queue wait and prefill included. decode_ms is
+ // only the generating span, and is absent unless the engine reported it.
+ decode_ms?: number | null;
context_length?: number | null;
context_usage?: number | null;
prompt_tokens?: number | null;
diff --git a/studio/frontend/tests/api-monitor-throughput.test.ts b/studio/frontend/tests/api-monitor-throughput.test.ts
new file mode 100644
index 00000000000..c59ce9d254d
--- /dev/null
+++ b/studio/frontend/tests/api-monitor-throughput.test.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { computeStats } from "../src/features/api-monitor/stats.ts";
+import type { ApiMonitorEntry } from "../src/features/chat/types/api.ts";
+
+// Waited 9s behind a busy slot, then generated 50 tokens in 1s: 5 tok/s rated against
+// the whole request, 50 against the decode window.
+function queuedEntry(overrides: Partial<ApiMonitorEntry> = {}): ApiMonitorEntry {
+ return {
+ id: "apireq_1",
+ endpoint: "/v1/chat/completions",
+ method: "POST",
+ model: "local-model",
+ prompt_preview: "hello",
+ reply_preview: "hi",
+ prompt_truncated: false,
+ reply_truncated: false,
+ status: "completed",
+ started_at: 1_000_000,
+ updated_at: 1_000_010,
+ finished_at: 1_000_010,
+ duration_ms: 10_000,
+ ttft_ms: 9_000,
+ decode_ms: 1_000,
+ completion_tokens: 50,
+ ...overrides,
+ } as ApiMonitorEntry;
+}
+
+test("throughput rates the decode window, not the queue wait", () => {
+ const stats = computeStats([queuedEntry()]);
+ assert.equal(stats.tokensPerSecond, 50);
+ // The wait is still visible as duration, just not charged to the model.
+ assert.equal(stats.avgDurationMs, 10_000);
+});
+
+test("a reply with no decode window is left out of the rate", () => {
+ const stats = computeStats([
+ queuedEntry({ ttft_ms: null, decode_ms: null }),
+ ]);
+ // Not folded back in at the whole-request rate, which would report 5 tok/s.
+ assert.equal(stats.tokensPerSecond, null);
+ assert.equal(stats.totalTokens, 50);
+});
+
+test("rating is total tokens over total decode time, not a mean of rates", () => {
+ // One tiny request must not outweigh a long one.
+ const stats = computeStats([
+ queuedEntry({ id: "a", completion_tokens: 1, decode_ms: 1_000 }),
+ queuedEntry({ id: "b", completion_tokens: 99, decode_ms: 1_000 }),
+ ]);
+ assert.equal(stats.tokensPerSecond, 50);
+});
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index c54c93ee6d7..21c71409d2b 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -1870,7 +1870,8 @@ def test_backfill_compares_server_keys_by_normalized_identity():
def test_monitor_stats_exclude_model_lifecycle_rows():
"""A load, unload or download is recorded as a monitor entry but is not an HTTP call."""
- src = " ".join(_read("features/api-monitor/use-api-monitor.ts").split())
+ # computeStats lives in stats.ts so it runs under `node --test`; the hook re-exports it.
+ src = " ".join(_read("features/api-monitor/stats.ts").split())
assert 'if (entry.kind === "lifecycle") { continue; }' in src
# "Requests" is a request count too, so it cannot stay entries.length.
assert "total: requests," in src