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.

Add API server monitor in Studio (#5558)

alkinun14188d6f4592
diff --git a/studio/backend/core/inference/api_monitor.py b/studio/backend/core/inference/api_monitor.py
new file mode 100644
index 00000000000..b4ecba1b9dd
--- /dev/null
+++ b/studio/backend/core/inference/api_monitor.py
@@ -0,0 +1,286 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Small in-memory monitor for OpenAI-compatible API traffic."""
+
+from __future__ import annotations
+
+import threading
+import time
+import uuid
+from collections import deque
+from dataclasses import dataclass
+from typing import Any, Optional
+
+
+_MAX_ENTRIES = 50
+_MAX_PROMPT_CHARS = 12000
+_MAX_REPLY_CHARS = 12000
+_PREVIEW_CHARS = 360
+
+
+def _trim(text: Optional[str], limit: int) -> str:
+ if not text:
+ return ""
+ if len(text) <= limit:
+ return text
+ # Guard against limit < 3 (slice would underflow).
+ if limit <= 3:
+ return "..."[:limit]
+ return text[: limit - 3] + "..."
+
+
+@dataclass
+class ApiMonitorEntry:
+ id: str
+ endpoint: str
+ method: str
+ model: str
+ prompt: str
+ status: str
+ started_at: float
+ updated_at: float
+ subject: Optional[str] = None
+ # Monotonic anchors so duration math survives wall-clock steps (NTP).
+ started_monotonic: float = 0.0
+ finished_monotonic: Optional[float] = None
+ reply: str = ""
+ finished_at: Optional[float] = None
+ context_length: Optional[int] = None
+ prompt_tokens: Optional[int] = None
+ completion_tokens: Optional[int] = None
+ total_tokens: Optional[int] = None
+ total_tokens_authoritative: bool = False
+ error: Optional[str] = None
+
+ def snapshot(self, *, include_details: bool = True) -> dict[str, Any]:
+ duration_ms = None
+ if self.finished_monotonic is not None:
+ duration_ms = max(
+ 0,
+ int((self.finished_monotonic - self.started_monotonic) * 1000),
+ )
+ elif self.finished_at is not None:
+ duration_ms = max(0, int((self.finished_at - self.started_at) * 1000))
+ context_usage = None
+ if self.total_tokens is not None and self.context_length:
+ context_usage = min(1.0, max(0.0, self.total_tokens / self.context_length))
+ payload = {
+ "id": self.id,
+ "endpoint": self.endpoint,
+ "method": self.method,
+ "model": self.model,
+ "prompt_preview": _trim(self.prompt, _PREVIEW_CHARS),
+ "reply_preview": _trim(self.reply, _PREVIEW_CHARS),
+ "prompt_truncated": len(self.prompt) > _PREVIEW_CHARS,
+ "reply_truncated": len(self.reply) > _PREVIEW_CHARS,
+ "status": self.status,
+ "started_at": self.started_at,
+ "updated_at": self.updated_at,
+ "finished_at": self.finished_at,
+ "duration_ms": duration_ms,
+ "context_length": self.context_length,
+ "context_usage": context_usage,
+ "prompt_tokens": self.prompt_tokens,
+ "completion_tokens": self.completion_tokens,
+ "total_tokens": self.total_tokens,
+ "error": self.error,
+ }
+ if include_details:
+ payload["prompt"] = self.prompt
+ payload["reply"] = self.reply
+ return payload
+
+
+class ApiMonitor:
+ def __init__(self, max_entries: int = _MAX_ENTRIES):
+ self._entries: deque[ApiMonitorEntry] = deque()
+ self._max_entries = max(0, max_entries)
+ self._lock = threading.Lock()
+
+ def start(
+ self,
+ *,
+ endpoint: str,
+ method: str,
+ model: str,
+ prompt: str,
+ context_length: Optional[int] = None,
+ subject: Optional[str] = None,
+ ) -> str:
+ now = time.time()
+ entry = ApiMonitorEntry(
+ id = f"apireq_{uuid.uuid4().hex[:12]}",
+ endpoint = endpoint,
+ method = method,
+ model = model or "default",
+ prompt = _trim(prompt, _MAX_PROMPT_CHARS),
+ status = "running",
+ started_at = now,
+ updated_at = now,
+ subject = subject,
+ started_monotonic = time.monotonic(),
+ context_length = context_length,
+ )
+ with self._lock:
+ self._entries.appendleft(entry)
+ self._trim_terminal_locked()
+ return entry.id
+
+ def append_reply(self, entry_id: Optional[str], text: str) -> None:
+ if not entry_id or not text:
+ return
+ with self._lock:
+ entry = self._find_locked(entry_id)
+ if entry is None:
+ return
+ entry.reply = _trim(entry.reply + text, _MAX_REPLY_CHARS)
+ entry.updated_at = time.time()
+
+ def set_reply(self, entry_id: Optional[str], text: str) -> None:
+ if not entry_id:
+ return
+ with self._lock:
+ entry = self._find_locked(entry_id)
+ if entry is None:
+ return
+ entry.reply = _trim(text, _MAX_REPLY_CHARS)
+ entry.updated_at = time.time()
+
+ def set_usage(
+ self,
+ entry_id: Optional[str],
+ *,
+ prompt_tokens: Optional[int] = None,
+ completion_tokens: Optional[int] = None,
+ total_tokens: Optional[int] = None,
+ context_length: Optional[int] = None,
+ ) -> None:
+ if not entry_id:
+ return
+ with self._lock:
+ entry = self._find_locked(entry_id)
+ if entry is None:
+ return
+ if prompt_tokens is not None:
+ entry.prompt_tokens = prompt_tokens
+ if completion_tokens is not None:
+ entry.completion_tokens = completion_tokens
+ if total_tokens is not None:
+ entry.total_tokens = total_tokens
+ entry.total_tokens_authoritative = True
+ elif not entry.total_tokens_authoritative and (
+ prompt_tokens is not None or completion_tokens is not None
+ ):
+ # Derive only when no authoritative total has been set;
+ # a later partial chunk must not clobber a provider total.
+ entry.total_tokens = (entry.prompt_tokens or 0) + (entry.completion_tokens or 0)
+ if context_length is not None:
+ entry.context_length = context_length
+ entry.updated_at = time.time()
+
+ def finish(
+ self,
+ entry_id: Optional[str],
+ status: str = "completed",
+ ) -> None:
+ if not entry_id:
+ return
+ with self._lock:
+ entry = self._find_locked(entry_id)
+ if entry is None:
+ return
+ # Idempotent: second call (e.g. [DONE] after the finally block
+ # already ran) must not move finished_*.
+ if entry.finished_at is not None:
+ return
+ now = time.time()
+ entry.status = status
+ entry.updated_at = now
+ entry.finished_at = now
+ entry.finished_monotonic = time.monotonic()
+ self._entries.remove(entry)
+ self._entries.appendleft(entry)
+ self._trim_terminal_locked()
+
+ def fail(self, entry_id: Optional[str], error: str) -> None:
+ if not entry_id:
+ return
+ with self._lock:
+ entry = self._find_locked(entry_id)
+ if entry is None:
+ return
+ if entry.finished_at is not None:
+ # Already terminal; refresh error text only.
+ if error:
+ entry.error = _trim(error, 1000)
+ return
+ now = time.time()
+ entry.status = "error"
+ entry.error = _trim(error, 1000)
+ entry.updated_at = now
+ entry.finished_at = now
+ entry.finished_monotonic = time.monotonic()
+ self._entries.remove(entry)
+ self._entries.appendleft(entry)
+ self._trim_terminal_locked()
+
+ def snapshot(
+ self,
+ *,
+ include_details: bool = True,
+ subject: Optional[str] = None,
+ ) -> list[dict[str, Any]]:
+ with self._lock:
+ return [
+ entry.snapshot(include_details = include_details)
+ for entry in self._entries
+ if subject is None or entry.subject == subject
+ ]
+
+ def get(
+ self,
+ entry_id: str,
+ *,
+ subject: Optional[str] = None,
+ ) -> Optional[dict[str, Any]]:
+ with self._lock:
+ entry = self._find_locked(entry_id)
+ if entry is None:
+ return None
+ if subject is not None and entry.subject != subject:
+ return None
+ return entry.snapshot(include_details = True)
+
+ def active_count(self, *, subject: Optional[str] = None) -> int:
+ with self._lock:
+ return sum(
+ 1
+ for entry in self._entries
+ if entry.status == "running" and (subject is None or entry.subject == subject)
+ )
+
+ def clear(self) -> None:
+ with self._lock:
+ self._entries.clear()
+
+ def _find_locked(self, entry_id: str) -> Optional[ApiMonitorEntry]:
+ for entry in self._entries:
+ if entry.id == entry_id:
+ return entry
+ return None
+
+ def _trim_terminal_locked(self) -> None:
+ terminal_seen = 0
+ kept: deque[ApiMonitorEntry] = deque()
+ for entry in self._entries:
+ if entry.status == "running":
+ kept.append(entry)
+ continue
+ if terminal_seen < self._max_entries:
+ kept.append(entry)
+ terminal_seen += 1
+ self._entries = kept
+
+
+api_monitor = ApiMonitor()
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index d7db0e6f8d5..da266bf7680 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -875,6 +875,7 @@ from auth.authentication import get_current_subject
from state.tool_approvals import resolve_tool_decision
from core.inference.key_exchange import decrypt_api_key
+from core.inference.api_monitor import api_monitor
from core.inference.providers import get_provider_info, get_base_url
from core.inference.external_provider import ExternalProviderClient
from core.inference.chat_templates import resolve_effective_chat_template_override
@@ -1297,6 +1298,423 @@ def _strip_tool_xml_for_display(text: str, *, auto_heal_tool_calls: bool) -> str
logger = get_logger(__name__)
+def _monitor_content_text(content) -> str:
+ if content is None:
+ return ""
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts: list[str] = []
+ for part in content:
+ if isinstance(part, dict):
+ ptype = part.get("type")
+ if ptype in ("text", "input_text", "output_text"):
+ text = part.get("text")
+ if isinstance(text, str):
+ parts.append(text)
+ elif ptype in ("image_url", "input_image", "image"):
+ parts.append("[image]")
+ else:
+ parts.append(f"[{ptype or 'content'}]")
+ else:
+ ptype = getattr(part, "type", None)
+ text = getattr(part, "text", None)
+ if isinstance(text, str):
+ parts.append(text)
+ elif ptype in ("image_url", "input_image", "image"):
+ parts.append("[image]")
+ elif ptype:
+ parts.append(f"[{ptype}]")
+ return "\n".join(parts)
+ return str(content)
+
+
+def _monitor_prompt_from_messages(messages) -> str:
+ lines: list[str] = []
+ for msg in messages or []:
+ role = msg.get("role") if isinstance(msg, dict) else getattr(msg, "role", "")
+ content = msg.get("content") if isinstance(msg, dict) else getattr(msg, "content", "")
+ tool_calls = (
+ msg.get("tool_calls") if isinstance(msg, dict) else getattr(msg, "tool_calls", None)
+ )
+ text = _monitor_content_text(content)
+ if tool_calls and not text:
+ text = "[tool calls]"
+ if text:
+ lines.append(f"{role or 'message'}: {text}")
+ return "\n\n".join(lines)
+
+
+def _monitor_usage(
+ monitor_id: Optional[str],
+ usage: Optional[dict],
+ context_length = None,
+):
+ if not usage:
+ return
+ api_monitor.set_usage(
+ monitor_id,
+ prompt_tokens = usage.get("prompt_tokens") or usage.get("input_tokens"),
+ completion_tokens = usage.get("completion_tokens") or usage.get("output_tokens"),
+ total_tokens = usage.get("total_tokens"),
+ context_length = context_length,
+ )
+
+
+def _monitor_call_text(name: Any, arguments: Any = None) -> str:
+ call_name = str(name or "tool")
+ if arguments is None or arguments == "":
+ return f"Tool call: {call_name}"
+ if not isinstance(arguments, str):
+ args_text = json.dumps(arguments, default = str)
+ else:
+ args_text = arguments
+ if len(args_text) > 500:
+ args_text = args_text[:497] + "..."
+ return f"Tool call: {call_name}({args_text})"
+
+
+def _monitor_tool_calls_text(tool_calls: Any) -> str:
+ if not isinstance(tool_calls, list):
+ return ""
+ parts: list[str] = []
+ for tool_call in tool_calls:
+ if not isinstance(tool_call, dict):
+ continue
+ fn = tool_call.get("function") or {}
+ if not isinstance(fn, dict):
+ fn = {}
+ name = fn.get("name") or tool_call.get("name") or "tool"
+ args = fn.get("arguments")
+ if args is None:
+ args = tool_call.get("arguments")
+ parts.append(_monitor_call_text(name, args))
+ return "\n".join(parts)
+
+
+def _monitor_openai_chunk(
+ monitor_id: Optional[str],
+ data: dict,
+ context_length = None,
+):
+ if not monitor_id:
+ return
+ _monitor_usage(monitor_id, data.get("usage"), context_length)
+ # Defensive: ignore malformed shapes so the helper never raises into the
+ # streaming generator and aborts the user's response.
+ choices = data.get("choices")
+ if not isinstance(choices, list) or not choices:
+ return
+ reply_parts: list[tuple[int, str]] = []
+ for idx, choice in enumerate(choices):
+ if not isinstance(choice, dict):
+ continue
+ delta = choice.get("delta") or {}
+ message = choice.get("message") or {}
+ content = delta.get("content") if isinstance(delta, dict) else None
+ if content:
+ api_monitor.append_reply(monitor_id, content)
+ continue
+ if isinstance(delta, dict):
+ tool_text = _monitor_tool_calls_text(delta.get("tool_calls"))
+ if tool_text:
+ api_monitor.append_reply(monitor_id, tool_text)
+ continue
+ if isinstance(choice.get("text"), str):
+ reply_parts.append((idx, choice["text"]))
+ elif isinstance(message, dict):
+ text = message.get("content")
+ if isinstance(text, str):
+ reply_parts.append((idx, text))
+ else:
+ tool_text = _monitor_tool_calls_text(message.get("tool_calls"))
+ if tool_text:
+ reply_parts.append((idx, tool_text))
+ if not reply_parts:
+ return
+ if len(choices) == 1:
+ api_monitor.append_reply(monitor_id, reply_parts[0][1])
+ return
+ api_monitor.append_reply(
+ monitor_id,
+ "\n\n".join(f"Choice {idx + 1}:\n{text}" for idx, text in reply_parts),
+ )
+
+
+def _monitor_openai_error_message(data: dict) -> Optional[str]:
+ error = data.get("error")
+ if isinstance(error, dict):
+ message = error.get("message")
+ if isinstance(message, str) and message:
+ return message
+ return json.dumps(error)
+ if isinstance(error, str) and error:
+ return error
+ return None
+
+
+def _monitor_openai_sse_line(
+ monitor_id: Optional[str],
+ raw_line: str,
+ context_length = None,
+) -> Optional[str]:
+ if not monitor_id:
+ return None
+ # SSE spec allows `data:value` and `data: value`; accept both.
+ if not raw_line.startswith("data:"):
+ return None
+ data_str = raw_line[5:].lstrip()
+ if data_str == "[DONE]":
+ api_monitor.finish(monitor_id)
+ return "done"
+ try:
+ data = json.loads(data_str)
+ except json.JSONDecodeError:
+ return None
+ if isinstance(data, dict):
+ error_message = _monitor_openai_error_message(data)
+ if error_message:
+ api_monitor.fail(monitor_id, error_message)
+ return "error"
+ _monitor_openai_chunk(monitor_id, data, context_length)
+ return None
+
+
+def _monitor_openai_sse_event(
+ monitor_id: Optional[str],
+ event: bytes,
+ context_length = None,
+) -> None:
+ for line in event.decode("utf-8", errors = "ignore").splitlines():
+ _monitor_openai_sse_line(monitor_id, line.strip(), context_length)
+
+
+def _monitor_anthropic_usage(
+ monitor_id: Optional[str],
+ usage: Optional[dict],
+ context_length = None,
+) -> None:
+ if not usage:
+ return
+ _monitor_usage(
+ monitor_id,
+ {
+ "prompt_tokens": usage.get("input_tokens") or usage.get("prompt_tokens"),
+ "completion_tokens": usage.get("output_tokens") or usage.get("completion_tokens"),
+ "total_tokens": usage.get("total_tokens"),
+ },
+ context_length,
+ )
+
+
+_ANTHROPIC_MONITOR_TOOL_BLOCKS: dict[str, dict[int, bool]] = {}
+
+
+def _monitor_anthropic_index(data: dict) -> int:
+ try:
+ return int(data.get("index") or 0)
+ except (TypeError, ValueError):
+ return 0
+
+
+def _monitor_anthropic_payload(
+ monitor_id: Optional[str],
+ data: dict,
+ context_length = None,
+) -> Optional[str]:
+ if not monitor_id or not isinstance(data, dict):
+ return None
+ event_type = data.get("type")
+ if event_type == "message_start":
+ message = data.get("message") or {}
+ if isinstance(message, dict):
+ _monitor_anthropic_usage(monitor_id, message.get("usage"), context_length)
+ return None
+ if event_type == "content_block_start":
+ content_block = data.get("content_block") or {}
+ if isinstance(content_block, dict) and content_block.get("type") == "tool_use":
+ index = _monitor_anthropic_index(data)
+ _ANTHROPIC_MONITOR_TOOL_BLOCKS.setdefault(monitor_id, {})[index] = False
+ api_monitor.append_reply(monitor_id, _monitor_call_text(content_block.get("name")))
+ return None
+ if event_type == "content_block_delta":
+ delta = data.get("delta") or {}
+ text = delta.get("text") if isinstance(delta, dict) else None
+ if isinstance(text, str) and text:
+ api_monitor.append_reply(monitor_id, text)
+ elif isinstance(delta, dict) and delta.get("type") == "input_json_delta":
+ index = _monitor_anthropic_index(data)
+ tool_blocks = _ANTHROPIC_MONITOR_TOOL_BLOCKS.get(monitor_id) or {}
+ if index in tool_blocks:
+ if not tool_blocks[index]:
+ api_monitor.append_reply(monitor_id, "\nInput: ")
+ tool_blocks[index] = True
+ partial_json = delta.get("partial_json")
+ if isinstance(partial_json, str) and partial_json:
+ api_monitor.append_reply(monitor_id, partial_json)
+ return None
+ if event_type == "content_block_stop":
+ index = _monitor_anthropic_index(data)
+ tool_blocks = _ANTHROPIC_MONITOR_TOOL_BLOCKS.get(monitor_id)
+ if tool_blocks is not None:
+ tool_blocks.pop(index, None)
+ if not tool_blocks:
+ _ANTHROPIC_MONITOR_TOOL_BLOCKS.pop(monitor_id, None)
+ return None
+ if event_type == "message_delta":
+ _monitor_anthropic_usage(monitor_id, data.get("usage"), context_length)
+ return None
+ if event_type == "error":
+ error = data.get("error") or {}
+ if isinstance(error, dict):
+ message = error.get("message") or json.dumps(error, default = str)
+ else:
+ message = str(error)
+ api_monitor.fail(monitor_id, message)
+ return "error"
+ return None
+
+
+def _monitor_anthropic_sse_line(
+ monitor_id: Optional[str],
+ raw_line: str,
+ context_length = None,
+) -> Optional[str]:
+ if not monitor_id or not raw_line.startswith("data:"):
+ return None
+ data_str = raw_line[5:].lstrip()
+ try:
+ data = json.loads(data_str)
+ except json.JSONDecodeError:
+ return None
+ return _monitor_anthropic_payload(monitor_id, data, context_length)
+
+
+def _monitor_anthropic_content_blocks(content: Any) -> str:
+ if not isinstance(content, list):
+ return ""
+ parts: list[str] = []
+ for block in content:
+ if not isinstance(block, dict):
+ continue
+ if block.get("type") == "text" and isinstance(block.get("text"), str):
+ parts.append(block["text"])
+ elif block.get("type") == "tool_use":
+ parts.append(_monitor_call_text(block.get("name"), block.get("input")))
+ return "".join(parts)
+
+
+def _monitor_anthropic_json_response(
+ response,
+ monitor_id: Optional[str],
+ context_length = None,
+) -> None:
+ if not monitor_id:
+ return
+ body = getattr(response, "body", b"")
+ try:
+ data = json.loads(body.decode("utf-8") if isinstance(body, bytes) else body)
+ except Exception:
+ api_monitor.finish(monitor_id)
+ return
+ if not isinstance(data, dict):
+ api_monitor.finish(monitor_id)
+ return
+ text = _monitor_anthropic_content_blocks(data.get("content"))
+ if text:
+ api_monitor.set_reply(monitor_id, text)
+ _monitor_anthropic_usage(monitor_id, data.get("usage"), context_length)
+ api_monitor.finish(monitor_id)
+
+
+def _monitor_anthropic_response(
+ response,
+ monitor_id,
+ context_length = None,
+ cancel_event = None,
+):
+ if not monitor_id:
+ return response
+ body_iterator = getattr(response, "body_iterator", None)
+ if body_iterator is None:
+ _monitor_anthropic_json_response(response, monitor_id, context_length)
+ return response
+
+ async def _monitored_body():
+ terminal = False
+ try:
+ async for chunk in body_iterator:
+ text = (
+ chunk.decode("utf-8", errors = "ignore")
+ if isinstance(chunk, (bytes, bytearray))
+ else str(chunk)
+ )
+ for line in text.splitlines():
+ if (
+ _monitor_anthropic_sse_line(
+ monitor_id,
+ line.strip(),
+ context_length,
+ )
+ == "error"
+ ):
+ terminal = True
+ yield chunk
+ if not terminal:
+ api_monitor.finish(
+ monitor_id,
+ "cancelled"
+ if cancel_event is not None and cancel_event.is_set()
+ else "completed",
+ )
+ _ANTHROPIC_MONITOR_TOOL_BLOCKS.pop(monitor_id, None)
+ except asyncio.CancelledError:
+ if cancel_event is not None:
+ cancel_event.set()
+ api_monitor.finish(monitor_id, "cancelled")
+ _ANTHROPIC_MONITOR_TOOL_BLOCKS.pop(monitor_id, None)
+ raise
+ except Exception as exc:
+ api_monitor.fail(monitor_id, _friendly_error(exc))
+ _ANTHROPIC_MONITOR_TOOL_BLOCKS.pop(monitor_id, None)
+ raise
+
+ response.body_iterator = _monitored_body()
+ return response
+
+
+def _monitor_context_length() -> Optional[int]:
+ llama_backend = get_llama_cpp_backend()
+ if getattr(llama_backend, "is_loaded", False):
+ context_length = _positive_int_or_none(getattr(llama_backend, "context_length", None))
+ if context_length is not None:
+ return context_length
+ backend = get_inference_backend()
+ if not backend.active_model_name:
+ return None
+ models = getattr(backend, "models", {}) or {}
+ model_info = models.get(backend.active_model_name, {}) if isinstance(models, dict) else {}
+ context_length = _positive_int_or_none(model_info.get("context_length"))
+ if context_length is not None:
+ return context_length
+ for candidate in (
+ getattr(backend, "context_length", None),
+ getattr(backend, "max_seq_length", None),
+ ):
+ context_length = _positive_int_or_none(candidate)
+ if context_length is not None:
+ return context_length
+ return None
+
+
+def _monitor_active_model() -> Optional[str]:
+ llama_backend = get_llama_cpp_backend()
+ if getattr(llama_backend, "is_loaded", False):
+ return getattr(llama_backend, "model_identifier", None)
+ backend = get_inference_backend()
+ return backend.active_model_name
+
+
def _validate_native_gguf_companion(
companion_path: str | None, gguf_path: str | None, label: str
) -> None:
@@ -2247,6 +2665,35 @@ async def confirm_tool_call(
return {"resolved": True}
+@studio_router.get("/monitor")
+async def get_api_monitor(current_subject: str = Depends(get_current_subject)):
+ """Return recent OpenAI-compatible API activity for Studio."""
+ active_model = _monitor_active_model()
+ active_requests = api_monitor.active_count(subject = current_subject)
+ if active_requests:
+ operating_status = "generating"
+ elif active_model:
+ operating_status = "ready"
+ else:
+ operating_status = "idle"
+ return {
+ "status": operating_status,
+ "active_model": active_model,
+ "context_length": _monitor_context_length(),
+ "active_requests": active_requests,
+ "entries": api_monitor.snapshot(include_details = False, subject = current_subject),
+ }
+
+
+@studio_router.get("/monitor/{entry_id}")
+async def get_api_monitor_entry(entry_id: str, current_subject: str = Depends(get_current_subject)):
+ """Return full prompt/reply details for one OpenAI-compatible API request."""
+ entry = api_monitor.get(entry_id, subject = current_subject)
+ if entry is None:
+ raise HTTPException(status_code = 404, detail = "Monitor entry not found")
+ return entry
+
+
@router.post("/generate/stream")
async def generate_stream(
request: GenerateRequest, current_subject: str = Depends(get_current_subject)
@@ -3167,7 +3614,9 @@ def _build_external_messages(
async def _proxy_to_external_provider(
- payload: ChatCompletionRequest, request: Request
+ payload: ChatCompletionRequest,
+ request: Request,
+ current_subject: Optional[str] = None,
) -> StreamingResponse:
"""
Proxy a chat completion request to an external LLM provider.
@@ -3238,6 +3687,16 @@ async def _proxy_to_external_provider(
provider_type = provider_type,
base_url = base_url,
)
+ monitor_id = None
+ if not getattr(request.state, "skip_api_monitor", False):
+ monitor_id = api_monitor.start(
+ endpoint = request.url.path,
+ method = request.method,
+ model = model,
+ prompt = _monitor_prompt_from_messages(payload.messages),
+ context_length = None,
+ subject = current_subject,
+ )
client = ExternalProviderClient(
provider_type = provider_type,
@@ -3279,14 +3738,29 @@ async def _proxy_to_external_provider(
)
try:
sent_done = False
+ stream_failed = False
async for line in gen:
+ monitor_event = _monitor_openai_sse_line(monitor_id, line)
+ if monitor_event is None:
+ try:
+ _monitor_openai_chunk(monitor_id, json.loads(line))
+ except Exception:
+ pass
+ if monitor_event == "error":
+ stream_failed = True
yield f"{line}\n\n"
- if "[DONE]" in line:
+ if monitor_event == "done":
sent_done = True
if not sent_done:
+ if not stream_failed:
+ api_monitor.finish(monitor_id)
yield "data: [DONE]\n\n"
+ except asyncio.CancelledError:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
except Exception as exc:
logger.error("external_provider.stream_error", error = str(exc))
+ api_monitor.fail(monitor_id, _friendly_error(exc))
finally:
try:
await gen.aclose()
@@ -3546,7 +4020,7 @@ async def openai_chat_completions(
)
if _wants_multiple_choices(payload):
_raise_unsupported_n("external provider chat completions")
- return await _proxy_to_external_provider(payload, request)
+ return await _proxy_to_external_provider(payload, request, current_subject)
# Reject a malformed function tool here: it would otherwise reach
# llama-server and surface as an opaque 500 "Failed to parse tools".
@@ -3595,12 +4069,49 @@ async def openai_chat_completions(
# ── Determine which backend is active ─────────────────────
# Single-model server: any model name serves the loaded model (drop-in
# OpenAI compat), so payload.model is only a fallback label here.
+ monitor_id = None
+
+ async def _monitored_generate_audio(model_label: str, context_length: Optional[int] = None):
+ tts_monitor_id = None
+ if not getattr(request.state, "skip_api_monitor", False):
+ tts_monitor_id = api_monitor.start(
+ endpoint = request.url.path,
+ method = request.method,
+ model = model_label,
+ prompt = _monitor_prompt_from_messages(payload.messages),
+ context_length = context_length,
+ subject = current_subject,
+ )
+ try:
+ response = await generate_audio(payload, request)
+ except asyncio.CancelledError:
+ api_monitor.finish(tts_monitor_id, "cancelled")
+ raise
+ except Exception as e:
+ api_monitor.fail(tts_monitor_id, _friendly_error(e))
+ raise
+ if isinstance(response, JSONResponse):
+ try:
+ body = json.loads(response.body.decode())
+ choices = body.get("choices") or []
+ message = (choices[0].get("message") or {}) if choices else {}
+ content = message.get("content")
+ if isinstance(content, str):
+ api_monitor.set_reply(tts_monitor_id, content)
+ except Exception:
+ pass
+ api_monitor.finish(tts_monitor_id)
+ return response
+
if using_gguf:
model_name = llama_backend.model_identifier or payload.model
if getattr(llama_backend, "_is_audio", False):
if _wants_multiple_choices(payload):
_raise_unsupported_n("GGUF audio chat completions")
- return await generate_audio(payload, request)
+ return await _monitored_generate_audio(
+ model_name,
+ context_length = llama_backend.context_length,
+ )
else:
backend = get_inference_backend()
if not backend.active_model_name:
@@ -3616,7 +4127,7 @@ async def openai_chat_completions(
# (Whisper is ASR not TTS -- handled below in audio input path)
model_info = backend.models.get(backend.active_model_name, {})
if model_info.get("is_audio") and model_info.get("audio_type") != "whisper":
- return await generate_audio(payload, request)
+ return await _monitored_generate_audio(model_name)
# ── Whisper without audio: return clear error ──
if model_info.get("audio_type") == "whisper" and not payload.audio_base64:
@@ -3625,10 +4136,25 @@ async def openai_chat_completions(
detail = "Whisper models require audio input. Please upload an audio file.",
)
+ monitor_id = None
+ if not getattr(request.state, "skip_api_monitor", False):
+ monitor_id = api_monitor.start(
+ endpoint = request.url.path,
+ method = request.method,
+ model = model_name,
+ prompt = _monitor_prompt_from_messages(payload.messages),
+ context_length = _monitor_context_length(),
+ subject = current_subject,
+ )
+
# ── Audio INPUT path: decode WAV and route to audio input generation ──
if payload.audio_base64 and model_info.get("has_audio_input"):
- audio_array = _decode_audio_base64(payload.audio_base64)
- system_prompt, chat_messages, _ = _extract_content_parts(payload.messages)
+ try:
+ audio_array = _decode_audio_base64(payload.audio_base64)
+ system_prompt, chat_messages, _ = _extract_content_parts(payload.messages)
+ except Exception as e:
+ api_monitor.fail(monitor_id, _friendly_error(e))
+ raise
cancel_event = threading.Event()
completion_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
created = int(time.time())
@@ -3674,16 +4200,20 @@ async def openai_chat_completions(
gen = audio_input_generate()
_DONE = object()
+ cancelled = False
while True:
if cancel_event.is_set():
+ cancelled = True
break
if await request.is_disconnected():
cancel_event.set()
+ api_monitor.finish(monitor_id, "cancelled")
return
chunk_text = await asyncio.to_thread(next, gen, _DONE)
if chunk_text is _DONE:
break
if chunk_text:
+ api_monitor.append_reply(monitor_id, chunk_text)
chunk = ChatCompletionChunk(
id = completion_id,
created = created,
@@ -3703,13 +4233,16 @@ async def openai_chat_completions(
model = model_name,
choices = [ChunkChoice(delta = ChoiceDelta(), finish_reason = "stop")],
)
+ api_monitor.finish(monitor_id, "cancelled" if cancelled else "completed")
yield f"data: {final_chunk.model_dump_json(exclude_none = True)}\n\n"
yield "data: [DONE]\n\n"
except asyncio.CancelledError:
cancel_event.set()
+ api_monitor.finish(monitor_id, "cancelled")
raise
except Exception as e:
logger.error(f"Error during audio input streaming: {e}", exc_info = True)
+ api_monitor.fail(monitor_id, _friendly_error(e))
yield f"data: {json.dumps({'error': {'message': _friendly_error(e), 'type': 'server_error'}})}\n\n"
finally:
_tracker.__exit__(None, None, None)
@@ -3724,7 +4257,13 @@ async def openai_chat_completions(
},
)
else:
- full_text = "".join(audio_input_generate())
+ try:
+ full_text = "".join(audio_input_generate())
+ except Exception as e:
+ api_monitor.fail(monitor_id, _friendly_error(e))
+ raise
+ api_monitor.set_reply(monitor_id, full_text)
+ api_monitor.finish(monitor_id)
response = ChatCompletion(
id = completion_id,
created = created,
@@ -3738,6 +4277,34 @@ async def openai_chat_completions(
)
return JSONResponse(content = response.model_dump())
+ if monitor_id is None and not getattr(request.state, "skip_api_monitor", False):
+ monitor_id = api_monitor.start(
+ endpoint = request.url.path,
+ method = request.method,
+ model = model_name,
+ prompt = _monitor_prompt_from_messages(payload.messages),
+ context_length = _monitor_context_length(),
+ subject = current_subject,
+ )
+
+ # Finalize the monitor entry on validation rejection before raising.
+ def _reject(status_code: int, detail: Any) -> "HTTPException":
+ if monitor_id is not None:
+ fail_detail = detail if isinstance(detail, str) else json.dumps(detail, default = str)
+ api_monitor.fail(monitor_id, fail_detail)
+ return HTTPException(status_code = status_code, detail = detail)
+
+ def _reject_unsupported_n(path_label: str) -> "HTTPException":
+ return _reject(
+ 400,
+ openai_error_body(
+ f"n > 1 is not supported for {path_label}.",
+ status = 400,
+ code = "unsupported_parameter",
+ param = "n",
+ ),
+ )
+
# ── Standard OpenAI function-calling pass-through (GGUF only) ────
# When a client (opencode / Claude Code via OpenAI compat / Cursor /
# Continue / ...) sends standard OpenAI `tools` without Studio's
@@ -3769,14 +4336,14 @@ async def openai_chat_completions(
and (_tools_passthrough or _has_response_format)
):
if _wants_multiple_choices(payload):
- _raise_unsupported_n("GGUF tool or response_format passthrough")
+ raise _reject_unsupported_n("GGUF tool or response_format passthrough")
if payload.audio_base64:
# This path forwards the request verbatim, so the transcoded audio
# never gets injected. (The agentic tool loop below does support
# audio.)
- raise HTTPException(
- status_code = 400,
- detail = "Audio input is not supported together with guided decoding or client-supplied tools yet.",
+ raise _reject(
+ 400,
+ "Audio input is not supported together with guided decoding or client-supplied tools yet.",
)
# Preserve the vision guard from the non-passthrough path below:
@@ -3791,9 +4358,9 @@ async def openai_chat_completions(
for m in payload.messages
)
):
- raise HTTPException(
- status_code = 400,
- detail = "Image provided but current GGUF model does not support vision.",
+ raise _reject(
+ 400,
+ "Image provided but current GGUF model does not support vision.",
)
cancel_event = threading.Event()
@@ -3809,21 +4376,20 @@ async def openai_chat_completions(
payload,
model_name,
completion_id,
+ monitor_id = monitor_id,
)
return await _openai_passthrough_non_streaming(
llama_backend,
payload,
model_name,
+ monitor_id = monitor_id,
)
# ── Parse messages (handles multimodal content parts) ─────
system_prompt, chat_messages, extracted_image_b64 = _extract_content_parts(payload.messages)
if not chat_messages:
- raise HTTPException(
- status_code = 400,
- detail = "At least one non-system message is required.",
- )
+ raise _reject(400, "At least one non-system message is required.")
# ── GGUF path: proxy to llama-server /v1/chat/completions ──
if using_gguf:
@@ -3836,25 +4402,19 @@ async def openai_chat_completions(
audio_format = "wav"
if payload.audio_base64:
if not getattr(llama_backend, "_has_audio_input", False):
- raise HTTPException(
- status_code = 400,
- detail = "Audio provided but current GGUF model does not support audio input.",
+ raise _reject(
+ 400,
+ "Audio provided but current GGUF model does not support audio input.",
)
if len(payload.audio_base64) > _MAX_AUDIO_B64_CHARS:
- raise HTTPException(
- status_code = 413,
- detail = "Audio file is too large (max ~25 MB).",
- )
+ raise _reject(413, "Audio file is too large (max ~25 MB).")
try:
audio_b64, audio_format = await asyncio.to_thread(
_prepare_audio_for_llama, payload.audio_base64
)
except Exception as e:
logger.warning("Audio decode failed: %s", e, exc_info = True)
- raise HTTPException(
- status_code = 400,
- detail = "Could not decode the provided audio file.",
- )
+ raise _reject(400, "Could not decode the provided audio file.")
gguf_messages, _ = _openai_messages_for_gguf_chat(
payload,
@@ -3918,9 +4478,9 @@ async def openai_chat_completions(
# Bypass Permissions suppresses confirm, so the stream requirement
# (the gate needs streaming to prompt) no longer applies.
if payload.confirm_tool_calls and not payload.bypass_permissions and not payload.stream:
- raise HTTPException(
- status_code = 400,
- detail = openai_error_body(
+ raise _reject(
+ 400,
+ openai_error_body(
"confirm_tool_calls requires stream=true for local tool execution.",
status = 400,
code = "invalid_request_error",
@@ -3928,7 +4488,7 @@ async def openai_chat_completions(
),
)
if _wants_multiple_choices(payload):
- _raise_unsupported_n("GGUF tool chat completions")
+ raise _reject_unsupported_n("GGUF tool chat completions")
# ── Tool-use system prompt nudge ──────────────────────
_nudge = _build_tool_action_nudge(
tools = tools_to_use,
@@ -4038,6 +4598,7 @@ async def openai_chat_completions(
break
if await request.is_disconnected():
cancel_event.set()
+ api_monitor.finish(monitor_id, "cancelled")
return
event = await asyncio.to_thread(next, gen, _tool_sentinel)
@@ -4086,6 +4647,7 @@ async def openai_chat_completions(
prev_text = clean_cumulative
if not new_text:
continue
+ api_monitor.append_reply(monitor_id, new_text)
chunk = ChatCompletionChunk(
id = completion_id,
created = created,
@@ -4121,16 +4683,22 @@ async def openai_chat_completions(
)
if usage_line is not None:
yield usage_line
+ _monitor_usage(monitor_id, _stream_usage, _monitor_context_length())
+ api_monitor.finish(
+ monitor_id, "cancelled" if cancel_event.is_set() else "completed"
+ )
yield "data: [DONE]\n\n"
except asyncio.CancelledError:
cancel_event.set()
+ api_monitor.finish(monitor_id, "cancelled")
raise
except Exception as e:
import traceback
tb = traceback.format_exc()
logger.error(f"Error during GGUF tool streaming: {e}\n{tb}")
+ api_monitor.fail(monitor_id, _friendly_error(e))
error_chunk = _openai_stream_error_chunk(e)
yield f"data: {json.dumps(error_chunk)}\n\n"
finally:
@@ -4179,7 +4747,7 @@ async def openai_chat_completions(
if payload.stream:
if _wants_multiple_choices(payload):
- _raise_unsupported_n("streaming GGUF chat completions")
+ raise _reject_unsupported_n("streaming GGUF chat completions")
_cancel_keys = (payload.cancel_id, payload.session_id, completion_id)
_tracker = _TrackedCancel(cancel_event, *_cancel_keys)
_tracker.__enter__()
@@ -4212,6 +4780,7 @@ async def openai_chat_completions(
break
if await request.is_disconnected():
cancel_event.set()
+ api_monitor.finish(monitor_id, "cancelled")
return
cumulative = await asyncio.to_thread(next, gen, _gguf_sentinel)
if cumulative is _gguf_sentinel:
@@ -4236,6 +4805,7 @@ async def openai_chat_completions(
prev_text = cumulative
if not new_text:
continue
+ api_monitor.append_reply(monitor_id, new_text)
chunk = ChatCompletionChunk(
id = completion_id,
created = created,
@@ -4272,13 +4842,19 @@ async def openai_chat_completions(
)
if usage_line is not None:
yield usage_line
+ _monitor_usage(monitor_id, _stream_usage, _monitor_context_length())
+ api_monitor.finish(
+ monitor_id, "cancelled" if cancel_event.is_set() else "completed"
+ )
yield "data: [DONE]\n\n"
except asyncio.CancelledError:
cancel_event.set()
+ api_monitor.finish(monitor_id, "cancelled")
raise
except Exception as e:
logger.error(f"Error during GGUF streaming: {e}", exc_info = True)
+ api_monitor.fail(monitor_id, _friendly_error(e))
error_chunk = _openai_stream_error_chunk(e)
yield f"data: {json.dumps(error_chunk)}\n\n"
finally:
@@ -4300,6 +4876,7 @@ async def openai_chat_completions(
_n = payload.n or 1
_choices = []
+ _monitor_replies = []
_prompt_tokens = 0
_sum_completion = 0
_prompt_details = None
@@ -4325,6 +4902,7 @@ async def openai_chat_completions(
finish_reason = _clamp_finish_reason(completion_finish),
)
)
+ _monitor_replies.append(full_text)
if completion_usage:
# The prompt is shared across all n choices, so count its
# tokens ONCE (OpenAI bills only generated tokens for each
@@ -4346,10 +4924,27 @@ async def openai_chat_completions(
prompt_tokens_details = _prompt_tokens_details(_prompt_details),
),
)
+ monitor_reply = full_text
+ if _n > 1:
+ monitor_reply = "\n\n".join(
+ f"Choice {_idx + 1}:\n{text}" for _idx, text in enumerate(_monitor_replies)
+ )
+ api_monitor.set_reply(monitor_id, monitor_reply)
+ _monitor_usage(
+ monitor_id,
+ {
+ "prompt_tokens": _prompt_tokens,
+ "completion_tokens": _sum_completion,
+ "total_tokens": _prompt_tokens + _sum_completion,
+ },
+ _monitor_context_length(),
+ )
+ api_monitor.finish(monitor_id)
return JSONResponse(content = response.model_dump())
except Exception as e:
logger.error(f"Error during GGUF completion: {e}", exc_info = True)
+ api_monitor.fail(monitor_id, _friendly_error(e))
# An over-context prompt makes llama-server return 400; map any
# upstream 4xx to a 400 client error rather than leaking a 500.
_cls = _classify_llama_generation_error(e)
@@ -4469,9 +5064,9 @@ async def openai_chat_completions(
# Bypass Permissions suppresses confirm, so the stream requirement
# (the gate needs streaming to prompt) no longer applies.
if payload.confirm_tool_calls and not payload.bypass_permissions and not payload.stream:
- raise HTTPException(
- status_code = 400,
- detail = openai_error_body(
+ raise _reject(
+ 400,
+ openai_error_body(
"confirm_tool_calls requires stream=true for local tool execution.",
status = 400,
code = "invalid_request_error",
@@ -4593,6 +5188,7 @@ async def openai_chat_completions(
if await request.is_disconnected():
cancel_event.set()
backend.reset_generation_state()
+ api_monitor.finish(monitor_id, "cancelled")
return
event = await asyncio.to_thread(next, gen, _sf_tool_sentinel)
@@ -4627,6 +5223,7 @@ async def openai_chat_completions(
prev_text = clean_cumulative
if not new_text:
continue
+ api_monitor.append_reply(monitor_id, new_text)
chunk = ChatCompletionChunk(
id = completion_id,
created = created,
@@ -4667,17 +5264,23 @@ async def openai_chat_completions(
)
if usage_line is not None:
yield usage_line
+ _monitor_usage(monitor_id, _stats.get("usage"))
+ api_monitor.finish(
+ monitor_id, "cancelled" if cancel_event.is_set() else "completed"
+ )
yield "data: [DONE]\n\n"
except asyncio.CancelledError:
cancel_event.set()
backend.reset_generation_state()
+ api_monitor.finish(monitor_id, "cancelled")
raise
except Exception:
backend.reset_generation_state()
# Generic wire message; full trace stays in the log (CWE-209:
# transformers/torch errors may leak paths).
logger.exception("safetensors tool stream error")
+ api_monitor.fail(monitor_id, "An internal error occurred.")
error_chunk = {
"error": {
"message": "An internal error occurred.",
@@ -4721,6 +5324,11 @@ async def openai_chat_completions(
return full_text
content_text = await asyncio.to_thread(_drain_to_text)
+ api_monitor.set_reply(monitor_id, content_text)
+ _stats = _sf_stats_holder.get("stats")
+ if _stats:
+ _monitor_usage(monitor_id, _stats.get("usage"))
+ api_monitor.finish(monitor_id, "cancelled" if cancel_event.is_set() else "completed")
response = ChatCompletion(
id = completion_id,
created = created,
@@ -4733,10 +5341,16 @@ async def openai_chat_completions(
],
)
return JSONResponse(content = response.model_dump())
+ except asyncio.CancelledError:
+ cancel_event.set()
+ backend.reset_generation_state()
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
except Exception:
backend.reset_generation_state()
# CWE-209: generic detail; full trace in log.
logger.exception("safetensors tool completion error")
+ api_monitor.fail(monitor_id, "An internal error occurred.")
raise HTTPException(
status_code = 500,
detail = "An internal error occurred.",
@@ -4830,11 +5444,13 @@ async def openai_chat_completions(
if await request.is_disconnected():
cancel_event.set()
backend.reset_generation_state()
+ api_monitor.finish(monitor_id, "cancelled")
return
new_text = cumulative[len(prev_text) :]
prev_text = cumulative
if not new_text:
continue
+ api_monitor.append_reply(monitor_id, new_text)
chunk = ChatCompletionChunk(
id = completion_id,
created = created,
@@ -4876,15 +5492,21 @@ async def openai_chat_completions(
)
if usage_line is not None:
yield usage_line
+ _monitor_usage(monitor_id, _stats.get("usage"))
+ api_monitor.finish(
+ monitor_id, "cancelled" if cancel_event.is_set() else "completed"
+ )
yield "data: [DONE]\n\n"
except asyncio.CancelledError:
cancel_event.set()
backend.reset_generation_state()
+ api_monitor.finish(monitor_id, "cancelled")
raise
except Exception as e:
backend.reset_generation_state()
logger.error(f"Error during OpenAI streaming: {e}", exc_info = True)
+ api_monitor.fail(monitor_id, _friendly_error(e))
error_chunk = {
"error": {
"message": _friendly_error(e),
@@ -4923,11 +5545,17 @@ async def openai_chat_completions(
)
],
)
+ api_monitor.set_reply(monitor_id, full_text)
+ _stats = stats_holder.get("stats")
+ if _stats:
+ _monitor_usage(monitor_id, _stats.get("usage"))
+ api_monitor.finish(monitor_id)
return JSONResponse(content = response.model_dump())
except Exception as e:
backend.reset_generation_state()
logger.error(f"Error during OpenAI completion: {e}", exc_info = True)
+ api_monitor.fail(monitor_id, _friendly_error(e))
raise HTTPException(status_code = 500, detail = safe_error_detail(e))
@@ -5137,6 +5765,19 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
body["max_tokens"] = llama_backend.context_length or _DEFAULT_MAX_TOKENS_FLOOR
target_url = f"{llama_backend.base_url}/v1/completions"
is_stream = body.get("stream", False)
+ raw_prompt = body.get("prompt", "")
+ if isinstance(raw_prompt, list):
+ prompt_text = "\n".join(str(part) for part in raw_prompt)
+ else:
+ prompt_text = str(raw_prompt)
+ monitor_id = api_monitor.start(
+ endpoint = request.url.path,
+ method = request.method,
+ model = str(body.get("model") or llama_backend.model_identifier or "default"),
+ prompt = prompt_text,
+ context_length = llama_backend.context_length,
+ subject = current_subject,
+ )
if is_stream:
@@ -5164,10 +5805,12 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S
resp = await _send_stream_with_preheader_cancel(client, req, request = request)
if resp is None:
+ api_monitor.finish(monitor_id, "cancelled")
return
if resp.status_code != 200:
err_bytes = await resp.aread()
err_text = err_bytes.decode("utf-8", errors = "replace")
+ api_monitor.fail(monitor_id, err_text[:500])
raise RuntimeError(f"llama-server returned {resp.status_code}: {err_text}")
disconnect_watcher = asyncio.create_task(
_await_disconnect_then_close(request, resp, disconnect_event)
@@ -5184,26 +5827,49 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
buffer += chunk
while b"\n\n" in buffer:
event, buffer = buffer.split(b"\n\n", 1)
+ _monitor_openai_sse_event(
+ monitor_id,
+ event,
+ llama_backend.context_length,
+ )
out = _cmpl_stream_event_out(event, _include_usage)
if out is not None:
yield out + b"\n\n"
if not disconnect_event.is_set() and buffer:
+ _monitor_openai_sse_event(
+ monitor_id,
+ buffer,
+ llama_backend.context_length,
+ )
out = _cmpl_stream_event_out(buffer, _include_usage)
if out is not None:
# Re-add the SSE separator the split consumed, so a final
# event arriving without a trailing blank line is still
# terminated for the client's parser.
yield out + b"\n\n"
+ if disconnect_event.is_set():
+ api_monitor.finish(monitor_id, "cancelled")
+ return
+ api_monitor.finish(monitor_id)
except (httpx.RemoteProtocolError, httpx.ReadError, httpx.CloseError) as e:
if not disconnect_event.is_set():
logger.error("openai_completions stream error: %s", e)
+ api_monitor.fail(monitor_id, _friendly_error(e))
error_chunk = _openai_stream_error_chunk(e)
yield f"data: {json.dumps(error_chunk)}\n\n".encode("utf-8")
return
+ api_monitor.finish(monitor_id, "cancelled")
+ return
+ except asyncio.CancelledError:
+ disconnect_event.set()
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
except Exception as e:
if disconnect_event.is_set():
+ api_monitor.finish(monitor_id, "cancelled")
return
logger.error("openai_completions stream error: %s", e)
+ api_monitor.fail(monitor_id, _friendly_error(e))
error_chunk = _openai_stream_error_chunk(e)
yield f"data: {json.dumps(error_chunk)}\n\n".encode("utf-8")
return
@@ -5231,15 +5897,28 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
return StreamingResponse(_stream(), media_type = "text/event-stream")
else:
- async with httpx.AsyncClient() as client:
- resp = await client.post(
- target_url,
- json = body,
- timeout = _llama_non_streaming_generation_timeout(),
- )
+ try:
+ async with httpx.AsyncClient() as client:
+ resp = await client.post(
+ target_url,
+ json = body,
+ timeout = _llama_non_streaming_generation_timeout(),
+ )
+ except asyncio.CancelledError:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
+ except Exception as e:
+ api_monitor.fail(monitor_id, _friendly_error(e))
+ raise
if resp.status_code != 200:
+ api_monitor.fail(monitor_id, resp.text[:500])
raise _openai_passthrough_error(resp.status_code, resp.text)
+ try:
+ _monitor_openai_chunk(monitor_id, resp.json(), llama_backend.context_length)
+ except Exception:
+ pass
+ api_monitor.finish(monitor_id)
return Response(
content = _rewrite_cmpl_id(resp.content),
@@ -5272,9 +5951,43 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(get
body = await request.json()
target_url = f"{llama_backend.base_url}/v1/embeddings"
+ raw_input = body.get("input", "")
+ if isinstance(raw_input, list):
+ prompt_text = "\n".join(str(part) for part in raw_input)
+ else:
+ prompt_text = str(raw_input)
+ monitor_id = None
+ if not getattr(request.state, "skip_api_monitor", False):
+ monitor_id = api_monitor.start(
+ endpoint = request.url.path,
+ method = request.method,
+ model = str(body.get("model") or llama_backend.model_identifier or "default"),
+ prompt = prompt_text,
+ context_length = llama_backend.context_length,
+ subject = current_subject,
+ )
- async with httpx.AsyncClient() as client:
- resp = await client.post(target_url, json = body, timeout = _DEFAULT_FIRST_TOKEN_TIMEOUT_S)
+ try:
+ async with httpx.AsyncClient() as client:
+ resp = await client.post(
+ target_url,
+ json = body,
+ timeout = _DEFAULT_FIRST_TOKEN_TIMEOUT_S,
+ )
+ except asyncio.CancelledError:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
+ except Exception as exc:
+ api_monitor.fail(monitor_id, _friendly_error(exc))
+ raise
+ if resp.status_code != 200:
+ api_monitor.fail(monitor_id, resp.text[:500])
+ else:
+ try:
+ _monitor_usage(monitor_id, resp.json().get("usage"), _monitor_context_length())
+ except Exception:
+ pass
+ api_monitor.finish(monitor_id)
return Response(
content = resp.content,
status_code = resp.status_code,
@@ -5788,84 +6501,128 @@ def _chat_tool_calls_to_responses_output(tool_calls: list[dict]) -> list[dict]:
async def _responses_non_streaming(
- payload: ResponsesRequest, messages: list[ChatMessage], request: Request
+ payload: ResponsesRequest,
+ messages: list[ChatMessage],
+ request: Request,
+ current_subject: Optional[str] = None,
) -> JSONResponse:
"""Handle a non-streaming Responses API call."""
chat_req = _build_chat_request(payload, messages, stream = False)
- result = await openai_chat_completions(chat_req, request)
-
- # openai_chat_completions returns a JSONResponse for non-streaming.
- if isinstance(result, JSONResponse):
- body = json.loads(result.body.decode())
- elif isinstance(result, Response):
- body = json.loads(result.body.decode())
- else:
- body = result
-
- choices = body.get("choices", [])
- text = ""
- reasoning_text = ""
- tool_calls: list[dict] = []
- if choices:
- msg = choices[0].get("message", {}) or {}
- raw_content = msg.get("content", "") or ""
- raw_text = raw_content if isinstance(raw_content, str) else json.dumps(raw_content)
- llama_backend = get_llama_cpp_backend()
- reasoning_text, text = _extract_responses_reasoning(
- raw_text,
- msg.get("reasoning_content"),
- parse_think_markers = _responses_should_parse_think_markers(chat_req, llama_backend),
+ request_state = getattr(request, "state", None)
+ if request_state is None:
+ request_state = type("_RequestState", (), {})()
+ try:
+ setattr(request, "state", request_state)
+ except Exception:
+ request_state = None
+ previous_skip_monitor = (
+ bool(getattr(request_state, "skip_api_monitor", False))
+ if request_state is not None
+ else False
+ )
+ monitor_id = None
+ if not previous_skip_monitor:
+ monitor_id = api_monitor.start(
+ endpoint = getattr(getattr(request, "url", None), "path", "/v1/responses"),
+ method = getattr(request, "method", "POST"),
+ model = payload.model,
+ prompt = _monitor_prompt_from_messages(messages),
+ context_length = _monitor_context_length(),
+ subject = current_subject,
)
- tool_calls = msg.get("tool_calls") or []
+ if request_state is not None:
+ request_state.skip_api_monitor = True
- usage_data = body.get("usage", {})
- input_tokens = usage_data.get("prompt_tokens", 0)
- output_tokens = usage_data.get("completion_tokens", 0)
-
- resp_id = f"resp_{uuid.uuid4().hex[:12]}"
+ try:
+ result = await openai_chat_completions(chat_req, request)
- # Responses API emits each tool call as its own top-level output item,
- # plus an optional assistant text message. Emit the text message only when
- # the model produced content, so clients expecting a pure tool-call turn
- # (finish_reason="tool_calls") don't see a spurious empty message item.
- output_items: list[dict] = []
- if reasoning_text and not text and not tool_calls:
- text = reasoning_text
- if reasoning_text:
- output_items.append(_responses_reasoning_output_item(reasoning_text))
- if text:
- msg_id = f"msg_{uuid.uuid4().hex[:12]}"
- output_items.append(
- ResponsesOutputMessage(
- id = msg_id,
- status = "completed",
- role = "assistant",
- content = [ResponsesOutputTextContent(text = text)],
- ).model_dump()
+ # openai_chat_completions returns a JSONResponse for non-streaming.
+ if isinstance(result, JSONResponse):
+ body = json.loads(result.body.decode())
+ elif isinstance(result, Response):
+ body = json.loads(result.body.decode())
+ else:
+ body = result
+
+ choices = body.get("choices", [])
+ text = ""
+ reasoning_text = ""
+ tool_calls: list[dict] = []
+ if choices:
+ msg = choices[0].get("message", {}) or {}
+ raw_content = msg.get("content", "") or ""
+ raw_text = raw_content if isinstance(raw_content, str) else json.dumps(raw_content)
+ llama_backend = get_llama_cpp_backend()
+ reasoning_text, text = _extract_responses_reasoning(
+ raw_text,
+ msg.get("reasoning_content"),
+ parse_think_markers = _responses_should_parse_think_markers(chat_req, llama_backend),
+ )
+ tool_calls = msg.get("tool_calls") or []
+
+ usage_data = body.get("usage", {})
+ input_tokens = usage_data.get("prompt_tokens", 0)
+ output_tokens = usage_data.get("completion_tokens", 0)
+
+ resp_id = f"resp_{uuid.uuid4().hex[:12]}"
+
+ # Responses API emits each tool call as its own top-level output item,
+ # plus an optional assistant text message. Emit the text message only when
+ # the model produced content, so clients expecting a pure tool-call turn
+ # (finish_reason="tool_calls") don't see a spurious empty message item.
+ output_items: list[dict] = []
+ if reasoning_text and not text and not tool_calls:
+ text = reasoning_text
+ if reasoning_text:
+ output_items.append(_responses_reasoning_output_item(reasoning_text))
+ if text:
+ msg_id = f"msg_{uuid.uuid4().hex[:12]}"
+ output_items.append(
+ ResponsesOutputMessage(
+ id = msg_id,
+ status = "completed",
+ role = "assistant",
+ content = [ResponsesOutputTextContent(text = text)],
+ ).model_dump()
+ )
+ output_items.extend(_chat_tool_calls_to_responses_output(tool_calls))
+
+ response = ResponsesResponse(
+ id = resp_id,
+ created_at = int(time.time()),
+ status = "completed",
+ model = body.get("model", payload.model),
+ output = output_items,
+ usage = ResponsesUsage(
+ input_tokens = input_tokens,
+ output_tokens = output_tokens,
+ total_tokens = input_tokens + output_tokens,
+ ),
+ temperature = payload.temperature,
+ top_p = payload.top_p,
+ max_output_tokens = payload.max_output_tokens,
+ instructions = payload.instructions,
)
- output_items.extend(_chat_tool_calls_to_responses_output(tool_calls))
-
- response = ResponsesResponse(
- id = resp_id,
- created_at = int(time.time()),
- status = "completed",
- model = body.get("model", payload.model),
- output = output_items,
- usage = ResponsesUsage(
- input_tokens = input_tokens,
- output_tokens = output_tokens,
- total_tokens = input_tokens + output_tokens,
- ),
- temperature = payload.temperature,
- top_p = payload.top_p,
- max_output_tokens = payload.max_output_tokens,
- instructions = payload.instructions,
- )
- return JSONResponse(content = response.model_dump())
+ api_monitor.set_reply(monitor_id, text or _monitor_tool_calls_text(tool_calls))
+ _monitor_usage(monitor_id, usage_data, _monitor_context_length())
+ api_monitor.finish(monitor_id)
+ return JSONResponse(content = response.model_dump())
+ except asyncio.CancelledError:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
+ except Exception as exc:
+ api_monitor.fail(monitor_id, _friendly_error(exc))
+ raise
+ finally:
+ if request_state is not None:
+ request_state.skip_api_monitor = previous_skip_monitor
async def _responses_stream(
- payload: ResponsesRequest, messages: list[ChatMessage], request: Request
+ payload: ResponsesRequest,
+ messages: list[ChatMessage],
+ request: Request,
+ monitor_id: Optional[str] = None,
):
"""Handle a streaming Responses API call, emitting named SSE events.
@@ -6130,9 +6887,11 @@ async def _responses_stream(
try:
resp = await _send_stream_with_preheader_cancel(client, req, request = request)
if resp is None:
+ api_monitor.finish(monitor_id, "cancelled")
return
except httpx.RequestError as e:
logger.error("responses stream: upstream unreachable: %s", e)
+ api_monitor.fail(monitor_id, _friendly_error(e))
yield _sse(
"response.failed",
{
@@ -6158,6 +6917,7 @@ async def _responses_stream(
resp.status_code,
err_text[:500],
)
+ api_monitor.fail(monitor_id, err_text[:500])
yield _sse(
"response.failed",
{
@@ -6209,6 +6969,11 @@ async def _responses_stream(
if usage:
input_tokens = usage.get("prompt_tokens", input_tokens)
output_tokens = usage.get("completion_tokens", output_tokens)
+ _monitor_usage(
+ monitor_id,
+ usage,
+ llama_backend.context_length,
+ )
continue
delta = choices[0].get("delta", {}) or {}
@@ -6234,6 +6999,7 @@ async def _responses_stream(
for event in _ensure_message_open():
yield event
full_text += visible_delta
+ api_monitor.append_reply(monitor_id, visible_delta)
yield _sse(
"response.output_text.delta",
{
@@ -6305,9 +7071,18 @@ async def _responses_stream(
if usage:
input_tokens = usage.get("prompt_tokens", input_tokens)
output_tokens = usage.get("completion_tokens", output_tokens)
+ _monitor_usage(
+ monitor_id,
+ usage,
+ llama_backend.context_length,
+ )
+ except asyncio.CancelledError:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
except (httpx.RemoteProtocolError, httpx.ReadError, httpx.CloseError) as e:
if not disconnect_event.is_set():
logger.error("responses stream error: %s", e)
+ api_monitor.fail(monitor_id, _friendly_error(e))
status_code = 400 if _classify_llama_generation_error(e) is not None else 500
yield _sse(
"response.failed",
@@ -6316,8 +7091,10 @@ async def _responses_stream(
return
except Exception as e:
if disconnect_event.is_set():
+ api_monitor.finish(monitor_id, "cancelled")
return
logger.error("responses stream error: %s", e)
+ api_monitor.fail(monitor_id, _friendly_error(e))
status_code = 400 if _classify_llama_generation_error(e) is not None else 500
yield _sse(
"response.failed",
@@ -6347,6 +7124,7 @@ async def _responses_stream(
pass
if disconnect_event.is_set():
+ api_monitor.finish(monitor_id, "cancelled")
return
final_reasoning, final_visible = extractor.finish()
@@ -6368,6 +7146,7 @@ async def _responses_stream(
for event in _ensure_message_open():
yield event
full_text += final_visible
+ api_monitor.append_reply(monitor_id, final_visible)
yield _sse(
"response.output_text.delta",
{
@@ -6382,6 +7161,7 @@ async def _responses_stream(
for event in _ensure_message_open():
yield event
full_text = full_reasoning
+ api_monitor.set_reply(monitor_id, full_text)
yield _sse(
"response.output_text.delta",
{
@@ -6528,6 +7308,7 @@ async def _responses_stream(
"arguments": st["arguments"],
},
}
+ api_monitor.append_reply(monitor_id, _monitor_call_text(st["name"], st["arguments"]))
yield _sse("response.output_item.done", item_done)
# response.completed
@@ -6548,6 +7329,7 @@ async def _responses_stream(
},
},
}
+ api_monitor.finish(monitor_id)
yield _sse("response.completed", completed_response)
return StreamingResponse(
@@ -6579,8 +7361,28 @@ async def openai_responses(
raise HTTPException(status_code = 400, detail = "No input provided.")
if payload.stream:
- return await _responses_stream(payload, messages, request)
- return await _responses_non_streaming(payload, messages, request)
+ monitor_id = None
+ if not getattr(request.state, "skip_api_monitor", False):
+ monitor_id = api_monitor.start(
+ endpoint = request.url.path,
+ method = request.method,
+ model = payload.model,
+ prompt = _monitor_prompt_from_messages(messages),
+ context_length = _monitor_context_length(),
+ subject = current_subject,
+ )
+ try:
+ return await _responses_stream(payload, messages, request, monitor_id)
+ except HTTPException as exc:
+ detail = exc.detail
+ if not isinstance(detail, str):
+ detail = json.dumps(detail, default = str)
+ api_monitor.fail(monitor_id, detail)
+ raise
+ except Exception as exc:
+ api_monitor.fail(monitor_id, _friendly_error(exc))
+ raise
+ return await _responses_non_streaming(payload, messages, request, current_subject)
# =====================================================================
@@ -6900,14 +7702,67 @@ async def anthropic_messages(
and payload.tool_choice.get("disable_parallel_tool_use")
)
+ monitor_id = None
+ monitor_context_length = _monitor_context_length()
+ request_state = getattr(request, "state", None)
+ if not getattr(request_state, "skip_api_monitor", False):
+ request_url = getattr(request, "url", None)
+ monitor_id = api_monitor.start(
+ endpoint = getattr(request_url, "path", "/v1/messages"),
+ method = getattr(request, "method", "POST"),
+ model = model_name,
+ prompt = _monitor_prompt_from_messages(openai_messages),
+ context_length = monitor_context_length,
+ subject = current_subject,
+ )
+
+ async def _monitored_anthropic(coro):
+ try:
+ response = await coro
+ except asyncio.CancelledError:
+ cancel_event.set()
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
+ except Exception as exc:
+ api_monitor.fail(monitor_id, _friendly_error(exc))
+ raise
+ return _monitor_anthropic_response(
+ response,
+ monitor_id,
+ monitor_context_length,
+ cancel_event,
+ )
+
# ── Client-side pass-through path ─────────────────────────
if client_tools:
openai_tools = openai_client_tools
if payload.stream:
- return await _anthropic_passthrough_stream(
- request,
- cancel_event,
+ return await _monitored_anthropic(
+ _anthropic_passthrough_stream(
+ request,
+ cancel_event,
+ llama_backend,
+ openai_messages,
+ openai_tools,
+ temperature,
+ top_p,
+ top_k,
+ payload.max_tokens,
+ message_id,
+ model_name,
+ stop = stop,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ tool_choice = openai_tool_choice,
+ session_id = payload.session_id,
+ cancel_id = payload.cancel_id,
+ disable_parallel_tool_use = _disable_parallel,
+ )
+ )
+ return await _monitored_anthropic(
+ _anthropic_passthrough_non_streaming(
llama_backend,
openai_messages,
openai_tools,
@@ -6922,26 +7777,8 @@ async def anthropic_messages(
repetition_penalty = repetition_penalty,
presence_penalty = presence_penalty,
tool_choice = openai_tool_choice,
- session_id = payload.session_id,
- cancel_id = payload.cancel_id,
disable_parallel_tool_use = _disable_parallel,
)
- return await _anthropic_passthrough_non_streaming(
- llama_backend,
- openai_messages,
- openai_tools,
- temperature,
- top_p,
- top_k,
- payload.max_tokens,
- message_id,
- model_name,
- stop = stop,
- min_p = min_p,
- repetition_penalty = repetition_penalty,
- presence_penalty = presence_penalty,
- tool_choice = openai_tool_choice,
- disable_parallel_tool_use = _disable_parallel,
)
if server_tools:
@@ -6949,6 +7786,10 @@ async def anthropic_messages(
if bool(getattr(payload, "confirm_tool_calls", False)) and not bool(
getattr(payload, "bypass_permissions", False)
):
+ api_monitor.fail(
+ monitor_id,
+ "confirm_tool_calls is not supported for Anthropic Messages server tools.",
+ )
raise HTTPException(
status_code = 400,
detail = anthropic_error_body(
@@ -7009,22 +7850,26 @@ async def anthropic_messages(
)
if payload.stream:
- return await _anthropic_tool_stream(
- request,
- cancel_event,
+ return await _monitored_anthropic(
+ _anthropic_tool_stream(
+ request,
+ cancel_event,
+ _run_tool_gen,
+ message_id,
+ model_name,
+ llama_backend = llama_backend,
+ openai_messages = openai_messages,
+ openai_tools = openai_tools,
+ disable_parallel_tool_use = _disable_parallel,
+ )
+ )
+ return await _monitored_anthropic(
+ _anthropic_tool_non_streaming(
_run_tool_gen,
message_id,
model_name,
- llama_backend = llama_backend,
- openai_messages = openai_messages,
- openai_tools = openai_tools,
disable_parallel_tool_use = _disable_parallel,
)
- return await _anthropic_tool_non_streaming(
- _run_tool_gen,
- message_id,
- model_name,
- disable_parallel_tool_use = _disable_parallel,
)
# ── No-tool path ──────────────────────────────────────────
@@ -7043,19 +7888,23 @@ async def anthropic_messages(
)
if payload.stream:
- return await _anthropic_plain_stream(
- request,
- cancel_event,
+ return await _monitored_anthropic(
+ _anthropic_plain_stream(
+ request,
+ cancel_event,
+ _run_plain_gen,
+ message_id,
+ model_name,
+ llama_backend = llama_backend,
+ openai_messages = openai_messages,
+ )
+ )
+ return await _monitored_anthropic(
+ _anthropic_plain_non_streaming(
_run_plain_gen,
message_id,
model_name,
- llama_backend = llama_backend,
- openai_messages = openai_messages,
)
- return await _anthropic_plain_non_streaming(
- _run_plain_gen,
- message_id,
- model_name,
)
@@ -8106,7 +8955,13 @@ def _build_openai_passthrough_body(
async def _openai_passthrough_stream(
- request, cancel_event, llama_backend, payload, model_name, completion_id
+ request,
+ cancel_event,
+ llama_backend,
+ payload,
+ model_name,
+ completion_id,
+ monitor_id: Optional[str] = None,
):
"""Streaming client-side pass-through for /v1/chat/completions.
@@ -8150,6 +9005,7 @@ async def _openai_passthrough_stream(
except httpx.RequestError as e:
# llama-server subprocess crashed / starting / unreachable.
logger.error("openai passthrough stream: upstream unreachable: %s", e)
+ api_monitor.fail(monitor_id, _friendly_error(e))
if resp is not None:
try:
await resp.aclose()
@@ -8164,6 +9020,7 @@ async def _openai_passthrough_stream(
detail = _friendly_error(e),
)
if resp is None:
+ api_monitor.finish(monitor_id, "cancelled")
try:
await client.aclose()
except Exception:
@@ -8205,6 +9062,7 @@ async def _openai_passthrough_stream(
await client.aclose()
except Exception:
pass
+ api_monitor.fail(monitor_id, err_text[:500])
raise _openai_passthrough_error(upstream_status, err_text)
async def _stream():
@@ -8218,6 +9076,7 @@ async def _openai_passthrough_stream(
disconnect_watcher = asyncio.create_task(
_await_disconnect_then_close(request, resp, cancel_event)
)
+ monitor_done = False
try:
lines_iter = resp.aiter_lines()
async for raw_line in _aiter_llama_stream_items(
@@ -8237,21 +9096,39 @@ async def _openai_passthrough_stream(
# relayed byte-for-byte.
if payload.parallel_tool_calls is False and '"tool_calls"' in raw_line:
raw_line = _cap_parallel_tool_calls_sse_line(raw_line)
+ monitor_event = _monitor_openai_sse_line(
+ monitor_id,
+ raw_line,
+ llama_backend.context_length,
+ )
# Relay verbatim to preserve llama-server's native id,
# finish_reason, delta.tool_calls, and usage chunks.
yield raw_line + "\n\n"
- if raw_line[6:].strip() == "[DONE]":
+ if monitor_event == "done" or raw_line[6:].strip() == "[DONE]":
+ monitor_done = True
break
+ if not monitor_done:
+ api_monitor.finish(
+ monitor_id,
+ "cancelled" if cancel_event.is_set() else "completed",
+ )
+ except asyncio.CancelledError:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
except (httpx.RemoteProtocolError, httpx.ReadError, httpx.CloseError):
# Watcher closed resp on cancel. Emit nothing extra; the client
# initiated the cancel or already disconnected.
if not cancel_event.is_set():
+ api_monitor.fail(monitor_id, "Stream interrupted")
raise
+ api_monitor.finish(monitor_id, "cancelled")
except Exception as e:
if cancel_event.is_set():
+ api_monitor.finish(monitor_id, "cancelled")
return
# 200 headers already flushed; errors must go in the SSE body.
logger.error("openai passthrough stream error: %s", e)
+ api_monitor.fail(monitor_id, _friendly_error(e))
err = _openai_stream_error_chunk(e)
yield f"data: {json.dumps(err)}\n\n"
finally:
@@ -8294,7 +9171,12 @@ async def _openai_passthrough_stream(
raise
-async def _openai_passthrough_non_streaming(llama_backend, payload, model_name):
+async def _openai_passthrough_non_streaming(
+ llama_backend,
+ payload,
+ model_name,
+ monitor_id: Optional[str] = None,
+):
"""Non-streaming client-side pass-through for /v1/chat/completions.
Returns llama-server's JSON response verbatim so the client sees the native
@@ -8317,11 +9199,15 @@ async def _openai_passthrough_non_streaming(llama_backend, payload, model_name):
json = body,
timeout = _llama_non_streaming_generation_timeout(),
)
+ except asyncio.CancelledError:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
except httpx.RequestError as e:
# llama-server subprocess crashed / starting / unreachable. Surface the
# same friendly message the sync chat path emits so operators don't see
# a bare 500 with no diagnostic.
logger.error("openai passthrough non-streaming: upstream unreachable: %s", e)
+ api_monitor.fail(monitor_id, _friendly_error(e))
raise HTTPException(
status_code = 502,
detail = _friendly_error(e),
@@ -8337,6 +9223,7 @@ async def _openai_passthrough_non_streaming(llama_backend, payload, model_name):
):
_truncate_budget -= 1
continue
+ api_monitor.fail(monitor_id, resp.text[:500])
raise _openai_passthrough_error(resp.status_code, resp.text)
# The guided-decoding fence wraps each choice's JSON content in a
@@ -8357,6 +9244,7 @@ async def _openai_passthrough_non_streaming(llama_backend, payload, model_name):
"openai passthrough non-streaming: response not JSON, relaying raw: %s",
exc,
)
+ api_monitor.finish(monitor_id)
return Response(content = resp.content, media_type = "application/json")
changed = False
@@ -8394,5 +9282,9 @@ async def _openai_passthrough_non_streaming(llama_backend, payload, model_name):
# Nothing mutated: relay the upstream bytes verbatim, skipping a redundant
# parse + re-serialize round-trip.
if not changed:
+ _monitor_openai_chunk(monitor_id, data, llama_backend.context_length)
+ api_monitor.finish(monitor_id)
return Response(content = resp.content, media_type = "application/json")
+ _monitor_openai_chunk(monitor_id, data, llama_backend.context_length)
+ api_monitor.finish(monitor_id)
return JSONResponse(content = data)
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index 0ed8de55320..92a87ce0459 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -33,6 +33,7 @@ from core.inference.anthropic_compat import (
AnthropicStreamEmitter,
AnthropicPassthroughEmitter,
)
+from core.inference.api_monitor import ApiMonitor
from routes.inference import (
_build_tool_action_nudge,
_normalize_anthropic_openai_images,
@@ -40,6 +41,7 @@ from routes.inference import (
_anthropic_requested_studio_tools,
_anthropic_passthrough_stream,
_anthropic_tool_non_streaming,
+ _monitor_anthropic_sse_line,
anthropic_messages,
)
from state.tool_policy import reset_tool_policy, set_tool_policy
@@ -50,6 +52,46 @@ from io import BytesIO as _BytesIO
from types import SimpleNamespace
+def test_streamed_anthropic_tool_use_records_api_monitor_reply(monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/messages",
+ method = "POST",
+ model = "m",
+ prompt = "hi",
+ )
+
+ for payload in (
+ {
+ "type": "content_block_start",
+ "index": 0,
+ "content_block": {
+ "type": "tool_use",
+ "id": "toolu_1",
+ "name": "lookup",
+ "input": {},
+ },
+ },
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {
+ "type": "input_json_delta",
+ "partial_json": '{"query":"weather"}',
+ },
+ },
+ {"type": "content_block_stop", "index": 0},
+ ):
+ _monitor_anthropic_sse_line(monitor_id, f"data: {json.dumps(payload)}")
+
+ entry = monitor.get(monitor_id)
+ assert entry is not None
+ assert entry["reply"] == 'Tool call: lookup\nInput: {"query":"weather"}'
+
+
# =====================================================================
# Tool nudge tests
# =====================================================================
@@ -1385,7 +1427,7 @@ def _mock_backend(monkeypatch, **overrides):
def _gen_plain(**kwargs):
calls.append(("plain", kwargs))
- yield {"type": "content", "text": "ok"}
+ yield "ok"
def _gen_tools(**kwargs):
calls.append(("tools", kwargs))
@@ -1396,6 +1438,8 @@ def _mock_backend(monkeypatch, **overrides):
is_vision = False,
supports_tools = True,
model_identifier = "test-model",
+ context_length = 4096,
+ count_chat_tokens = lambda *args, **kwargs: 2,
generate_chat_completion = _gen_plain,
generate_chat_completion_with_tools = _gen_tools,
calls = calls,
@@ -1426,6 +1470,112 @@ def _reset_policy():
class TestAnthropicMessagesToolRouting:
+ class _Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/messages")
+ method = "POST"
+
+ async def is_disconnected(self):
+ return False
+
+ @staticmethod
+ def _consume_response(response):
+ async def _consume():
+ chunks = []
+ async for chunk in response.body_iterator:
+ chunks.append(chunk)
+ return chunks
+
+ return _drive(_consume())
+
+ def test_plain_non_streaming_records_api_monitor_entry(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ _mock_backend(monkeypatch, context_length = 2048)
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ payload = _basic_payload()
+
+ response = _drive(anthropic_messages(payload, request = self._Request(), current_subject = "t"))
+
+ assert response.status_code == 200
+ [entry] = monitor.snapshot()
+ assert entry["endpoint"] == "/v1/messages"
+ assert entry["status"] == "completed"
+ assert entry["model"] == "test-model"
+ assert entry["prompt_preview"] == "user: hi"
+ assert entry["reply_preview"] == "ok"
+ assert entry["context_length"] == 2048
+ assert monitor.active_count() == 0
+
+ def test_tool_use_non_streaming_records_api_monitor_reply(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ def _gen_tools(**_kwargs):
+ yield {
+ "type": "tool_start",
+ "tool_call_id": "call_1",
+ "tool_name": "lookup",
+ "arguments": {"query": "weather"},
+ }
+
+ _mock_backend(
+ monkeypatch,
+ context_length = 2048,
+ generate_chat_completion_with_tools = _gen_tools,
+ )
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ payload = _basic_payload(
+ enable_tools = True,
+ tools = [{"type": "web_search_20250305", "name": "web_search"}],
+ )
+
+ response = _drive(anthropic_messages(payload, request = self._Request(), current_subject = "t"))
+
+ assert response.status_code == 200
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply_preview"] == 'Tool call: lookup({"query": "weather"})'
+
+ def test_plain_streaming_records_active_and_completed_monitor_entry(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ _mock_backend(monkeypatch, context_length = 2048)
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ payload = _basic_payload(stream = True)
+
+ response = _drive(anthropic_messages(payload, request = self._Request(), current_subject = "t"))
+
+ assert monitor.active_count() == 1
+ self._consume_response(response)
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply_preview"] == "ok"
+ assert entry["prompt_tokens"] == 2
+ assert entry["context_length"] == 2048
+ assert monitor.active_count() == 0
+
+ def test_plain_streaming_pre_response_cancel_finalizes_monitor(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ async def _cancelled_before_response(*_args, **_kwargs):
+ raise asyncio.CancelledError()
+
+ _mock_backend(monkeypatch, context_length = 2048)
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "_anthropic_plain_stream", _cancelled_before_response)
+ payload = _basic_payload(stream = True)
+
+ with pytest.raises(asyncio.CancelledError):
+ _drive(anthropic_messages(payload, request = self._Request(), current_subject = "t"))
+
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert monitor.active_count() == 0
+
def test_mixed_server_and_client_tools_rejected_with_400(self, monkeypatch):
_mock_backend(monkeypatch)
payload = _basic_payload(
diff --git a/studio/backend/tests/test_api_monitor.py b/studio/backend/tests/test_api_monitor.py
new file mode 100644
index 00000000000..f0943cd76c1
--- /dev/null
+++ b/studio/backend/tests/test_api_monitor.py
@@ -0,0 +1,222 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from core.inference.api_monitor import ApiMonitor, _trim
+
+
+def test_api_monitor_tracks_reply_usage_and_context():
+ monitor = ApiMonitor(max_entries = 3)
+
+ entry_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "local-model",
+ prompt = "user: hello",
+ context_length = 100,
+ )
+ monitor.append_reply(entry_id, "hi")
+ monitor.append_reply(entry_id, " there")
+ monitor.set_usage(
+ entry_id,
+ prompt_tokens = 4,
+ completion_tokens = 6,
+ )
+ monitor.finish(entry_id)
+
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply"] == "hi there"
+ assert entry["total_tokens"] == 10
+ assert entry["context_usage"] == 0.1
+ assert entry["duration_ms"] is not None
+
+
+def test_api_monitor_summary_omits_full_prompt_and_reply():
+ monitor = ApiMonitor(max_entries = 3)
+ entry_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "local-model",
+ prompt = "p" * 500,
+ )
+ monitor.set_reply(entry_id, "r" * 500)
+
+ [summary] = monitor.snapshot(include_details = False)
+ assert "prompt" not in summary
+ assert "reply" not in summary
+ assert summary["prompt_preview"].endswith("...")
+ assert summary["reply_preview"].endswith("...")
+ assert summary["prompt_truncated"] is True
+ assert summary["reply_truncated"] is True
+
+ detail = monitor.get(entry_id)
+ assert detail is not None
+ assert detail["prompt"] == "p" * 500
+ assert detail["reply"] == "r" * 500
+
+
+def test_api_monitor_filters_entries_by_subject():
+ monitor = ApiMonitor(max_entries = 3)
+ alice = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "alice prompt",
+ subject = "alice",
+ )
+ bob = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "bob prompt",
+ subject = "bob",
+ )
+ monitor.finish(bob)
+
+ alice_entries = monitor.snapshot(subject = "alice")
+ assert [entry["id"] for entry in alice_entries] == [alice]
+ assert monitor.get(bob, subject = "alice") is None
+ assert monitor.get(bob, subject = "bob")["id"] == bob
+ assert monitor.active_count(subject = "alice") == 1
+ assert monitor.active_count(subject = "bob") == 0
+
+
+def test_api_monitor_keeps_bounded_recent_history():
+ monitor = ApiMonitor(max_entries = 2)
+
+ first = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "first",
+ )
+ second = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "second",
+ )
+ third = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "third",
+ )
+ monitor.finish(first)
+ monitor.finish(second)
+ monitor.finish(third)
+
+ entries = monitor.snapshot()
+ ids = [entry["id"] for entry in entries]
+ assert ids[0] == third
+ assert [entry["prompt"] for entry in entries] == ["third", "second"]
+ assert first not in ids
+ assert monitor.active_count() == 0
+
+
+def test_api_monitor_keeps_running_entries_beyond_history_limit():
+ monitor = ApiMonitor(max_entries = 1)
+
+ running = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "running",
+ )
+ for prompt in ("done-1", "done-2", "done-3"):
+ entry_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = prompt,
+ )
+ monitor.finish(entry_id)
+
+ entries = monitor.snapshot()
+ ids = [entry["id"] for entry in entries]
+ assert running in ids
+ assert monitor.active_count() == 1
+
+ monitor.finish(running)
+ [entry] = monitor.snapshot()
+ assert entry["id"] == running
+ assert entry["status"] == "completed"
+ assert monitor.active_count() == 0
+
+
+def test_api_monitor_finish_is_idempotent():
+ monitor = ApiMonitor(max_entries = 2)
+ entry_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "hi",
+ )
+ monitor.finish(entry_id)
+ first = monitor.snapshot()[0]
+ monitor.finish(entry_id)
+ second = monitor.snapshot()[0]
+ assert first["finished_at"] == second["finished_at"]
+ assert first["duration_ms"] == second["duration_ms"]
+
+
+def test_api_monitor_preserves_authoritative_total_tokens():
+ monitor = ApiMonitor(max_entries = 2)
+ entry_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "hi",
+ )
+ monitor.set_usage(
+ entry_id,
+ prompt_tokens = 10,
+ completion_tokens = 20,
+ total_tokens = 33,
+ )
+ # A later partial chunk omitting `total_tokens` must not clobber 33.
+ monitor.set_usage(entry_id, prompt_tokens = 11)
+ assert monitor.snapshot()[0]["total_tokens"] == 33
+
+
+def test_api_monitor_recomputes_derived_total_tokens():
+ monitor = ApiMonitor(max_entries = 2)
+ entry_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "m",
+ prompt = "hi",
+ )
+ monitor.set_usage(entry_id, prompt_tokens = 10)
+ assert monitor.snapshot()[0]["total_tokens"] == 10
+
+ monitor.set_usage(entry_id, completion_tokens = 20)
+ entry = monitor.snapshot()[0]
+ assert entry["prompt_tokens"] == 10
+ assert entry["completion_tokens"] == 20
+ assert entry["total_tokens"] == 30
+
+
+def test_api_monitor_duration_non_negative_under_clock_step(monkeypatch):
+ import core.inference.api_monitor as m
+
+ fake_now = [1000.0]
+ monkeypatch.setattr(m.time, "time", lambda: fake_now[0])
+ monitor = ApiMonitor(max_entries = 1)
+ entry_id = monitor.start(
+ endpoint = "/x",
+ method = "POST",
+ model = "m",
+ prompt = "hi",
+ )
+ fake_now[0] = 500.0
+ monitor.finish(entry_id)
+ assert monitor.snapshot()[0]["duration_ms"] >= 0
+
+
+def test_api_monitor_trim_guards_tiny_limit():
+ assert _trim("abcdefgh", 2) == ".."
+ assert _trim("abcdefgh", 0) == ""
+ assert _trim("abcdefgh", 3) == "..."
+ assert _trim("abcdefgh", 4) == "a..."
+ assert _trim("abcdefgh", 100) == "abcdefgh"
diff --git a/studio/backend/tests/test_offline_gguf_cache_fallback.py b/studio/backend/tests/test_offline_gguf_cache_fallback.py
index c00e98ad7e3..a2a505f4798 100644
--- a/studio/backend/tests/test_offline_gguf_cache_fallback.py
+++ b/studio/backend/tests/test_offline_gguf_cache_fallback.py
@@ -209,10 +209,10 @@ class TestGgufVariantFileResolution:
return [_types.SimpleNamespace(path = path, size = 1) for path in paths if path is not None]
def fake_download(
- *,
repo_id,
filename,
token = None,
+ **_kwargs,
):
downloaded.append(filename)
return f"/fake/{repo_id}/{filename}"
@@ -229,7 +229,7 @@ class TestGgufVariantFileResolution:
),
patch("huggingface_hub.get_paths_info", fake_get_paths_info),
patch("huggingface_hub.try_to_load_from_cache", lambda *_a, **_k: None),
- patch("huggingface_hub.hf_hub_download", fake_download),
+ patch("core.inference.llama_cpp.hf_hub_download_with_xet_fallback", fake_download),
):
out = backend._download_gguf(
hf_repo = "ggml-org/models",
@@ -256,10 +256,10 @@ class TestGgufVariantFileResolution:
return [_types.SimpleNamespace(path = path, size = 1) for path in paths if path is not None]
def fake_download(
- *,
repo_id,
filename,
token = None,
+ **_kwargs,
):
downloaded.append(filename)
return f"/fake/{repo_id}/{filename}"
@@ -269,7 +269,7 @@ class TestGgufVariantFileResolution:
patch("huggingface_hub.list_repo_files", lambda *_a, **_k: files),
patch("huggingface_hub.get_paths_info", fake_get_paths_info),
patch("huggingface_hub.try_to_load_from_cache", lambda *_a, **_k: None),
- patch("huggingface_hub.hf_hub_download", fake_download),
+ patch("core.inference.llama_cpp.hf_hub_download_with_xet_fallback", fake_download),
):
out = backend._download_gguf(
hf_repo = "org/repo",
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index b2b22f89347..8442d05cdc6 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -7,6 +7,7 @@ import os
import sys
import asyncio
import json
+import threading
from types import SimpleNamespace
_backend = os.path.join(os.path.dirname(__file__), "..")
@@ -27,20 +28,29 @@ from models.inference import (
from core.inference.anthropic_compat import (
anthropic_tool_choice_to_openai,
)
+from core.inference.api_monitor import ApiMonitor
from routes.inference import (
_build_chat_request,
_build_openai_passthrough_body,
_build_passthrough_payload,
_clamp_finish_reason,
+ _cmpl_stream_event_out,
_coalesce_consecutive_user_turns,
_drop_empty_assistant_sentinels,
_effective_max_tokens,
_extract_content_parts,
_friendly_error,
_merge_user_content,
+ _monitor_openai_chunk,
+ _monitor_openai_sse_event,
_openai_messages_for_gguf_chat,
+ _openai_passthrough_non_streaming,
+ _openai_passthrough_stream,
_openai_stream_usage_chunk,
+ _proxy_to_external_provider,
_set_or_prepend_system_message,
+ openai_completions,
+ openai_embeddings,
openai_chat_completions,
)
from state.tool_policy import reset_tool_policy
@@ -325,7 +335,8 @@ class TestChatCompletionRequestToolFields:
captured = {}
- async def _fake_proxy(payload, request):
+ async def _fake_proxy(payload, request, current_subject):
+ assert current_subject == "test-user"
captured["stream"] = payload.stream
return JSONResponse({"choices": [], "object": "chat.completion"})
@@ -460,6 +471,7 @@ class TestChatCompletionRequestToolFields:
supports_tools = False
is_vision = False
_is_audio = False
+ context_length = 4096
client = self._v1_client(monkeypatch, _GGUFBackend())
resp = client.post(
@@ -473,13 +485,18 @@ class TestChatCompletionRequestToolFields:
self._assert_unsupported_n(resp)
def test_n_rejected_for_gguf_tools_passthrough_path(self, monkeypatch):
+ import routes.inference as inference_route
+
class _GGUFBackend:
is_loaded = True
model_identifier = "test-gguf"
supports_tools = True
is_vision = False
_is_audio = False
+ context_length = 4096
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
client = self._v1_client(monkeypatch, _GGUFBackend())
resp = client.post(
"/v1/chat/completions",
@@ -498,6 +515,10 @@ class TestChatCompletionRequestToolFields:
},
)
self._assert_unsupported_n(resp)
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "error"
+ assert "n > 1 is not supported" in entry["error"]
+ assert monitor.active_count() == 0
def test_n_rejected_for_non_gguf_path(self, monkeypatch):
class _NoGGUFBackend:
@@ -540,6 +561,8 @@ class TestChatCompletionRequestToolFields:
"_detect_safetensors_features",
lambda backend, chat_template: {"supports_tools": True},
)
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inference_route, "api_monitor", monitor)
client = self._v1_client(monkeypatch, _NoGGUFBackend(), _InferenceBackend())
resp = client.post(
"/v1/chat/completions",
@@ -556,6 +579,10 @@ class TestChatCompletionRequestToolFields:
body = resp.json()
assert body["error"]["param"] == "confirm_tool_calls"
assert "requires stream=true" in body["error"]["message"]
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "error"
+ assert "confirm_tool_calls requires stream=true" in entry["error"]
+ assert monitor.active_count() == 0
def test_multiturn_tool_loop_messages(self):
req = ChatCompletionRequest(
@@ -887,6 +914,35 @@ class TestOpenAICompatibilityHelpers:
assert usage["completion_tokens"] == 7
assert usage["total_tokens"] == 7
+ def test_completion_stream_monitor_reads_usage_before_client_strip(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/completions",
+ method = "POST",
+ model = "m",
+ prompt = "hi",
+ context_length = 100,
+ )
+ event = (
+ b'data: {"id":"chatcmpl-test","choices":[{"text":"done","finish_reason":"stop"}],'
+ b'"usage":{"prompt_tokens":4,"completion_tokens":6,"total_tokens":10}}\n'
+ )
+
+ _monitor_openai_sse_event(monitor_id, event, context_length = 100)
+ out = _cmpl_stream_event_out(event, include_usage = False)
+
+ assert out is not None
+ assert b'"usage"' not in out
+ [entry] = monitor.snapshot()
+ assert entry["reply"] == "done"
+ assert entry["prompt_tokens"] == 4
+ assert entry["completion_tokens"] == 6
+ assert entry["total_tokens"] == 10
+ assert entry["context_usage"] == 0.1
+
def test_developer_message_preserves_existing_system_prompt(self):
payload = ChatCompletionRequest(
messages = [
@@ -1168,6 +1224,10 @@ class TestGgufVisionMessages:
class TestGgufVisionToolRouting:
class _Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/chat/completions")
+ method = "POST"
+
async def is_disconnected(self):
return False
@@ -1203,9 +1263,12 @@ class TestGgufVisionToolRouting:
is_vision = True,
supports_tools = True,
model_identifier = "gemma-4-12b-it-GGUF",
+ context_length = 4096,
generate_chat_completion = _plain,
generate_chat_completion_with_tools = _tools,
)
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)
payload = ChatCompletionRequest(
@@ -1258,9 +1321,12 @@ class TestGgufVisionToolRouting:
is_vision = False,
supports_tools = True,
model_identifier = "test-gguf",
+ context_length = 4096,
generate_chat_completion = _plain,
generate_chat_completion_with_tools = _tools,
)
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)
payload = ChatCompletionRequest(
@@ -1292,10 +1358,13 @@ class TestGgufVisionToolRouting:
is_vision = False,
supports_tools = True,
model_identifier = "test-gguf",
+ context_length = 4096,
generate_chat_completion = _plain,
generate_chat_completion_with_tools = _tools,
)
monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
payload = ChatCompletionRequest(
model = "default",
@@ -1316,6 +1385,62 @@ class TestGgufVisionToolRouting:
)
assert exc.value.status_code == 400
assert "requires stream=true" in exc.value.detail["error"]["message"]
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "error"
+ assert "confirm_tool_calls requires stream=true" in entry["error"]
+ assert monitor.active_count() == 0
+
+ def test_non_streaming_gguf_n_records_all_monitor_replies(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ calls = {"count": 0}
+
+ def _generate(**_kwargs):
+ calls["count"] += 1
+ text = f"reply {calls['count']}"
+ yield text
+ yield {
+ "type": "metadata",
+ "usage": {
+ "prompt_tokens": 3,
+ "completion_tokens": calls["count"],
+ "total_tokens": 3 + calls["count"],
+ },
+ }
+
+ backend = SimpleNamespace(
+ is_loaded = True,
+ is_vision = False,
+ supports_tools = False,
+ _is_audio = False,
+ model_identifier = "test-gguf",
+ context_length = 4096,
+ generate_chat_completion = _generate,
+ )
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)
+
+ payload = ChatCompletionRequest(
+ model = "default",
+ n = 2,
+ messages = [{"role": "user", "content": "two please"}],
+ )
+
+ response = self._drive(
+ openai_chat_completions(
+ payload,
+ request = self._Request(),
+ current_subject = "test",
+ )
+ )
+ body = json.loads(response.body)
+
+ assert [c["message"]["content"] for c in body["choices"]] == ["reply 1", "reply 2"]
+ [entry] = monitor.snapshot()
+ assert entry["reply"] == "Choice 1:\nreply 1\n\nChoice 2:\nreply 2"
+ assert entry["completion_tokens"] == 3
+ assert monitor.active_count() == 0
def test_standard_gguf_merges_system_and_developer_messages(self, monkeypatch):
import routes.inference as inf_mod
@@ -1336,6 +1461,7 @@ class TestGgufVisionToolRouting:
is_vision = False,
supports_tools = False,
model_identifier = "test-gguf",
+ context_length = 4096,
generate_chat_completion = _generate,
)
monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)
@@ -1369,6 +1495,8 @@ class TestGgufVisionToolRouting:
import routes.inference as inf_mod
seen_seeds = []
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
def _generate(**kwargs):
seen_seeds.append(kwargs.get("seed"))
@@ -1388,6 +1516,7 @@ class TestGgufVisionToolRouting:
is_vision = False,
supports_tools = False,
model_identifier = "test-gguf",
+ context_length = 4096,
generate_chat_completion = _generate,
)
monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)
@@ -1406,6 +1535,1081 @@ class TestGgufVisionToolRouting:
assert seen_seeds == expected
assert [choice["index"] for choice in body["choices"]] == [0, 1, 2]
+ assert body["usage"]["prompt_tokens"] == 5
+ assert body["usage"]["completion_tokens"] == 21
+ [entry] = monitor.snapshot()
+ assert entry["prompt_tokens"] == 5
+ assert entry["completion_tokens"] == 21
+ assert entry["total_tokens"] == 26
+
+
+class TestApiMonitorProviderAndCompletionStreams:
+ class _Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/chat/completions")
+ method = "POST"
+
+ async def is_disconnected(self):
+ return False
+
+ def test_external_non_streaming_json_updates_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class DummyExternalClient:
+ def __init__(self, **_kwargs):
+ pass
+
+ async def stream_chat_completion(self, **kwargs):
+ assert kwargs["stream"] is False
+ yield json.dumps(
+ {
+ "choices": [{"message": {"content": "provider [DONE] reply"}}],
+ "usage": {
+ "prompt_tokens": 3,
+ "completion_tokens": 4,
+ "total_tokens": 7,
+ },
+ }
+ )
+
+ async def close(self):
+ pass
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "ExternalProviderClient", DummyExternalClient)
+ payload = ChatCompletionRequest(
+ model = "default",
+ external_model = "gpt-test",
+ provider_type = "openai",
+ provider_base_url = "https://api.openai.com/v1",
+ messages = [ChatMessage(role = "user", content = "hi")],
+ )
+
+ response = await _proxy_to_external_provider(payload, self._Request())
+ chunks = []
+ async for chunk in response.body_iterator:
+ chunks.append(chunk)
+
+ assert chunks[-1] == "data: [DONE]\n\n"
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply"] == "provider [DONE] reply"
+ assert entry["prompt_tokens"] == 3
+ assert entry["completion_tokens"] == 4
+ assert entry["total_tokens"] == 7
+
+ asyncio.run(_run())
+
+ def test_external_stream_cancel_finalizes_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class DummyExternalClient:
+ def __init__(self, **_kwargs):
+ pass
+
+ async def stream_chat_completion(self, **_kwargs):
+ yield 'data: {"choices":[{"delta":{"content":"hello"}}]}'
+ await asyncio.sleep(3600)
+
+ async def close(self):
+ pass
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "ExternalProviderClient", DummyExternalClient)
+ payload = ChatCompletionRequest(
+ model = "default",
+ external_model = "gpt-test",
+ provider_type = "openai",
+ provider_base_url = "https://api.openai.com/v1",
+ messages = [ChatMessage(role = "user", content = "hi")],
+ stream = True,
+ )
+
+ response = await _proxy_to_external_provider(payload, self._Request())
+ iterator = response.body_iterator
+ first = await anext(iterator)
+ assert "hello" in first
+
+ pending = asyncio.create_task(anext(iterator))
+ await asyncio.sleep(0)
+ pending.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await pending
+
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert entry["reply"] == "hello"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_completions_preheader_cancel_finalizes_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/completions")
+ method = "POST"
+
+ async def json(self):
+ return {"prompt": "hi", "stream": True}
+
+ async def is_disconnected(self):
+ return False
+
+ async def fake_send(*_args, **_kwargs):
+ return None
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = True,
+ base_url = "http://llama.test",
+ context_length = 4096,
+ model_identifier = "gguf",
+ ),
+ )
+ monkeypatch.setattr(inf_mod, "_send_stream_with_preheader_cancel", fake_send)
+
+ response = await openai_completions(Request(), current_subject = "test")
+ chunks = []
+ async for chunk in response.body_iterator:
+ chunks.append(chunk)
+
+ assert chunks == []
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_completions_stream_cancel_finalizes_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/completions")
+ method = "POST"
+
+ async def json(self):
+ return {"prompt": "hi", "stream": True}
+
+ async def is_disconnected(self):
+ return False
+
+ async def fake_send(*_args, **_kwargs):
+ return httpx.Response(200, content = b"")
+
+ async def fake_items(*_args, **_kwargs):
+ yield b'data: {"choices":[{"text":"hello"}]}\n\n'
+ await asyncio.sleep(3600)
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = True,
+ base_url = "http://llama.test",
+ context_length = 4096,
+ model_identifier = "gguf",
+ ),
+ )
+ monkeypatch.setattr(inf_mod, "_send_stream_with_preheader_cancel", fake_send)
+ monkeypatch.setattr(inf_mod, "_aiter_llama_stream_items", fake_items)
+
+ response = await openai_completions(Request(), current_subject = "test")
+ iterator = response.body_iterator
+ first = await anext(iterator)
+ assert b"hello" in first
+
+ pending = asyncio.create_task(anext(iterator))
+ await asyncio.sleep(0)
+ pending.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await pending
+
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert entry["reply"] == "hello"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_completions_non_streaming_post_error_finalizes_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/completions")
+ method = "POST"
+
+ async def json(self):
+ return {"prompt": "hi", "stream": False}
+
+ class FailingAsyncClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return False
+
+ async def post(self, *_args, **_kwargs):
+ raise httpx.ConnectError("llama down")
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(
+ inf_mod.httpx,
+ "AsyncClient",
+ lambda *args, **kwargs: FailingAsyncClient(),
+ )
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = True,
+ base_url = "http://llama.test",
+ context_length = 4096,
+ model_identifier = "gguf",
+ ),
+ )
+
+ with pytest.raises(httpx.ConnectError):
+ await openai_completions(Request(), current_subject = "test")
+
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "error"
+ assert "Lost connection to the model server" in entry["error"]
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_monitor_openai_chunk_records_all_choice_replies(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+
+ _monitor_openai_chunk(
+ monitor_id,
+ {
+ "choices": [
+ {"text": "first"},
+ {"text": "second"},
+ ],
+ "usage": {
+ "prompt_tokens": 2,
+ "completion_tokens": 5,
+ "total_tokens": 7,
+ },
+ },
+ 4096,
+ )
+
+ entry = monitor.get(monitor_id)
+ assert entry["reply"] == "Choice 1:\nfirst\n\nChoice 2:\nsecond"
+ assert entry["prompt_tokens"] == 2
+ assert entry["completion_tokens"] == 5
+ assert entry["context_length"] == 4096
+
+ def test_monitor_openai_chunk_records_tool_call_reply(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+
+ _monitor_openai_chunk(
+ monitor_id,
+ {
+ "choices": [
+ {
+ "message": {
+ "tool_calls": [
+ {
+ "type": "function",
+ "function": {
+ "name": "lookup",
+ "arguments": '{"query":"weather"}',
+ },
+ }
+ ]
+ }
+ }
+ ]
+ },
+ 4096,
+ )
+
+ entry = monitor.get(monitor_id)
+ assert entry["reply"] == 'Tool call: lookup({"query":"weather"})'
+
+ def test_embeddings_request_is_counted_active_and_completed(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/embeddings")
+ method = "POST"
+
+ async def json(self):
+ return {"input": ["alpha", "beta"], "model": "embed"}
+
+ class FakeAsyncClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return False
+
+ async def post(self, *_args, **_kwargs):
+ assert monitor.active_count() == 1
+ return httpx.Response(
+ 200,
+ json = {
+ "data": [{"embedding": [0.1]}],
+ "usage": {"prompt_tokens": 4, "total_tokens": 4},
+ },
+ )
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(
+ inf_mod.httpx,
+ "AsyncClient",
+ lambda *args, **kwargs: FakeAsyncClient(),
+ )
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = True,
+ base_url = "http://llama.test",
+ context_length = 4096,
+ model_identifier = "gguf",
+ ),
+ )
+
+ response = await openai_embeddings(Request(), current_subject = "test")
+
+ assert response.status_code == 200
+ [entry] = monitor.snapshot()
+ assert entry["endpoint"] == "/v1/embeddings"
+ assert entry["status"] == "completed"
+ assert entry["prompt_preview"] == "alpha\nbeta"
+ assert entry["prompt_tokens"] == 4
+ assert entry["total_tokens"] == 4
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_passthrough_stream_task_cancel_finalizes_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class Request:
+ async def is_disconnected(self):
+ return False
+
+ async def fake_send(*_args, **_kwargs):
+ return httpx.Response(200, content = b"")
+
+ async def fake_items(*_args, **_kwargs):
+ yield 'data: {"choices":[{"delta":{"content":"hello"}}]}'
+ await asyncio.sleep(3600)
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "_send_stream_with_preheader_cancel", fake_send)
+ monkeypatch.setattr(inf_mod, "_aiter_llama_stream_items", fake_items)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "hi")],
+ stream = True,
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "lookup",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ ],
+ )
+
+ response = await _openai_passthrough_stream(
+ Request(),
+ threading.Event(),
+ SimpleNamespace(
+ base_url = "http://llama.test",
+ context_length = 4096,
+ _request_reasoning_kwargs = lambda *_args, **_kwargs: None,
+ ),
+ payload,
+ "gguf",
+ "chatcmpl-test",
+ monitor_id = monitor_id,
+ )
+ iterator = response.body_iterator
+ first = await anext(iterator)
+ assert "hello" in first
+
+ pending = asyncio.create_task(anext(iterator))
+ await asyncio.sleep(0)
+ pending.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await pending
+
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert entry["reply"] == "hello"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_passthrough_non_streaming_cancel_finalizes_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class CancellingAsyncClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return False
+
+ async def post(self, *_args, **_kwargs):
+ raise asyncio.CancelledError()
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(
+ inf_mod.httpx,
+ "AsyncClient",
+ lambda *args, **kwargs: CancellingAsyncClient(),
+ )
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "hi")],
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "lookup",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ ],
+ )
+
+ with pytest.raises(asyncio.CancelledError):
+ await _openai_passthrough_non_streaming(
+ SimpleNamespace(
+ base_url = "http://llama.test",
+ context_length = 4096,
+ _request_reasoning_kwargs = lambda *_args, **_kwargs: None,
+ ),
+ payload,
+ "gguf",
+ monitor_id = monitor_id,
+ )
+
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_passthrough_clean_eof_finalizes_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class Request:
+ async def is_disconnected(self):
+ return False
+
+ async def fake_send(*_args, **_kwargs):
+ return httpx.Response(200, content = b"")
+
+ async def fake_items(*_args, **_kwargs):
+ yield 'data: {"choices":[{"delta":{"content":"hello"}}]}'
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "_send_stream_with_preheader_cancel", fake_send)
+ monkeypatch.setattr(inf_mod, "_aiter_llama_stream_items", fake_items)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "hi")],
+ stream = True,
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "lookup",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ ],
+ )
+
+ response = await _openai_passthrough_stream(
+ Request(),
+ threading.Event(),
+ SimpleNamespace(
+ base_url = "http://llama.test",
+ context_length = 4096,
+ _request_reasoning_kwargs = lambda *_args, **_kwargs: None,
+ ),
+ payload,
+ "gguf",
+ "chatcmpl-test",
+ monitor_id = monitor_id,
+ )
+ chunks = []
+ async for chunk in response.body_iterator:
+ chunks.append(chunk)
+
+ assert chunks == ['data: {"choices":[{"delta":{"content":"hello"}}]}\n\n']
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply"] == "hello"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+
+class TestApiMonitorSafetensorsUsage:
+ class _Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/chat/completions")
+ method = "POST"
+
+ def test_non_streaming_safetensors_records_usage(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class DummyBackend:
+ active_model_name = "safe-model"
+ models = {"safe-model": {"context_length": 2048}}
+
+ def generate_chat_response(self, *, stats_holder, **_kwargs):
+ stats_holder["stats"] = {
+ "usage": {
+ "prompt_tokens": 8,
+ "completion_tokens": 5,
+ "total_tokens": 13,
+ }
+ }
+ yield "safe reply"
+
+ def reset_generation_state(self):
+ pass
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = False,
+ supports_tools = False,
+ is_vision = False,
+ context_length = None,
+ ),
+ )
+ monkeypatch.setattr(inf_mod, "get_inference_backend", lambda: DummyBackend())
+ monkeypatch.setattr(
+ inf_mod,
+ "_detect_safetensors_features",
+ lambda *_args, **_kwargs: {"supports_tools": False},
+ )
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "hi")],
+ )
+
+ response = await openai_chat_completions(
+ payload,
+ request = self._Request(),
+ current_subject = "test",
+ )
+ body = json.loads(response.body)
+
+ assert body["choices"][0]["message"]["content"] == "safe reply"
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply"] == "safe reply"
+ assert entry["prompt_tokens"] == 8
+ assert entry["completion_tokens"] == 5
+ assert entry["total_tokens"] == 13
+ assert entry["context_length"] == 2048
+
+ asyncio.run(_run())
+
+ def test_non_streaming_safetensors_tool_cancel_records_cancelled(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ reset_tool_policy()
+
+ class DummyBackend:
+ active_model_name = "safe-model"
+ models = {"safe-model": {"context_length": 2048}}
+
+ def generate_chat_response(self, **_kwargs):
+ raise AssertionError("plain safetensors path should not be used")
+
+ def generate_chat_completion_with_tools(
+ self, *, cancel_event, stats_holder, **_kwargs
+ ):
+ stats_holder["stats"] = {
+ "usage": {
+ "prompt_tokens": 8,
+ "completion_tokens": 5,
+ "total_tokens": 13,
+ }
+ }
+ yield {"type": "content", "text": "partial"}
+ cancel_event.set()
+ yield {"type": "content", "text": "ignored"}
+
+ def reset_generation_state(self):
+ pass
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = False,
+ supports_tools = False,
+ is_vision = False,
+ context_length = None,
+ ),
+ )
+ monkeypatch.setattr(inf_mod, "get_inference_backend", lambda: DummyBackend())
+ monkeypatch.setattr(
+ inf_mod,
+ "_detect_safetensors_features",
+ lambda *_args, **_kwargs: {"supports_tools": True},
+ )
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "hi")],
+ enable_tools = True,
+ enabled_tools = ["web_search"],
+ cancel_id = "safe-cancel",
+ )
+
+ response = await openai_chat_completions(
+ payload,
+ request = self._Request(),
+ current_subject = "test",
+ )
+ body = json.loads(response.body)
+
+ assert body["choices"][0]["message"]["content"] == "partial"
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert entry["reply"] == "partial"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_non_streaming_safetensors_tool_task_cancel_finalizes_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ reset_tool_policy()
+ reset_called = False
+
+ class DummyBackend:
+ active_model_name = "safe-model"
+ models = {"safe-model": {"context_length": 2048}}
+
+ def generate_chat_response(self, **_kwargs):
+ raise AssertionError("plain safetensors path should not be used")
+
+ def generate_chat_completion_with_tools(self, **_kwargs):
+ yield {"type": "content", "text": "unused"}
+
+ def reset_generation_state(self):
+ nonlocal reset_called
+ reset_called = True
+
+ async def fake_to_thread(*_args, **_kwargs):
+ raise asyncio.CancelledError()
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod.asyncio, "to_thread", fake_to_thread)
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = False,
+ supports_tools = False,
+ is_vision = False,
+ context_length = None,
+ ),
+ )
+ monkeypatch.setattr(inf_mod, "get_inference_backend", lambda: DummyBackend())
+ monkeypatch.setattr(
+ inf_mod,
+ "_detect_safetensors_features",
+ lambda *_args, **_kwargs: {"supports_tools": True},
+ )
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "hi")],
+ enable_tools = True,
+ enabled_tools = ["web_search"],
+ cancel_id = "safe-cancel",
+ )
+
+ with pytest.raises(asyncio.CancelledError):
+ await openai_chat_completions(
+ payload,
+ request = self._Request(),
+ current_subject = "test",
+ )
+
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert monitor.active_count() == 0
+ assert reset_called is True
+
+ asyncio.run(_run())
+
+
+class TestApiMonitorAudioInput:
+ def _patch_audio_backend(self, monkeypatch, chunks):
+ import routes.inference as inf_mod
+
+ class DummyAudioBackend:
+ active_model_name = "audio-model"
+ models = {
+ "audio-model": {
+ "has_audio_input": True,
+ "audio_type": "audio-input",
+ }
+ }
+
+ def generate_audio_input_response(self, **_kwargs):
+ yield from chunks
+
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(is_loaded = False),
+ )
+ monkeypatch.setattr(
+ inf_mod,
+ "get_inference_backend",
+ lambda: DummyAudioBackend(),
+ )
+ monkeypatch.setattr(
+ inf_mod,
+ "_decode_audio_base64",
+ lambda _payload: object(),
+ )
+ return inf_mod
+
+ def test_audio_input_non_streaming_records_active_monitor(self, monkeypatch):
+ async def _run():
+ inf_mod = self._patch_audio_backend(monkeypatch, ["hello", " world"])
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "describe this audio")],
+ audio_base64 = "ZmFrZQ==",
+ )
+ request = SimpleNamespace(
+ state = SimpleNamespace(),
+ url = SimpleNamespace(path = "/v1/chat/completions"),
+ method = "POST",
+ )
+
+ response = await openai_chat_completions(
+ payload,
+ request = request,
+ current_subject = "test",
+ )
+ body = json.loads(response.body)
+
+ assert body["choices"][0]["message"]["content"] == "hello world"
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply"] == "hello world"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_audio_input_streaming_records_monitor_reply(self, monkeypatch):
+ async def _run():
+ inf_mod = self._patch_audio_backend(monkeypatch, ["hello", " world"])
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+
+ async def is_disconnected():
+ return False
+
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "describe this audio")],
+ audio_base64 = "ZmFrZQ==",
+ stream = True,
+ )
+ request = SimpleNamespace(
+ state = SimpleNamespace(),
+ url = SimpleNamespace(path = "/v1/chat/completions"),
+ method = "POST",
+ is_disconnected = is_disconnected,
+ )
+
+ response = await openai_chat_completions(
+ payload,
+ request = request,
+ current_subject = "test",
+ )
+ chunks = []
+ async for chunk in response.body_iterator:
+ chunks.append(chunk.decode() if isinstance(chunk, bytes) else chunk)
+
+ assert chunks[-1] == "data: [DONE]\n\n"
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply"] == "hello world"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_non_gguf_tts_auto_route_records_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class DummyTtsBackend:
+ active_model_name = "tts-model"
+ models = {
+ "tts-model": {
+ "is_audio": True,
+ "audio_type": "snac",
+ }
+ }
+
+ async def fake_generate_audio(
+ _payload,
+ _request,
+ current_subject = None,
+ ):
+ return inf_mod.JSONResponse(
+ content = {
+ "choices": [
+ {
+ "message": {
+ "content": "[Generated audio]",
+ }
+ }
+ ]
+ }
+ )
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(is_loaded = False),
+ )
+ monkeypatch.setattr(inf_mod, "get_inference_backend", lambda: DummyTtsBackend())
+ monkeypatch.setattr(inf_mod, "generate_audio", fake_generate_audio)
+
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "say hello")],
+ )
+ request = SimpleNamespace(
+ state = SimpleNamespace(),
+ url = SimpleNamespace(path = "/v1/chat/completions"),
+ method = "POST",
+ )
+
+ response = await inf_mod.openai_chat_completions(
+ payload,
+ request = request,
+ current_subject = "test",
+ )
+
+ assert json.loads(response.body)["choices"][0]["message"]["content"] == (
+ "[Generated audio]"
+ )
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["model"] == "tts-model"
+ assert entry["reply"] == "[Generated audio]"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_non_gguf_tts_cancel_finalizes_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class DummyTtsBackend:
+ active_model_name = "tts-model"
+ models = {
+ "tts-model": {
+ "is_audio": True,
+ "audio_type": "snac",
+ }
+ }
+
+ async def fake_generate_audio(
+ _payload,
+ _request,
+ current_subject = None,
+ ):
+ raise asyncio.CancelledError()
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(is_loaded = False),
+ )
+ monkeypatch.setattr(inf_mod, "get_inference_backend", lambda: DummyTtsBackend())
+ monkeypatch.setattr(inf_mod, "generate_audio", fake_generate_audio)
+
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "say hello")],
+ )
+ request = SimpleNamespace(
+ state = SimpleNamespace(),
+ url = SimpleNamespace(path = "/v1/chat/completions"),
+ method = "POST",
+ )
+
+ with pytest.raises(asyncio.CancelledError):
+ await inf_mod.openai_chat_completions(
+ payload,
+ request = request,
+ current_subject = "test",
+ )
+
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert entry["model"] == "tts-model"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_gguf_tts_auto_route_records_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ async def fake_generate_audio(
+ _payload,
+ _request,
+ current_subject = None,
+ ):
+ return inf_mod.JSONResponse(
+ content = {
+ "choices": [
+ {
+ "message": {
+ "content": "[Generated audio]",
+ }
+ }
+ ]
+ }
+ )
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = True,
+ _is_audio = True,
+ model_identifier = "gguf-tts",
+ context_length = 2048,
+ ),
+ )
+ monkeypatch.setattr(inf_mod, "generate_audio", fake_generate_audio)
+
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "say hello")],
+ )
+ request = SimpleNamespace(
+ state = SimpleNamespace(),
+ url = SimpleNamespace(path = "/v1/chat/completions"),
+ method = "POST",
+ )
+
+ await inf_mod.openai_chat_completions(
+ payload,
+ request = request,
+ current_subject = "test",
+ )
+
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["model"] == "gguf-tts"
+ assert entry["context_length"] == 2048
+ assert entry["reply"] == "[Generated audio]"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
# =====================================================================
diff --git a/studio/backend/tests/test_responses_tool_passthrough.py b/studio/backend/tests/test_responses_tool_passthrough.py
index 89155c2dafd..0bea3556686 100644
--- a/studio/backend/tests/test_responses_tool_passthrough.py
+++ b/studio/backend/tests/test_responses_tool_passthrough.py
@@ -40,6 +40,7 @@ from fastapi import HTTPException
from fastapi.responses import JSONResponse
from pydantic import ValidationError
+from core.inference.api_monitor import ApiMonitor
from models.inference import (
ChatMessage,
ResponsesFunctionCallInputItem,
@@ -781,6 +782,129 @@ class TestResponsesNonStreamingAdapter:
assert "<think>" not in body["output"][1]["content"][0]["text"]
assert "</think>" not in body["output"][1]["content"][0]["text"]
+ def test_monitor_records_translated_visible_text(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ async def fake_chat_completions(chat_req, request):
+ assert request.state.skip_api_monitor is True
+ return JSONResponse(
+ content = {
+ "model": "test-model",
+ "choices": [{"message": {"content": "<think>plan</think>answer"}}],
+ "usage": {"prompt_tokens": 2, "completion_tokens": 3},
+ }
+ )
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "openai_chat_completions", fake_chat_completions)
+ payload = ResponsesRequest(input = "hi", reasoning = {"effort": "high"})
+ messages = [ChatMessage(role = "user", content = "hi")]
+ request = SimpleNamespace(
+ state = SimpleNamespace(),
+ url = SimpleNamespace(path = "/v1/responses"),
+ method = "POST",
+ )
+
+ async def run():
+ response = await _responses_non_streaming(payload, messages, request)
+ return json.loads(response.body.decode())
+
+ body = asyncio.run(run())
+
+ assert body["output"][0]["content"] == [{"type": "reasoning_text", "text": "plan"}]
+ assert body["output"][1]["content"][0]["text"] == "answer"
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply"] == "answer"
+ assert entry["prompt_tokens"] == 2
+ assert entry["completion_tokens"] == 3
+ assert request.state.skip_api_monitor is False
+
+ def test_monitor_records_tool_only_reply(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ async def fake_chat_completions(chat_req, request):
+ assert request.state.skip_api_monitor is True
+ return JSONResponse(
+ content = {
+ "model": "test-model",
+ "choices": [
+ {
+ "message": {
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {
+ "name": "lookup",
+ "arguments": '{"query":"weather"}',
+ },
+ }
+ ],
+ }
+ }
+ ],
+ "usage": {"prompt_tokens": 2, "completion_tokens": 3},
+ }
+ )
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "openai_chat_completions", fake_chat_completions)
+ payload = ResponsesRequest(
+ input = "hi",
+ tools = [{"type": "function", "name": "lookup"}],
+ )
+ messages = [ChatMessage(role = "user", content = "hi")]
+ request = SimpleNamespace(
+ state = SimpleNamespace(),
+ url = SimpleNamespace(path = "/v1/responses"),
+ method = "POST",
+ )
+
+ async def run():
+ response = await _responses_non_streaming(payload, messages, request)
+ return json.loads(response.body.decode())
+
+ body = asyncio.run(run())
+
+ assert body["output"][0]["type"] == "function_call"
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply"] == 'Tool call: lookup({"query":"weather"})'
+ assert request.state.skip_api_monitor is False
+
+ def test_cancelled_chat_completion_finalizes_monitor(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ async def fake_chat_completions(chat_req, request):
+ assert request.state.skip_api_monitor is True
+ raise asyncio.CancelledError()
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "openai_chat_completions", fake_chat_completions)
+ payload = ResponsesRequest(input = "hi")
+ messages = [ChatMessage(role = "user", content = "hi")]
+ request = SimpleNamespace(
+ state = SimpleNamespace(),
+ url = SimpleNamespace(path = "/v1/responses"),
+ method = "POST",
+ )
+
+ async def run():
+ with pytest.raises(asyncio.CancelledError):
+ await _responses_non_streaming(payload, messages, request)
+
+ asyncio.run(run())
+
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert monitor.active_count() == 0
+ assert request.state.skip_api_monitor is False
+
def test_literal_think_tags_remain_visible_without_reasoning_request(self, monkeypatch):
body = self._run_with_message(monkeypatch, {"content": "show <think>x</think> tags"})
@@ -939,6 +1063,275 @@ class TestResponsesStreamAdapter:
assert completed["response"]["output"][0]["content"][0]["text"] == "plan"
assert completed["response"]["output"][1]["content"][0]["text"] == "33"
+ def test_usage_only_chunk_updates_monitor(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ chunks = [
+ {"choices": [{"delta": {"content": "33"}}]},
+ {"choices": [], "usage": {"prompt_tokens": 2, "completion_tokens": 3}},
+ ]
+ 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["status"] == "completed"
+ assert entry["reply"] == "33"
+ assert entry["prompt_tokens"] == 2
+ assert entry["completion_tokens"] == 3
+ assert entry["total_tokens"] == 5
+ assert entry["context_length"] == 4096
+
+ def test_function_call_chunk_updates_monitor_reply(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ chunks = [
+ {
+ "choices": [
+ {
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_1",
+ "function": {
+ "name": "lookup",
+ "arguments": '{"query":"weather"}',
+ },
+ }
+ ]
+ }
+ }
+ ]
+ }
+ ]
+ 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)
+
+ lines = asyncio.run(run())
+
+ assert self._payloads(lines, "response.output_item.done")[-1]["item"]["name"] == "lookup"
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply"] == 'Tool call: lookup({"query":"weather"})'
+
+ def test_preheader_cancel_finalizes_monitor(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ self._install_stream_mock(monkeypatch, [])
+ 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",
+ )
+
+ async def fake_send(*_args, **_kwargs):
+ return None
+
+ monkeypatch.setattr(inf_mod, "_send_stream_with_preheader_cancel", fake_send)
+ 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["status"] == "cancelled"
+ assert monitor.active_count() == 0
+
+ def test_stream_task_cancel_finalizes_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ async def fake_send(*_args, **_kwargs):
+ return httpx.Response(200, content = b"")
+
+ async def fake_items(*_args, **_kwargs):
+ yield 'data: {"choices":[{"delta":{"content":"hello"}}]}'
+ await asyncio.sleep(3600)
+
+ self._install_stream_mock(monkeypatch, [])
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "_send_stream_with_preheader_cancel", fake_send)
+ monkeypatch.setattr(inf_mod, "_aiter_llama_stream_items", fake_items)
+ 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")]
+
+ response = await _responses_stream(
+ payload,
+ messages,
+ self._Request(),
+ monitor_id = monitor_id,
+ )
+ iterator = response.body_iterator
+ first = ""
+ for _ in range(8):
+ first = await anext(iterator)
+ if "hello" in first:
+ break
+ else:
+ pytest.fail("stream did not emit text delta")
+
+ pending = asyncio.create_task(anext(iterator))
+ await asyncio.sleep(0)
+ pending.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await pending
+
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert entry["reply"] == "hello"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
+ def test_final_visible_text_updates_monitor(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ class FakeExtractor:
+ def __init__(self, **_kwargs):
+ pass
+
+ def feed(
+ self,
+ _content,
+ _reasoning_content = None,
+ ):
+ return "", ""
+
+ def finish(self):
+ return "", "tail"
+
+ self._install_stream_mock(monkeypatch, [{"choices": [{"delta": {"content": "<tai"}}]}])
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "_ResponsesReasoningExtractor", FakeExtractor)
+ 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)
+
+ lines = asyncio.run(run())
+
+ assert self._payloads(lines, "response.output_text.delta")[-1]["delta"] == "tail"
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply"] == "tail"
+
+ def test_reasoning_only_fallback_updates_monitor(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ class FakeExtractor:
+ def __init__(self, **_kwargs):
+ pass
+
+ def feed(
+ self,
+ _content,
+ _reasoning_content = None,
+ ):
+ return "", ""
+
+ def finish(self):
+ return "plan", ""
+
+ self._install_stream_mock(monkeypatch, [{"choices": [{"delta": {"content": "<think>"}}]}])
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "_ResponsesReasoningExtractor", FakeExtractor)
+ 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)
+
+ lines = asyncio.run(run())
+
+ assert self._payloads(lines, "response.output_text.delta")[-1]["delta"] == "plan"
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply"] == "plan"
+
def test_literal_think_tags_stream_as_visible_text_without_reasoning_request(self, monkeypatch):
chunks = [
{"choices": [{"delta": {"content": "show <thi"}}]},
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 33493ecda04..2d2fa81012c 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -10,7 +10,9 @@ import type {
ThreadRecord,
} from "../types";
import type {
+ ApiMonitorEntry,
AudioGenerationResponse,
+ ApiMonitorResponse,
GgufVariantsResponse,
InferenceStatusResponse,
ListLorasResponse,
@@ -70,6 +72,18 @@ export async function getInferenceStatus(): Promise<InferenceStatusResponse> {
return parseJsonOrThrow<InferenceStatusResponse>(response);
}
+export async function getApiMonitor(): Promise<ApiMonitorResponse> {
+ const response = await authFetch("/api/inference/monitor");
+ return parseJsonOrThrow<ApiMonitorResponse>(response);
+}
+
+export async function getApiMonitorEntry(id: string): Promise<ApiMonitorEntry> {
+ const response = await authFetch(
+ `/api/inference/monitor/${encodeURIComponent(id)}`,
+ );
+ return parseJsonOrThrow<ApiMonitorEntry>(response);
+}
+
export async function loadModel(
payload: LoadModelRequest,
): Promise<LoadModelResponse> {
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index 2f0e30fdcf1..781172fb4f9 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -193,6 +193,38 @@ export interface InferenceStatusResponse {
spec_fallback_reason?: string | null;
}
+export interface ApiMonitorEntry {
+ id: string;
+ endpoint: string;
+ method: string;
+ model: string;
+ prompt?: string;
+ reply?: string;
+ prompt_preview: string;
+ reply_preview: string;
+ prompt_truncated: boolean;
+ reply_truncated: boolean;
+ status: "running" | "completed" | "cancelled" | "error";
+ started_at: number;
+ updated_at: number;
+ finished_at?: number | null;
+ duration_ms?: number | null;
+ context_length?: number | null;
+ context_usage?: number | null;
+ prompt_tokens?: number | null;
+ completion_tokens?: number | null;
+ total_tokens?: number | null;
+ error?: string | null;
+}
+
+export interface ApiMonitorResponse {
+ status: "idle" | "ready" | "generating";
+ active_model?: string | null;
+ context_length?: number | null;
+ active_requests: number;
+ entries: ApiMonitorEntry[];
+}
+
export interface AudioGenerationResponse {
id: string;
object: string;
diff --git a/studio/frontend/src/features/settings/components/api-monitor-console.tsx b/studio/frontend/src/features/settings/components/api-monitor-console.tsx
new file mode 100644
index 00000000000..36d09115aee
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/api-monitor-console.tsx
@@ -0,0 +1,393 @@
+// 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 { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import {
+ ActivityIcon,
+ ChevronDownIcon,
+ CircleIcon,
+ RefreshCwIcon,
+} from "lucide-react";
+import {
+ type ReactElement,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { getApiMonitor, getApiMonitorEntry } from "../../chat/api/chat-api";
+import type { ApiMonitorEntry, ApiMonitorResponse } from "../../chat/types/api";
+
+const API_INFERENCE_PREFIX_RE = /^\/api\/inference/;
+const V1_PREFIX_RE = /^\/v1\//;
+
+function formatTime(value: number): string {
+ return new Date(value * 1000).toLocaleTimeString([], {
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ });
+}
+
+function formatDuration(value?: number | null): string {
+ if (value == null) {
+ return "Running";
+ }
+ if (value < 1000) {
+ return `${value} ms`;
+ }
+ return `${(value / 1000).toFixed(value < 10000 ? 1 : 0)} s`;
+}
+
+function formatTokens(entry: ApiMonitorEntry): string {
+ if (entry.total_tokens != null) {
+ return `${entry.total_tokens.toLocaleString()} tokens`;
+ }
+ if (entry.prompt_tokens != null || entry.completion_tokens != null) {
+ const prompt = entry.prompt_tokens ?? 0;
+ const completion = entry.completion_tokens ?? 0;
+ return `${(prompt + completion).toLocaleString()} tokens`;
+ }
+ return "Tokens pending";
+}
+
+function compactEndpoint(endpoint: string): string {
+ return endpoint
+ .replace(API_INFERENCE_PREFIX_RE, "/api")
+ .replace(V1_PREFIX_RE, "/");
+}
+
+function statusTone(status: ApiMonitorEntry["status"]): string {
+ if (status === "running") {
+ return "text-emerald-500";
+ }
+ if (status === "error") {
+ return "text-destructive";
+ }
+ if (status === "cancelled") {
+ return "text-amber-500";
+ }
+ return "text-muted-foreground";
+}
+
+function UsageBar({ value }: { value?: number | null }): ReactElement | null {
+ if (value == null) {
+ return null;
+ }
+ const pct = Math.max(0, Math.min(100, Math.round(value * 100)));
+ return (
+ <div className="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-muted">
+ <div
+ className="h-full rounded-full bg-primary"
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ );
+}
+
+function MonitorEntry({
+ entry,
+ detail,
+ expanded,
+ loading,
+ onToggle,
+}: {
+ entry: ApiMonitorEntry;
+ detail?: ApiMonitorEntry;
+ expanded: boolean;
+ loading: boolean;
+ onToggle: () => void;
+}): ReactElement {
+ const hasCurrentDetail =
+ detail &&
+ detail.status === entry.status &&
+ detail.updated_at >= entry.updated_at;
+ const prompt = detail?.prompt ?? entry.prompt_preview;
+ const replyText = hasCurrentDetail
+ ? detail.error ?? detail.reply ?? entry.error ?? entry.reply_preview
+ : entry.error ?? entry.reply_preview;
+ const reply = replyText || (entry.status === "running" ? "Waiting..." : "No reply");
+
+ return (
+ <article className="rounded-lg border border-border/70 bg-background">
+ <button
+ type="button"
+ onClick={onToggle}
+ className="flex w-full min-w-0 items-start justify-between gap-3 p-3 text-left"
+ aria-expanded={expanded}
+ >
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-center gap-2">
+ <CircleIcon
+ className={cn("size-2.5 fill-current", statusTone(entry.status))}
+ />
+ <span className="truncate text-xs font-medium">
+ {compactEndpoint(entry.endpoint)}
+ </span>
+ </div>
+ <div className="mt-1 truncate text-[11px] text-muted-foreground">
+ {entry.model}
+ </div>
+ <div className="mt-2 line-clamp-2 whitespace-pre-wrap break-words text-xs text-muted-foreground">
+ {entry.error ||
+ entry.reply_preview ||
+ entry.prompt_preview ||
+ (entry.status === "running" ? "Waiting..." : "No preview")}
+ </div>
+ </div>
+ <div className="flex shrink-0 items-start gap-2 text-right text-[11px] text-muted-foreground">
+ <div>
+ <div>{formatTime(entry.started_at)}</div>
+ <div>{formatDuration(entry.duration_ms)}</div>
+ </div>
+ <ChevronDownIcon
+ className={cn(
+ "mt-0.5 size-3.5 transition-transform",
+ expanded && "rotate-180",
+ )}
+ />
+ </div>
+ </button>
+
+ {expanded ? (
+ <div className="border-t border-border/60 p-3 pt-2">
+ <div className="grid gap-2">
+ <div>
+ <div className="mb-1 flex items-center justify-between gap-2 text-[10px] font-semibold uppercase text-muted-foreground">
+ <span>Prompt</span>
+ {entry.prompt_truncated && !detail ? <span>Preview</span> : null}
+ </div>
+ <pre className="max-h-44 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted/45 p-2 text-xs leading-5">
+ {loading && !detail ? "Loading..." : prompt || "No prompt text"}
+ </pre>
+ </div>
+ <div>
+ <div className="mb-1 flex items-center justify-between gap-2 text-[10px] font-semibold uppercase text-muted-foreground">
+ <span>Reply</span>
+ {entry.reply_truncated && !detail ? <span>Preview</span> : null}
+ </div>
+ <pre className="max-h-44 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted/45 p-2 text-xs leading-5">
+ {loading && !detail ? "Loading..." : reply}
+ </pre>
+ </div>
+ </div>
+
+ <div className="mt-3 text-[11px] text-muted-foreground">
+ {formatTokens(entry)}
+ {entry.context_length ? (
+ <> / {entry.context_length.toLocaleString()} context</>
+ ) : null}
+ <UsageBar value={entry.context_usage} />
+ </div>
+ </div>
+ ) : null}
+ </article>
+ );
+}
+
+export function ApiMonitorConsole(): ReactElement {
+ const [data, setData] = useState<ApiMonitorResponse | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [refreshing, setRefreshing] = useState(false);
+ const [expandedIds, setExpandedIds] = useState<Set<string>>(() => new Set());
+ const [details, setDetails] = useState<Record<string, ApiMonitorEntry>>({});
+ const [loadingDetails, setLoadingDetails] = useState<Set<string>>(
+ () => new Set(),
+ );
+ const loadingDetailsRef = useRef<Set<string>>(new Set());
+ const detailsRef = useRef<Record<string, ApiMonitorEntry>>({});
+
+ const loadMonitor = useCallback(async (): Promise<void> => {
+ setRefreshing(true);
+ try {
+ setData(await getApiMonitor());
+ setError(null);
+ } catch (err: unknown) {
+ setError(err instanceof Error ? err.message : "Monitor unavailable");
+ } finally {
+ setRefreshing(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ let cancelled = false;
+ let timer: number | undefined;
+
+ function schedule(): void {
+ timer = window.setTimeout(poll, 1500);
+ }
+
+ function poll(): void {
+ getApiMonitor()
+ .then((next) => {
+ if (cancelled) {
+ return;
+ }
+ setData(next);
+ setError(null);
+ })
+ .catch((err: unknown) => {
+ if (cancelled) {
+ return;
+ }
+ setError(err instanceof Error ? err.message : "Monitor unavailable");
+ })
+ .finally(() => {
+ if (!cancelled) {
+ schedule();
+ }
+ });
+ }
+
+ poll();
+ return () => {
+ cancelled = true;
+ if (timer !== undefined) {
+ window.clearTimeout(timer);
+ }
+ };
+ }, []);
+
+ const statusLabel = data?.status ?? "idle";
+ const hasActive = (data?.active_requests ?? 0) > 0;
+ const entries = useMemo(() => data?.entries ?? [], [data]);
+ const loadDetail = useCallback(
+ (id: string): void => {
+ if (loadingDetailsRef.current.has(id)) {
+ return;
+ }
+ loadingDetailsRef.current.add(id);
+ setLoadingDetails((prev) => new Set(prev).add(id));
+ getApiMonitorEntry(id)
+ .then((entry) => {
+ setDetails((prev) => {
+ const next = { ...prev, [id]: entry };
+ detailsRef.current = next;
+ return next;
+ });
+ })
+ .catch(() => {
+ setDetails((prev) => {
+ const next = { ...prev };
+ delete next[id];
+ detailsRef.current = next;
+ return next;
+ });
+ })
+ .finally(() => {
+ loadingDetailsRef.current.delete(id);
+ setLoadingDetails((prev) => {
+ const next = new Set(prev);
+ next.delete(id);
+ return next;
+ });
+ });
+ },
+ [],
+ );
+
+ const toggleEntry = useCallback(
+ (entry: ApiMonitorEntry): void => {
+ setExpandedIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(entry.id)) {
+ next.delete(entry.id);
+ } else {
+ next.add(entry.id);
+ loadDetail(entry.id);
+ }
+ return next;
+ });
+ },
+ [loadDetail],
+ );
+
+ useEffect(() => {
+ for (const entry of entries) {
+ if (!expandedIds.has(entry.id)) {
+ continue;
+ }
+ const cached = detailsRef.current[entry.id];
+ if (!cached || cached.status !== entry.status || entry.status === "running") {
+ loadDetail(entry.id);
+ }
+ }
+ }, [entries, expandedIds, loadDetail]);
+
+ return (
+ <section className="flex min-w-0 flex-col rounded-lg border border-border/70 bg-background">
+ <div className="flex min-w-0 items-start justify-between gap-3 border-b border-border/60 px-4 py-3">
+ <div className="flex min-w-0 gap-3">
+ <div className="relative mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md border border-border/70 bg-muted/40">
+ <ActivityIcon className="size-4 text-foreground" />
+ {hasActive ? (
+ <span className="absolute right-1 top-1 size-2 rounded-full bg-emerald-500" />
+ ) : null}
+ </div>
+ <div className="min-w-0">
+ <h2 className="text-sm font-semibold text-foreground">
+ API monitor
+ </h2>
+ <p className="truncate text-xs text-muted-foreground">
+ {data?.active_model ?? "No model loaded"}
+ </p>
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <div className="rounded-full border border-border px-2.5 py-1 text-xs capitalize text-muted-foreground">
+ {statusLabel}
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => void loadMonitor()}
+ disabled={refreshing}
+ >
+ <RefreshCwIcon
+ className={cn("size-3.5", refreshing && "animate-spin")}
+ />
+ Refresh
+ </Button>
+ </div>
+ </div>
+
+ <div className="flex items-center justify-between border-b border-border/60 px-4 py-2 text-xs text-muted-foreground">
+ <span>
+ {(data?.active_requests ?? 0).toLocaleString()} active /{" "}
+ {entries.length.toLocaleString()} recent
+ </span>
+ {data?.context_length ? (
+ <span>{data.context_length.toLocaleString()} context</span>
+ ) : null}
+ </div>
+
+ <div className="max-h-[420px] min-h-24 overflow-y-auto p-3">
+ {error ? (
+ <div className="rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">
+ {error}
+ </div>
+ ) : entries.length === 0 ? (
+ <div className="rounded-lg border border-border/70 p-4 text-sm text-muted-foreground">
+ No API traffic yet
+ </div>
+ ) : (
+ <div className="grid gap-3">
+ {entries.map((entry) => (
+ <MonitorEntry
+ key={entry.id}
+ entry={entry}
+ detail={details[entry.id]}
+ expanded={expandedIds.has(entry.id)}
+ loading={loadingDetails.has(entry.id)}
+ onToggle={() => toggleEntry(entry)}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
index 64f3ef66214..e83ecebfc84 100644
--- a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
@@ -14,6 +14,7 @@ import { translate, useT } from "@/i18n";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useCallback, useEffect, useState } from "react";
import { fetchApiKeys, revokeApiKey, type ApiKey } from "../api/api-keys";
+import { ApiMonitorConsole } from "../components/api-monitor-console";
import { ApiKeyRow } from "../components/api-key-row";
import { CreateKeyForm } from "../components/create-key-form";
import { KeyRevealCard } from "../components/key-reveal-card";
@@ -166,6 +167,8 @@ export function ApiKeysTab() {
)}
</section>
+ <ApiMonitorConsole />
+
<UsageExamples apiKey={revealed} />
<Dialog open={revokeTarget !== null} onOpenChange={(o) => !o && setRevokeTarget(null)}>