Skip to content

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

Studio: simplify the inference backend (#6490)

oobaboogae6b4480832df
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 0d32a7cc384..b6f83b760c8 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -13,7 +13,6 @@ import json
import os
import re
import struct
-import structlog
from loggers import get_logger
import shutil
import signal
@@ -40,15 +39,7 @@ from core.inference.llama_server_args import (
strip_split_mode_only,
)
from core.tool_healing import (
- _TC_END_TAG_RE,
- _TC_FUNC_CLOSE_RE,
- _TC_FUNC_START_RE,
- _TC_JSON_START_RE,
- _TC_PARAM_CLOSE_RE,
- _TC_PARAM_START_RE,
_TOOL_ALL_PATS,
- _TOOL_CLOSED_PATS,
- parse_tool_calls_from_text,
strip_tool_call_markup,
)
from utils.native_path_leases import child_env_without_native_path_secret
@@ -379,6 +370,13 @@ def _period_from_layer_types(layer_types: list) -> Optional[int]:
return None
+def _swa_entry_from_layer_types(lt) -> Optional[object]:
+ """Period int, or per-layer bool mask, from a transformers ``layer_types`` list."""
+ if isinstance(lt, list) and lt:
+ return _period_from_layer_types(lt) or ["full" not in str(t).lower() for t in lt]
+ return None
+
+
def _fetch_swa_entry_from_hf(repo_id: str) -> Optional[object]:
try:
from huggingface_hub import hf_hub_download
@@ -392,10 +390,7 @@ def _fetch_swa_entry_from_hf(repo_id: str) -> Optional[object]:
period = src.get("sliding_window_pattern")
if isinstance(period, int) and period > 0:
return period
- lt = src.get("layer_types")
- if isinstance(lt, list) and lt:
- return _period_from_layer_types(lt) or ["full" not in str(t).lower() for t in lt]
- return None
+ return _swa_entry_from_layer_types(src.get("layer_types"))
def _arch_aliases(arch: str) -> tuple:
@@ -412,10 +407,7 @@ def _swa_entry_from_config_obj(cfg) -> Optional[object]:
period = getattr(src, "sliding_window_pattern", None)
if isinstance(period, int) and period > 0:
return period
- lt = getattr(src, "layer_types", None)
- if isinstance(lt, list) and lt:
- return _period_from_layer_types(lt) or ["full" not in str(t).lower() for t in lt]
- return None
+ return _swa_entry_from_layer_types(getattr(src, "layer_types", None))
_SWA_PATTERN_SOURCE_RE = re.compile(r"sliding_window_pattern\s*(?::\s*[\w\[\], ]*)?\s*=\s*(\d+)")
@@ -581,12 +573,14 @@ def detect_reasoning_flags(
) -> dict:
"""Classify a chat template's reasoning and tool-calling capabilities.
- Returns the same five keys as the GGUF sniffer: ``supports_reasoning``,
- ``reasoning_style`` (``"enable_thinking"`` | ``"reasoning_effort"``),
- ``reasoning_always_on``, ``supports_preserve_thinking``,
- ``supports_tools``. Used by both the llama-server backend at load time
- and the safetensors/transformers paths in ``routes/inference`` so they
- agree on what the frontend sees.
+ Returns the same six keys as the GGUF sniffer: ``supports_reasoning``,
+ ``reasoning_style`` (``"enable_thinking"`` | ``"reasoning_effort"`` |
+ ``"enable_thinking_effort"``), ``reasoning_always_on``,
+ ``reasoning_effort_levels``, ``supports_preserve_thinking``,
+ ``supports_tools``. A falsy ``chat_template`` yields the all-default dict.
+ Used by both the llama-server backend at load time and the
+ safetensors/transformers paths in ``routes/inference`` so they agree on
+ what the frontend sees.
"""
flags = {
"supports_reasoning": False,
@@ -606,7 +600,7 @@ def detect_reasoning_flags(
if ("reasoning_effort" in tpl and "enable_thinking" in tpl)
else []
)
- if "enable_thinking" in tpl and "reasoning_effort" in tpl and effort_levels:
+ if effort_levels:
# GLM-5.2-style: an enable_thinking on/off gate PLUS a reasoning_effort
# level among a discrete set (e.g. 'high' | 'max'). Distinct from
# gpt-oss (reasoning_effort only, no on/off gate) and Qwen
@@ -1374,6 +1368,12 @@ class LlamaCppBackend:
def base_url(self) -> str:
return f"http://127.0.0.1:{self._port}"
+ @property
+ def _auth_headers(self) -> "Optional[dict[str, str]]":
+ """Bearer header matching the --api-key direct-stream mode uses, else
+ None (so unauthenticated llama-server calls don't get a spurious 401)."""
+ return {"Authorization": f"Bearer {self._api_key}"} if self._api_key else None
+
@property
def model_identifier(self) -> Optional[str]:
return self._model_identifier
@@ -1652,6 +1652,30 @@ class LlamaCppBackend:
# ── Binary discovery ──────────────────────────────────────────
+ @staticmethod
+ def _resolved_studio_root_and_is_legacy() -> "tuple[Optional[Path], bool]":
+ """Resolve the Studio install root and classify it as the legacy
+ ~/.unsloth/studio root vs. a custom (env/venv-inferred) root.
+
+ Returns (resolved_root, is_legacy). On any import/resolution failure the
+ root is treated as legacy and resolved_root is None -- callers must read
+ resolved_root only when is_legacy is False. Shared by
+ _find_llama_server_binary (discovery) and _kill_orphaned_servers
+ (cleanup) so the two never disagree on which root is legacy.
+ """
+ try:
+ from utils.paths.storage_roots import studio_root as _sr # noqa: WPS433
+
+ resolved = _sr()
+ legacy_studio = Path.home() / ".unsloth" / "studio"
+ try:
+ is_legacy = resolved.resolve() == legacy_studio.resolve()
+ except (OSError, ValueError):
+ is_legacy = resolved == legacy_studio
+ return (None if is_legacy else resolved), is_legacy
+ except (ImportError, OSError, ValueError):
+ return None, True
+
@staticmethod
def _find_llama_server_binary(*, include_denied: bool = False) -> Optional[str]:
"""
@@ -1738,33 +1762,16 @@ class LlamaCppBackend:
# 2-4. Match installer layout: env-mode -> $STUDIO_HOME/llama.cpp;
# default/HOME-redirect -> ~/.unsloth/llama.cpp (sibling of studio).
legacy_llama = Path.home() / ".unsloth" / "llama.cpp"
- try:
- from utils.paths.storage_roots import studio_root as _sr # noqa: WPS433
-
- _resolved_sr = _sr()
- _legacy_studio = Path.home() / ".unsloth" / "studio"
- try:
- _is_legacy = _resolved_sr.resolve() == _legacy_studio.resolve()
- except (OSError, ValueError):
- _is_legacy = _resolved_sr == _legacy_studio
- if _is_legacy:
- search_roots = [legacy_llama]
- else:
- # _kill_orphaned_servers excludes the legacy root in custom
- # mode; discovery must match so we never spawn a server we
- # then refuse to clean up. UNSLOTH_LLAMA_CPP_PATH (handled
- # earlier) is the explicit way to share a build across roots.
- search_roots = [_resolved_sr / "llama.cpp"]
- except (ImportError, OSError, ValueError):
+ _resolved_sr, _is_legacy = LlamaCppBackend._resolved_studio_root_and_is_legacy()
+ if _is_legacy:
search_roots = [legacy_llama]
- _seen_roots: set[str] = set()
- _unique_roots: list[Path] = []
- for r in search_roots:
- k = str(r)
- if k not in _seen_roots:
- _seen_roots.add(k)
- _unique_roots.append(r)
- for unsloth_home in _unique_roots:
+ else:
+ # _kill_orphaned_servers excludes the legacy root in custom mode;
+ # discovery must match so we never spawn a server we then refuse to
+ # clean up. UNSLOTH_LLAMA_CPP_PATH (handled earlier) is the explicit
+ # way to share a build across roots.
+ search_roots = [_resolved_sr / "llama.cpp"]
+ for unsloth_home in search_roots:
hit, locked = _scan_pinned(_layout_candidates(unsloth_home))
if locked is not None:
return _unavailable(locked)
@@ -1986,6 +1993,36 @@ class LlamaCppBackend:
return total
+ @staticmethod
+ def _resolve_visible_physical_ids() -> Optional[list[int]]:
+ """Physical GPU ids behind the active visibility mask (HIP/ROCR/CUDA on
+ ROCm, CUDA otherwise). None when no mask is set; empty list for an empty
+ mask. Shared by the APU / datacenter / free-memory probes so they agree
+ on the ordinal->physical mapping."""
+ try:
+ import torch
+ is_rocm = getattr(torch.version, "hip", None) is not None
+ except Exception:
+ is_rocm = False
+ if is_rocm:
+ hip_v = os.environ.get("HIP_VISIBLE_DEVICES")
+ rocr_v = os.environ.get("ROCR_VISIBLE_DEVICES")
+ cvd = (
+ hip_v
+ if hip_v is not None
+ else rocr_v
+ if rocr_v is not None
+ else os.environ.get("CUDA_VISIBLE_DEVICES")
+ )
+ else:
+ cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
+ if cvd is None:
+ return None
+ try:
+ return [int(x.strip()) for x in cvd.split(",") if x.strip()]
+ except ValueError:
+ return None
+
@staticmethod
def _amd_apu_wants_unified_memory(gpu_indices = None) -> bool:
"""True only for AMD unified-memory APUs (gfx1150/gfx1151), where
@@ -2002,21 +2039,7 @@ class LlamaCppBackend:
return False
# Map visible ordinal -> physical id via the active ROCm mask (HIP,
# then ROCR, then CUDA), mirroring _get_gpu_memory's ROCm branch.
- physical_ids: Optional[list[int]] = None
- hip_v = os.environ.get("HIP_VISIBLE_DEVICES")
- rocr_v = os.environ.get("ROCR_VISIBLE_DEVICES")
- cvd = (
- hip_v
- if hip_v is not None
- else rocr_v
- if rocr_v is not None
- else os.environ.get("CUDA_VISIBLE_DEVICES")
- )
- if cvd is not None:
- try:
- physical_ids = [int(x.strip()) for x in cvd.split(",") if x.strip()]
- except ValueError:
- physical_ids = None
+ physical_ids = LlamaCppBackend._resolve_visible_physical_ids()
arch_by_id: dict[int, str] = {}
for ordinal in range(torch.cuda.device_count()):
try:
@@ -2068,13 +2091,7 @@ class LlamaCppBackend:
# Mirror _get_gpu_free_memory: map visible ordinal -> physical id via
# CUDA_VISIBLE_DEVICES; unset/unparsable leaves physical id == ordinal.
- physical_ids: Optional[list[int]] = None
- cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
- if cvd is not None:
- try:
- physical_ids = [int(x.strip()) for x in cvd.split(",") if x.strip()]
- except ValueError:
- physical_ids = None
+ physical_ids = LlamaCppBackend._resolve_visible_physical_ids()
pattern = LlamaCppBackend._DATACENTER_GPU_RE
names_by_id: dict[int, str] = {}
@@ -2228,29 +2245,12 @@ class LlamaCppBackend:
# feed these IDs back into the subprocess as CVD, so visible ordinals
# must be translated to physical indices first; otherwise CVD=2,3
# gets rewritten to 0,1 and targets the wrong GPUs.
- physical_ids: Optional[list[int]] = None
# Match utils/hardware/hardware.py::_get_parent_visible_gpu_spec:
# treat an empty mask (HIP_VISIBLE_DEVICES="") as "no GPUs" rather
# than falling through. ``or`` would coerce "" to the wrong source.
- if getattr(torch.version, "hip", None) is not None:
- hip_v = os.environ.get("HIP_VISIBLE_DEVICES")
- rocr_v = os.environ.get("ROCR_VISIBLE_DEVICES")
- cvd = (
- hip_v
- if hip_v is not None
- else rocr_v
- if rocr_v is not None
- else os.environ.get("CUDA_VISIBLE_DEVICES")
- )
- else:
- cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
- if cvd is not None:
- try:
- # Empty mask (CVD="") yields an empty list -> no GPUs,
- # consistent with the nvidia-smi path.
- physical_ids = [int(x.strip()) for x in cvd.split(",") if x.strip()]
- except ValueError:
- physical_ids = None
+ # Empty mask (CVD="") yields an empty list -> no GPUs, consistent
+ # with the nvidia-smi path.
+ physical_ids = LlamaCppBackend._resolve_visible_physical_ids()
gpus = []
for ordinal in range(torch.cuda.device_count()):
free_bytes, total_bytes = torch.cuda.mem_get_info(ordinal)
@@ -2489,8 +2489,7 @@ class LlamaCppBackend:
lib_dirs = []
# WSL: system HIP before the bundle's (which segfaults on /dev/dxg).
- for _wsl_rocm in _wsl_system_rocm_lib_dirs():
- lib_dirs.append(_wsl_rocm)
+ lib_dirs.extend(_wsl_system_rocm_lib_dirs())
if lib_dirs:
env.setdefault("HSA_ENABLE_DXG_DETECTION", "1")
lib_dirs.append(binary_dir)
@@ -2502,33 +2501,8 @@ class LlamaCppBackend:
import glob as _glob
for _nv_pattern in [
- os.path.join(
- sys.prefix,
- "lib",
- "python*",
- "site-packages",
- "nvidia",
- "cu*",
- "lib",
- ),
- os.path.join(
- sys.prefix,
- "lib",
- "python*",
- "site-packages",
- "nvidia",
- "cudnn",
- "lib",
- ),
- os.path.join(
- sys.prefix,
- "lib",
- "python*",
- "site-packages",
- "nvidia",
- "nvjitlink",
- "lib",
- ),
+ os.path.join(sys.prefix, "lib", "python*", "site-packages", "nvidia", _sub, "lib")
+ for _sub in ("cu*", "cudnn", "nvjitlink")
]:
for _nv_dir in _glob.glob(_nv_pattern):
if os.path.isdir(_nv_dir):
@@ -2643,6 +2617,12 @@ class LlamaCppBackend:
return self._n_kv_heads_by_layer[layer_idx]
return fallback
+ def _legacy_head_dim(self) -> int:
+ """Head-dim fallback for GGUFs without explicit key/value dims. Reached
+ only via the legacy branch of _can_estimate_kv(), so _embedding_length
+ is non-None here."""
+ return self._embedding_length // self._n_heads if self._n_heads else 128 # type: ignore[operator]
+
def _estimate_kv_cache_bytes(
self,
n_ctx: int,
@@ -2706,7 +2686,7 @@ class LlamaCppBackend:
n_attn = -(-n_layers // fai) if fai > 0 else n_layers # ceiling division
if key_len is not None and val_len is not None:
return int(n_attn * n_ctx * n_kv * (key_len + val_len) * bpe)
- head_dim = self._embedding_length // self._n_heads if self._n_heads else 128 # type: ignore[operator]
+ head_dim = self._legacy_head_dim()
return int(n_attn * n_ctx * n_kv * 2 * head_dim * bpe)
# Path 3: Sliding window (Gemma 2/3/3n/4, gpt-oss, Cohere2 ...). Pattern
@@ -2773,7 +2753,7 @@ class LlamaCppBackend:
return int(n_layers_kv * n_ctx * n_kv * (key_len + val_len) * bpe)
# Path 5: Legacy fallback (old GGUFs without explicit dimensions)
- head_dim = self._embedding_length // self._n_heads if self._n_heads else 128 # type: ignore[operator]
+ head_dim = self._legacy_head_dim()
return int(2 * n_kv * head_dim * n_layers_kv * n_ctx * bpe)
def _draft_backend_for(self, drafter_path: str) -> Optional["LlamaCppBackend"]:
@@ -3337,8 +3317,8 @@ class LlamaCppBackend:
attr = arch_keys.get(key)
if attr == "n_kv_heads" and val_a is not None:
self._n_kv_heads_by_layer = [int(x) for x in val_a]
- if self._n_kv_heads is None and val_a:
- self._n_kv_heads = max(int(x) for x in val_a)
+ if self._n_kv_heads is None and self._n_kv_heads_by_layer:
+ self._n_kv_heads = max(self._n_kv_heads_by_layer)
elif attr == "sliding_window_pattern" and val_a is not None:
self._sliding_window_pattern = [bool(x) for x in val_a]
sliding_window_pattern_period = None
@@ -3437,8 +3417,6 @@ class LlamaCppBackend:
alongside llama-server. Returns None if neither can be found.
"""
import importlib.util
- import os
- import sys
# Visual-server binary: env override, else next to llama-server or in the
# install's build/bin (where the prebuilt/installer puts it). .exe on Windows.
@@ -3498,8 +3476,6 @@ class LlamaCppBackend:
visual decoder) and wait for health. Presents the same /v1 + /health
interface as llama-server, so the rest of Studio is unchanged.
"""
- import os
-
assets = self._find_diffusion_assets()
if assets is None:
raise RuntimeError(
@@ -3608,9 +3584,8 @@ class LlamaCppBackend:
# (auto-sized to VRAM). Read it back so the UI context bar shows the real budget.
chosen = maxtok
try:
- import re as _re
for _ln in reversed(self._stdout_lines):
- _m = _re.search(r"MAXTOK=(\d+)", _ln)
+ _m = re.search(r"MAXTOK=(\d+)", _ln)
if _m:
chosen = int(_m.group(1))
break
@@ -3802,13 +3777,9 @@ class LlamaCppBackend:
hf_token,
cancel_event = self._cancel_event,
)
- except RuntimeError as e:
- if "Cancelled" in str(e):
- raise
- raise RuntimeError(
- f"Failed to download GGUF file '{gguf_filename}' from {hf_repo}: {e}"
- )
except Exception as e:
+ if isinstance(e, RuntimeError) and "Cancelled" in str(e):
+ raise
raise RuntimeError(
f"Failed to download GGUF file '{gguf_filename}' from {hf_repo}: {e}"
)
@@ -4387,6 +4358,16 @@ class LlamaCppBackend:
out.append(tok)
return out
+ @staticmethod
+ def _redacted_cmd_for_log(cmd: "list[str]") -> "list[str]":
+ """Copy of cmd with the value after --api-key replaced by <redacted>."""
+ out = list(cmd)
+ if "--api-key" in out:
+ ki = out.index("--api-key") + 1
+ if ki < len(out):
+ out[ki] = "<redacted>"
+ return out
+
def _start_llama_process(self, cmd: list[str], env: dict) -> None:
"""Spawn llama-server from cmd and start draining its output.
@@ -4423,12 +4404,7 @@ class LlamaCppBackend:
# Log the argv per attempt (the text-only mmproj retry re-enters here
# with --mmproj stripped), redacting the API key.
- _log_cmd = list(cmd)
- if "--api-key" in _log_cmd:
- _ki = _log_cmd.index("--api-key") + 1
- if _ki < len(_log_cmd):
- _log_cmd[_ki] = "<redacted>"
- logger.info(f"Starting llama-server: {' '.join(_log_cmd)}")
+ logger.info(f"Starting llama-server: {' '.join(self._redacted_cmd_for_log(cmd))}")
self._process = subprocess.Popen(
cmd,
@@ -4541,36 +4517,8 @@ class LlamaCppBackend:
except Exception as exc:
logger.debug("Fast-path audio probe failed: %s", exc)
detected = None
- if detected in ("snac", "bicodec", "dac"):
- with self._lock:
- if not self._healthy:
- return False
- try:
- self.init_audio_codec(detected)
- self._is_audio = True
- self._audio_type = detected
- except Exception as exc:
- logger.warning(
- "Failed to init audio codec '%s': %s",
- detected,
- exc,
- )
- self._audio_probed = False
- return False
- elif detected:
- # csm / whisper / audio_vlm: track type but keep
- # _is_audio False -- GGUF TTS routing only fires for
- # snac/bicodec/dac.
- with self._lock:
- if not self._healthy:
- return False
- self._audio_type = detected
- # Re-derive after a retried probe (_mmproj_has_audio persists).
- from utils.models.model_config import is_audio_input_type
-
- self._has_audio_input = bool(is_audio_input_type(self._audio_type)) or bool(
- self._mmproj_has_audio
- )
+ if not self._apply_detected_audio(detected):
+ return False
if not self._healthy:
return False
return True
@@ -5076,13 +5024,12 @@ class LlamaCppBackend:
)
_pin_fraction = self._GPU_PIN_VRAM_FRACTION - _flat_mtp_reserve
- if tensor_parallel and effective_is_vision:
- logger.info(
- "Tensor parallelism skipped for vision model: "
- "--split-mode tensor is incompatible with --mmproj "
- "in the current llama.cpp build; using layer split."
- )
- tensor_parallel = False
+ def _restore_after_tensor_downgrade():
+ # Tensor mode dropped a quantized KV and stripped the cache
+ # extras (it rejects quantized); layer split supports them, so
+ # restore the original type + extras (minus --split-mode) and
+ # clear the env flag so the layer launch re-emits them.
+ nonlocal cache_type_kv, _cache_type_from_env, extra_args
if _tensor_dropped_cache_type_kv is not None:
cache_type_kv = _tensor_dropped_cache_type_kv
_cache_type_from_env = False
@@ -5092,6 +5039,15 @@ class LlamaCppBackend:
else extra_args
)
+ if tensor_parallel and effective_is_vision:
+ logger.info(
+ "Tensor parallelism skipped for vision model: "
+ "--split-mode tensor is incompatible with --mmproj "
+ "in the current llama.cpp build; using layer split."
+ )
+ tensor_parallel = False
+ _restore_after_tensor_downgrade()
+
# Tensor mode replicates a compute buffer on every GPU, so drop
# GPUs below that reserve from the set up front (gpu_indices
# becomes the CUDA_VISIBLE_DEVICES mask, fully excluding them).
@@ -5130,21 +5086,9 @@ class LlamaCppBackend:
)
tensor_parallel = False
# Layer split supports a quantized KV the tensor attempt
- # dropped; restore it and re-emit it (clear the env flag the
- # tensor re-adoption may have set, so the restored type wins
- # over a stale inherited env on the layer launch).
- if _tensor_dropped_cache_type_kv is not None:
- cache_type_kv = _tensor_dropped_cache_type_kv
- _cache_type_from_env = False
- # Restore the original extras (with the real, possibly
- # asymmetric, --cache-type-k/-v the tensor attempt stripped),
- # then drop the user --split-mode tensor so the downgrade
- # actually applies (extras are appended last).
- extra_args = strip_split_mode_only(
- _tensor_dropped_extra_args
- if _tensor_dropped_extra_args is not None
- else extra_args
- )
+ # dropped; restore the original cache type + extras (minus
+ # --split-mode) so the layer launch re-emits them.
+ _restore_after_tensor_downgrade()
if tensor_parallel and tp_gpus:
# Pooled usable budget (after each device's compute buffer)
@@ -5177,18 +5121,9 @@ class LlamaCppBackend:
"per-device compute buffers; falling back to layer split."
)
tensor_parallel = False
- # Restore the dropped quantized KV (layer split supports
- # it); clear the env flag so the restored type is emitted.
- if _tensor_dropped_cache_type_kv is not None:
- cache_type_kv = _tensor_dropped_cache_type_kv
- _cache_type_from_env = False
- # Restore the original (possibly asymmetric) cache extras
- # too, dropping only the user --split-mode tensor.
- extra_args = strip_split_mode_only(
- _tensor_dropped_extra_args
- if _tensor_dropped_extra_args is not None
- else extra_args
- )
+ # Restore the dropped quantized KV + original cache extras
+ # (minus --split-mode); layer split supports them.
+ _restore_after_tensor_downgrade()
if tensor_parallel and tp_gpus:
# Tensor-parallel allocation; see _plan_tensor_parallel.
@@ -5637,10 +5572,9 @@ class LlamaCppBackend:
logger.info(f"Using mmproj for vision: {launch_mmproj_path}")
# Option C: --api-key for direct client access when enabled
- import os as _os
import secrets as _secrets
- if _os.getenv("UNSLOTH_DIRECT_STREAM", "0") == "1":
+ if os.getenv("UNSLOTH_DIRECT_STREAM", "0") == "1":
self._api_key = _secrets.token_urlsafe(32)
cmd.extend(["--api-key", self._api_key])
logger.info("llama-server started with --api-key for direct streaming")
@@ -5676,12 +5610,7 @@ class LlamaCppBackend:
cmd.extend(str(a) for a in extra_args)
logger.info(f"Appending user extra args to llama-server: {list(extra_args)}")
- _log_cmd = list(cmd)
- if "--api-key" in _log_cmd:
- _ki = _log_cmd.index("--api-key") + 1
- if _ki < len(_log_cmd):
- _log_cmd[_ki] = "<redacted>"
- logger.info(f"Starting llama-server: {' '.join(_log_cmd)}")
+ logger.info(f"Starting llama-server: {' '.join(self._redacted_cmd_for_log(cmd))}")
# Library paths so llama-server finds its shared libs and CUDA DLLs.
env = self._llama_server_env_for_binary(binary)
@@ -6139,37 +6068,8 @@ class LlamaCppBackend:
except Exception as exc:
logger.debug("Audio probe failed: %s", exc)
detected = None
- if detected in ("snac", "bicodec", "dac"):
- with self._lock:
- if not self._healthy:
- return False
- try:
- self.init_audio_codec(detected)
- self._is_audio = True
- self._audio_type = detected
- except Exception as exc:
- # Surface as HTTP 500 (matches pre-PR contract).
- logger.warning(
- "Failed to init audio codec '%s': %s",
- detected,
- exc,
- )
- self._audio_probed = False
- return False
- elif detected:
- # csm / whisper / audio_vlm: track type but keep _is_audio
- # False -- GGUF TTS routing only fires for snac/bicodec/dac.
- with self._lock:
- if not self._healthy:
- return False
- self._audio_type = detected
-
- # Audio input = token probe (audio_vlm/whisper) OR mmproj encoder.
- from utils.models.model_config import is_audio_input_type
-
- self._has_audio_input = bool(is_audio_input_type(self._audio_type)) or bool(
- self._mmproj_has_audio
- )
+ if not self._apply_detected_audio(detected):
+ return False
if not self._healthy:
return False
@@ -6318,6 +6218,8 @@ class LlamaCppBackend:
if mtp_draft_path:
flags.extend(["--model-draft", mtp_draft_path])
logger.info(f"Using separate MTP drafter: {mtp_draft_path}")
+ spec_value = mtp_token
+ ngram_knobs: list[str] = []
if chain_ngram:
ngram_knobs = _build_ngram_mod_flags(caps)
if ngram_knobs:
@@ -6327,25 +6229,8 @@ class LlamaCppBackend:
"llama-server lacks ngram-mod tuning "
"flags; loading MTP only (no ngram chain)"
)
- spec_value = mtp_token
- flags.extend(
- [
- "--spec-type",
- spec_value,
- n_max_flag,
- str(draft_n_max),
- ]
- )
- flags.extend(ngram_knobs)
- else:
- flags.extend(
- [
- "--spec-type",
- mtp_token,
- n_max_flag,
- str(draft_n_max),
- ]
- )
+ flags.extend(["--spec-type", spec_value, n_max_flag, str(draft_n_max)])
+ flags.extend(ngram_knobs)
self._speculative_type = "draft-mtp"
chain_label = "chained ngram-mod" if chain_ngram else "MTP-only"
logger.info(f"Spec decoding: {mtp_token} ({chain_label})")
@@ -6686,7 +6571,6 @@ class LlamaCppBackend:
# Clean up temp chat template file.
if hasattr(self, "_chat_template_file") and self._chat_template_file:
try:
- import os
os.unlink(self._chat_template_file.name)
except Exception:
pass
@@ -6964,20 +6848,10 @@ class LlamaCppBackend:
install_roots: list[Path] = []
# Env-mode custom root (mirrors _find_llama_server_binary).
- _is_custom_root = False
- try:
- from utils.paths.storage_roots import studio_root as _sr # noqa: WPS433
-
- _resolved_sr = _sr()
- _legacy_studio = Path.home() / ".unsloth" / "studio"
- try:
- _is_custom_root = _resolved_sr.resolve() != _legacy_studio.resolve()
- except (OSError, ValueError):
- _is_custom_root = _resolved_sr != _legacy_studio
- if _is_custom_root:
- install_roots.append(_resolved_sr / "llama.cpp")
- except (ImportError, OSError, ValueError):
- pass
+ _resolved_sr, _is_legacy = LlamaCppBackend._resolved_studio_root_and_is_legacy()
+ _is_custom_root = not _is_legacy
+ if _is_custom_root:
+ install_roots.append(_resolved_sr / "llama.cpp")
# Primary install dir (default mode only). Env-mode skips this so a
# custom-root Studio can't kill a default-install Studio's server.
@@ -7139,12 +7013,10 @@ class LlamaCppBackend:
tokens generate (e.g. under --split-mode tensor). False on any error so
the caller can drop MTP and retry.
"""
- url = f"http://127.0.0.1:{self._port}/completion"
+ url = f"{self.base_url}/completion"
payload = {"prompt": "Hi", "n_predict": 4, "temperature": 0.0, "stream": False}
- # Match the --api-key auth direct-stream mode uses, else a spurious 401.
- headers = {"Authorization": f"Bearer {self._api_key}"} if self._api_key else None
try:
- resp = httpx.post(url, json = payload, timeout = timeout, headers = headers)
+ resp = httpx.post(url, json = payload, timeout = timeout, headers = self._auth_headers)
except Exception as e:
logger.debug(f"MTP decode probe failed: {e}")
return False
@@ -7272,7 +7144,7 @@ class LlamaCppBackend:
) -> bool:
"""Poll llama-server's /health until 200; also detect early exit/crash."""
deadline = time.monotonic() + timeout
- url = f"http://127.0.0.1:{self._port}/health"
+ url = f"{self.base_url}/health"
while time.monotonic() < deadline:
# Process crashed?
@@ -7341,7 +7213,7 @@ class LlamaCppBackend:
The memory-fit step or ``--parallel`` slot split can leave this below
the requested ``-c``; requests are validated against this value.
"""
- url = f"http://127.0.0.1:{self._port}/props"
+ url = f"{self.base_url}/props"
try:
resp = httpx.get(url, timeout = 5.0)
if resp.status_code != 200:
@@ -7414,6 +7286,33 @@ class LlamaCppBackend:
# ── Generation (proxy to llama-server) ────────────────────────
+ @contextlib.contextmanager
+ def _open_stream(self, url: str, payload: dict, cancel_event):
+ """Open a streaming POST to llama-server, retrying through prefill, and
+ yield ``(response, first_token_deadline)`` once a 200 lands. Owns the
+ httpx.Client + auth headers for the stream's lifetime; raises
+ RuntimeError on a non-200. Shared scaffold for the streaming consumers,
+ which differ only in how they parse the SSE body."""
+ stream_timeout = httpx.Timeout(connect = 10, read = 0.5, write = 10, pool = 10)
+ with httpx.Client(
+ timeout = stream_timeout, limits = httpx.Limits(max_keepalive_connections = 0)
+ ) as client:
+ first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S
+ with self._stream_with_retry(
+ client,
+ url,
+ payload,
+ cancel_event,
+ headers = self._auth_headers,
+ first_token_deadline = first_token_deadline,
+ ) as response:
+ if response.status_code != 200:
+ error_body = response.read().decode()
+ raise RuntimeError(
+ f"llama-server returned {response.status_code}: {error_body}"
+ )
+ yield response, first_token_deadline
+
@staticmethod
def _iter_text_cancellable(
response: "httpx.Response",
@@ -7663,119 +7562,102 @@ class LlamaCppBackend:
_metadata_finish_reason = None
try:
- # Prefill can use the long first-token timeout; body reads are lowered after headers.
- stream_timeout = httpx.Timeout(connect = 10, read = 0.5, write = 10, pool = 10)
- _auth_headers = {"Authorization": f"Bearer {self._api_key}"} if self._api_key else None
- with httpx.Client(
- timeout = stream_timeout, limits = httpx.Limits(max_keepalive_connections = 0)
- ) as client:
- first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S
- with self._stream_with_retry(
- client,
- url,
- payload,
+ with self._open_stream(url, payload, cancel_event) as (
+ response,
+ first_token_deadline,
+ ):
+ buffer = ""
+ has_content_tokens = False
+ reasoning_text = ""
+ for raw_chunk in self._iter_text_cancellable(
+ response,
cancel_event,
- headers = _auth_headers,
first_token_deadline = first_token_deadline,
- ) as response:
- if response.status_code != 200:
- error_body = response.read().decode()
- raise RuntimeError(
- f"llama-server returned {response.status_code}: {error_body}"
- )
+ ):
+ buffer += raw_chunk
+ while "\n" in buffer:
+ line, buffer = buffer.split("\n", 1)
+ line = line.strip()
- buffer = ""
- has_content_tokens = False
- reasoning_text = ""
- for raw_chunk in self._iter_text_cancellable(
- response,
- cancel_event,
- first_token_deadline = first_token_deadline,
- ):
- buffer += raw_chunk
- while "\n" in buffer:
- line, buffer = buffer.split("\n", 1)
- line = line.strip()
+ if not line:
+ continue
+ if line == "data: [DONE]":
+ if in_thinking:
+ if has_content_tokens:
+ # Real thinking + content: close the tag
+ cumulative += "</think>"
+ yield cumulative
+ else:
+ # Only reasoning_content, no content:
+ # model put its whole reply in reasoning
+ # (e.g. Qwen3 always-think). Show it as
+ # the main response, not a thinking block.
+ cumulative = reasoning_text
+ yield cumulative
+ _stream_done = True
+ break # exit inner while
+ if not line.startswith("data: "):
+ continue
- if not line:
+ try:
+ data = json.loads(line[6:])
+ # Diffusion frame (per-step canvas) from the shim: forward untouched so
+ # the frontend renders it in place. No assistant text, so it never enters
+ # the cumulative content.
+ if data.get("type") == "diffusion_frame":
+ yield data
continue
- if line == "data: [DONE]":
- if in_thinking:
- if has_content_tokens:
- # Real thinking + content: close the tag
+ # Capture server timings/usage from final chunks.
+ _chunk_timings = data.get("timings")
+ if _chunk_timings:
+ _metadata_timings = _chunk_timings
+ _chunk_usage = data.get("usage")
+ if _chunk_usage:
+ _metadata_usage = _chunk_usage
+ choices = data.get("choices", [])
+ if choices:
+ delta = choices[0].get("delta", {})
+ _fr = choices[0].get("finish_reason")
+ if _fr:
+ _metadata_finish_reason = _fr
+
+ # Reasoning/thinking tokens: llama-server
+ # sends these as "reasoning_content"; wrap
+ # in <think> tags for the frontend parser.
+ reasoning = delta.get("reasoning_content", "")
+ if reasoning:
+ reasoning_text += reasoning
+ if not in_thinking:
+ cumulative += "<think>"
+ in_thinking = True
+ cumulative += reasoning
+ yield cumulative
+
+ token = delta.get("content", "")
+ if token:
+ has_content_tokens = True
+ if in_thinking:
cumulative += "</think>"
- yield cumulative
- else:
- # Only reasoning_content, no content:
- # model put its whole reply in reasoning
- # (e.g. Qwen3 always-think). Show it as
- # the main response, not a thinking block.
- cumulative = reasoning_text
- yield cumulative
- _stream_done = True
- break # exit inner while
- if not line.startswith("data: "):
- continue
-
- try:
- data = json.loads(line[6:])
- # Diffusion frame (per-step canvas) from the shim: forward untouched so
- # the frontend renders it in place. No assistant text, so it never enters
- # the cumulative content.
- if data.get("type") == "diffusion_frame":
- yield data
- continue
- # Capture server timings/usage from final chunks.
- _chunk_timings = data.get("timings")
- if _chunk_timings:
- _metadata_timings = _chunk_timings
- _chunk_usage = data.get("usage")
- if _chunk_usage:
- _metadata_usage = _chunk_usage
- choices = data.get("choices", [])
- if choices:
- delta = choices[0].get("delta", {})
- _fr = choices[0].get("finish_reason")
- if _fr:
- _metadata_finish_reason = _fr
-
- # Reasoning/thinking tokens: llama-server
- # sends these as "reasoning_content"; wrap
- # in <think> tags for the frontend parser.
- reasoning = delta.get("reasoning_content", "")
- if reasoning:
- reasoning_text += reasoning
- if not in_thinking:
- cumulative += "<think>"
- in_thinking = True
- cumulative += reasoning
- yield cumulative
-
- token = delta.get("content", "")
- if token:
- has_content_tokens = True
- if in_thinking:
- cumulative += "</think>"
- in_thinking = False
- cumulative += token
- yield cumulative
- except json.JSONDecodeError:
- logger.debug(f"Skipping malformed SSE line: {line[:100]}")
- if _stream_done:
- break # exit outer for
- if _metadata_usage or _metadata_timings or _metadata_finish_reason:
- _metadata_usage = _backfill_usage_from_timings(
- _metadata_usage, _metadata_timings
- )
- yield {
- "type": "metadata",
- # Never None: a finish-only metadata event (no usage,
- # no timings) would otherwise crash consumers that do
- # usage.get(...) on the non-streaming paths.
- "usage": _metadata_usage or {},
- "timings": _metadata_timings,
- "finish_reason": _metadata_finish_reason,
- }
+ in_thinking = False
+ cumulative += token
+ yield cumulative
+ except json.JSONDecodeError:
+ logger.debug(f"Skipping malformed SSE line: {line[:100]}")
+ if _stream_done:
+ break # exit outer for
+ if _metadata_usage or _metadata_timings or _metadata_finish_reason:
+ _metadata_usage = _backfill_usage_from_timings(
+ _metadata_usage, _metadata_timings
+ )
+ yield {
+ "type": "metadata",
+ # Never None: a finish-only metadata event (no usage,
+ # no timings) would otherwise crash consumers that do
+ # usage.get(...) on the non-streaming paths.
+ "usage": _metadata_usage or {},
+ "timings": _metadata_timings,
+ "finish_reason": _metadata_finish_reason,
+ }
except httpx.ConnectError as e:
# Server already down. If this was an MTP+tensor crash, recover by
@@ -7889,6 +7771,42 @@ class LlamaCppBackend:
text = pat.sub("", text)
return text
+ def _build_metadata_event(usage, timings, finish_reason):
+ """Final usage+timings metadata event for the given pass, merging its
+ usage/timings with the running cross-iteration accumulators. None when
+ there is nothing to report."""
+ _fu = _backfill_usage_from_timings(usage, timings) or {}
+ _fp = _fu.get("prompt_tokens", 0)
+ _tc = _fu.get("completion_tokens", 0) + _accumulated_completion_tokens
+ if not (usage or timings or _accumulated_completion_tokens or finish_reason):
+ return None
+ _mt = dict(timings) if timings else {}
+ if _accumulated_predicted_ms or _accumulated_predicted_n:
+ _mt["predicted_ms"] = _mt.get("predicted_ms", 0) + _accumulated_predicted_ms
+ _mt["predicted_n"] = _mt.get("predicted_n", 0) + _accumulated_predicted_n
+ if _mt["predicted_ms"] > 0:
+ _mt["predicted_per_second"] = _mt["predicted_n"] / (
+ _mt["predicted_ms"] / 1000.0
+ )
+ return {
+ "type": "metadata",
+ "usage": {
+ "prompt_tokens": _fp,
+ "completion_tokens": _tc,
+ "total_tokens": _fp + _tc,
+ },
+ "timings": _mt,
+ "finish_reason": finish_reason,
+ }
+
+ def _flush_reasoning_and_buffer():
+ """Append buffered reasoning (as a <think> block) then the held
+ content_buffer to the cumulative display text."""
+ nonlocal cumulative_display
+ if reasoning_accum:
+ cumulative_display += "<think>" + reasoning_accum + "</think>"
+ cumulative_display += content_buffer
+
tool_controller = ToolLoopController(
tools = tools,
auto_heal_tool_calls = auto_heal_tool_calls,
@@ -7927,7 +7845,7 @@ class LlamaCppBackend:
if not active_tools:
_append_budget_exhausted_nudge = False
break
- _tool_xml_signals = TOOL_XML_SIGNALS if active_tools else ()
+ _tool_xml_signals = TOOL_XML_SIGNALS
# Build payload -- stream: True so we detect tool signals
# in the first 1-2 chunks without a non-streaming penalty.
@@ -7960,10 +7878,6 @@ class LlamaCppBackend:
payload["seed"] = seed
try:
- _auth_headers = (
- {"Authorization": f"Bearer {self._api_key}"} if self._api_key else None
- )
-
# ── Speculative buffer state machine ──────────────────
# BUFFERING: accumulate content, check for tool signals
# STREAMING: no tool detected, yield tokens to caller
@@ -7989,194 +7903,220 @@ class LlamaCppBackend:
provisional_render_html_tool_call_ids = set()
_suppress_visible_output = _forced_tool_call_pending
- stream_timeout = httpx.Timeout(
- connect = 10,
- read = 0.5,
- write = 10,
- pool = 10,
- )
- with httpx.Client(
- timeout = stream_timeout,
- limits = httpx.Limits(max_keepalive_connections = 0),
- ) as client:
- first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S
- with self._stream_with_retry(
- client,
- url,
- payload,
+ with self._open_stream(url, payload, cancel_event) as (
+ response,
+ first_token_deadline,
+ ):
+ raw_buf = ""
+ for raw_chunk in self._iter_text_cancellable(
+ response,
cancel_event,
- headers = _auth_headers,
first_token_deadline = first_token_deadline,
- ) as response:
- if response.status_code != 200:
- error_body = response.read().decode()
- raise RuntimeError(
- f"llama-server returned {response.status_code}: {error_body}"
- )
+ ):
+ raw_buf += raw_chunk
+ while "\n" in raw_buf:
+ line, raw_buf = raw_buf.split("\n", 1)
+ line = line.strip()
- raw_buf = ""
- for raw_chunk in self._iter_text_cancellable(
- response,
- cancel_event,
- first_token_deadline = first_token_deadline,
- ):
- raw_buf += raw_chunk
- while "\n" in raw_buf:
- line, raw_buf = raw_buf.split("\n", 1)
- line = line.strip()
+ if not line:
+ continue
+ if line == "data: [DONE]":
+ # Flush thinking state for STREAMING
+ if detect_state == _S_STREAMING and in_thinking:
+ if has_content_tokens:
+ cumulative_display += "</think>"
+ if not _suppress_visible_output:
+ yield {
+ "type": "content",
+ "text": _strip_tool_markup(
+ cumulative_display,
+ final = True,
+ ),
+ }
+ else:
+ cumulative_display = reasoning_accum
+ if not _suppress_visible_output:
+ yield {
+ "type": "content",
+ "text": cumulative_display,
+ }
+ _stream_done = True
+ break # exit inner while
+ if not line.startswith("data: "):
+ continue
- if not line:
- continue
- if line == "data: [DONE]":
- # Flush thinking state for STREAMING
- if detect_state == _S_STREAMING and in_thinking:
- if has_content_tokens:
- cumulative_display += "</think>"
- if not _suppress_visible_output:
- yield {
- "type": "content",
- "text": _strip_tool_markup(
- cumulative_display,
- final = True,
- ),
- }
- else:
- cumulative_display = reasoning_accum
- if not _suppress_visible_output:
- yield {
- "type": "content",
- "text": cumulative_display,
- }
- _stream_done = True
- break # exit inner while
- if not line.startswith("data: "):
+ try:
+ chunk_data = json.loads(line[6:])
+ _ct = chunk_data.get("timings")
+ if _ct:
+ _iter_timings = _ct
+ _cu = chunk_data.get("usage")
+ if _cu:
+ _iter_usage = _cu
+
+ choices = chunk_data.get("choices", [])
+ if not choices:
continue
- try:
- chunk_data = json.loads(line[6:])
- _ct = chunk_data.get("timings")
- if _ct:
- _iter_timings = _ct
- _cu = chunk_data.get("usage")
- if _cu:
- _iter_usage = _cu
-
- choices = chunk_data.get("choices", [])
- if not choices:
- continue
-
- delta = choices[0].get("delta", {})
- _fr = choices[0].get("finish_reason")
- if _fr:
- _iter_finish_reason = _fr
-
- # ── Structured tool_calls ──
- tc_deltas = delta.get("tool_calls")
- if tc_deltas:
- # llama-server can emit visible assistant
- # preface content before native structured
- # tool_calls. Preserve content_accum as
- # the assistant pre-tool text and still
- # drain/execute the structured call.
- has_structured_tc = True
- detect_state = _S_DRAINING
- for tc_d in tc_deltas:
- idx = tc_d.get("index", 0)
- if idx not in tool_calls_acc:
- tool_calls_acc[idx] = {
- "id": tc_d.get("id", f"call_{idx}"),
- "type": "function",
- "function": {
- "name": "",
- "arguments": "",
- },
- }
- elif tc_d.get("id"):
- # Update ID if a real one
- # arrives on a later delta.
- tool_calls_acc[idx]["id"] = tc_d["id"]
- func = tc_d.get("function", {})
- if func.get("name"):
- tool_calls_acc[idx]["function"]["name"] += func[
- "name"
- ]
- if func.get("arguments"):
- tool_calls_acc[idx]["function"]["arguments"] += (
- func["arguments"]
+ delta = choices[0].get("delta", {})
+ _fr = choices[0].get("finish_reason")
+ if _fr:
+ _iter_finish_reason = _fr
+
+ # ── Structured tool_calls ──
+ tc_deltas = delta.get("tool_calls")
+ if tc_deltas:
+ # llama-server can emit visible assistant
+ # preface content before native structured
+ # tool_calls. Preserve content_accum as
+ # the assistant pre-tool text and still
+ # drain/execute the structured call.
+ has_structured_tc = True
+ detect_state = _S_DRAINING
+ for tc_d in tc_deltas:
+ idx = tc_d.get("index", 0)
+ if idx not in tool_calls_acc:
+ tool_calls_acc[idx] = {
+ "id": tc_d.get("id", f"call_{idx}"),
+ "type": "function",
+ "function": {
+ "name": "",
+ "arguments": "",
+ },
+ }
+ elif tc_d.get("id"):
+ # Update ID if a real one
+ # arrives on a later delta.
+ tool_calls_acc[idx]["id"] = tc_d["id"]
+ func = tc_d.get("function", {})
+ if func.get("name"):
+ tool_calls_acc[idx]["function"]["name"] += func["name"]
+ if func.get("arguments"):
+ tool_calls_acc[idx]["function"]["arguments"] += func[
+ "arguments"
+ ]
+ current_name = tool_calls_acc[idx]["function"].get(
+ "name", ""
+ )
+ fallback_id = f"call_{idx}"
+ current_id = tool_calls_acc[idx].get("id", fallback_id)
+ already_started = (
+ current_id in provisional_render_html_tool_call_ids
+ )
+ has_real_id = current_id != fallback_id
+ if (
+ current_name == "render_html"
+ and not _tool_succeeded("render_html")
+ and any(
+ (
+ (tool.get("function") or {}).get("name")
+ == "render_html"
)
- current_name = tool_calls_acc[idx]["function"].get(
- "name", ""
+ for tool in active_tools
)
- fallback_id = f"call_{idx}"
- current_id = tool_calls_acc[idx].get("id", fallback_id)
- already_started = (
- current_id in provisional_render_html_tool_call_ids
- )
- has_real_id = current_id != fallback_id
- if (
- current_name == "render_html"
- and not _tool_succeeded("render_html")
- and any(
- (
- (tool.get("function") or {}).get("name")
- == "render_html"
- )
- for tool in active_tools
- )
- and not already_started
- and not provisional_render_html_tool_call_ids
- and has_real_id
- ):
- provisional_render_html_tool_call_ids.add(
- current_id
- )
- yield {
- "type": "tool_start",
- "tool_name": "render_html",
- "tool_call_id": current_id,
- "arguments": {},
- "provenance": tool_event_provenance(
- provisional = True,
- ),
- }
- continue
-
- # ── Reasoning tokens ──
- # Yield only in STREAMING. In BUFFERING and
- # DRAINING, accumulate silently so we don't
- # corrupt the consumer's prev_text tracker
- # (routes/inference.py never resets it
- # between tool iterations).
- reasoning = delta.get("reasoning_content", "")
- if reasoning:
- reasoning_accum += reasoning
- if detect_state == _S_STREAMING:
- if not in_thinking:
- cumulative_display += "<think>"
- in_thinking = True
- cumulative_display += reasoning
+ and not already_started
+ and not provisional_render_html_tool_call_ids
+ and has_real_id
+ ):
+ provisional_render_html_tool_call_ids.add(current_id)
+ yield {
+ "type": "tool_start",
+ "tool_name": "render_html",
+ "tool_call_id": current_id,
+ "arguments": {},
+ "provenance": tool_event_provenance(
+ provisional = True,
+ ),
+ }
+ continue
+
+ # ── Reasoning tokens ──
+ # Yield only in STREAMING. In BUFFERING and
+ # DRAINING, accumulate silently so we don't
+ # corrupt the consumer's prev_text tracker
+ # (routes/inference.py never resets it
+ # between tool iterations).
+ reasoning = delta.get("reasoning_content", "")
+ if reasoning:
+ reasoning_accum += reasoning
+ if detect_state == _S_STREAMING:
+ if not in_thinking:
+ cumulative_display += "<think>"
+ in_thinking = True
+ cumulative_display += reasoning
+ if not _suppress_visible_output:
+ yield {
+ "type": "content",
+ "text": cumulative_display,
+ }
+
+ # ── Content tokens ──
+ token = delta.get("content", "")
+ if token:
+ has_content_tokens = True
+ content_accum += token
+
+ if detect_state == _S_DRAINING:
+ pass # accumulate silently
+
+ elif detect_state == _S_STREAMING:
+ if in_thinking:
+ cumulative_display += "</think>"
+ in_thinking = False
+ cumulative_display += token
+ cleaned = _strip_tool_markup_streaming(cumulative_display)
+ if len(cleaned) > len(_last_emitted):
+ _last_emitted = cleaned
if not _suppress_visible_output:
yield {
"type": "content",
- "text": cumulative_display,
+ "text": cleaned,
}
- # ── Content tokens ──
- token = delta.get("content", "")
- if token:
- has_content_tokens = True
- content_accum += token
-
- if detect_state == _S_DRAINING:
- pass # accumulate silently
-
- elif detect_state == _S_STREAMING:
- if in_thinking:
- cumulative_display += "</think>"
- in_thinking = False
- cumulative_display += token
+ elif detect_state == _S_BUFFERING:
+ content_buffer += token
+ stripped_buf = content_buffer.lstrip()
+ if not stripped_buf:
+ continue
+
+ # Check tool signal prefixes.
+ is_prefix = False
+ is_match = False
+ for sig in _tool_xml_signals:
+ if stripped_buf.startswith(sig):
+ is_match = True
+ break
+ if sig.startswith(stripped_buf):
+ is_prefix = True
+ break
+
+ if is_match:
+ # Tool signal -- flush any visible
+ # prefix before DRAINING so the
+ # route sends it before tool_start.
+ _flush_reasoning_and_buffer()
cleaned = _strip_tool_markup_streaming(
- cumulative_display
+ cumulative_display,
+ force = True,
+ )
+ if len(cleaned) > len(_last_emitted):
+ _last_emitted = cleaned
+ if not _suppress_visible_output:
+ yield {
+ "type": "content",
+ "text": cleaned,
+ }
+ detect_state = _S_DRAINING
+ elif is_prefix and len(stripped_buf) < _MAX_BUFFER_CHARS:
+ pass # keep buffering
+ else:
+ # Not a tool -- flush buffer
+ detect_state = _S_STREAMING
+ # Flush reasoning accumulated
+ # during BUFFERING.
+ _flush_reasoning_and_buffer()
+ cleaned = _strip_tool_markup(
+ cumulative_display,
)
if len(cleaned) > len(_last_emitted):
_last_emitted = cleaned
@@ -8186,73 +8126,10 @@ class LlamaCppBackend:
"text": cleaned,
}
- elif detect_state == _S_BUFFERING:
- content_buffer += token
- stripped_buf = content_buffer.lstrip()
- if not stripped_buf:
- continue
-
- # Check tool signal prefixes.
- is_prefix = False
- is_match = False
- for sig in _tool_xml_signals:
- if stripped_buf.startswith(sig):
- is_match = True
- break
- if sig.startswith(stripped_buf):
- is_prefix = True
- break
-
- if is_match:
- # Tool signal -- flush any visible
- # prefix before DRAINING so the
- # route sends it before tool_start.
- if reasoning_accum:
- cumulative_display += "<think>"
- cumulative_display += reasoning_accum
- cumulative_display += "</think>"
- cumulative_display += content_buffer
- cleaned = _strip_tool_markup_streaming(
- cumulative_display,
- force = True,
- )
- if len(cleaned) > len(_last_emitted):
- _last_emitted = cleaned
- if not _suppress_visible_output:
- yield {
- "type": "content",
- "text": cleaned,
- }
- detect_state = _S_DRAINING
- elif (
- is_prefix and len(stripped_buf) < _MAX_BUFFER_CHARS
- ):
- pass # keep buffering
- else:
- # Not a tool -- flush buffer
- detect_state = _S_STREAMING
- # Flush reasoning accumulated
- # during BUFFERING.
- if reasoning_accum:
- cumulative_display += "<think>"
- cumulative_display += reasoning_accum
- cumulative_display += "</think>"
- cumulative_display += content_buffer
- cleaned = _strip_tool_markup(
- cumulative_display,
- )
- if len(cleaned) > len(_last_emitted):
- _last_emitted = cleaned
- if not _suppress_visible_output:
- yield {
- "type": "content",
- "text": cleaned,
- }
-
- except json.JSONDecodeError:
- logger.debug(f"Skipping malformed SSE line: {line[:100]}")
- if _stream_done:
- break # exit outer for
+ except json.JSONDecodeError:
+ logger.debug(f"Skipping malformed SSE line: {line[:100]}")
+ if _stream_done:
+ break # exit outer for
# ── Resolve BUFFERING at stream end ──
if detect_state == _S_BUFFERING:
@@ -8263,11 +8140,7 @@ class LlamaCppBackend:
detect_state = _S_STREAMING
if content_buffer:
# Flush reasoning first.
- if reasoning_accum:
- cumulative_display += "<think>"
- cumulative_display += reasoning_accum
- cumulative_display += "</think>"
- cumulative_display += content_buffer
+ _flush_reasoning_and_buffer()
if not _suppress_visible_output:
yield {
"type": "content",
@@ -8388,31 +8261,11 @@ class LlamaCppBackend:
# Content was already streamed. Yield metadata.
yield {"type": "status", "text": ""}
- _fu = _backfill_usage_from_timings(_iter_usage, _iter_timings) or {}
- _fc = _fu.get("completion_tokens", 0)
- _fp = _fu.get("prompt_tokens", 0)
- _tc = _fc + _accumulated_completion_tokens
- if _iter_usage or _iter_timings or _accumulated_completion_tokens:
- _mt = dict(_iter_timings) if _iter_timings else {}
- if _accumulated_predicted_ms or _accumulated_predicted_n:
- _mt["predicted_ms"] = (
- _mt.get("predicted_ms", 0) + _accumulated_predicted_ms
- )
- _tn = _mt.get("predicted_n", 0) + _accumulated_predicted_n
- _mt["predicted_n"] = _tn
- _tms = _mt["predicted_ms"]
- if _tms > 0:
- _mt["predicted_per_second"] = _tn / (_tms / 1000.0)
- yield {
- "type": "metadata",
- "usage": {
- "prompt_tokens": _fp,
- "completion_tokens": _tc,
- "total_tokens": _fp + _tc,
- },
- "timings": _mt,
- "finish_reason": _iter_finish_reason,
- }
+ _meta = _build_metadata_event(
+ _iter_usage, _iter_timings, _iter_finish_reason
+ )
+ if _meta is not None:
+ yield _meta
return
# Safety net caught tool XML -- treat as tool call.
@@ -8463,31 +8316,11 @@ class LlamaCppBackend:
content_accum = _strip_tool_markup(content_accum, final = True)
if content_accum:
yield {"type": "content", "text": content_accum}
- _fu = _backfill_usage_from_timings(_iter_usage, _iter_timings) or {}
- _fc = _fu.get("completion_tokens", 0)
- _fp = _fu.get("prompt_tokens", 0)
- _tc = _fc + _accumulated_completion_tokens
- if _iter_usage or _iter_timings or _accumulated_completion_tokens:
- _mt = dict(_iter_timings) if _iter_timings else {}
- if _accumulated_predicted_ms or _accumulated_predicted_n:
- _mt["predicted_ms"] = (
- _mt.get("predicted_ms", 0) + _accumulated_predicted_ms
- )
- _tn = _mt.get("predicted_n", 0) + _accumulated_predicted_n
- _mt["predicted_n"] = _tn
- _tms = _mt["predicted_ms"]
- if _tms > 0:
- _mt["predicted_per_second"] = _tn / (_tms / 1000.0)
- yield {
- "type": "metadata",
- "usage": {
- "prompt_tokens": _fp,
- "completion_tokens": _tc,
- "total_tokens": _fp + _tc,
- },
- "timings": _mt,
- "finish_reason": _iter_finish_reason,
- }
+ _meta = _build_metadata_event(
+ _iter_usage, _iter_timings, _iter_finish_reason
+ )
+ if _meta is not None:
+ yield _meta
return
# ── Execute tool calls ──
@@ -8688,125 +8521,85 @@ class LlamaCppBackend:
_stream_done = False
try:
- stream_timeout = httpx.Timeout(connect = 10, read = 0.5, write = 10, pool = 10)
- _auth_headers = {"Authorization": f"Bearer {self._api_key}"} if self._api_key else None
- with httpx.Client(
- timeout = stream_timeout, limits = httpx.Limits(max_keepalive_connections = 0)
- ) as client:
- first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S
- with self._stream_with_retry(
- client,
- url,
- stream_payload,
+ with self._open_stream(url, stream_payload, cancel_event) as (
+ response,
+ first_token_deadline,
+ ):
+ buffer = ""
+ for raw_chunk in self._iter_text_cancellable(
+ response,
cancel_event,
- headers = _auth_headers,
first_token_deadline = first_token_deadline,
- ) as response:
- if response.status_code != 200:
- error_body = response.read().decode()
- raise RuntimeError(
- f"llama-server returned {response.status_code}: {error_body}"
- )
+ ):
+ buffer += raw_chunk
+ while "\n" in buffer:
+ line, buffer = buffer.split("\n", 1)
+ line = line.strip()
- buffer = ""
- for raw_chunk in self._iter_text_cancellable(
- response,
- cancel_event,
- first_token_deadline = first_token_deadline,
- ):
- buffer += raw_chunk
- while "\n" in buffer:
- line, buffer = buffer.split("\n", 1)
- line = line.strip()
+ if not line:
+ continue
+ if line == "data: [DONE]":
+ if in_thinking:
+ if has_content_tokens:
+ cumulative += "</think>"
+ yield {
+ "type": "content",
+ "text": _strip_tool_markup(cumulative, final = True),
+ }
+ else:
+ cumulative = reasoning_text
+ yield {"type": "content", "text": cumulative}
+ _stream_done = True
+ break # exit inner while
+ if not line.startswith("data: "):
+ continue
- if not line:
- continue
- if line == "data: [DONE]":
- if in_thinking:
- if has_content_tokens:
+ try:
+ chunk_data = json.loads(line[6:])
+ # Capture server timings/usage from final chunks.
+ _chunk_timings = chunk_data.get("timings")
+ if _chunk_timings:
+ _metadata_timings = _chunk_timings
+ _chunk_usage = chunk_data.get("usage")
+ if _chunk_usage:
+ _metadata_usage = _chunk_usage
+ choices = chunk_data.get("choices", [])
+ if choices:
+ delta = choices[0].get("delta", {})
+ _fr = choices[0].get("finish_reason")
+ if _fr:
+ _metadata_finish_reason = _fr
+
+ reasoning = delta.get("reasoning_content", "")
+ if reasoning:
+ reasoning_text += reasoning
+ if not in_thinking:
+ cumulative += "<think>"
+ in_thinking = True
+ cumulative += reasoning
+ yield {"type": "content", "text": cumulative}
+
+ token = delta.get("content", "")
+ if token:
+ has_content_tokens = True
+ if in_thinking:
cumulative += "</think>"
- yield {
- "type": "content",
- "text": _strip_tool_markup(cumulative, final = True),
- }
- else:
- cumulative = reasoning_text
- yield {"type": "content", "text": cumulative}
- _stream_done = True
- break # exit inner while
- if not line.startswith("data: "):
- continue
-
- try:
- chunk_data = json.loads(line[6:])
- # Capture server timings/usage from final chunks.
- _chunk_timings = chunk_data.get("timings")
- if _chunk_timings:
- _metadata_timings = _chunk_timings
- _chunk_usage = chunk_data.get("usage")
- if _chunk_usage:
- _metadata_usage = _chunk_usage
- choices = chunk_data.get("choices", [])
- if choices:
- delta = choices[0].get("delta", {})
- _fr = choices[0].get("finish_reason")
- if _fr:
- _metadata_finish_reason = _fr
-
- reasoning = delta.get("reasoning_content", "")
- if reasoning:
- reasoning_text += reasoning
- if not in_thinking:
- cumulative += "<think>"
- in_thinking = True
- cumulative += reasoning
- yield {"type": "content", "text": cumulative}
-
- token = delta.get("content", "")
- if token:
- has_content_tokens = True
- if in_thinking:
- cumulative += "</think>"
- in_thinking = False
- cumulative += token
- cleaned = _strip_tool_markup(cumulative)
- # Emit only when cleaned text grows (monotonic).
- if len(cleaned) > len(_last_emitted):
- _last_emitted = cleaned
- yield {"type": "content", "text": cleaned}
- except json.JSONDecodeError:
- logger.debug(f"Skipping malformed SSE line: {line[:100]}")
- if _stream_done:
- break # exit outer for
- _final_usage = _metadata_usage or {}
- _final_completion = _final_usage.get("completion_tokens", 0)
- _final_prompt = _final_usage.get("prompt_tokens", 0)
- _total_completion = _final_completion + _accumulated_completion_tokens
- if _metadata_usage or _metadata_timings or _metadata_finish_reason:
- _merged_timings = dict(_metadata_timings) if _metadata_timings else {}
- if _accumulated_predicted_ms or _accumulated_predicted_n:
- _merged_timings["predicted_ms"] = (
- _merged_timings.get("predicted_ms", 0) + _accumulated_predicted_ms
- )
- _total_predicted_n = (
- _merged_timings.get("predicted_n", 0) + _accumulated_predicted_n
- )
- _merged_timings["predicted_n"] = _total_predicted_n
- _total_predicted_ms = _merged_timings["predicted_ms"]
- if _total_predicted_ms > 0:
- _merged_timings["predicted_per_second"] = _total_predicted_n / (
- _total_predicted_ms / 1000.0
- )
- yield {
- "type": "metadata",
- "usage": {
- "prompt_tokens": _final_prompt,
- "completion_tokens": _total_completion,
- "total_tokens": _final_prompt + _total_completion,
- },
- "timings": _merged_timings,
- "finish_reason": _metadata_finish_reason,
- }
+ in_thinking = False
+ cumulative += token
+ cleaned = _strip_tool_markup(cumulative)
+ # Emit only when cleaned text grows (monotonic).
+ if len(cleaned) > len(_last_emitted):
+ _last_emitted = cleaned
+ yield {"type": "content", "text": cleaned}
+ except json.JSONDecodeError:
+ logger.debug(f"Skipping malformed SSE line: {line[:100]}")
+ if _stream_done:
+ break # exit outer for
+ _meta = _build_metadata_event(
+ _metadata_usage, _metadata_timings, _metadata_finish_reason
+ )
+ if _meta is not None:
+ yield _meta
except httpx.ConnectError:
raise RuntimeError("Lost connection to llama-server")
@@ -8844,8 +8637,6 @@ class LlamaCppBackend:
continue
if not isinstance(block, dict):
return True
- if block.get("type") == "text" and isinstance(block.get("text"), str):
- continue
if isinstance(block.get("text"), str):
continue
return True
@@ -8866,9 +8657,7 @@ class LlamaCppBackend:
parts = []
for block in content:
if isinstance(block, dict):
- if block.get("type") == "text" and isinstance(block.get("text"), str):
- parts.append(block["text"])
- elif isinstance(block.get("text"), str):
+ if isinstance(block.get("text"), str):
parts.append(block["text"])
elif isinstance(block, str):
parts.append(block)
@@ -8883,8 +8672,7 @@ class LlamaCppBackend:
system_text = _block_text(system)
try:
- _auth_headers = {"Authorization": f"Bearer {self._api_key}"} if self._api_key else None
- with httpx.Client(timeout = 10, headers = _auth_headers) as client:
+ with httpx.Client(timeout = 10, headers = self._auth_headers) as client:
def _tokenize(text: str) -> int:
r = client.post(
@@ -8963,12 +8751,44 @@ class LlamaCppBackend:
logger.debug(f"Audio type detection failed: {e}")
return None
+ def _apply_detected_audio(self, detected: Optional[str]) -> bool:
+ """Apply a probed audio codec under self._lock. Returns True to continue
+ the load (codec inited OK, or nothing to init), False to abort (server
+ unhealthy or codec init failed). Shared by the fast-path retry and the
+ main load path."""
+ if detected in ("snac", "bicodec", "dac"):
+ with self._lock:
+ if not self._healthy:
+ return False
+ try:
+ self.init_audio_codec(detected)
+ self._is_audio = True
+ self._audio_type = detected
+ except Exception as exc:
+ # Surface as HTTP 500 (matches pre-PR contract).
+ logger.warning("Failed to init audio codec '%s': %s", detected, exc)
+ self._audio_probed = False
+ return False
+ elif detected:
+ # csm / whisper / audio_vlm: track type but keep _is_audio False --
+ # GGUF TTS routing only fires for snac/bicodec/dac.
+ with self._lock:
+ if not self._healthy:
+ return False
+ self._audio_type = detected
+ # Audio input = token probe (audio_vlm/whisper) OR mmproj encoder.
+ from utils.models.model_config import is_audio_input_type
+
+ self._has_audio_input = bool(is_audio_input_type(self._audio_type)) or bool(
+ self._mmproj_has_audio
+ )
+ return True
+
def _detect_audio_type_strict(self) -> Optional[str]:
"""Codec name on match, None on non-audio, raises on transport/JSON errors."""
if not self.is_loaded:
return None
- _auth_headers = {"Authorization": f"Bearer {self._api_key}"} if self._api_key else None
- with httpx.Client(timeout = 10, headers = _auth_headers) as client:
+ with httpx.Client(timeout = 10, headers = self._auth_headers) as client:
def _detok(tid: int) -> str:
# Non-200 means "marker not in vocab" -- keep probing.
@@ -9082,8 +8902,9 @@ class LlamaCppBackend:
if need_ids:
payload["n_probs"] = 1
- _auth_headers = {"Authorization": f"Bearer {self._api_key}"} if self._api_key else None
- with httpx.Client(timeout = httpx.Timeout(300, connect = 10), headers = _auth_headers) as client:
+ with httpx.Client(
+ timeout = httpx.Timeout(300, connect = 10), headers = self._auth_headers
+ ) as client:
resp = client.post(f"{self.base_url}/completion", json = payload)
if resp.status_code != 200:
raise RuntimeError(f"llama-server returned {resp.status_code}: {resp.text}")
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index eb597caa0ab..4887cbe0303 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -15,7 +15,6 @@ from fastapi.responses import StreamingResponse, JSONResponse, Response
from typing import Any, List, Optional, Union
import json
import httpx
-import structlog
from loggers import get_logger
import asyncio
import threading
@@ -119,6 +118,11 @@ def _template_raise_message(error_text: str, chat_template: Optional[str]) -> Op
return candidate if candidate and candidate in chat_template else None
+_LOST_CONNECTION_MSG = (
+ "Lost connection to the model server. It may have crashed -- try reloading the model."
+)
+
+
def _friendly_error(exc: Exception) -> str:
"""Extract a user-friendly message from known llama-server errors."""
if isinstance(exc, httpx.ReadTimeout):
@@ -139,9 +143,7 @@ def _friendly_error(exc: Exception) -> str:
# WriteError, PoolTimeout, ...) means the llama-server subprocess is
# unreachable -- crashed or still coming up.
if isinstance(exc, httpx.RequestError):
- return (
- "Lost connection to the model server. It may have crashed -- try reloading the model."
- )
+ return _LOST_CONNECTION_MSG
msg = str(exc)
m = _re.search(
r"request \((\d+) tokens?\) exceeds the available context size \((\d+) tokens?\)",
@@ -154,9 +156,7 @@ def _friendly_error(exc: Exception) -> str:
f"or shorten the conversation."
)
if "Lost connection to llama-server" in msg:
- return (
- "Lost connection to the model server. It may have crashed -- try reloading the model."
- )
+ return _LOST_CONNECTION_MSG
template_msg = _template_raise_message(msg, _loaded_chat_template())
if template_msg:
return f"An internal error occurred: {template_msg}"
@@ -229,6 +229,24 @@ def _raise_unsupported_n(path_label: str) -> None:
_raise_unsupported_openai_parameter("n", f"n > 1 is not supported for {path_label}.")
+def _sse_streaming_response(content) -> StreamingResponse:
+ """A ``text/event-stream`` response with the standard SSE headers used by
+ every streaming path here: no client/proxy caching, no proxy buffering, and
+ a one-shot connection. Two callers build their response inline instead: the
+ external-provider proxy omits ``Connection: close``, and the OpenAI
+ passthrough returns an empty ``keep-alive`` stream when the request is
+ cancelled before the upstream response starts."""
+ return StreamingResponse(
+ content,
+ media_type = "text/event-stream",
+ headers = {
+ "Cache-Control": "no-cache",
+ "Connection": "close",
+ "X-Accel-Buffering": "no",
+ },
+ )
+
+
def _openai_stream_error_chunk(exc) -> dict:
"""Build an in-band OpenAI error chunk for a mid-stream failure. Once the
stream's 200 headers are flushed the status can't change, so the error must
@@ -403,12 +421,11 @@ def _apply_overflow_truncation(body: dict, err_text: str) -> bool:
if counts:
n_prompt, n_ctx = counts
keep_ratio = min(0.95, (_OVERFLOW_PROMPT_TARGET_FRACTION * n_ctx) / max(1, n_prompt))
- # Scale the server-token target into char-estimate units.
- target_est = int(total_est * keep_ratio)
else:
n_ctx = None
keep_ratio = 0.6 # no counts in the error; cut conservatively
- target_est = int(total_est * keep_ratio)
+ # Scale the server-token target into char-estimate units.
+ target_est = int(total_est * keep_ratio)
new_messages, dropped = _truncate_middle_messages(messages, keep_ratio)
if dropped:
@@ -522,6 +539,52 @@ def _openai_stream_usage_chunk(
return f"data: {usage_chunk.model_dump_json(exclude_none = True)}\n\n"
+def _chat_chunk_sse(completion_id, created, model_name, *, delta, finish_reason) -> str:
+ """One ``ChatCompletionChunk`` as an SSE ``data:`` line. The role / content /
+ final chunks every in-process streamer emits differ only in their ``delta``
+ and ``finish_reason``."""
+ chunk = ChatCompletionChunk(
+ id = completion_id,
+ created = created,
+ model = model_name,
+ choices = [ChunkChoice(delta = delta, finish_reason = finish_reason)],
+ )
+ return f"data: {chunk.model_dump_json(exclude_none = True)}\n\n"
+
+
+def _chat_role_chunk(completion_id, created, model_name) -> str:
+ """Opening assistant-role chunk for a chat stream."""
+ return _chat_chunk_sse(
+ completion_id,
+ created,
+ model_name,
+ delta = ChoiceDelta(role = "assistant"),
+ finish_reason = None,
+ )
+
+
+def _chat_content_chunk(completion_id, created, model_name, text) -> str:
+ """A content-delta chunk carrying ``text``."""
+ return _chat_chunk_sse(
+ completion_id,
+ created,
+ model_name,
+ delta = ChoiceDelta(content = text),
+ finish_reason = None,
+ )
+
+
+def _chat_final_chunk(completion_id, created, model_name, finish_reason) -> str:
+ """Terminal stop chunk (empty delta) carrying the finish reason."""
+ return _chat_chunk_sse(
+ completion_id,
+ created,
+ model_name,
+ delta = ChoiceDelta(),
+ finish_reason = finish_reason,
+ )
+
+
def _rewrite_cmpl_id(raw: bytes) -> bytes:
"""Rewrite llama-server's chat-style ``chatcmpl-`` ids to the ``cmpl-``
prefix OpenAI's legacy /v1/completions use. Anchored on the ``"id":`` key
@@ -669,21 +732,11 @@ except ImportError:
def _llama_non_streaming_generation_timeout() -> httpx.Timeout:
- return httpx.Timeout(
- connect = _DEFAULT_FIRST_TOKEN_TIMEOUT_S,
- read = _DEFAULT_FIRST_TOKEN_TIMEOUT_S,
- write = _DEFAULT_FIRST_TOKEN_TIMEOUT_S,
- pool = _DEFAULT_FIRST_TOKEN_TIMEOUT_S,
- )
+ return httpx.Timeout(_DEFAULT_FIRST_TOKEN_TIMEOUT_S)
def _llama_streaming_generation_timeout() -> httpx.Timeout:
- return httpx.Timeout(
- connect = _DEFAULT_FIRST_TOKEN_TIMEOUT_S,
- read = _DEFAULT_FIRST_TOKEN_TIMEOUT_S,
- write = _DEFAULT_FIRST_TOKEN_TIMEOUT_S,
- pool = _DEFAULT_FIRST_TOKEN_TIMEOUT_S,
- )
+ return httpx.Timeout(_DEFAULT_FIRST_TOKEN_TIMEOUT_S)
def _set_stream_response_read_timeout(
@@ -697,6 +750,41 @@ def _set_stream_response_read_timeout(
pass
+async def _aclose_stream_resources(
+ *,
+ watchers = (),
+ iterator = None,
+ resp = None,
+ client = None,
+) -> None:
+ """Tear down an httpx streaming generator's resources in the required order:
+ cancel + await each watcher task, then aclose() the byte/line iterator, the
+ response, and the client. Each step swallows its own exceptions so teardown
+ always completes. See _anthropic_passthrough_stream for the ordering rationale."""
+ for watcher in watchers:
+ if watcher is not None:
+ watcher.cancel()
+ try:
+ await watcher
+ except (asyncio.CancelledError, Exception):
+ pass
+ if iterator is not None:
+ try:
+ await iterator.aclose()
+ except Exception:
+ pass
+ if resp is not None:
+ try:
+ await resp.aclose()
+ except Exception:
+ pass
+ if client is not None:
+ try:
+ await client.aclose()
+ except Exception:
+ pass
+
+
async def _preheader_cancelled(cancel_event = None, request: Optional[Request] = None) -> bool:
if cancel_event is not None and cancel_event.is_set():
return True
@@ -837,11 +925,9 @@ from models.inference import (
ImageContentPart,
ImageUrl,
ResponsesRequest,
- ResponsesInputMessage,
ResponsesInputTextPart,
ResponsesInputImagePart,
ResponsesOutputTextPart,
- ResponsesUnknownContentPart,
ResponsesUnknownInputItem,
ResponsesFunctionCallInputItem,
ResponsesFunctionCallOutputInputItem,
@@ -879,14 +965,13 @@ 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.llama_http import nonstreaming_client
-from core.inference.providers import get_provider_info, get_base_url
+from core.inference.providers import get_base_url
from core.inference.external_provider import ExternalProviderClient
from core.inference.chat_templates import resolve_effective_chat_template_override
from storage import providers_db
from utils.utils import safe_error_detail, log_and_http_error
import io
-import wave
import base64
import numpy as np
from datetime import date as _date
@@ -984,6 +1069,26 @@ _ARTIFACT_PREVIEW_FRAME_HTML = """<!doctype html>
</html>"""
+async def _authenticate_header_or_query(request: Request, token: Optional[str]) -> str:
+ """Resolve the bearer token from the Authorization header or the ``?token=``
+ query param (needed for <img src> / <iframe>, which can't send custom
+ headers), validate it, and return the subject. Raises 401 when absent."""
+ auth_header = request.headers.get("authorization")
+ if auth_header and auth_header.lower().startswith("bearer "):
+ jwt_token = auth_header[7:]
+ elif token:
+ jwt_token = token
+ else:
+ raise HTTPException(
+ status_code = status.HTTP_401_UNAUTHORIZED,
+ detail = "Missing authentication token",
+ )
+ from fastapi.security import HTTPAuthorizationCredentials
+
+ creds = HTTPAuthorizationCredentials(scheme = "Bearer", credentials = jwt_token)
+ return await get_current_subject(creds)
+
+
@studio_router.get("/artifact-preview-frame", include_in_schema = False)
async def artifact_preview_frame(
request: Request,
@@ -993,20 +1098,7 @@ async def artifact_preview_frame(
"""Serve the opaque sandbox shell used for client-side HTML canvases."""
if allow_network:
- auth_header = request.headers.get("authorization")
- if auth_header and auth_header.lower().startswith("bearer "):
- jwt_token = auth_header[7:]
- elif token:
- jwt_token = token
- else:
- raise HTTPException(
- status_code = status.HTTP_401_UNAUTHORIZED,
- detail = "Missing authentication token",
- )
- from fastapi.security import HTTPAuthorizationCredentials
-
- creds = HTTPAuthorizationCredentials(scheme = "Bearer", credentials = jwt_token)
- await get_current_subject(creds)
+ await _authenticate_header_or_query(request, token)
csp = (
_ARTIFACT_PREVIEW_FRAME_NETWORK_CSP if allow_network else _ARTIFACT_PREVIEW_FRAME_STRICT_CSP
@@ -1028,21 +1120,10 @@ def _detect_safetensors_features(backend, chat_template: Optional[str]) -> dict:
match across backends. gpt-oss is overridden: Harmony routes reasoning and
tools through tokenizer channels, not template markup."""
model_id = getattr(backend, "active_model_name", None)
- flags = (
- detect_reasoning_flags(
- chat_template,
- model_identifier = model_id,
- log_source = "safetensors",
- )
- if chat_template
- else {
- "supports_reasoning": False,
- "reasoning_style": "enable_thinking",
- "reasoning_always_on": False,
- "reasoning_effort_levels": [],
- "supports_preserve_thinking": False,
- "supports_tools": False,
- }
+ flags = detect_reasoning_flags(
+ chat_template,
+ model_identifier = model_id,
+ log_source = "safetensors",
)
# Our safetensors loop only parses <tool_call>{json}</tool_call> and
# <function=name>...</function>. Llama uses <|python_tag|>, Mistral uses
@@ -1275,6 +1356,57 @@ def _build_tool_action_nudge(*, tools: list[dict], model_name: str) -> str:
)
+# Nudge appended when the RAG knowledge-base tool is active: ground answers in
+# the attached documents instead of model memory.
+_RAG_GROUNDING_NUDGE = (
+ "The user has attached documents to this conversation. Relevant "
+ "passages are retrieved and provided to you automatically; base "
+ "your answer on them and cite them. You can also call "
+ "search_knowledge_base to look for more. Do not answer from "
+ "memory when the attached documents are relevant."
+)
+
+
+async def _select_request_tools(
+ payload: ChatCompletionRequest, *, tools_on: bool, mcp_allowed: bool
+) -> list[dict]:
+ """Resolve the tool list for a chat request: built-ins filtered by the
+ caller's opt-in (empty when MCP-only), the RAG tool dropped without a
+ retrieval scope, then enabled MCP tools appended. An empty result means the
+ caller should skip the tool loop, so a model-emitted built-in call can't
+ piggy-back on the empty allow-list."""
+ from core.inference.tools import ALL_TOOLS, get_enabled_mcp_tools
+
+ if not tools_on:
+ # MCP-only request: skip built-ins, leave room for MCP tools.
+ tools = []
+ elif payload.enabled_tools is not None:
+ tools = [t for t in ALL_TOOLS if t["function"]["name"] in payload.enabled_tools]
+ else:
+ # Copy so the shared module-global tool list can't be mutated by callers.
+ tools = list(ALL_TOOLS)
+ # Drop the RAG tool without a scope: nothing to search over.
+ if not payload.rag_scope:
+ tools = [t for t in tools if t["function"]["name"] != "search_knowledge_base"]
+ if mcp_allowed:
+ tools = tools + await get_enabled_mcp_tools()
+ return tools
+
+
+def _apply_rag_nudge(nudge: str, tools: list[dict], *, rag_scope) -> str:
+ """Append the RAG grounding nudge to ``nudge`` when the knowledge-base tool
+ is active (search_knowledge_base present and a retrieval scope is set). The
+ date is prefixed when the tool nudge is empty (RAG-only tool set). Returns
+ ``nudge`` unchanged when RAG isn't active."""
+ tool_names = {(t.get("function") or {}).get("name") for t in (tools or [])}
+ if "search_knowledge_base" not in tool_names or not rag_scope:
+ return nudge
+ if not nudge:
+ date_line = f"The current date is {_date.today().isoformat()}."
+ return date_line + " " + _RAG_GROUNDING_NUDGE
+ return nudge + " " + _RAG_GROUNDING_NUDGE
+
+
# Strip tool-call XML the speculative buffer in core/inference/llama_cpp.py
# split across the visible/DRAIN boundary. Four leak shapes:
# 1. well-formed `<tool_call>...</tool_call>` / `<function=...>...</function>`
@@ -1671,17 +1803,16 @@ def _monitor_anthropic_response(
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
+ finally:
+ _ANTHROPIC_MONITOR_TOOL_BLOCKS.pop(monitor_id, None)
response.body_iterator = _monitored_body()
return response
@@ -2144,6 +2275,23 @@ def _model_json_response(model, status_code: int = 200) -> Response:
)
+_NOT_SUPPORTED_HINTS = (
+ "No config file found",
+ "not yet supported",
+ "is not supported",
+ "does not support",
+)
+
+
+def _maybe_unsupported_message(msg: str) -> str:
+ """Rewrite a load/validate error into the friendly "not supported yet"
+ message when it matches a known unsupported-model signature; otherwise
+ return ``msg`` unchanged."""
+ if any(h.lower() in msg.lower() for h in _NOT_SUPPORTED_HINTS):
+ return f"This model is not supported yet. Try a different model. (Original error: {msg})"
+ return msg
+
+
@router.post("/load", response_model = LoadResponse)
async def load_model(
request: LoadRequest,
@@ -2229,9 +2377,7 @@ async def load_model(
)
inference_config = load_inference_config(llama_backend.model_identifier)
- _gguf_audio = (
- llama_backend._audio_type if hasattr(llama_backend, "_audio_type") else None
- )
+ _gguf_audio = getattr(llama_backend, "_audio_type", None)
_gguf_is_audio = getattr(llama_backend, "_is_audio", False)
return LoadResponse(
status = "already_loaded",
@@ -2465,7 +2611,6 @@ async def load_model(
speculative_type = request.speculative_type,
spec_draft_n_max = request.spec_draft_n_max,
n_parallel = _n_parallel,
- extra_args = extra_llama_args,
)
if config.gguf_hf_repo:
# HF mode: download via huggingface_hub then start llama-server
@@ -2713,12 +2858,6 @@ async def load_model(
raise HTTPException(status_code = 400, detail = str(e))
except Exception as e:
# Friendlier message for models Unsloth cannot load.
- not_supported_hints = [
- "No config file found",
- "not yet supported",
- "is not supported",
- "does not support",
- ]
if native_grant_backed:
redacted_msg = redact_native_paths(str(e))
logger.error(
@@ -2726,17 +2865,13 @@ async def load_model(
model_log_label,
redacted_msg,
)
- msg = redacted_msg
- if any(h.lower() in msg.lower() for h in not_supported_hints):
- msg = f"This model is not supported yet. Try a different model. (Original error: {msg})"
+ msg = _maybe_unsupported_message(redacted_msg)
raise HTTPException(
status_code = 500,
detail = f"Failed to load native model {model_log_label}: {msg}",
)
logger.error(f"Error loading model: {e}", exc_info = True)
- msg = redact_native_paths(str(e))
- if any(h.lower() in msg.lower() for h in not_supported_hints):
- msg = f"This model is not supported yet. Try a different model. (Original error: {msg})"
+ msg = _maybe_unsupported_message(redact_native_paths(str(e)))
raise HTTPException(status_code = 500, detail = f"Failed to load model: {msg}")
@@ -2937,12 +3072,6 @@ async def validate_model(
logger.warning("GGUF runtime missing while validating '%s': %s", request.model_path, e)
raise HTTPException(status_code = 400, detail = str(e))
except Exception as e:
- not_supported_hints = [
- "No config file found",
- "not yet supported",
- "is not supported",
- "does not support",
- ]
if native_grant_backed:
redacted_msg = redact_native_paths(str(e))
logger.error(
@@ -2950,9 +3079,7 @@ async def validate_model(
model_log_label,
redacted_msg,
)
- msg = redacted_msg
- if any(h.lower() in msg.lower() for h in not_supported_hints):
- msg = f"This model is not supported yet. Try a different model. (Original error: {msg})"
+ msg = _maybe_unsupported_message(redacted_msg)
raise HTTPException(
status_code = 400,
detail = f"Invalid native model {model_log_label}: {msg}",
@@ -2969,8 +3096,7 @@ async def validate_model(
if isinstance(e, (RuntimeError, ValueError)):
msg = redact_native_paths(str(e)).strip()
if msg:
- if any(h.lower() in msg.lower() for h in not_supported_hints):
- msg = f"This model is not supported yet. Try a different model. (Original error: {msg})"
+ msg = _maybe_unsupported_message(msg)
raise HTTPException(
status_code = 400,
detail = msg,
@@ -3184,14 +3310,7 @@ async def generate_stream(
except (RuntimeError, ValueError):
pass
- return StreamingResponse(
- stream(),
- media_type = "text/event-stream",
- headers = {
- "Cache-Control": "no-cache",
- "Connection": "close",
- },
- )
+ return _sse_streaming_response(stream())
@router.get("/status", response_model = InferenceStatusResponse)
@@ -3431,7 +3550,7 @@ async def generate_audio(
)
try:
- wav_bytes, sample_rate = await asyncio.get_event_loop().run_in_executor(None, gen)
+ wav_bytes, sample_rate = await asyncio.to_thread(gen)
except Exception as e:
logger.error(f"Audio generation error: {e}", exc_info = True)
raise HTTPException(status_code = 500, detail = safe_error_detail(e))
@@ -3464,7 +3583,6 @@ async def generate_audio(
def _decode_audio_base64(b64: str) -> np.ndarray:
"""Decode base64 audio (any format) → float32 numpy array at 16kHz."""
- import torch
import torchaudio
import tempfile
import os
@@ -3485,11 +3603,9 @@ def _decode_audio_base64(b64: str) -> np.ndarray:
finally:
os.unlink(tmp_path)
- # Convert to mono if stereo
if waveform.shape[0] > 1:
waveform = waveform.mean(dim = 0, keepdim = True)
- # Resample to 16kHz if needed
if sr != 16000:
resampler = torchaudio.transforms.Resample(orig_freq = sr, new_freq = 16000)
waveform = resampler(waveform)
@@ -3852,6 +3968,25 @@ def _build_external_messages(
cleaned.append(_stripped)
return cleaned
+ def _openai_responses_part(item: Any) -> Optional[dict[str, Any]]:
+ """Rebuild a forwarded OpenAI Responses assistant part (`reasoning` or
+ `image_generation_call`); returns None for any other part type."""
+ if item.type == "reasoning":
+ reasoning: dict[str, Any] = {
+ "type": "reasoning",
+ "id": item.id,
+ "summary": item.summary,
+ }
+ if item.status:
+ reasoning["status"] = item.status
+ return reasoning
+ if item.type == "image_generation_call":
+ image_ref: dict[str, Any] = {"type": "image_generation_call", "id": item.id}
+ if getattr(item, "response_id", None):
+ image_ref["response_id"] = item.response_id
+ return image_ref
+ return None
+
result = []
for msg in messages:
# Drop role=tool messages whose matching server-builtin tool_call was
@@ -3921,26 +4056,16 @@ def _build_external_messages(
"image_url": {"url": part.image_url.url},
}
)
- elif part.type == "reasoning" and openai and msg.role == "assistant":
- reasoning: dict[str, Any] = {
- "type": "reasoning",
- "id": part.id,
- "summary": part.summary,
- }
- if part.status:
- reasoning["status"] = part.status
- parts.append(reasoning)
elif (
- part.type == "image_generation_call" and openai and msg.role == "assistant"
+ openai
+ and msg.role == "assistant"
+ and (_rp := _openai_responses_part(part)) is not None
):
- # ExternalProviderClient maps this onto a top-level
- # Responses input item after the current user prompt,
- # or onto `previous_response_id` when response_id is
- # available from the prior turn.
- image_ref = {"type": "image_generation_call", "id": part.id}
- if getattr(part, "response_id", None):
- image_ref["response_id"] = part.response_id
- parts.append(image_ref)
+ # ExternalProviderClient maps image_generation_call onto a
+ # top-level Responses input item after the current user
+ # prompt, or onto `previous_response_id` when response_id
+ # is available from the prior turn.
+ parts.append(_rp)
elif part.type == "input_document" and document_provider:
# ExternalProviderClient maps this onto Anthropic's
# `document` or OpenAI Responses' `input_file` block;
@@ -3989,20 +4114,12 @@ def _build_external_messages(
for p in msg.content:
if p.type == "text":
preserved.append({"type": "text", "text": p.text})
- elif p.type == "reasoning" and openai and msg.role == "assistant":
- reasoning: dict[str, Any] = {
- "type": "reasoning",
- "id": p.id,
- "summary": p.summary,
- }
- if p.status:
- reasoning["status"] = p.status
- preserved.append(reasoning)
- elif p.type == "image_generation_call" and openai and msg.role == "assistant":
- image_ref = {"type": "image_generation_call", "id": p.id}
- if getattr(p, "response_id", None):
- image_ref["response_id"] = p.response_id
- preserved.append(image_ref)
+ elif (
+ openai
+ and msg.role == "assistant"
+ and (_rp := _openai_responses_part(p)) is not None
+ ):
+ preserved.append(_rp)
elif p.type == "compaction" and anthropic:
preserved.append({"type": "compaction", "content": p.content})
if msg.role == "assistant" and not preserved:
@@ -4560,7 +4677,6 @@ 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,
@@ -4609,18 +4725,7 @@ async def openai_chat_completions(
async def audio_input_stream():
try:
- first_chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(role = "assistant"),
- finish_reason = None,
- )
- ],
- )
- yield f"data: {first_chunk.model_dump_json(exclude_none = True)}\n\n"
+ yield _chat_role_chunk(completion_id, created, model_name)
gen = audio_input_generate()
_DONE = object()
@@ -4638,27 +4743,12 @@ async def openai_chat_completions(
break
if chunk_text:
api_monitor.append_reply(monitor_id, chunk_text)
- chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(content = chunk_text),
- finish_reason = None,
- )
- ],
+ yield _chat_content_chunk(
+ completion_id, created, model_name, chunk_text
)
- yield f"data: {chunk.model_dump_json(exclude_none = True)}\n\n"
- final_chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- 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 _chat_final_chunk(completion_id, created, model_name, "stop")
yield "data: [DONE]\n\n"
except asyncio.CancelledError:
cancel_event.set()
@@ -4671,15 +4761,7 @@ async def openai_chat_completions(
finally:
_tracker.__exit__(None, None, None)
- return StreamingResponse(
- audio_input_stream(),
- media_type = "text/event-stream",
- headers = {
- "Cache-Control": "no-cache",
- "Connection": "close",
- "X-Accel-Buffering": "no",
- },
- )
+ return _sse_streaming_response(audio_input_stream())
else:
try:
full_text = "".join(audio_input_generate())
@@ -4869,27 +4951,9 @@ async def openai_chat_completions(
use_tools = (_tools_on or _mcp_allowed) and llama_backend.supports_tools
if use_tools:
- from core.inference.tools import ALL_TOOLS, get_enabled_mcp_tools
-
- if not _tools_on:
- # MCP-only request: skip built-ins, leave room for MCP tools.
- tools_to_use = []
- elif payload.enabled_tools is not None:
- tools_to_use = [
- t for t in ALL_TOOLS if t["function"]["name"] in payload.enabled_tools
- ]
- else:
- tools_to_use = ALL_TOOLS
-
- # Drop the RAG tool without a scope: nothing to search over.
- if not payload.rag_scope:
- tools_to_use = [
- t for t in tools_to_use if t["function"]["name"] != "search_knowledge_base"
- ]
-
- if _mcp_allowed:
- tools_to_use = tools_to_use + await get_enabled_mcp_tools()
-
+ tools_to_use = await _select_request_tools(
+ payload, tools_on = _tools_on, mcp_allowed = _mcp_allowed
+ )
# Skip the tool loop when no tool survived, so the safetensors
# loop's "empty = allow all" semantic can't reach built-in tools
# the caller didn't opt into. Callers who omit enabled_tools still
@@ -4920,19 +4984,7 @@ async def openai_chat_completions(
)
# Nudge the model to ground in attached documents instead of memory.
- _tool_names = {(t.get("function") or {}).get("name") for t in (tools_to_use or [])}
- _rag_active = "search_knowledge_base" in _tool_names and payload.rag_scope
- if _rag_active:
- _rag_nudge = (
- "The user has attached documents to this conversation. Relevant "
- "passages are retrieved and provided to you automatically; base "
- "your answer on them and cite them. You can also call "
- "search_knowledge_base to look for more. Do not answer from "
- "memory when the attached documents are relevant."
- )
- # Prefix the date when the tool nudge is empty (RAG-only tool set).
- _date_line = f"The current date is {_date.today().isoformat()}."
- _nudge = _date_line + " " + _rag_nudge if not _nudge else _nudge + " " + _rag_nudge
+ _nudge = _apply_rag_nudge(_nudge, tools_to_use, rag_scope = payload.rag_scope)
if _nudge:
# Append nudge to system prompt (preserve user's prompt)
@@ -4997,18 +5049,7 @@ async def openai_chat_completions(
async def gguf_tool_stream():
gen = None
try:
- first_chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(role = "assistant"),
- finish_reason = None,
- )
- ],
- )
- yield f"data: {first_chunk.model_dump_json(exclude_none = True)}\n\n"
+ yield _chat_role_chunk(completion_id, created, model_name)
# Iterate the sync generator in a thread so the event loop
# stays free for disconnect detection.
@@ -5072,31 +5113,14 @@ async def openai_chat_completions(
if not new_text:
continue
api_monitor.append_reply(monitor_id, new_text)
- chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(content = new_text),
- finish_reason = None,
- )
- ],
- )
- yield f"data: {chunk.model_dump_json(exclude_none = True)}\n\n"
-
- final_chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(),
- finish_reason = _clamp_finish_reason(_stream_finish),
- )
- ],
+ yield _chat_content_chunk(completion_id, created, model_name, new_text)
+
+ yield _chat_final_chunk(
+ completion_id,
+ created,
+ model_name,
+ _clamp_finish_reason(_stream_finish),
)
- yield f"data: {final_chunk.model_dump_json(exclude_none = True)}\n\n"
usage_line = _openai_stream_usage_chunk(
payload,
completion_id,
@@ -5118,10 +5142,7 @@ async def openai_chat_completions(
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}")
+ logger.error(f"Error during GGUF tool streaming: {e}", exc_info = True)
api_monitor.fail(monitor_id, _friendly_error(e))
# Recover if an MTP+tensor crash killed the server mid-stream.
get_llama_cpp_backend()._maybe_recover_from_mtp_crash(e)
@@ -5135,15 +5156,7 @@ async def openai_chat_completions(
pass
_tracker.__exit__(None, None, None)
- return StreamingResponse(
- gguf_tool_stream(),
- media_type = "text/event-stream",
- headers = {
- "Cache-Control": "no-cache",
- "Connection": "close",
- "X-Accel-Buffering": "no",
- },
- )
+ return _sse_streaming_response(gguf_tool_stream())
# ── Standard GGUF path (no tools) ─────────────────────
@@ -5180,19 +5193,7 @@ async def openai_chat_completions(
async def gguf_stream_chunks():
try:
- # First chunk: role
- first_chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(role = "assistant"),
- finish_reason = None,
- )
- ],
- )
- yield f"data: {first_chunk.model_dump_json(exclude_none = True)}\n\n"
+ yield _chat_role_chunk(completion_id, created, model_name)
# Iterate the sync generator in a thread so the event loop
# stays free for disconnect detection.
@@ -5232,32 +5233,14 @@ async def openai_chat_completions(
if not new_text:
continue
api_monitor.append_reply(monitor_id, new_text)
- chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(content = new_text),
- finish_reason = None,
- )
- ],
- )
- yield f"data: {chunk.model_dump_json(exclude_none = True)}\n\n"
-
- # Final chunk
- final_chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(),
- finish_reason = _clamp_finish_reason(_stream_finish),
- )
- ],
+ yield _chat_content_chunk(completion_id, created, model_name, new_text)
+
+ yield _chat_final_chunk(
+ completion_id,
+ created,
+ model_name,
+ _clamp_finish_reason(_stream_finish),
)
- yield f"data: {final_chunk.model_dump_json(exclude_none = True)}\n\n"
usage_line = _openai_stream_usage_chunk(
payload,
completion_id,
@@ -5286,15 +5269,7 @@ async def openai_chat_completions(
finally:
_tracker.__exit__(None, None, None)
- return StreamingResponse(
- gguf_stream_chunks(),
- media_type = "text/event-stream",
- headers = {
- "Cache-Control": "no-cache",
- "Connection": "close",
- "X-Accel-Buffering": "no",
- },
- )
+ return _sse_streaming_response(gguf_stream_chunks())
else:
try:
# ``n`` requests several independent completions; the single
@@ -5462,26 +5437,9 @@ async def openai_chat_completions(
)
if _sf_use_tools:
- from core.inference.tools import ALL_TOOLS, get_enabled_mcp_tools
-
- if not _sf_tools_on:
- _sf_tools_to_use = []
- elif payload.enabled_tools is not None:
- _sf_tools_to_use = [
- t for t in ALL_TOOLS if t["function"]["name"] in payload.enabled_tools
- ]
- else:
- _sf_tools_to_use = ALL_TOOLS
-
- # Drop the RAG tool unless the request carries a retrieval scope.
- if not payload.rag_scope:
- _sf_tools_to_use = [
- t for t in _sf_tools_to_use if t["function"]["name"] != "search_knowledge_base"
- ]
-
- if _sf_mcp_allowed:
- _sf_tools_to_use = _sf_tools_to_use + await get_enabled_mcp_tools()
-
+ _sf_tools_to_use = await _select_request_tools(
+ payload, tools_on = _sf_tools_on, mcp_allowed = _sf_mcp_allowed
+ )
# Mirror the GGUF path: refuse to enter the tool loop when nothing
# survived, so a model-emitted built-in call can't piggy-back on the
# empty allow-list.
@@ -5507,23 +5465,7 @@ async def openai_chat_completions(
)
# RAG nudge, mirroring the GGUF path.
- _sf_tool_names = {(t.get("function") or {}).get("name") for t in (_sf_tools_to_use or [])}
- _sf_rag_active = "search_knowledge_base" in _sf_tool_names and payload.rag_scope
- if _sf_rag_active:
- _sf_rag_nudge = (
- "The user has attached documents to this conversation. Relevant "
- "passages are retrieved and provided to you automatically; base "
- "your answer on them and cite them. You can also call "
- "search_knowledge_base to look for more. Do not answer from "
- "memory when the attached documents are relevant."
- )
- # Prefix the date when the tool nudge is empty (RAG-only tool set).
- _sf_date_line = f"The current date is {_date.today().isoformat()}."
- _sf_nudge = (
- _sf_date_line + " " + _sf_rag_nudge
- if not _sf_nudge
- else _sf_nudge + " " + _sf_rag_nudge
- )
+ _sf_nudge = _apply_rag_nudge(_sf_nudge, _sf_tools_to_use, rag_scope = payload.rag_scope)
_sf_system_prompt = system_prompt
if _sf_nudge:
@@ -5594,18 +5536,7 @@ async def openai_chat_completions(
async def sf_tool_stream():
gen = None
try:
- first_chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(role = "assistant"),
- finish_reason = None,
- )
- ],
- )
- yield f"data: {first_chunk.model_dump_json(exclude_none = True)}\n\n"
+ yield _chat_role_chunk(completion_id, created, model_name)
gen = sf_generate_with_tools()
prev_text = ""
@@ -5652,31 +5583,9 @@ async def openai_chat_completions(
if not new_text:
continue
api_monitor.append_reply(monitor_id, new_text)
- chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(content = new_text),
- finish_reason = None,
- )
- ],
- )
- yield f"data: {chunk.model_dump_json(exclude_none = True)}\n\n"
+ yield _chat_content_chunk(completion_id, created, model_name, new_text)
- final_chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(),
- finish_reason = "stop",
- )
- ],
- )
- yield f"data: {final_chunk.model_dump_json(exclude_none = True)}\n\n"
+ yield _chat_final_chunk(completion_id, created, model_name, "stop")
# Usage chunk from the last turn, same shape as the
# GGUF tool loop's metadata. Request-scoped holder, so
# concurrent streams cannot read each other's stats.
@@ -5725,15 +5634,7 @@ async def openai_chat_completions(
_sf_tracker.__exit__(None, None, None)
if payload.stream:
- return StreamingResponse(
- sf_tool_stream(),
- media_type = "text/event-stream",
- headers = {
- "Cache-Control": "no-cache",
- "Connection": "close",
- "X-Accel-Buffering": "no",
- },
- )
+ return _sse_streaming_response(sf_tool_stream())
# Non-streaming JSON: drain the loop, build one ChatCompletion.
try:
@@ -5836,18 +5737,7 @@ async def openai_chat_completions(
async def stream_chunks():
try:
- first_chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(role = "assistant"),
- finish_reason = None,
- )
- ],
- )
- yield f"data: {first_chunk.model_dump_json(exclude_none = True)}\n\n"
+ yield _chat_role_chunk(completion_id, created, model_name)
prev_text = ""
# Run the sync generator in a thread pool to avoid blocking the
@@ -5879,31 +5769,9 @@ async def openai_chat_completions(
if not new_text:
continue
api_monitor.append_reply(monitor_id, new_text)
- chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(content = new_text),
- finish_reason = None,
- )
- ],
- )
- yield f"data: {chunk.model_dump_json(exclude_none = True)}\n\n"
+ yield _chat_content_chunk(completion_id, created, model_name, new_text)
- final_chunk = ChatCompletionChunk(
- id = completion_id,
- created = created,
- model = model_name,
- choices = [
- ChunkChoice(
- delta = ChoiceDelta(),
- finish_reason = "stop",
- )
- ],
- )
- yield f"data: {final_chunk.model_dump_json(exclude_none = True)}\n\n"
+ yield _chat_final_chunk(completion_id, created, model_name, "stop")
# Usage chunk (choices=[], usage set), same shape as the
# GGUF path so the speed popover works for MLX too.
# Request-scoped holder, so concurrent streams cannot
@@ -5934,10 +5802,11 @@ async def openai_chat_completions(
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))
+ _msg = _friendly_error(e)
+ api_monitor.fail(monitor_id, _msg)
error_chunk = {
"error": {
- "message": _friendly_error(e),
+ "message": _msg,
"type": "server_error",
},
}
@@ -5945,15 +5814,7 @@ async def openai_chat_completions(
finally:
_tracker.__exit__(None, None, None)
- return StreamingResponse(
- stream_chunks(),
- media_type = "text/event-stream",
- headers = {
- "Cache-Control": "no-cache",
- "Connection": "close",
- "X-Accel-Buffering": "no",
- },
- )
+ return _sse_streaming_response(stream_chunks())
# ── Non-streaming response ────────────────────────────────────
else:
@@ -6017,20 +5878,7 @@ async def serve_sandbox_file(
from fastapi.responses import FileResponse
# ── Authentication (header or query param) ──────────────────
- auth_header = request.headers.get("authorization")
- if auth_header and auth_header.lower().startswith("bearer "):
- jwt_token = auth_header[7:]
- elif token:
- jwt_token = token
- else:
- raise HTTPException(
- status_code = status.HTTP_401_UNAUTHORIZED,
- detail = "Missing authentication token",
- )
- from fastapi.security import HTTPAuthorizationCredentials
-
- creds = HTTPAuthorizationCredentials(scheme = "Bearer", credentials = jwt_token)
- await get_current_subject(creds)
+ await _authenticate_header_or_query(request, token)
# ── Filename sanitization ───────────────────────────────────
safe_filename = os.path.basename(filename)
@@ -6173,6 +6021,14 @@ async def openai_retrieve_model(model_id: str, current_subject: str = Depends(ge
# =====================================================================
+def _flatten_monitor_prompt(value) -> str:
+ """Flatten an OpenAI prompt/input field (str or list) into the single
+ string the api_monitor prompt preview expects."""
+ if isinstance(value, list):
+ return "\n".join(str(part) for part in value)
+ return str(value)
+
+
@router.post("/completions")
async def openai_completions(request: Request, current_subject: str = Depends(get_current_subject)):
"""
@@ -6193,11 +6049,7 @@ 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)
+ prompt_text = _flatten_monitor_prompt(body.get("prompt", ""))
monitor_id = api_monitor.start(
endpoint = request.url.path,
method = request.method,
@@ -6302,28 +6154,14 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
yield f"data: {json.dumps(error_chunk)}\n\n".encode("utf-8")
return
finally:
- if disconnect_watcher is not None:
- disconnect_watcher.cancel()
- try:
- await disconnect_watcher
- except (asyncio.CancelledError, Exception):
- pass
- if bytes_iter is not None:
- try:
- await bytes_iter.aclose()
- except Exception:
- pass
- if resp is not None:
- try:
- await resp.aclose()
- except Exception:
- pass
- try:
- await client.aclose()
- except Exception:
- pass
+ await _aclose_stream_resources(
+ watchers = (disconnect_watcher,),
+ iterator = bytes_iter,
+ resp = resp,
+ client = client,
+ )
- return StreamingResponse(_stream(), media_type = "text/event-stream")
+ return _sse_streaming_response(_stream())
else:
try:
resp = await nonstreaming_client().post(
@@ -6378,11 +6216,7 @@ 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)
+ prompt_text = _flatten_monitor_prompt(body.get("input", ""))
monitor_id = None
if not getattr(request.state, "skip_api_monitor", False):
monitor_id = api_monitor.start(
@@ -6744,14 +6578,17 @@ def _normalise_responses_input(payload: ResponsesRequest) -> list[ChatMessage]:
if payload.instructions:
system_parts.append(payload.instructions)
+ def _with_system(msgs: list[ChatMessage]) -> list[ChatMessage]:
+ if not system_parts:
+ return msgs
+ merged = "\n\n".join(p for p in system_parts if p)
+ return [ChatMessage(role = "system", content = merged), *msgs]
+
# Simple string input
if isinstance(payload.input, str):
if payload.input:
messages.append(ChatMessage(role = "user", content = payload.input))
- if system_parts:
- merged = "\n\n".join(p for p in system_parts if p)
- return [ChatMessage(role = "system", content = merged), *messages]
- return messages
+ return _with_system(messages)
for item in payload.input:
if isinstance(item, ResponsesFunctionCallInputItem):
@@ -6836,10 +6673,7 @@ def _normalise_responses_input(payload: ResponsesRequest) -> list[ChatMessage]:
else:
messages.append(ChatMessage(role = item.role, content = parts))
- if system_parts:
- merged = "\n\n".join(p for p in system_parts if p)
- return [ChatMessage(role = "system", content = merged), *messages]
- return messages
+ return _with_system(messages)
def _build_chat_request(
@@ -6963,9 +6797,7 @@ async def _responses_non_streaming(
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):
+ if isinstance(result, Response):
body = json.loads(result.body.decode())
else:
body = result
@@ -7134,6 +6966,14 @@ async def _responses_stream(
next_output_index += 1
return output_index
+ def _apply_usage(u) -> None:
+ nonlocal input_tokens, output_tokens
+ if not u:
+ return
+ input_tokens = u.get("prompt_tokens", input_tokens)
+ output_tokens = u.get("completion_tokens", output_tokens)
+ _monitor_usage(monitor_id, u, llama_backend.context_length)
+
def _ensure_reasoning_open() -> list[str]:
if reasoning_state["opened"]:
return []
@@ -7391,15 +7231,7 @@ async def _responses_stream(
choices = chunk_data.get("choices", [])
if not choices:
- usage = chunk_data.get("usage")
- 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,
- )
+ _apply_usage(chunk_data.get("usage"))
continue
delta = choices[0].get("delta", {}) or {}
@@ -7493,15 +7325,7 @@ async def _responses_stream(
# if not, stash).
st["arguments"] += arg_delta
- usage = chunk_data.get("usage")
- 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,
- )
+ _apply_usage(chunk_data.get("usage"))
except asyncio.CancelledError:
api_monitor.finish(monitor_id, "cancelled")
raise
@@ -7528,26 +7352,12 @@ async def _responses_stream(
)
return
finally:
- if disconnect_watcher is not None:
- disconnect_watcher.cancel()
- try:
- await disconnect_watcher
- except (asyncio.CancelledError, Exception):
- pass
- if lines_iter is not None:
- try:
- await lines_iter.aclose()
- except Exception:
- pass
- if resp is not None:
- try:
- await resp.aclose()
- except Exception:
- pass
- try:
- await client.aclose()
- except Exception:
- pass
+ await _aclose_stream_resources(
+ watchers = (disconnect_watcher,),
+ iterator = lines_iter,
+ resp = resp,
+ client = client,
+ )
if disconnect_event.is_set():
api_monitor.finish(monitor_id, "cancelled")
@@ -7758,15 +7568,7 @@ async def _responses_stream(
api_monitor.finish(monitor_id)
yield _sse("response.completed", completed_response)
- return StreamingResponse(
- event_generator(),
- media_type = "text/event-stream",
- headers = {
- "Cache-Control": "no-cache",
- "Connection": "close",
- "X-Accel-Buffering": "no",
- },
- )
+ return _sse_streaming_response(event_generator())
@router.post("/responses")
@@ -7857,6 +7659,20 @@ def _select_anthropic_server_tools(
return [tool for tool in all_tools if tool["function"]["name"] in selected_names]
+def _image_bytes_to_png_b64(raw: bytes) -> str:
+ """Decode raw image bytes and re-encode to a base64-ascii PNG string.
+
+ llama-server's stb_image only handles a few formats (JPEG/PNG/BMP/...); re-
+ encoding to PNG keeps JPEG/WebP/... inputs loadable. Raises on undecodable
+ input; callers wrap the call in ``try`` -> HTTPException(400)."""
+ from PIL import Image
+
+ img = Image.open(io.BytesIO(raw)).convert("RGB")
+ buf = io.BytesIO()
+ img.save(buf, format = "PNG")
+ return base64.b64encode(buf.getvalue()).decode("ascii")
+
+
def _normalize_anthropic_openai_images(openai_messages: list[dict], is_vision: bool) -> bool:
"""Enforce the vision guard on translated Anthropic messages and normalize
any base64-data-URL ``image_url`` parts to PNG.
@@ -7871,8 +7687,6 @@ def _normalize_anthropic_openai_images(openai_messages: list[dict], is_vision: b
when images are present but the active model isn't a vision model, or when
an image cannot be decoded.
"""
- from PIL import Image
-
has_image = False
for msg in openai_messages:
content = msg.get("content")
@@ -7898,10 +7712,7 @@ def _normalize_anthropic_openai_images(openai_messages: list[dict], is_vision: b
try:
_, b64data = url.split(",", 1)
raw = base64.b64decode(b64data)
- img = Image.open(io.BytesIO(raw)).convert("RGB")
- buf = io.BytesIO()
- img.save(buf, format = "PNG")
- png_b64 = base64.b64encode(buf.getvalue()).decode("ascii")
+ png_b64 = _image_bytes_to_png_b64(raw)
except Exception:
raise HTTPException(
status_code = 400,
@@ -8430,15 +8241,7 @@ async def _anthropic_tool_stream(
for line in emitter.finish(stop_reason = stop_reason, stop_sequence = None):
yield line
- return StreamingResponse(
- _stream(),
- media_type = "text/event-stream",
- headers = {
- "Cache-Control": "no-cache",
- "Connection": "close",
- "X-Accel-Buffering": "no",
- },
- )
+ return _sse_streaming_response(_stream())
async def _anthropic_plain_stream(
@@ -8497,15 +8300,7 @@ async def _anthropic_plain_stream(
for line in emitter.finish(stop_reason = stop_reason, stop_sequence = None):
yield line
- return StreamingResponse(
- _stream(),
- media_type = "text/event-stream",
- headers = {
- "Cache-Control": "no-cache",
- "Connection": "close",
- "X-Accel-Buffering": "no",
- },
- )
+ return _sse_streaming_response(_stream())
def _anthropic_map_generation_error(e: Exception) -> HTTPException:
@@ -8534,6 +8329,25 @@ def _collect_anthropic_events(run_gen) -> list:
raise _anthropic_map_generation_error(e)
+def _anthropic_message_json_response(
+ message_id, model_name, content_blocks, stop_reason, usage
+) -> Response:
+ """Assemble the terminal Anthropic non-streaming JSON response shared by the
+ tool / plain / passthrough paths."""
+ return _model_json_response(
+ AnthropicMessagesResponse(
+ id = message_id,
+ model = model_name,
+ content = content_blocks,
+ stop_reason = stop_reason,
+ usage = AnthropicUsage(
+ input_tokens = usage.get("prompt_tokens", 0),
+ output_tokens = usage.get("completion_tokens", 0),
+ ),
+ )
+ )
+
+
async def _anthropic_tool_non_streaming(
run_gen,
message_id,
@@ -8626,17 +8440,9 @@ async def _anthropic_tool_non_streaming(
captured_finish_reason, had_tool_calls = ends_on_tool_use
)
- resp = AnthropicMessagesResponse(
- id = message_id,
- model = model_name,
- content = content_blocks,
- stop_reason = stop_reason,
- usage = AnthropicUsage(
- input_tokens = usage.get("prompt_tokens", 0),
- output_tokens = usage.get("completion_tokens", 0),
- ),
+ return _anthropic_message_json_response(
+ message_id, model_name, content_blocks, stop_reason, usage
)
- return _model_json_response(resp)
async def _anthropic_plain_non_streaming(run_gen, message_id, model_name):
@@ -8668,17 +8474,9 @@ async def _anthropic_plain_non_streaming(run_gen, message_id, model_name):
stop_reason = openai_finish_to_anthropic_stop(captured_finish_reason, had_tool_calls = False)
- resp = AnthropicMessagesResponse(
- id = message_id,
- model = model_name,
- content = content_blocks,
- stop_reason = stop_reason,
- usage = AnthropicUsage(
- input_tokens = usage.get("prompt_tokens", 0),
- output_tokens = usage.get("completion_tokens", 0),
- ),
+ return _anthropic_message_json_response(
+ message_id, model_name, content_blocks, stop_reason, usage
)
- return _model_json_response(resp)
# =====================================================================
@@ -8896,17 +8694,6 @@ async def _anthropic_passthrough_stream(
_drop_parallel_tool_call_deltas(chunk)
for line in emitter.feed_chunk(chunk):
yield line
- except (httpx.RemoteProtocolError, httpx.ReadError, httpx.CloseError) as e:
- if not cancel_event.is_set():
- logger.error("anthropic_messages passthrough stream error: %s", e)
- get_llama_cpp_backend()._maybe_recover_from_mtp_crash(e)
- event = _anthropic_stream_error_event(
- e,
- force = True,
- )
- if event is not None:
- yield event
- return
except Exception as e:
if not cancel_event.is_set():
logger.error("anthropic_messages passthrough stream error: %s", e)
@@ -8919,46 +8706,18 @@ async def _anthropic_passthrough_stream(
yield event
return
finally:
- if cancel_watcher is not None:
- cancel_watcher.cancel()
- try:
- await cancel_watcher
- except (asyncio.CancelledError, Exception):
- pass
- if disconnect_watcher is not None:
- disconnect_watcher.cancel()
- try:
- await disconnect_watcher
- except (asyncio.CancelledError, Exception):
- pass
- if lines_iter is not None:
- try:
- await lines_iter.aclose()
- except Exception:
- pass
- if resp is not None:
- try:
- await resp.aclose()
- except Exception:
- pass
- try:
- await client.aclose()
- except Exception:
- pass
+ await _aclose_stream_resources(
+ watchers = (cancel_watcher, disconnect_watcher),
+ iterator = lines_iter,
+ resp = resp,
+ client = client,
+ )
_tracker.__exit__(None, None, None)
for line in emitter.finish():
yield line
- return StreamingResponse(
- _stream(),
- media_type = "text/event-stream",
- headers = {
- "Cache-Control": "no-cache",
- "Connection": "close",
- "X-Accel-Buffering": "no",
- },
- )
+ return _sse_streaming_response(_stream())
async def _anthropic_passthrough_non_streaming(
@@ -9041,17 +8800,9 @@ async def _anthropic_passthrough_non_streaming(
stop_reason = openai_finish_to_anthropic_stop(finish_reason, had_tool_calls = bool(tool_calls))
usage = data.get("usage") or {}
- resp_obj = AnthropicMessagesResponse(
- id = message_id,
- model = model_name,
- content = content_blocks,
- stop_reason = stop_reason,
- usage = AnthropicUsage(
- input_tokens = usage.get("prompt_tokens", 0),
- output_tokens = usage.get("completion_tokens", 0),
- ),
+ return _anthropic_message_json_response(
+ message_id, model_name, content_blocks, stop_reason, usage
)
- return _model_json_response(resp_obj)
# =====================================================================
@@ -9212,6 +8963,27 @@ def _strip_provider_synthetic_tool_history(messages: list[dict]) -> list[dict]:
return out
+def _splice_image_into_last_user(messages: list[dict], image_part: dict) -> None:
+ """Splice an image content part into the last user message, in place.
+
+ String content becomes a text part plus the image; an existing content-part
+ list gets the image appended; any other shape is replaced by the lone image.
+ With no user message present, a new user turn carrying the image is appended."""
+ for msg in reversed(messages):
+ if msg.get("role") != "user":
+ continue
+ existing = msg.get("content")
+ if isinstance(existing, str):
+ msg["content"] = [{"type": "text", "text": existing}, image_part]
+ elif isinstance(existing, list):
+ existing.append(image_part)
+ else:
+ msg["content"] = [image_part]
+ break
+ else:
+ messages.append({"role": "user", "content": [image_part]})
+
+
def _openai_messages_for_passthrough(payload) -> list[dict]:
"""Build OpenAI-format message dicts for the /v1/chat/completions
passthrough path.
@@ -9235,15 +9007,8 @@ def _openai_messages_for_passthrough(payload) -> list[dict]:
return messages
try:
- import base64 as _b64
- from io import BytesIO as _BytesIO
- from PIL import Image as _Image
-
- raw = _b64.b64decode(payload.image_base64)
- img = _Image.open(_BytesIO(raw)).convert("RGB")
- buf = _BytesIO()
- img.save(buf, format = "PNG")
- png_b64 = _b64.b64encode(buf.getvalue()).decode("ascii")
+ raw = base64.b64decode(payload.image_base64)
+ png_b64 = _image_bytes_to_png_b64(raw)
except Exception:
raise HTTPException(
status_code = 400,
@@ -9253,19 +9018,7 @@ def _openai_messages_for_passthrough(payload) -> list[dict]:
data_url = f"data:image/png;base64,{png_b64}"
image_part = {"type": "image_url", "image_url": {"url": data_url}}
- for msg in reversed(messages):
- if msg.get("role") != "user":
- continue
- existing = msg.get("content")
- if isinstance(existing, str):
- msg["content"] = [{"type": "text", "text": existing}, image_part]
- elif isinstance(existing, list):
- existing.append(image_part)
- else:
- msg["content"] = [image_part]
- break
- else:
- messages.append({"role": "user", "content": [image_part]})
+ _splice_image_into_last_user(messages, image_part)
return messages
@@ -9300,19 +9053,7 @@ def _openai_messages_for_gguf_chat(payload, is_vision: bool) -> tuple[list[dict]
"url": f"data:image/png;base64,{payload.image_base64}",
},
}
- for msg in reversed(messages):
- if msg.get("role") != "user":
- continue
- existing = msg.get("content")
- if isinstance(existing, str):
- msg["content"] = [{"type": "text", "text": existing}, image_part]
- elif isinstance(existing, list):
- existing.append(image_part)
- else:
- msg["content"] = [image_part]
- break
- else:
- messages.append({"role": "user", "content": [image_part]})
+ _splice_image_into_last_user(messages, image_part)
has_image = _normalize_anthropic_openai_images(messages, is_vision)
return messages, has_image
@@ -9433,15 +9174,7 @@ async def _openai_passthrough_stream(
# 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()
- except Exception:
- pass
- try:
- await client.aclose()
- except Exception:
- pass
+ await _aclose_stream_resources(resp = resp, client = client)
raise HTTPException(
status_code = 502,
detail = _friendly_error(e),
@@ -9561,40 +9294,15 @@ async def _openai_passthrough_stream(
err = _openai_stream_error_chunk(e)
yield f"data: {json.dumps(err)}\n\n"
finally:
- cancel_watcher.cancel()
- try:
- await cancel_watcher
- except (asyncio.CancelledError, Exception):
- pass
- disconnect_watcher.cancel()
- try:
- await disconnect_watcher
- except (asyncio.CancelledError, Exception):
- pass
- if lines_iter is not None:
- try:
- await lines_iter.aclose()
- except Exception:
- pass
- try:
- await resp.aclose()
- except Exception:
- pass
- try:
- await client.aclose()
- except Exception:
- pass
+ await _aclose_stream_resources(
+ watchers = (cancel_watcher, disconnect_watcher),
+ iterator = lines_iter,
+ resp = resp,
+ client = client,
+ )
_tracker.__exit__(None, None, None)
- return StreamingResponse(
- _stream(),
- media_type = "text/event-stream",
- headers = {
- "Cache-Control": "no-cache",
- "Connection": "close",
- "X-Accel-Buffering": "no",
- },
- )
+ return _sse_streaming_response(_stream())
except BaseException:
_tracker.__exit__(None, None, None)
raise
@@ -9708,12 +9416,10 @@ async def _openai_passthrough_non_streaming(
msg["content"] = f"```json\n{stripped}\n```"
changed = True
- # 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)
+ if not changed:
+ # Nothing mutated: relay the upstream bytes verbatim, skipping a
+ # redundant parse + re-serialize round-trip.
+ return Response(content = resp.content, media_type = "application/json")
return JSONResponse(content = data)
diff --git a/studio/backend/tests/test_mtp_vram_budget.py b/studio/backend/tests/test_mtp_vram_budget.py
index 02f0c37b4df..0efbbf596d6 100644
--- a/studio/backend/tests/test_mtp_vram_budget.py
+++ b/studio/backend/tests/test_mtp_vram_budget.py
@@ -878,8 +878,10 @@ class TestExtraArgsMtpDetection:
# f16/f16 on the layer fallback) (#6312).
load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
assert "_tensor_dropped_extra_args=list(extra_args)" in load
- # All three tensor->layer downgrade points restore the saved originals.
- assert load.count("strip_split_mode_only(_tensor_dropped_extra_argsif") == 3
+ # The original extras are restored via one shared closure, called at all
+ # three tensor->layer downgrade points.
+ assert "strip_split_mode_only(_tensor_dropped_extra_argsif" in load
+ assert load.count("_restore_after_tensor_downgrade()") >= 3
def test_load_model_tensor_skips_reserve_for_cpu_drafter(self):
# A separate CPU-offloaded drafter (no embedded head) uses no GPU, so the
diff --git a/studio/backend/tests/test_sse_streaming_headers.py b/studio/backend/tests/test_sse_streaming_headers.py
new file mode 100644
index 00000000000..ef6022fa26b
--- /dev/null
+++ b/studio/backend/tests/test_sse_streaming_headers.py
@@ -0,0 +1,22 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression tests for the shared SSE streaming-response helper.
+
+Streaming endpoints must disable proxy buffering (``X-Accel-Buffering: no``);
+without it a reverse proxy (nginx / cloudflare tunnel) buffers the response and
+tokens stop appearing in real time. The native ``/generate/stream`` and legacy
+``/v1/completions`` streams historically omitted it and now route through the
+shared helper, so locking the helper's headers guards every standard path.
+"""
+
+import routes.inference as inference_route
+
+
+def test_sse_helper_sets_no_proxy_buffering_headers():
+ resp = inference_route._sse_streaming_response(iter(()))
+ assert resp.media_type == "text/event-stream"
+ # Starlette lowercases header keys in init_headers.
+ assert resp.headers["cache-control"] == "no-cache"
+ assert resp.headers["connection"] == "close"
+ assert resp.headers["x-accel-buffering"] == "no"
diff --git a/studio/backend/tests/test_tensor_parallel.py b/studio/backend/tests/test_tensor_parallel.py
index 86ac79eda9f..1248386020e 100644
--- a/studio/backend/tests/test_tensor_parallel.py
+++ b/studio/backend/tests/test_tensor_parallel.py
@@ -1153,4 +1153,7 @@ def test_load_model_restores_quantized_kv_on_tensor_downgrade():
# GPU-count and capacity-gate downgrades.
compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
assert "_tensor_dropped_cache_type_kv=cache_type_kv" in compact # captured pre-null
- assert compact.count("cache_type_kv=_tensor_dropped_cache_type_kv") >= 2 # restored
+ # Restore is shared in one closure, called at every tensor->layer downgrade.
+ assert "cache_type_kv=_tensor_dropped_cache_type_kv" in compact # restored in the closure
+ assert "def_restore_after_tensor_downgrade():" in compact # one shared restore helper
+ assert compact.count("_restore_after_tensor_downgrade()") >= 3 # called at each downgrade