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: keep tools available when a picture is attached (#10092)

Nilay97e12a25e962
diff --git a/studio/backend/core/inference/chat_template_helpers.py b/studio/backend/core/inference/chat_template_helpers.py
index 58006c63117..b02f5dfd9fb 100644
--- a/studio/backend/core/inference/chat_template_helpers.py
+++ b/studio/backend/core/inference/chat_template_helpers.py
@@ -1832,18 +1832,26 @@ def _template_reads_tools(
value,
tools,
prefer_tool_use: bool = True,
+ require_tools_variable: bool = False,
) -> bool:
"""True unless the template selected out of *value* takes no part in tool calling.
Reading the ``tools`` variable is the direct case. Replaying tool calls counts too:
such a template round-trips a tool turn it never advertised, so the schema came from
- the caller's own system prompt and the catalog is authorized after all."""
+ the caller's own system prompt and the catalog is authorized after all.
+
+ ``require_tools_variable`` drops that second clause, for callers asking whether THIS
+ render puts the schema in the prompt: a template that only round-trips renders
+ byte-identically with and without a catalog, so the healer would otherwise promote
+ calls for tools the model never saw (#7066)."""
bodies = _selected_template_strings_from_value(value, tools, prefer_tool_use = prefer_tool_use)
if not bodies:
# Unreadable, not proven silent. Emptying the catalog here would disable healing
# for every model whose template shape this module cannot parse, which is a
# feature regression rather than the narrow authorization fix (#7066).
return True
+ if require_tools_variable:
+ return any(_reads_tools_variable(body) for body in bodies)
return any(_reads_tools_variable(body) or _round_trips_tool_calls(body) for body in bodies)
@@ -1866,14 +1874,33 @@ def _accepts_tools_kwarg(target) -> bool:
return "tools" in parameters
-def _renders_tool_schema(target, template, tools) -> bool:
- """True unless the template *target* will select provably cannot advertise tools."""
+def _renders_tool_schema(
+ target,
+ template,
+ tools,
+ template_is_processor: bool = False,
+) -> bool:
+ """True unless the template *target* will select provably cannot advertise tools.
+
+ A processor is held to the stricter test: its render has no native-template fallback
+ behind it (a text model's template cannot place the image), so what the processor's own
+ body does with ``tools`` is the whole answer.
+
+ ``template_is_processor`` says the *template* is a processor body even though *target*
+ is not: under the orchestrator the route has only the body mirrored through worker IPC,
+ which would otherwise be judged by the permissive tokenizer rule (#10092)."""
if tools and not _accepts_tools_kwarg(target):
return False
value = template or getattr(target, "chat_template", None)
if not value:
value = getattr(getattr(target, "tokenizer", None), "chat_template", None)
- return _template_reads_tools(value, tools, prefer_tool_use = not _is_processor(target))
+ is_processor = template_is_processor or _is_processor(target)
+ return _template_reads_tools(
+ value,
+ tools,
+ prefer_tool_use = not is_processor,
+ require_tools_variable = is_processor,
+ )
def renderable_tool_catalog_for_targets(
@@ -1883,6 +1910,7 @@ def renderable_tool_catalog_for_targets(
cache = None,
active_model_name = None,
template = None,
+ template_is_processor: bool = False,
):
"""The catalog safe under every object a backend could render this turn with.
@@ -1907,11 +1935,13 @@ def renderable_tool_catalog_for_targets(
# sanitized during the render, so a tool dropped from the prompt stayed authorized
# for healing. One None target profiles as unprofilable and takes the curated
# sweep, the safe direction (#7066).
- return renderable_tool_catalog(tools, None, model_info, cache, active_model_name, template)
+ return renderable_tool_catalog(
+ tools, None, model_info, cache, active_model_name, template, template_is_processor
+ )
catalog = tools
for target in live:
catalog = renderable_tool_catalog(
- catalog, target, model_info, cache, active_model_name, template
+ catalog, target, model_info, cache, active_model_name, template, template_is_processor
)
if not catalog:
return catalog
@@ -1925,6 +1955,7 @@ def renderable_tool_catalog(
cache = None,
active_model_name = None,
template = None,
+ template_is_processor: bool = False,
):
"""The catalog that survives EVERY template this request could render with.
@@ -1958,13 +1989,16 @@ def renderable_tool_catalog(
)
return []
- active_renders_tools = _renders_tool_schema(tokenizer, template, tools)
+ active_renders_tools = _renders_tool_schema(
+ tokenizer, template, tools, template_is_processor = template_is_processor
+ )
# A processor stays on "default" and the VLM path renders straight through
# apply_chat_template_for_generation, with no native-template fallback behind it
# (mlx_inference.py). When that default body never reads ``tools`` the schema cannot
# reach the prompt at all, so every tool in the catalog is unadvertised and healing a
# text-form call would promote one the model was never shown (#7066).
- if _is_processor(tokenizer) and not active_renders_tools:
+ # Counts here too: the orchestrator passes tokenizer=None, not a processor (#10092).
+ if (template_is_processor or _is_processor(tokenizer)) and not active_renders_tools:
return _unadvertised()
# Resolved rather than read: render_native_template fetches it during the render, so on
# the FIRST request needing the fallback the cache is still empty and this would hand
@@ -2937,6 +2971,185 @@ def last_user_text(messages: list) -> str:
return ""
+def count_structured_images(content) -> int:
+ """Number of structured image parts in a message *content* (or a bare part)."""
+ if isinstance(content, list):
+ return sum(count_structured_images(item) for item in content)
+ if not isinstance(content, dict):
+ return 0
+ if str(content.get("type", "")).lower() in ("image", "image_url", "input_image"):
+ return 1
+ return count_structured_images(content.get("content"))
+
+
+def structured_media_reprs(content) -> set:
+ """Every spelling a template could print a structured image part as."""
+ if isinstance(content, list):
+ values = (
+ {str(content), json.dumps(content, ensure_ascii = False)}
+ if count_structured_images(content)
+ else set()
+ )
+ for item in content:
+ values.update(structured_media_reprs(item))
+ return values
+ if not isinstance(content, dict):
+ return set()
+ if str(content.get("type", "")).lower() in ("image", "image_url", "input_image"):
+ return {str(content), json.dumps(content, ensure_ascii = False)}
+ return structured_media_reprs(content.get("content"))
+
+
+def prompt_serializes_structured_media(prompt, messages) -> bool:
+ """Detect templates that embed the exact structured media object repr."""
+ from core.inference.message_content import content_to_text
+
+ media_reprs = set()
+ for message in messages:
+ if isinstance(message, dict):
+ media_reprs.update(structured_media_reprs(message.get("content")))
+ text_content = [
+ content_to_text(message.get("content")) for message in messages if isinstance(message, dict)
+ ]
+ return any(
+ prompt.count(media_repr) > sum(content.count(media_repr) for content in text_content)
+ for media_repr in media_reprs
+ )
+
+
+def vlm_prompt_issue(prompt, messages) -> Optional[str]:
+ """Name the way a VLM render came back unusable, else None.
+
+ Shared by both backends so a defect one of them refuses stays refused by the other.
+ """
+ if not isinstance(prompt, str) or not prompt.strip():
+ return "an empty prompt"
+ if prompt_serializes_structured_media(prompt, messages):
+ return "serialized structured image content"
+ return None
+
+
+def messages_have_tool_history(messages) -> bool:
+ """True when the conversation replays a tool call or a tool result."""
+ return any(
+ isinstance(message, dict)
+ and (
+ message.get("role") == "tool"
+ or message.get("tool_calls")
+ or message.get("tool_call_id")
+ )
+ for message in messages
+ )
+
+
+def messages_with_attached_image(
+ messages: list,
+ system_prompt: str = "",
+ fallback_user_text: str = "",
+ structured_content: bool = False,
+) -> list:
+ """The conversation to render for a turn that carries an attached image.
+
+ Prepends *system_prompt* as a leading system turn, then injects an ``{"type": "image"}``
+ part into the LAST user turn and leaves every other turn -- assistant ``tool_calls``
+ and ``role="tool"`` results included -- exactly as the caller sent it. Rebuilding from
+ the newest user TEXT instead dropped the folded system instruction and the tool history
+ an OpenAI tool loop replays (#10092).
+
+ Nothing the caller owns is mutated: callers still read those dicts after generation,
+ and a retry re-renders the same list.
+
+ *structured_content* wraps content in part lists, as a processor template expects; MLX
+ may render through the nested text tokenizer, whose template expects a string.
+
+ *fallback_user_text* stands in for a user turn with no text of its own, and opens one
+ when there is no user turn at all. Left empty, the conversation is unchanged, so a
+ backend that would rather refuse an image nobody asked about keeps refusing it.
+ """
+ conversation = list(messages or [])
+ if structured_content:
+ # EVERY message: a processor template raises on a replayed turn left as a string.
+ def _as_parts(message):
+ if not isinstance(message, dict):
+ return message
+ body = message.get("content")
+ if isinstance(body, list):
+ return message
+ if isinstance(body, str) and body:
+ return {**message, "content": [{"type": "text", "text": body}]}
+ # exclude_none strips content from an assistant tool-call turn entirely.
+ return {**message, "content": []}
+
+ conversation = [_as_parts(m) for m in conversation]
+ if system_prompt:
+ conversation.insert(
+ 0,
+ {
+ "role": "system",
+ "content": (
+ [{"type": "text", "text": system_prompt}]
+ if structured_content
+ else system_prompt
+ ),
+ },
+ )
+ # Once: a reverse scan would mark a nudge retry's correction, not the question.
+ if any(
+ isinstance(m, dict)
+ and isinstance(m.get("content"), list)
+ and count_structured_images(m["content"])
+ for m in conversation
+ ):
+ return conversation
+ for index in range(len(conversation) - 1, -1, -1):
+ message = conversation[index]
+ if not isinstance(message, dict) or message.get("role") != "user":
+ continue
+ content = message.get("content", "")
+ if isinstance(content, str):
+ parts = [{"type": "image"}, {"type": "text", "text": content or fallback_user_text}]
+ elif isinstance(content, list):
+ parts = list(content)
+ if not count_structured_images(parts):
+ parts.insert(0, {"type": "image"})
+ else:
+ break
+ conversation[index] = {**message, "content": parts}
+ return conversation
+ if fallback_user_text:
+ conversation.append(
+ {
+ "role": "user",
+ "content": [{"type": "image"}, {"type": "text", "text": fallback_user_text}],
+ }
+ )
+ return conversation
+
+
+def render_advertising_tools(render, tools):
+ """Render with *tools*, and say whether the prompt actually carries them.
+
+ Returns ``(prompt, advertised)``. *render* takes a catalog and returns a prompt.
+
+ Comparing the two renders rather than reading the body: a body that merely names the
+ ``tools`` variable can still drop the schema, and a renderer taking ``tools=`` through
+ ``**kwargs`` can swallow it without ever raising.
+
+ The no-tools probe runs FIRST so the prompt this turn uses is the last thing the
+ renderer produced, for anything that caches or observes the render. A probe that raises
+ answers "advertised": the render that failed is the throwaway one.
+ """
+ if not tools:
+ return render(None), False
+ try:
+ without_tools = render(None)
+ except Exception as exc:
+ logger.debug("No-tools probe failed; keeping the tools prompt: %s", exc)
+ return render(tools), True
+ prompt = render(tools)
+ return prompt, prompt != without_tools
+
+
def append_assistant_turn(
conversation: list,
assistant_msg: dict,
@@ -2986,6 +3199,7 @@ def render_prompt_with_boundary(
processor,
messages: list,
continue_final_message: bool = False,
+ tools: Optional[list] = None,
) -> str:
"""Render *messages* through a renderer's own chat template.
@@ -2994,23 +3208,44 @@ def render_prompt_with_boundary(
partial from *messages* (which the caller already swept) rather than a separate copy:
a raw partial could close the turn or open another role instead of resuming (#7066).
"""
+ extra = {"tools": tools} if tools else {}
partial = trailing_assistant_text(messages) if continue_final_message else None
if not partial:
- return processor.apply_chat_template(messages, add_generation_prompt = True, tokenize = False)
+ return processor.apply_chat_template(
+ messages, add_generation_prompt = True, tokenize = False, **extra
+ )
try:
return processor.apply_chat_template(
messages,
add_generation_prompt = False,
continue_final_message = True,
tokenize = False,
+ **extra,
)
except TypeError:
prefix = processor.apply_chat_template(
- messages[:-1], add_generation_prompt = True, tokenize = False
+ messages[:-1], add_generation_prompt = True, tokenize = False, **extra
)
return f"{strip_open_reasoning_prefill(prefix)}{partial}"
+def neutralize_for_render(tokenizer, messages: list, tools: Optional[list]):
+ """Sweep the catalog and the messages for control markup, in the one correct order.
+
+ Returns ``(messages, tools, markup)``. One place because the sweep is order dependent:
+ a call site that re-derived it swept the messages against a profile the render would
+ not select (#7066).
+ """
+ # Gated on the loaded model's own markers, so another family's sentinel is left alone.
+ markup = markup_for_tokenizer(tokenizer, tools)
+ tools = neutralize_tool_descriptions(tools, None, markup)
+ # Sanitizing can empty the catalog, which flips the selector, so re-profile first
+ # or the messages are swept against a template this request will not use (#7066).
+ if bool(tools) != bool(markup and getattr(markup, "selected_with_tools", False)):
+ markup = markup_for_tokenizer(tokenizer, tools)
+ return neutralize_control_markup_in_messages(messages, None, markup), tools, markup
+
+
def apply_chat_template_for_generation(
tokenizer,
messages: list,
@@ -3027,17 +3262,8 @@ def apply_chat_template_for_generation(
With *continue_final_message* the prompt ends inside the trailing assistant
turn, so the model resumes the partial instead of restarting it."""
- # Shared choke point for the transformers and MLX backends (#7066). Gated on the
- # loaded model's own markers, so text naming another family's sentinel is left alone.
- _markup = markup_for_tokenizer(tokenizer, tools)
- tools = neutralize_tool_descriptions(tools, None, _markup)
- # Sanitizing can empty the catalog, and an empty catalog renders with "default" rather
- # than "tool_use". Re-profile before sweeping the messages, or they are swept against a
- # template this request will not use and a default-only delimiter reaches the prompt
- # raw. Order matters: the catalog is sanitized first so the selector is settled (#7066).
- if bool(tools) != bool(_markup and getattr(_markup, "selected_with_tools", False)):
- _markup = markup_for_tokenizer(tokenizer, tools)
- messages = neutralize_control_markup_in_messages(messages, None, _markup)
+ # Shared choke point for the transformers and MLX backends (#7066).
+ messages, tools, _markup = neutralize_for_render(tokenizer, messages, tools)
reasoning_kwargs: dict = {}
if enable_thinking is not None:
reasoning_kwargs["enable_thinking"] = enable_thinking
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.py
index 18f96018546..72bf5884fde 100644
--- a/studio/backend/core/inference/inference.py
+++ b/studio/backend/core/inference/inference.py
@@ -1148,6 +1148,7 @@ class InferenceBackend:
cancel_event = cancel_event,
presence_penalty = presence_penalty,
continue_final_message = continue_final_message,
+ tools = tools,
)
return
else:
@@ -1292,6 +1293,7 @@ class InferenceBackend:
cancel_event = None,
presence_penalty: float = 0.0,
continue_final_message: bool = False,
+ tools: Optional[list] = None,
) -> Generator[str, None, None]:
"""Handle vision model generation with true token-by-token streaming."""
# Reset so a failed or uncountable run cannot surface stale stats.
@@ -1308,8 +1310,12 @@ class InferenceBackend:
# prompts from the turn that asked the question.
from core.inference.chat_template_helpers import (
last_user_text,
+ messages_have_tool_history,
+ messages_with_attached_image,
+ render_advertising_tools,
render_prompt_with_boundary,
trailing_assistant_text,
+ vlm_prompt_issue,
)
user_message = last_user_text(messages)
@@ -1320,61 +1326,144 @@ class InferenceBackend:
# Prepare vision messages
if image:
- user_msg = {
- "role": "user",
- "content": [
- {"type": "image"},
- {"type": "text", "text": user_message},
- ],
- }
- if system_prompt:
- vision_messages = [
- {
- "role": "system",
- "content": [{"type": "text", "text": system_prompt}],
- },
- user_msg,
- ]
- else:
- vision_messages = [user_msg]
-
- # Resume the partial answer instead of opening a new turn.
- if continue_partial:
- vision_messages.append(
- {
- "role": "assistant",
- "content": [{"type": "text", "text": continue_partial}],
- }
+ # Ordinary vision turns keep the historic collapse; full history is unbounded.
+ has_tool_history = messages_have_tool_history(messages)
+ # Client-tools route signature: tool_choice="none" and a forced unknown name
+ # also arrive tools=None, and the catalog alone missed them (#10092).
+ folded_system = not system_prompt and any(
+ isinstance(m, dict) and m.get("role") in ("system", "developer") for m in messages
+ )
+ if bool(tools) or has_tool_history or folded_system:
+ # Rebuilding from newest user TEXT dropped the system turn and the tool
+ # history an OpenAI tool loop replays (#10092).
+ vision_messages = messages_with_attached_image(
+ messages,
+ system_prompt = system_prompt,
+ fallback_user_text = user_message,
+ structured_content = True,
)
- # Processor's own template skips the choke point (#7066). Rebind user_msg
- # so the no-system retry keeps the copy. Profiled from the processor, so a
- # vision request is gated on the loaded model exactly as the text path is.
- from core.inference.chat_template_helpers import markup_for_tokenizer
-
- vision_messages = neutralize_control_markup_in_messages(
- vision_messages, None, markup_for_tokenizer(processor)
- )
- user_msg = next(m for m in reversed(vision_messages) if m.get("role") == "user")
+ # The conversation the LAST render used, not the no-tools probe's (#10092).
+ rendered_with: dict = {"messages": vision_messages}
- def _render_vision(msgs):
- # Partial taken from the swept msgs, not the raw pre-sweep capture.
- return render_prompt_with_boundary(
- processor, msgs, continue_final_message = bool(continue_partial)
- )
+ def _render_vision(catalog):
+ rendered_with["messages"] = vision_messages
+ try:
+ rendered = self._apply_chat_template_for_generation(
+ processor,
+ vision_messages,
+ tools = catalog,
+ continue_final_message = bool(continue_partial),
+ )
+ except Exception as e: # noqa: F841 -- read by the fallback below
+ without_system = [
+ m
+ for m in vision_messages
+ if not (isinstance(m, dict) and m.get("role") == "system")
+ ]
+ # Only where an unsupported system role is the last explanation.
+ if (
+ has_tool_history
+ or rendered_with.get("system_ok")
+ or len(without_system) == len(vision_messages)
+ ):
+ raise
+ logger.warning(
+ f"Vision processor for '{self.active_model_name}' may not support "
+ f"system messages; retrying without. Original error: {e}"
+ )
+ rendered = self._apply_chat_template_for_generation(
+ processor,
+ without_system,
+ tools = catalog,
+ continue_final_message = bool(continue_partial),
+ )
+ rendered_with["messages"] = without_system
+ return rendered
+ else:
+ # A render that kept the system turn proves the role is supported.
+ if any(
+ isinstance(m, dict) and m.get("role") == "system"
+ for m in vision_messages
+ ):
+ rendered_with["system_ok"] = True
+ return rendered
+
+ input_text, tools_advertised = render_advertising_tools(_render_vision, tools)
+ vision_messages = rendered_with["messages"]
+
+ prompt_issue = vlm_prompt_issue(input_text, vision_messages)
+ if prompt_issue and has_tool_history:
+ raise RuntimeError(
+ f"Vision chat template returned {prompt_issue} and cannot be recovered "
+ "without dropping tool-call history."
+ )
+ if prompt_issue:
+ raise RuntimeError(f"Vision chat template returned {prompt_issue}.")
- try:
- input_text = _render_vision(vision_messages)
- except Exception as e:
- if system_prompt:
+ if tools and not tools_advertised:
+ # Served anyway: refusing turns an answerable question into an error.
logger.warning(
- f"Vision processor for '{self.active_model_name}' may not support "
- f"system messages; retrying without. Original error: {e}"
+ "Vision chat template for '%s' rendered the same prompt with and "
+ "without the requested tools; serving the turn without the catalog.",
+ self.active_model_name,
)
- vision_messages = [m for m in vision_messages if m.get("role") != "system"]
- input_text = _render_vision(vision_messages)
+ else:
+ user_msg = {
+ "role": "user",
+ "content": [
+ {"type": "image"},
+ {"type": "text", "text": user_message},
+ ],
+ }
+ if system_prompt:
+ vision_messages = [
+ {
+ "role": "system",
+ "content": [{"type": "text", "text": system_prompt}],
+ },
+ user_msg,
+ ]
else:
- raise
+ vision_messages = [user_msg]
+
+ # Resume the partial answer instead of opening a new turn.
+ if continue_partial:
+ vision_messages.append(
+ {
+ "role": "assistant",
+ "content": [{"type": "text", "text": continue_partial}],
+ }
+ )
+
+ # Processor's own template skips the choke point (#7066). Rebind user_msg
+ # so the no-system retry keeps the copy.
+ from core.inference.chat_template_helpers import markup_for_tokenizer
+
+ vision_messages = neutralize_control_markup_in_messages(
+ vision_messages, None, markup_for_tokenizer(processor)
+ )
+ user_msg = next(m for m in reversed(vision_messages) if m.get("role") == "user")
+
+ def _render_collapsed_vision(msgs):
+ # Partial taken from the swept msgs, not the raw pre-sweep capture.
+ return render_prompt_with_boundary(
+ processor, msgs, continue_final_message = bool(continue_partial)
+ )
+
+ try:
+ input_text = _render_collapsed_vision(vision_messages)
+ except Exception as e:
+ # Safe here: no catalog and no tool history to hide a failure behind.
+ if system_prompt:
+ logger.warning(
+ f"Vision processor for '{self.active_model_name}' may not support "
+ f"system messages; retrying without. Original error: {e}"
+ )
+ vision_messages = [m for m in vision_messages if m.get("role") != "system"]
+ input_text = _render_collapsed_vision(vision_messages)
+ else:
+ raise
inputs = processor(
image,
input_text,
@@ -1404,8 +1493,9 @@ class InferenceBackend:
protocol_source = processor,
# The text-only VLM fallback above did not render with the
# processor template, so its native markers do not describe
- # this request's response protocol.
- reasoning_channel_markers = detect_reasoning_channel_markers(processor)
+ # this request's response protocol. Passing *tools* matches the
+ # render: a named template selects "tool_use", not "default".
+ reasoning_channel_markers = detect_reasoning_channel_markers(processor, tools = tools)
if image
else None,
reasoning_channel_markers_resolved = True,
@@ -2845,7 +2935,29 @@ class InferenceBackend:
"format_type": "generic",
"special_tokens": {},
"template_name": None,
+ # An image turn renders through the PROCESSOR, a different template file for
+ # most VLMs, and this mirrored dict is all the route ever sees (#10092, #7066).
+ "processor_template": None,
+ # Distinct from processor_template: a template-less processor still places
+ # the image, falling back to the tokenizer body.
+ "renders_image": False,
}
+ processor = self.models[model_name].get("processor")
+ # Same predicate as the image-ignoring fallback: FastVisionModel may return a raw
+ # tokenizer, whose body an image render never selects.
+ try:
+ from transformers import ProcessorMixin
+ processes_images = processor is not None and (
+ isinstance(processor, ProcessorMixin) or hasattr(processor, "image_processor")
+ )
+ except Exception:
+ processes_images = processor is not None and hasattr(processor, "image_processor")
+ chat_template_info["renders_image"] = bool(processes_images)
+ if processes_images:
+ processor_template = getattr(processor, "chat_template", None)
+ # Narrowing the named-template list form away disables the image-turn override.
+ if isinstance(processor_template, (str, dict, list, tuple)) and processor_template:
+ chat_template_info["processor_template"] = processor_template
try:
from utils.datasets import MODEL_TO_TEMPLATE_MAPPER
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index a5a5f21ee4b..51de37ad720 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -5,7 +5,6 @@ Drop-in replacement for InferenceBackend — same interface, uses mlx-lm/mlx-vlm
instead of torch/transformers for model loading and generation.
"""
-import json
import os
import re
import sys
@@ -18,14 +17,19 @@ from core.inference.runtime_context import (
runtime_context_length,
)
from core.inference.chat_template_helpers import (
+ # Aliased to this module's historic names; bodies moved to the shared helper (#10092).
+ count_structured_images as _count_vlm_images,
detect_reasoning_channel_markers,
make_reasoning_normalizer,
markup_for_tokenizer,
+ messages_have_tool_history as _vlm_messages_have_tool_history,
+ messages_with_attached_image,
neutralize_control_markup_in_messages,
normalize_reasoning_snapshots,
prompt_opens_reasoning_channel,
strip_open_reasoning_prefill,
trailing_assistant_text,
+ vlm_prompt_issue as _vlm_prompt_issue,
)
from utils.models.model_config import is_audio_input_type
from loggers import get_logger
@@ -338,68 +342,6 @@ def _classify_mlx_audio_type(
return config_audio_type
-def _count_vlm_images(content):
- if isinstance(content, list):
- return sum(_count_vlm_images(item) for item in content)
- if not isinstance(content, dict):
- return 0
- if str(content.get("type", "")).lower() in ("image", "image_url", "input_image"):
- return 1
- return _count_vlm_images(content.get("content"))
-
-
-def _vlm_media_reprs(content):
- if isinstance(content, list):
- values = (
- {str(content), json.dumps(content, ensure_ascii = False)}
- if _count_vlm_images(content)
- else set()
- )
- for item in content:
- values.update(_vlm_media_reprs(item))
- return values
- if not isinstance(content, dict):
- return set()
- if str(content.get("type", "")).lower() in ("image", "image_url", "input_image"):
- return {str(content), json.dumps(content, ensure_ascii = False)}
- return _vlm_media_reprs(content.get("content"))
-
-
-def _prompt_serializes_vlm_media(prompt, messages):
- """Detect templates that embed the exact structured media object repr."""
- media_reprs = set()
- for message in messages:
- if isinstance(message, dict):
- media_reprs.update(_vlm_media_reprs(message.get("content")))
- text_content = [
- content_to_text(message.get("content")) for message in messages if isinstance(message, dict)
- ]
- return any(
- prompt.count(media_repr) > sum(content.count(media_repr) for content in text_content)
- for media_repr in media_reprs
- )
-
-
-def _vlm_prompt_issue(prompt, messages):
- if not isinstance(prompt, str) or not prompt.strip():
- return "an empty prompt"
- if _prompt_serializes_vlm_media(prompt, messages):
- return "serialized structured image content"
- return None
-
-
-def _vlm_messages_have_tool_history(messages):
- return any(
- isinstance(message, dict)
- and (
- message.get("role") == "tool"
- or message.get("tool_calls")
- or message.get("tool_call_id")
- )
- for message in messages
- )
-
-
def _mlx_config_field(model, name):
"""Read a config field in either shape a loaded MLX model exposes it in.
@@ -1986,7 +1928,22 @@ class MLXInferenceBackend:
"format_type": "generic",
"special_tokens": {},
"template_name": None,
+ # The body _generate_vlm renders an image turn with, not the tokenizer body.
+ "processor_template": None,
+ "renders_image": False,
}
+ from core.inference.chat_template_helpers import (
+ chat_render_target as _chat_render_target,
+ )
+
+ _proc = entry.get("processor")
+ # A processor template alone does not mean the render selects it (#7066).
+ _proc_tpl = (
+ getattr(_proc, "chat_template", None) if _chat_render_target(_proc) is _proc else None
+ )
+ if isinstance(_proc_tpl, (str, dict, list, tuple)) and _proc_tpl:
+ info["processor_template"] = _proc_tpl
+ info["renders_image"] = _proc is not None and bool(getattr(self, "_is_vlm", False))
try:
tpl = (
getattr(tok, "chat_template", None)
@@ -2195,23 +2152,23 @@ class MLXInferenceBackend:
# Reset so a failed run cannot surface stale stats.
self.last_generation_stats = None
- full_messages = self._with_system_prompt(messages, system_prompt)
-
- # Inject image into the last user message for VLM
+ # Shared with the transformers vision path so both render the same turns (#10092).
if self._is_vlm and image is not None:
- for msg in reversed(full_messages):
- if msg.get("role") == "user":
- content = msg.get("content", "")
- if isinstance(content, str):
- msg["content"] = [
- {"type": "image"},
- {"type": "text", "text": content},
- ]
- elif isinstance(content, list):
- has_image = _count_vlm_images(content) > 0
- if not has_image:
- content.insert(0, {"type": "image"})
- break
+ # Processor templates want part lists, the tokenizer fallback wants strings.
+ from core.inference.chat_template_helpers import (
+ chat_render_target as _chat_render_target,
+ )
+ _renders_via_processor = (
+ self._processor is not None
+ and _chat_render_target(self._processor) is self._processor
+ )
+ full_messages = messages_with_attached_image(
+ messages,
+ system_prompt = system_prompt,
+ structured_content = _renders_via_processor,
+ )
+ else:
+ full_messages = self._with_system_prompt(messages, system_prompt)
if self._is_vlm:
stream = self._generate_vlm(
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index c3ef6c9d578..08a4a7a8080 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -540,6 +540,9 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:
"format_type": _tpl_info.get("format_type", "generic"),
"template_name": _tpl_info.get("template_name"),
"special_tokens": _tpl_info.get("special_tokens", {}) or {},
+ # The IMAGE-turn body; the whitelist is the only way out.
+ "processor_template": _tpl_info.get("processor_template"),
+ "renders_image": _tpl_info.get("renders_image"),
}
except Exception as _tpl_exc:
logger.warning("chat_template_info forward failed: %s", _tpl_exc)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index ce279de99c4..276c4f25315 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3327,6 +3327,8 @@ def _detect_safetensors_features(
backend,
chat_template: Optional[str],
tools = None,
+ prefer_tool_use: bool = True,
+ reasoning_fallback: bool = True,
) -> dict:
"""Classify reasoning/tool capabilities via the GGUF classifier so flags
match across backends. gpt-oss is overridden: Harmony routes reasoning and
@@ -3335,7 +3337,9 @@ def _detect_safetensors_features(
feature_template = chat_template
try:
from core.inference.chat_template_helpers import _selected_template_strings_from_value
- selected_templates = _selected_template_strings_from_value(chat_template, tools)
+ selected_templates = _selected_template_strings_from_value(
+ chat_template, tools, prefer_tool_use = prefer_tool_use
+ )
if selected_templates:
feature_template = selected_templates[0]
except Exception:
@@ -3345,7 +3349,8 @@ def _detect_safetensors_features(
model_identifier = model_id,
log_source = "safetensors",
)
- if not flags.get("supports_reasoning"):
+ # The fallback widens to the tokenizer body, wrong when ONE body was asked about.
+ if not flags.get("supports_reasoning") and reasoning_fallback:
try:
from core.inference.chat_template_helpers import (
detect_reasoning_channel_markers_from_template,
@@ -17938,6 +17943,30 @@ def _extract_content_parts(messages: list) -> tuple[str, list[dict], "Optional[s
)
+def _user_ordinal_supplying_the_image(messages: list) -> Optional[int]:
+ """Which user turn, counted among user turns, the selected image came from.
+
+ ``_extract_content_parts`` takes the newest user image from ANYWHERE in the thread
+ while the renderers attach it to the newest user turn (#10092). Ordinal rather than
+ index: the passthrough rebuild folds system/developer turns together.
+ """
+ ordinal = None
+ seen = 0
+ for msg in messages:
+ if msg.role != "user":
+ continue
+ if isinstance(msg.content, list):
+ for part in msg.content:
+ if part.type != "image_url":
+ continue
+ url = getattr(getattr(part, "image_url", None), "url", "") or ""
+ if url.startswith("data:") and url.partition(",")[2]:
+ ordinal = seen
+ break
+ seen += 1
+ return ordinal
+
+
def _images_in_last_user_message(messages: list) -> int:
"""Image parts on the newest user turn.
@@ -22240,15 +22269,37 @@ async def produce_openai_chat_completions(
except Exception:
_sf_probe_messages = None
- def _sf_response_protocol(tools = None):
- features = _detect_safetensors_features(backend, _sf_tpl, tools = tools)
+ def _sf_response_protocol(
+ tools = None,
+ template = None,
+ prefer_tool_use = True,
+ ):
+ body = _sf_tpl if template is None else template
+ # Forward only the non-default: unconditional breaks stubs predating the parameter.
+ _pref = {} if prefer_tool_use else {"prefer_tool_use": False}
+ if template is not None:
+ # One specific body, so no reasoning rescue from an unselected branch.
+ _pref["reasoning_fallback"] = False
+ features = _detect_safetensors_features(backend, body, tools = tools, **_pref)
+ # The prefill probe needs the ONE body that renders, not the collection (#10092).
+ try:
+ from core.inference.chat_template_helpers import (
+ _selected_template_strings_from_value,
+ )
+ _selected = _selected_template_strings_from_value(
+ body, tools, prefer_tool_use = prefer_tool_use
+ )
+ if _selected:
+ body = _selected[0]
+ except Exception:
+ logger.debug("safetensors_prefill_template_selection_failed", exc_info = True)
parse_think = bool(
features.get("supports_reasoning") or features.get("reasoning_always_on")
)
reasoning_prefilled = _sf_reasoning_prefill_mode(
features,
payload.enable_thinking,
- _sf_tpl,
+ body,
reasoning_effort = payload.reasoning_effort,
messages = _sf_probe_messages,
)
@@ -22820,17 +22871,38 @@ async def produce_openai_chat_completions(
# tools into the template, generate one turn, heal text-form calls (#6801).
# supports_tools=False falls through to plain relay (GGUF gate parity).
_sf_has_tool_msgs = any(m.role == "tool" or m.tool_calls for m in payload.messages)
+ # Resolved BEFORE the capability gate below, which classifies from this body (#10092).
+ _sf_image_tpl = (
+ (_sf_model_info.get("chat_template_info") or {}).get("processor_template")
+ if image is not None
+ else None
+ )
+ # Differs from processor_template: a template-less processor still places the image.
+ _sf_renders_image = image is not None and bool(
+ (_sf_model_info.get("chat_template_info") or {}).get("renders_image")
+ )
+ if _sf_image_tpl is not None:
+ # The WHOLE protocol, not just tool support: a processor body can carry a reasoning
+ # channel the tokenizer never declares, whose <think> markup then leaked as visible
+ # content. prefer_tool_use is off: a processor never selects "tool_use" (#10092).
+ _sf_features, _sf_parse_think, _sf_reasoning_prefilled = _sf_response_protocol(
+ _sf_template_tools,
+ template = _sf_image_tpl,
+ prefer_tool_use = False,
+ )
+ _sf_supports_tools = _sf_features.get("supports_tools", False)
# Gate on _sf_use_tools (did the server-side path claim the request?), not
# raw mcp_enabled: an empty MCP registry must not silently drop client tools.
_sf_client_tools = (
# Read the resolved value, not a fresh _effective_enable_tools: the gate
# above withdraws the launcher default for exactly these requests, and
# recomputing here would hide that and drop the client catalog.
- not _sf_tools_on
+ # Once an image rules out the server loop the passthrough takes the request, or
+ # image-plus-tools is answered with prose and no schemas at all (#10092).
+ (not _sf_tools_on or (image is not None and not _sf_use_tools))
and not _sf_use_tools
- and image is None
and not _sf_is_gptoss
- and _sf_features.get("supports_tools", False)
+ and _sf_supports_tools
and ((payload.tools and len(payload.tools) > 0) or _sf_has_tool_msgs)
)
# apply_chat_template sanitizes the catalog it renders, so a tool dropped for unsafe
@@ -22859,6 +22931,8 @@ async def produce_openai_chat_completions(
_sf_chat_targets = (
(_sf_mlx_target,) if _sf_hf_target is _sf_mlx_target else (_sf_mlx_target, _sf_hf_target)
)
+ # Qwen2.5-VL's processor body never mentions tools while its tokenizer body does, so
+ # healing from the tokenizer body promotes a call the render never carried (#7066).
_sf_healing_tools = (
# Safe under EVERY template this turn could select: when the active one drops the
# schema the render falls back to the native template, whose profile can drop a tool
@@ -22871,6 +22945,8 @@ async def produce_openai_chat_completions(
_sf_chat_targets,
_sf_model_info,
active_model_name = backend.active_model_name,
+ template = _sf_image_tpl,
+ template_is_processor = _sf_image_tpl is not None,
)
if _sf_client_tools
else None
@@ -22890,6 +22966,28 @@ async def produce_openai_chat_completions(
),
system_prompt,
)
+ # Mark the turn that owns the image so the newest-user-turn scan does not move an
+ # older picture onto a later question. Gated on _sf_renders_image, not on an image:
+ # a text-template render must not be handed part lists (#10092).
+ if _sf_renders_image:
+ _sf_image_ordinal = _user_ordinal_supplying_the_image(payload.messages)
+ if _sf_image_ordinal is not None:
+ _sf_seen_users = 0
+ for _sf_idx, _sf_msg in enumerate(gen_kwargs["messages"]):
+ if not isinstance(_sf_msg, dict) or _sf_msg.get("role") != "user":
+ continue
+ if _sf_seen_users == _sf_image_ordinal:
+ _sf_body = _sf_msg.get("content")
+ if isinstance(_sf_body, str):
+ gen_kwargs["messages"][_sf_idx] = {
+ **_sf_msg,
+ "content": [
+ {"type": "image"},
+ {"type": "text", "text": _sf_body},
+ ],
+ }
+ break
+ _sf_seen_users += 1
gen_kwargs["system_prompt"] = ""
# tool_choice="none": keep history templating but advertise no tools
# (heal_gate is off, markup would relay as prose). A forced function
@@ -22916,7 +23014,12 @@ async def produce_openai_chat_completions(
# known. This standard path now has the exact schemas that will be rendered,
# so resolve reasoning parsing again to keep empty registries, forced-tool
# misses, and tool_choice="none" on the marker-free template branch.
- _, _sf_parse_think, _sf_reasoning_prefilled = _sf_response_protocol(gen_kwargs.get("tools"))
+ # Re-resolving from the tokenizer body here would undo the reclassification above.
+ _, _sf_parse_think, _sf_reasoning_prefilled = _sf_response_protocol(
+ gen_kwargs.get("tools"),
+ template = _sf_image_tpl,
+ prefer_tool_use = _sf_image_tpl is None,
+ )
# Request-scoped usage/timings receptacle (filled at gen_done).
stats_holder: dict = {}
@@ -23272,8 +23375,16 @@ async def produce_openai_chat_completions(
# completion count.
_first_stats = stats_holder.pop("stats", None)
try:
+ # Mark the owning turn before the correction is appended,
+ # or the reverse scan attaches the picture to it (#10092).
+ _nudge_base = gen_kwargs["messages"]
+ if _sf_renders_image:
+ from core.inference.chat_template_helpers import (
+ messages_with_attached_image as _nudge_attach,
+ )
+ _nudge_base = _nudge_attach(_nudge_base)
retry_messages = [
- *gen_kwargs["messages"],
+ *_nudge_base,
*nudge_messages(_data, _sf_heal),
]
retry_text = await _run_blocking_generation(
diff --git a/studio/backend/tests/test_current_date_prompt_settings.py b/studio/backend/tests/test_current_date_prompt_settings.py
index bdb18e4b2be..b9750bdc144 100644
--- a/studio/backend/tests/test_current_date_prompt_settings.py
+++ b/studio/backend/tests/test_current_date_prompt_settings.py
@@ -197,7 +197,7 @@ class TestExternalProviderMessages:
assert out[0] == {"role": "system", "content": "The current date is 2026-08-15."}
assert out[1] == {"role": "user", "content": "hi"}
- def test_date_prefixes_text_inside_structured_system_content(self):
+ def test_date_prefixes_text_inside_structured_content(self):
messages = [{"role": "system", "content": [{"type": "text", "text": "Be terse."}]}]
out = self._prepend(messages)
assert len(out) == 1
diff --git a/studio/backend/tests/test_mcp_session_resources.py b/studio/backend/tests/test_mcp_session_resources.py
index bae4252dd0c..71a192f995f 100644
--- a/studio/backend/tests/test_mcp_session_resources.py
+++ b/studio/backend/tests/test_mcp_session_resources.py
@@ -133,9 +133,9 @@ def test_repeated_open_close_does_not_accumulate_threads(tiny):
for i in range(12):
call_tool_sync(HTTP_URL, None, "t", {}, scope = f"chat-{i}")
close_mcp_sessions()
- assert _settle(lambda: _session_threads() <= before), (
- f"leaked threads after 12 cycles: {_session_threads()} vs {before}"
- )
+ assert _settle(
+ lambda: _session_threads() <= before
+ ), f"leaked threads after 12 cycles: {_session_threads()} vs {before}"
def test_repeated_open_close_does_not_accumulate_descriptors(tiny):
diff --git a/studio/backend/tests/test_mcp_upgrade_compat.py b/studio/backend/tests/test_mcp_upgrade_compat.py
index 4ef03ed9fe3..434bc698be0 100644
--- a/studio/backend/tests/test_mcp_upgrade_compat.py
+++ b/studio/backend/tests/test_mcp_upgrade_compat.py
@@ -107,9 +107,9 @@ def test_only_stdio_answers_the_liveness_probe():
from fastmcp.client.transports import SSETransport, StreamableHttpTransport
for cls in (StreamableHttpTransport, SSETransport):
transport = cls(url = "https://x.test/mcp")
- assert not hasattr(transport, "_is_session_dead"), (
- f"{cls.__name__} grew a liveness probe; _transport_dead can use it now"
- )
+ assert not hasattr(
+ transport, "_is_session_dead"
+ ), f"{cls.__name__} grew a liveness probe; _transport_dead can use it now"
def test_the_installed_fastmcp_meets_the_declared_floor():
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index 3cf90bcdc0b..63fa16bc941 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -720,19 +720,21 @@ def test_mlx_vlm_generation_selects_renderer_by_capability(monkeypatch):
def test_mlx_vlm_image_injection_reuses_media_aliases(monkeypatch):
- from core.inference.mlx_inference import MLXInferenceBackend, _prompt_serializes_vlm_media
+ # Moved to chat_template_helpers so the transformers vision path shares it (#10092).
+ from core.inference.chat_template_helpers import prompt_serializes_structured_media
+ from core.inference.mlx_inference import MLXInferenceBackend
media = [{"type": "image"}]
quoted = [{"role": "user", "content": media}, {"role": "user", "content": f"Explain {media}"}]
- assert _prompt_serializes_vlm_media(f"<image>\n{media[0]}", quoted[:1])
- assert not _prompt_serializes_vlm_media(f"<image>\nExplain {media}", quoted)
- assert _prompt_serializes_vlm_media(f"User: {media}\nExplain {media}", quoted)
+ assert prompt_serializes_structured_media(f"<image>\n{media[0]}", quoted[:1])
+ assert not prompt_serializes_structured_media(f"<image>\nExplain {media}", quoted)
+ assert prompt_serializes_structured_media(f"User: {media}\nExplain {media}", quoted)
quoted[1]["content"] = [{"type": "text", "text": f'Explain "this" {media}'}]
- assert not _prompt_serializes_vlm_media(f'<image>\nExplain "this" {media}', quoted)
+ assert not prompt_serializes_structured_media(f'<image>\nExplain "this" {media}', quoted)
json_media = [{"type": "image_url"}]
json_repr = '{"type": "image_url"}'
- assert _prompt_serializes_vlm_media(f"<image>\n{json_repr}", [{"content": json_media}])
- assert not _prompt_serializes_vlm_media(
+ assert prompt_serializes_structured_media(f"<image>\n{json_repr}", [{"content": json_media}])
+ assert not prompt_serializes_structured_media(
f"<image>\nExplain {json_repr}",
[{"content": json_media}, {"content": f"Explain {json_repr}"}],
)
diff --git a/studio/backend/tests/test_sf_client_tools_passthrough.py b/studio/backend/tests/test_sf_client_tools_passthrough.py
index a005616211d..3a2a0a9f4c5 100644
--- a/studio/backend/tests/test_sf_client_tools_passthrough.py
+++ b/studio/backend/tests/test_sf_client_tools_passthrough.py
@@ -105,6 +105,9 @@ class _ScriptedBackend:
def reset_generation_state(self, caller_cancel_event = None):
self.reset_count += 1
+ def resize_image(self, image):
+ return image
+
def _fixed(*snapshots):
"""Responder that always replays the given cumulative snapshots."""
@@ -1172,3 +1175,51 @@ def test_completion_details_are_summed_with_the_completion_they_describe():
)
assert folded["usage"]["completion_tokens"] == 50
assert folded["usage"]["completion_tokens_details"] == {"reasoning_tokens": 10}
+
+
+_PNG_1x1 = (
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk"
+ "+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
+)
+
+
+def _vision_backend(*snapshots):
+ backend = _ScriptedBackend(_fixed(*snapshots))
+ backend.models["sf-model"]["is_vision"] = True
+ return backend
+
+
+def _image_message(text = "run the tests"):
+ return ChatMessage(
+ role = "user",
+ content = [
+ {"type": "text", "text": text},
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{_PNG_1x1}"}},
+ ],
+ )
+
+
+def test_image_turn_keeps_the_client_tool_catalog(monkeypatch):
+ backend = _vision_backend(_CALL_XML)
+ payload = _request(messages = [_image_message()], tools = [LOOKUP_TOOL], stream = False)
+ body = _json_body(_call(payload, monkeypatch, backend))
+
+ assert backend.calls[0]["tools"] == [LOOKUP_TOOL]
+ assert backend.calls[0]["image"] is not None
+ choice = body["choices"][0]
+ assert choice["finish_reason"] == "tool_calls"
+ assert choice["message"]["tool_calls"][0]["function"]["name"] == "lookup"
+
+
+def test_legacy_image_field_keeps_the_client_tool_catalog(monkeypatch):
+ backend = _vision_backend(_CALL_XML)
+ payload = _request(
+ messages = [ChatMessage(role = "user", content = "run the tests")],
+ image_base64 = _PNG_1x1,
+ tools = [LOOKUP_TOOL],
+ stream = False,
+ )
+ _call(payload, monkeypatch, backend)
+
+ assert backend.calls[0]["tools"] == [LOOKUP_TOOL]
+ assert backend.calls[0]["image"] is not None
diff --git a/studio/backend/tests/test_vision_client_tools.py b/studio/backend/tests/test_vision_client_tools.py
new file mode 100644
index 00000000000..247769751bb
--- /dev/null
+++ b/studio/backend/tests/test_vision_client_tools.py
@@ -0,0 +1,1169 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Repros for the four defects in PR #10092 (client tools on a vision turn).
+
+Route-level tests stub ``generate_chat_response`` entirely, so these call
+``_generate_vision_response`` directly against a fake processor instead.
+"""
+
+import importlib
+import importlib.machinery
+import json
+import sys
+import threading
+import types
+from unittest.mock import MagicMock
+
+import pytest
+
+
+_STUBBED: list[str] = []
+
+
+def _stub_if_missing(
+ name,
+ attrs = (),
+ named_spec = False,
+):
+ """Register a stub for a dep this job does not install. A real install is left alone.
+
+ Same helper and reason as test_audio_type_inconclusive.py: unstubbed, this module fails
+ COLLECTION under the studio-backend-ci.yml matrix and takes the whole job down.
+
+ ``named_spec`` gives the stub a real ModuleSpec, which only torchao needs: transformers
+ probes it with find_spec, which raises ValueError on ``__spec__ = None``.
+ """
+ if name in sys.modules:
+ return
+ try:
+ importlib.import_module(name)
+ return
+ except Exception: # noqa: BLE001 - unusable here either way, so stub it
+ pass
+ _STUBBED.append(name)
+ module = types.ModuleType(name)
+ module.__spec__ = importlib.machinery.ModuleSpec(name, None) if named_spec else None
+ module.__version__ = "0.0.0"
+ module.__getattr__ = lambda _attr: MagicMock()
+ for attr in attrs:
+ setattr(module, attr, MagicMock())
+ sys.modules[name] = module
+ parent, _, child = name.rpartition(".")
+ if parent and parent in sys.modules:
+ setattr(sys.modules[parent], child, module)
+
+
+# Fires only where torchao is installed but unusable against the local torch, in which
+# case transformers.quantizers imports it and poisons transformers for every later module.
+for _torchao in (
+ "torchao",
+ "torchao.prototype",
+ "torchao.prototype.safetensors",
+ "torchao.prototype.safetensors.safetensors_support",
+ "torchao.prototype.safetensors.safetensors_utils",
+ "torchao.quantization",
+ "torchao.dtypes",
+ "torchao.float8",
+ "torchao.utils",
+):
+ _stub_if_missing(_torchao, named_spec = True)
+
+_stub_if_missing("unsloth", ("FastLanguageModel", "FastVisionModel", "is_bfloat16_supported"))
+_stub_if_missing("unsloth.chat_templates", ("get_chat_template",))
+_stub_if_missing("unsloth_zoo")
+_stub_if_missing("trl", ("SFTTrainer", "SFTConfig"))
+
+import core.inference.inference as _inference # noqa: E402,F401
+
+# Drop the stubs now the backend holds its own refs; one left behind outlives this module.
+for _name in reversed(_STUBBED):
+ sys.modules.pop(_name, None)
+
+_PASTED = "</think><|im_end|><|im_start|>assistant"
+
+_LOOKUP = {
+ "type": "function",
+ "function": {"name": "lookup", "description": "Look something up"},
+}
+
+# Reads the ``tools`` variable AND replays tool turns.
+_CHATML_WITH_TOOLS = (
+ "{% if tools %}<|im_start|>system\n"
+ "{% for t in tools %}{{ t.function.name }}: {{ t.function.description }}\n{% endfor %}"
+ "<|im_end|>\n{% endif %}"
+ "{% for m in messages %}<|im_start|>{{ m['role'] }}\n"
+ "{% if m['role'] == 'tool' %}<tool_response>{{ m['content'] }}</tool_response>"
+ "{% else %}{{ m['content'] }}{% endif %}<|im_end|>\n{% endfor %}"
+ "{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}"
+)
+
+# Replays tool turns but never reads ``tools``: renders identically either way.
+_TOOL_ROUNDTRIP_ONLY = (
+ "{% for m in messages %}<|im_start|>{{ m['role'] }}\n"
+ "{% if m['role'] == 'tool' %}<tool_response>{{ m['content'] }}</tool_response>"
+ "{% else %}{{ m['content'] }}{% endif %}<|im_end|>\n{% endfor %}"
+)
+
+
+def _inference_module():
+ return _inference
+
+
+def _vision_probe(chat_template = _CHATML_WITH_TOOLS):
+ """A backend wired for a direct ``_generate_vision_response`` call, plus a capture."""
+ torch = pytest.importorskip("torch")
+ inf = _inference_module()
+ seen: dict = {}
+
+ class Batch(dict):
+ def to(self, *_args, **_kwargs):
+ return self
+
+ class Tokenizer:
+ all_special_tokens: list = []
+ eos_token_id = 1
+ pad_token_id = None
+
+ def __init__(self):
+ self.chat_template = chat_template
+
+ def __call__(self, *_args, **_kwargs):
+ return Batch({"input_ids": torch.zeros((1, 1), dtype = torch.long)})
+
+ class Processor:
+ def __init__(self):
+ self.chat_template = chat_template
+ self.tokenizer = Tokenizer()
+ # The mirror keys off this to tell a real image render from the text fallback.
+ self.image_processor = object()
+
+ def apply_chat_template(self, messages, **kwargs):
+ seen["messages"] = messages
+ seen["tools"] = kwargs.get("tools")
+ if kwargs.get("tools") and "tools" in chat_template:
+ return "PROMPT-WITH-TOOLS"
+ return "PROMPT"
+
+ def __call__(self, *_args, **_kwargs):
+ return Batch({"input_ids": torch.zeros((1, 1), dtype = torch.long)})
+
+ class Model:
+ device = "cpu"
+ generation_config = type("Cfg", (), {"eos_token_id": 1})()
+ config = generation_config
+
+ def generate(self, **_kwargs):
+ return None
+
+ class EmptyStreamer:
+ def __next__(self):
+ raise StopIteration
+
+ def end(self):
+ return None
+
+ backend = inf.InferenceBackend.__new__(inf.InferenceBackend)
+ backend.active_model_name = "vision-tools"
+ backend._generation_lock = threading.Lock()
+ processor = Processor()
+ backend.models = {
+ "vision-tools": {"model": Model(), "processor": processor, "tokenizer": processor}
+ }
+ backend.format_chat_prompt = lambda *_args, **_kwargs: "text-only"
+ backend._make_text_streamer = lambda *_args, **_kwargs: EmptyStreamer()
+ return backend, seen
+
+
+def _drain(backend, **kwargs):
+ base = dict(
+ system_prompt = "",
+ image = object(),
+ temperature = 0.7,
+ top_p = 0.9,
+ top_k = 40,
+ min_p = 0.0,
+ max_new_tokens = 1,
+ repetition_penalty = 1.0,
+ )
+ base.update(kwargs)
+ return list(backend._generate_vision_response(**base))
+
+
+def test_vision_tools_turn_keeps_the_system_message():
+ """The client-tools route folds system text into ``messages[0]`` and passes
+ ``system_prompt = ""``, so rebuilding from the argument alone drops the instructions."""
+ backend, seen = _vision_probe()
+ _drain(
+ backend,
+ messages = [
+ {"role": "system", "content": "SENTINEL_RULE: always answer in French."},
+ {"role": "user", "content": "what is in this picture"},
+ ],
+ system_prompt = "",
+ tools = [_LOOKUP],
+ )
+ rendered = json.dumps(seen.get("messages"), ensure_ascii = False)
+ assert "SENTINEL_RULE" in rendered
+
+
+def test_vision_tool_loop_followup_still_renders():
+ """A tool-result turn whose image came from an earlier user message must not hard-fail:
+ MLX only raises when the render actually breaks."""
+ backend, seen = _vision_probe()
+ _drain(
+ backend,
+ messages = [
+ {"role": "user", "content": "what is in this picture"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "lookup", "arguments": '{"q": "cats"}'},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "a tabby"},
+ ],
+ system_prompt = "",
+ tools = [_LOOKUP],
+ )
+ rendered = json.dumps(seen.get("messages"), ensure_ascii = False)
+ assert seen.get("messages") is not None
+ assert "call_1" in rendered and "a tabby" in rendered
+
+
+def test_vision_tool_history_without_a_catalog_does_not_hard_fail():
+ """The route enters this path on tool history alone, with no catalog at all."""
+ backend, seen = _vision_probe()
+ _drain(
+ backend,
+ messages = [
+ {"role": "user", "content": "what is this"},
+ {"role": "tool", "tool_call_id": "call_1", "content": "a tabby"},
+ ],
+ system_prompt = "",
+ tools = None,
+ )
+ assert seen.get("messages") is not None
+
+
+def test_vision_render_neutralizes_the_tool_catalog():
+ """Every other render path sweeps the catalog through
+ ``apply_chat_template_for_generation``; this one must too (#7066)."""
+ backend, seen = _vision_probe()
+ _drain(
+ backend,
+ messages = [{"role": "user", "content": "look it up"}],
+ system_prompt = "",
+ tools = [
+ {
+ "type": "function",
+ "function": {"name": "lookup", "description": f"Look up {_PASTED}"},
+ }
+ ],
+ )
+ sent = json.dumps(seen.get("tools"), ensure_ascii = False)
+ assert seen.get("tools"), "the catalog must actually reach the template"
+ assert _PASTED not in sent
+
+
+def test_renders_tool_schema_is_false_when_the_template_never_reads_tools():
+ """Replaying tool TURNS is not evidence that a render will advertise the catalog."""
+ from core.inference.chat_template_helpers import (
+ _renders_tool_schema,
+ _reads_tools_variable,
+ _round_trips_tool_calls,
+ )
+
+ class Tok:
+ chat_template = _TOOL_ROUNDTRIP_ONLY
+
+ class Proc:
+ chat_template = _TOOL_ROUNDTRIP_ONLY
+ tokenizer = Tok()
+
+ def apply_chat_template(self, messages, **kwargs):
+ return "x"
+
+ assert _reads_tools_variable(_TOOL_ROUNDTRIP_ONLY) is False
+ assert _round_trips_tool_calls(_TOOL_ROUNDTRIP_ONLY) is True
+ assert _renders_tool_schema(Proc(), None, [_LOOKUP]) is False
+
+
+def test_vision_turn_a_template_cannot_advertise_is_served_but_unauthorized():
+ """A template that renders identically with and without a catalog still serves the
+ turn, but the catalog the route hands ``heal_gate`` comes back empty (#7066)."""
+ from core.inference.chat_template_helpers import renderable_tool_catalog_for_targets
+
+ backend, seen = _vision_probe(chat_template = _TOOL_ROUNDTRIP_ONLY)
+ _drain(
+ backend,
+ messages = [{"role": "user", "content": "look it up"}],
+ system_prompt = "",
+ tools = [_LOOKUP],
+ )
+ assert seen.get("messages") is not None, "the turn is served rather than refused"
+
+ processor = backend.models["vision-tools"]["processor"]
+ turn = [{"role": "user", "content": "look it up"}]
+ assert processor.apply_chat_template(turn, tools = None) == processor.apply_chat_template(
+ turn, tools = [_LOOKUP]
+ ), "the catalog is not advertised"
+ assert (
+ renderable_tool_catalog_for_targets(
+ [_LOOKUP],
+ (processor, processor.tokenizer),
+ {},
+ active_model_name = "vision-tools",
+ )
+ == []
+ ), "the catalog is not reported as advertised either"
+
+
+def test_the_stubs_do_not_outlive_this_module():
+ """A leaked stub silently disables coverage in every module collected after this one."""
+ for name in _STUBBED:
+ assert name not in sys.modules, name
+
+
+def test_tool_choice_none_on_an_image_turn_keeps_the_system_message():
+ """tool_choice="none" reaches the renderer as tools=None, so keying the
+ history-preserving branch on the catalog alone dropped the folded instruction (#10092)."""
+ backend, seen = _vision_probe()
+ _drain(
+ backend,
+ messages = [
+ {"role": "system", "content": "SENTINEL_RULE: always answer in French."},
+ {"role": "user", "content": "what is in this picture"},
+ ],
+ system_prompt = "",
+ tools = None,
+ )
+ assert "SENTINEL_RULE" in json.dumps(seen.get("messages"), ensure_ascii = False)
+
+
+def test_the_no_tools_probe_does_not_strip_the_system_turn_from_the_real_render():
+ """A processor can reject a system turn on the throwaway no-tools probe and accept it
+ with a catalog. The probe's fallback must not decide what the real render sends."""
+ calls: list = []
+
+ backend, seen = _vision_probe()
+ processor = backend.models["vision-tools"]["processor"]
+ original = processor.apply_chat_template
+
+ def _picky(messages, **kwargs):
+ has_system = any(m.get("role") == "system" for m in messages)
+ calls.append({"tools": kwargs.get("tools"), "has_system": has_system})
+ if not kwargs.get("tools") and has_system:
+ raise ValueError("System role not supported without tools")
+ return original(messages, **kwargs)
+
+ processor.apply_chat_template = _picky
+ _drain(
+ backend,
+ messages = [
+ {"role": "system", "content": "SENTINEL_RULE: always answer in French."},
+ {"role": "user", "content": "look it up"},
+ ],
+ system_prompt = "",
+ tools = [_LOOKUP],
+ )
+ assert calls[-1]["has_system"] is True
+ assert "SENTINEL_RULE" in json.dumps(seen.get("messages"), ensure_ascii = False)
+
+
+_PROCESSOR_TEMPLATE_NO_TOOLS = (
+ "{% for m in messages %}<|im_start|>{{ m['role'] }}\n{{ m['content'] }}"
+ "<|im_end|>\n{% endfor %}"
+)
+
+
+def test_the_processor_template_is_mirrored_for_the_route_to_profile():
+ """The orchestrator keeps no live processor, so without the mirrored body healing is
+ authorized from a tokenizer template the image render never selects (#10092)."""
+ backend, _seen = _vision_probe()
+ info = backend.models["vision-tools"]
+ info["processor"].chat_template = _PROCESSOR_TEMPLATE_NO_TOOLS
+ info["tokenizer"] = info["processor"]
+ backend._load_chat_template_info("vision-tools")
+
+ mirrored = backend.models["vision-tools"]["chat_template_info"]
+ assert mirrored["processor_template"] == _PROCESSOR_TEMPLATE_NO_TOOLS
+
+
+def test_a_processor_that_cannot_process_images_is_not_mirrored():
+ """FastVisionModel hands back a raw tokenizer for some vision-marked models, whose
+ image is ignored, so mirroring that body would profile a render that never happens."""
+ backend, _seen = _vision_probe()
+ info = backend.models["vision-tools"]
+ del info["processor"].image_processor
+ info["processor"].chat_template = _PROCESSOR_TEMPLATE_NO_TOOLS
+ backend._load_chat_template_info("vision-tools")
+
+ mirrored = backend.models["vision-tools"]["chat_template_info"]
+ assert mirrored["processor_template"] is None
+
+
+def test_the_named_template_list_form_survives_the_mirror():
+ """Discarding the named-template list form at the mirror would silently drop the
+ image-turn override for Hermes-style models."""
+ listed = [
+ {"name": "default", "template": _PROCESSOR_TEMPLATE_NO_TOOLS},
+ {"name": "tool_use", "template": _CHATML_WITH_TOOLS},
+ ]
+ backend, _seen = _vision_probe()
+ backend.models["vision-tools"]["processor"].chat_template = listed
+ backend._load_chat_template_info("vision-tools")
+
+ assert backend.models["vision-tools"]["chat_template_info"]["processor_template"] == listed
+
+ mlx = pytest.importorskip("core.inference.mlx_inference")
+
+ class _Proc:
+ chat_template = listed
+ tokenizer = None
+
+ mlx_backend = mlx.MLXInferenceBackend.__new__(mlx.MLXInferenceBackend)
+ mlx_backend.models = {"m": {"processor": _Proc(), "tokenizer": None}}
+ mlx_backend._populate_chat_template_info("m", _CHATML_WITH_TOOLS)
+
+ assert mlx_backend.models["m"]["chat_template_info"]["processor_template"] == listed
+
+
+def test_a_processor_body_that_cannot_advertise_empties_the_healing_catalog():
+ """The route profiles the mirrored processor body for image turns, so a body with no
+ tool handling at all must leave nothing authorized to heal."""
+ from core.inference.chat_template_helpers import renderable_tool_catalog_for_targets
+
+ catalog = renderable_tool_catalog_for_targets(
+ [_LOOKUP],
+ (None,),
+ {"chat_template_info": {"template": _CHATML_WITH_TOOLS}},
+ template = _PROCESSOR_TEMPLATE_NO_TOOLS,
+ )
+ assert catalog == []
+
+ text_catalog = renderable_tool_catalog_for_targets(
+ [_LOOKUP],
+ (None,),
+ {"chat_template_info": {"template": _CHATML_WITH_TOOLS}},
+ )
+ assert text_catalog
+
+
+def test_the_worker_forwards_the_processor_template_to_the_parent():
+ """This whitelist is the ONLY way the body reaches the route; omitting the key
+ profiles image turns from the tokenizer template (#10092)."""
+ import ast
+ import pathlib
+
+ source = pathlib.Path("core/inference/worker.py").read_text()
+ tree = ast.parse(source)
+ keys: set = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Dict):
+ continue
+ literals = {k.value for k in node.keys if isinstance(k, ast.Constant)}
+ if "has_template" in literals and "format_type" in literals:
+ keys |= literals
+ assert "processor_template" in keys, sorted(keys)
+
+
+def test_a_replay_only_processor_body_is_not_authorized_for_healing():
+ """A mirrored processor body has no live target, so the permissive tokenizer rule
+ would authorize a body that replays tool turns but never advertises them."""
+ from core.inference.chat_template_helpers import renderable_tool_catalog_for_targets
+
+ catalog = renderable_tool_catalog_for_targets(
+ [_LOOKUP],
+ (None,),
+ {"chat_template_info": {"template": _CHATML_WITH_TOOLS}},
+ template = _TOOL_ROUNDTRIP_ONLY,
+ template_is_processor = True,
+ )
+ assert catalog == []
+
+ # A tokenizer body keeps the round-trip clause: a native template sits behind it.
+ assert renderable_tool_catalog_for_targets(
+ [_LOOKUP],
+ (None,),
+ {"chat_template_info": {"template": _CHATML_WITH_TOOLS}},
+ template = _TOOL_ROUNDTRIP_ONLY,
+ )
+
+
+def test_the_mlx_backend_mirrors_the_processor_template_too():
+ """MLX builds chat_template_info itself, so the field has to be captured on both
+ backends or an MLX image turn is authorized from the tokenizer body (#10092)."""
+ mlx = pytest.importorskip("core.inference.mlx_inference")
+
+ class _Proc:
+ chat_template = _PROCESSOR_TEMPLATE_NO_TOOLS
+ tokenizer = None
+
+ backend = mlx.MLXInferenceBackend.__new__(mlx.MLXInferenceBackend)
+ backend.models = {"m": {"processor": _Proc(), "tokenizer": None}}
+ backend._populate_chat_template_info("m", _CHATML_WITH_TOOLS)
+
+ info = backend.models["m"]["chat_template_info"]
+ assert info["processor_template"] == _PROCESSOR_TEMPLATE_NO_TOOLS
+ assert info["template"] == _CHATML_WITH_TOOLS
+
+
+def test_a_processor_body_is_not_rescued_by_the_native_tokenizer_template(monkeypatch):
+ """A processor body has no native-template fallback behind it, so a native template
+ that reads tools must not re-authorize the catalog."""
+ from core.inference import chat_template_helpers as helpers
+
+ monkeypatch.setattr(helpers, "resolve_native_chat_template", lambda *a, **k: _CHATML_WITH_TOOLS)
+ catalog = helpers.renderable_tool_catalog_for_targets(
+ [_LOOKUP],
+ (None,),
+ {"chat_template_info": {"template": _CHATML_WITH_TOOLS}},
+ template = _PROCESSOR_TEMPLATE_NO_TOOLS,
+ template_is_processor = True,
+ )
+ assert catalog == []
+
+
+def test_a_folded_system_turn_is_wrapped_as_content_parts():
+ """The folded instruction arrives as a bare string, which a parts-expecting processor
+ raised on, and the no-system retry then dropped it (#10092)."""
+ from core.inference.chat_template_helpers import messages_with_attached_image
+
+ out = messages_with_attached_image(
+ [
+ {"role": "system", "content": "SENTINEL_RULE"},
+ {"role": "user", "content": "what is this"},
+ ],
+ system_prompt = "",
+ structured_content = True,
+ )
+ assert out[0]["content"] == [{"type": "text", "text": "SENTINEL_RULE"}]
+ assert out[0] is not None
+
+
+def test_a_nudge_retry_keeps_the_image_on_the_question_turn():
+ """A plain reverse scan hands the image marker to the nudge retry's appended
+ correction, so the question that asked about the picture renders image-less (#10092)."""
+ from core.inference.chat_template_helpers import (
+ count_structured_images,
+ messages_with_attached_image,
+ )
+
+ original = messages_with_attached_image([{"role": "user", "content": "what is in this"}])
+ assert count_structured_images(original[-1]["content"]) == 1
+
+ retried = messages_with_attached_image(
+ [
+ *original,
+ {"role": "assistant", "content": "I will look it up"},
+ {"role": "user", "content": "call the tool now"},
+ ]
+ )
+ question = [m for m in retried if m["role"] == "user"][0]
+ correction = [m for m in retried if m["role"] == "user"][-1]
+ assert count_structured_images(question["content"]) == 1
+ assert not isinstance(correction["content"], list) or not count_structured_images(
+ correction["content"]
+ )
+
+
+def test_an_mlx_processor_without_apply_chat_template_is_not_mirrored():
+ """A processor template alone does not mean the render selects it; mirroring it anyway
+ profiles an unused body with processor semantics (#10092)."""
+ mlx = pytest.importorskip("core.inference.mlx_inference")
+
+ class _Tok:
+ chat_template = _CHATML_WITH_TOOLS
+
+ class _ProcNoApply:
+ chat_template = _PROCESSOR_TEMPLATE_NO_TOOLS
+ apply_chat_template = None
+ tokenizer = _Tok()
+
+ backend = mlx.MLXInferenceBackend.__new__(mlx.MLXInferenceBackend)
+ backend.models = {"m": {"processor": _ProcNoApply(), "tokenizer": _Tok()}}
+ backend._populate_chat_template_info("m", _CHATML_WITH_TOOLS)
+
+ assert backend.models["m"]["chat_template_info"]["processor_template"] is None
+
+
+_PNG_DATA_URL = (
+ "data:image/png;base64,"
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
+)
+
+
+def _image_request(**kwargs):
+ from models.inference import ChatCompletionRequest, ChatMessage
+
+ base = dict(
+ model = "default",
+ messages = [
+ ChatMessage(
+ role = "user",
+ content = [
+ {"type": "text", "text": "what is in this picture"},
+ {"type": "image_url", "image_url": {"url": _PNG_DATA_URL}},
+ ],
+ )
+ ],
+ )
+ base.update(kwargs)
+ return ChatCompletionRequest(**base)
+
+
+def test_an_image_with_explicit_enable_tools_still_passes_the_client_catalog():
+ """The server loop refuses images, so withdrawing the client catalog too answered an
+ image-plus-tools request with prose and no schemas at all (#10092)."""
+ import os
+ import sys
+
+ import pytest as _pytest
+
+ # conftest puts the backend root on sys.path, not the tests directory.
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import test_sf_client_tools_passthrough as passthrough
+
+ backend = passthrough._ScriptedBackend(passthrough._fixed("a plain answer"))
+ backend.models["sf-model"]["is_vision"] = True
+ payload = _image_request(tools = [passthrough.LOOKUP_TOOL], enable_tools = True, stream = False)
+
+ monkeypatch = _pytest.MonkeyPatch()
+ try:
+ passthrough._call(payload, monkeypatch, backend)
+ finally:
+ monkeypatch.undo()
+
+ assert backend.calls, "generation never ran"
+ assert backend.calls[0]["tools"] == [passthrough.LOOKUP_TOOL]
+
+
+def test_image_tool_support_is_classified_from_the_processor_template():
+ """A VLM whose processor template advertises tools its nested tokenizer never does had
+ the catalog disabled and reached generation with no schemas (#10092)."""
+ import asyncio
+ import os
+ import sys
+
+ import pytest as _pytest
+
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import routes.inference as inf
+ import test_sf_client_tools_passthrough as passthrough
+
+ backend = passthrough._ScriptedBackend(passthrough._fixed("a plain answer"))
+ backend.models["sf-model"]["is_vision"] = True
+ backend.models["sf-model"]["chat_template_info"] = {
+ "template": _PROCESSOR_TEMPLATE_NO_TOOLS,
+ "processor_template": _CHATML_WITH_TOOLS,
+ }
+ payload = _image_request(tools = [passthrough.LOOKUP_TOOL], stream = False)
+
+ monkeypatch = _pytest.MonkeyPatch()
+ try:
+ passthrough._install(monkeypatch, backend)
+ monkeypatch.setattr(
+ inf,
+ "_detect_safetensors_features",
+ lambda _backend, template, **k: {"supports_tools": template == _CHATML_WITH_TOOLS},
+ )
+
+ async def _run():
+ return await inf.openai_chat_completions(
+ payload, request = passthrough._Request(), current_subject = "u"
+ )
+
+ asyncio.run(_run())
+ finally:
+ monkeypatch.undo()
+
+ assert backend.calls, "generation never ran"
+ assert backend.calls[0]["tools"] == [passthrough.LOOKUP_TOOL]
+
+
+def test_mlx_selects_structured_content_for_a_processor_render():
+ """A processor template wants part lists and the nested-tokenizer fallback wants plain
+ strings, so the choice follows whichever body chat_render_target selects (#10092)."""
+ mlx = pytest.importorskip("core.inference.mlx_inference")
+
+ seen: dict = {}
+
+ def _spy(messages, **kwargs):
+ seen.update(kwargs)
+ return list(messages)
+
+ class _Proc:
+ chat_template = _PROCESSOR_TEMPLATE_NO_TOOLS
+
+ def apply_chat_template(self, *_a, **_k):
+ return ""
+
+ backend = mlx.MLXInferenceBackend.__new__(mlx.MLXInferenceBackend)
+ backend._model = object()
+ backend._is_vlm = True
+ backend._processor = _Proc()
+ backend.last_generation_stats = None
+ backend._generate_vlm = lambda *a, **k: iter(())
+
+ original = mlx.messages_with_attached_image
+ mlx.messages_with_attached_image = _spy
+ try:
+ list(
+ backend.generate_chat_response(
+ [{"role": "user", "content": "what is this"}],
+ system_prompt = "",
+ image = object(),
+ )
+ )
+ finally:
+ mlx.messages_with_attached_image = original
+
+ assert seen.get("structured_content") is True
+
+
+def test_a_named_processor_template_is_classified_without_tool_use():
+ """A ProcessorMixin render never implicitly selects the "tool_use" branch, so gating on
+ it advertised a catalog the prompt never shows (#10092)."""
+ import asyncio
+ import os
+ import sys
+
+ import pytest as _pytest
+
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import routes.inference as inf
+ import test_sf_client_tools_passthrough as passthrough
+
+ backend = passthrough._ScriptedBackend(passthrough._fixed("a plain answer"))
+ backend.models["sf-model"]["is_vision"] = True
+ backend.models["sf-model"]["chat_template_info"] = {
+ "template": _PROCESSOR_TEMPLATE_NO_TOOLS,
+ "processor_template": {
+ "default": _PROCESSOR_TEMPLATE_NO_TOOLS,
+ "tool_use": _CHATML_WITH_TOOLS,
+ },
+ }
+ payload = _image_request(tools = [passthrough.LOOKUP_TOOL], stream = False)
+
+ monkeypatch = _pytest.MonkeyPatch()
+ try:
+ passthrough._install(monkeypatch, backend)
+ # Honour prefer_tool_use through the real selector; a stub ignoring it cannot fail.
+ from core.inference.chat_template_helpers import (
+ _selected_template_strings_from_value,
+ )
+
+ def _features(
+ _b,
+ template,
+ tools = None,
+ prefer_tool_use = True,
+ **_k,
+ ):
+ selected = _selected_template_strings_from_value(
+ template, tools, prefer_tool_use = prefer_tool_use
+ )
+ body = selected[0] if selected else (template if isinstance(template, str) else "")
+ return {"supports_tools": body == _CHATML_WITH_TOOLS}
+
+ monkeypatch.setattr(inf, "_detect_safetensors_features", _features)
+
+ async def _run():
+ return await inf.openai_chat_completions(
+ payload, request = passthrough._Request(), current_subject = "u"
+ )
+
+ asyncio.run(_run())
+ finally:
+ monkeypatch.undo()
+
+ assert backend.calls, "generation never ran"
+ assert not backend.calls[0]["tools"]
+
+
+def test_a_historical_image_stays_on_the_turn_that_sent_it():
+ """_extract_content_parts takes the newest image from anywhere in the thread while the
+ renderers attach it to the newest user turn, moving it onto a later question (#10092)."""
+ import asyncio
+ import os
+ import sys
+
+ import pytest as _pytest
+
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import routes.inference as inf
+ import test_sf_client_tools_passthrough as passthrough
+ from models.inference import ChatCompletionRequest, ChatMessage
+
+ backend = passthrough._ScriptedBackend(passthrough._fixed("a plain answer"))
+ backend.models["sf-model"]["is_vision"] = True
+ backend.models["sf-model"]["chat_template_info"] = {
+ "template": _CHATML_WITH_TOOLS,
+ "processor_template": _CHATML_WITH_TOOLS,
+ "renders_image": True,
+ }
+ payload = ChatCompletionRequest(
+ model = "default",
+ tools = [passthrough.LOOKUP_TOOL],
+ stream = False,
+ messages = [
+ ChatMessage(
+ role = "user",
+ content = [
+ {"type": "text", "text": "IMAGE_QUESTION about the picture"},
+ {"type": "image_url", "image_url": {"url": _PNG_DATA_URL}},
+ ],
+ ),
+ ChatMessage(role = "assistant", content = "it is a dot"),
+ ChatMessage(role = "user", content = "LATER_QUESTION unrelated to it"),
+ ],
+ )
+
+ monkeypatch = _pytest.MonkeyPatch()
+ try:
+ passthrough._call(payload, monkeypatch, backend)
+ finally:
+ monkeypatch.undo()
+
+ assert backend.calls, "generation never ran"
+ sent = backend.calls[0]["messages"]
+ owning = [m for m in sent if m.get("role") == "user"][0]
+ later = [m for m in sent if m.get("role") == "user"][-1]
+ assert isinstance(owning["content"], list), owning
+ assert any(p.get("type") == "image" for p in owning["content"])
+ assert not isinstance(later["content"], list) or not any(
+ p.get("type") == "image" for p in later["content"]
+ )
+
+
+def test_a_tool_loop_replay_is_wrapped_for_a_part_based_processor():
+ """A parts-expecting processor template raises while iterating replayed assistant and
+ role="tool" turns left as bare strings, turning a valid request into a 500 (#10092)."""
+ from core.inference.chat_template_helpers import messages_with_attached_image
+
+ out = messages_with_attached_image(
+ [
+ {"role": "system", "content": "SENTINEL_RULE"},
+ {"role": "user", "content": "what is in this"},
+ {"role": "assistant", "content": "ASSISTANT_TEXT"},
+ {"role": "tool", "content": "TOOL_RESULT"},
+ ],
+ structured_content = True,
+ )
+ by_role = {m["role"]: m["content"] for m in out}
+ assert by_role["assistant"] == [{"type": "text", "text": "ASSISTANT_TEXT"}]
+ assert by_role["tool"] == [{"type": "text", "text": "TOOL_RESULT"}]
+ assert by_role["system"] == [{"type": "text", "text": "SENTINEL_RULE"}]
+ assert any(p.get("type") == "image" for p in by_role["user"])
+
+
+def test_an_assistant_tool_call_turn_without_content_is_still_parts():
+ """exclude_none drops content entirely from a standard assistant tool-call turn, and an
+ iterating template raises on the missing key just as on a bare string (#10092)."""
+ from core.inference.chat_template_helpers import messages_with_attached_image
+
+ out = messages_with_attached_image(
+ [
+ {"role": "user", "content": "what is in this"},
+ # exclude_none leaves no content key at all.
+ {"role": "assistant", "tool_calls": [{"id": "c1", "type": "function"}]},
+ {"role": "tool", "content": ""},
+ ],
+ structured_content = True,
+ )
+ assert all(isinstance(m["content"], list) for m in out), out
+ assistant = [m for m in out if m["role"] == "assistant"][0]
+ assert assistant["content"] == []
+ assert assistant["tool_calls"] == [{"id": "c1", "type": "function"}]
+
+
+def test_image_reasoning_is_classified_from_the_processor_template():
+ """A processor template can carry a reasoning channel the tokenizer never declares, so
+ classifying only supports_tools from it leaked <think> markup into the answer (#10092)."""
+ import asyncio
+ import os
+ import sys
+
+ import pytest as _pytest
+
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import routes.inference as inf
+ import test_sf_client_tools_passthrough as passthrough
+
+ backend = passthrough._ScriptedBackend(
+ passthrough._fixed("<think>hidden reasoning</think>the visible answer")
+ )
+ backend.models["sf-model"]["is_vision"] = True
+ backend.models["sf-model"]["chat_template_info"] = {
+ "template": _PROCESSOR_TEMPLATE_NO_TOOLS,
+ "processor_template": _CHATML_WITH_TOOLS,
+ }
+ payload = _image_request(stream = False)
+
+ monkeypatch = _pytest.MonkeyPatch()
+ try:
+ passthrough._install(monkeypatch, backend)
+ monkeypatch.setattr(
+ inf,
+ "_detect_safetensors_features",
+ lambda _b, template, **k: {
+ "supports_tools": False,
+ "supports_reasoning": template == _CHATML_WITH_TOOLS,
+ },
+ )
+
+ async def _run():
+ return await inf.openai_chat_completions(
+ payload, request = passthrough._Request(), current_subject = "u"
+ )
+
+ body = passthrough._json_body(asyncio.run(_run()))
+ finally:
+ monkeypatch.undo()
+
+ message = body["choices"][0]["message"]
+ assert message["reasoning_content"] == "hidden reasoning", message
+ assert "hidden reasoning" not in (message["content"] or "")
+
+
+def test_the_prefill_probe_gets_the_selected_processor_body():
+ """Handed the whole named collection, the prefill probe's <think> guard tests the
+ dict's keys and misses a selected branch that prefills an open block (#10092)."""
+ import asyncio
+ import os
+ import sys
+
+ import pytest as _pytest
+
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import routes.inference as inf
+ import test_sf_client_tools_passthrough as passthrough
+
+ collection = {"default": "DEFAULT_BODY <think></think>", "tool_use": "TOOL_BODY"}
+ backend = passthrough._ScriptedBackend(passthrough._fixed("an answer"))
+ backend.models["sf-model"]["is_vision"] = True
+ backend.models["sf-model"]["chat_template_info"] = {
+ "template": _PROCESSOR_TEMPLATE_NO_TOOLS,
+ "processor_template": collection,
+ }
+ seen: list = []
+
+ monkeypatch = _pytest.MonkeyPatch()
+ try:
+ passthrough._install(monkeypatch, backend)
+ real = inf._sf_reasoning_prefill_mode
+ monkeypatch.setattr(
+ inf,
+ "_sf_reasoning_prefill_mode",
+ lambda features, enable, template, **k: (
+ seen.append(template) or real(features, enable, template, **k)
+ ),
+ )
+
+ async def _run():
+ return await inf.openai_chat_completions(
+ _image_request(stream = False),
+ request = passthrough._Request(),
+ current_subject = "u",
+ )
+
+ asyncio.run(_run())
+ finally:
+ monkeypatch.undo()
+
+ assert seen, "the prefill probe never ran"
+ assert collection["default"] in seen, seen
+ assert not any(isinstance(t, dict) for t in seen), seen
+
+
+def test_no_image_marker_when_the_render_falls_back_to_the_tokenizer():
+ """A vision-marked model whose processor cannot handle images renders the tokenizer
+ text path, so marking the owning turn handed a string-only template part lists (#10092)."""
+ import asyncio
+ import os
+ import sys
+
+ import pytest as _pytest
+
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import test_sf_client_tools_passthrough as passthrough
+
+ backend = passthrough._ScriptedBackend(passthrough._fixed("a plain answer"))
+ backend.models["sf-model"]["is_vision"] = True
+ backend.models["sf-model"]["chat_template_info"] = {"template": _CHATML_WITH_TOOLS}
+ payload = _image_request(tools = [passthrough.LOOKUP_TOOL], stream = False)
+
+ monkeypatch = _pytest.MonkeyPatch()
+ try:
+ passthrough._call(payload, monkeypatch, backend)
+ finally:
+ monkeypatch.undo()
+
+ assert backend.calls, "generation never ran"
+ for message in backend.calls[0]["messages"]:
+ body = message.get("content")
+ if isinstance(body, list):
+ assert not any(p.get("type") == "image" for p in body), message
+
+
+def test_an_image_capable_processor_without_a_template_still_marks_its_turn():
+ """A processor with no template of its own still places the image, so keying the marker
+ on the template left a historical image on the newest, unrelated question (#10092)."""
+ import os
+ import sys
+
+ import pytest as _pytest
+
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import test_sf_client_tools_passthrough as passthrough
+ from models.inference import ChatCompletionRequest, ChatMessage
+
+ backend = passthrough._ScriptedBackend(passthrough._fixed("a plain answer"))
+ backend.models["sf-model"]["is_vision"] = True
+ backend.models["sf-model"]["chat_template_info"] = {
+ "template": _CHATML_WITH_TOOLS,
+ "renders_image": True,
+ }
+ payload = ChatCompletionRequest(
+ model = "default",
+ tools = [passthrough.LOOKUP_TOOL],
+ stream = False,
+ messages = [
+ ChatMessage(
+ role = "user",
+ content = [
+ {"type": "text", "text": "IMAGE_QUESTION"},
+ {"type": "image_url", "image_url": {"url": _PNG_DATA_URL}},
+ ],
+ ),
+ ChatMessage(role = "assistant", content = "a dot"),
+ ChatMessage(role = "user", content = "LATER_QUESTION"),
+ ],
+ )
+ monkeypatch = _pytest.MonkeyPatch()
+ try:
+ passthrough._call(payload, monkeypatch, backend)
+ finally:
+ monkeypatch.undo()
+
+ sent = [m for m in backend.calls[0]["messages"] if m.get("role") == "user"]
+ assert isinstance(sent[0]["content"], list), sent[0]
+ assert any(p.get("type") == "image" for p in sent[0]["content"])
+ assert not isinstance(sent[-1]["content"], list) or not any(
+ p.get("type") == "image" for p in sent[-1]["content"]
+ )
+
+
+def test_a_catalog_render_failure_does_not_drop_the_system_turn():
+ """Once the no-tools probe kept the system turn the role is supported, so a failure on
+ the tools render must not drop the caller's instructions (#10092)."""
+ calls: list = []
+
+ backend, seen = _vision_probe()
+
+ def _apply(processor, messages, **kwargs):
+ calls.append(messages)
+ if kwargs.get("tools"):
+ raise ValueError("this processor cannot render a catalog")
+ return "probe ok"
+
+ backend._apply_chat_template_for_generation = _apply
+
+ with pytest.raises(ValueError, match = "cannot render a catalog"):
+ _drain(
+ backend,
+ messages = [
+ {"role": "system", "content": "SENTINEL_RULE"},
+ {"role": "user", "content": "what is in this"},
+ ],
+ system_prompt = "",
+ tools = [_LOOKUP],
+ )
+
+ assert all(any(m.get("role") == "system" for m in attempt) for attempt in calls), calls
+
+
+def test_reasoning_is_not_rescued_from_the_tokenizer_body_on_an_image_turn():
+ """The reasoning search must not widen to the tokenizer body when the caller asked
+ about ONE body, or the image turn enables a channel its renderer never selected (#10092).
+
+ Deliberately does NOT stub _detect_safetensors_features: stubbing it made an earlier
+ version of this check pass with the fix reverted.
+ """
+ import routes.inference as inf
+
+ from core.inference.chat_template_helpers import _GEMMA_TEMPLATE_OPENERS
+
+ processor_body = "{{ messages }} plain, no reasoning"
+
+ class _Backend:
+ active_model_name = "m"
+ models = {
+ "m": {
+ "chat_template_info": {
+ "template": _GEMMA_TEMPLATE_OPENERS[0] + " {{ messages }}",
+ "processor_template": processor_body,
+ "renders_image": True,
+ }
+ }
+ }
+
+ backend = _Backend()
+ features = inf._detect_safetensors_features(
+ backend, processor_body, prefer_tool_use = False, reasoning_fallback = False
+ )
+ widened = inf._detect_safetensors_features(backend, processor_body, prefer_tool_use = False)
+
+ assert not features.get("supports_reasoning"), features
+ # If the widened call ever stops being True the test no longer proves anything.
+ assert widened.get("supports_reasoning"), widened
+
+
+def test_the_nudge_retry_skips_the_image_marker_on_a_text_only_fallback():
+ """The nudge retry's image marker must be keyed on renders_image, not on the image
+ alone, or a text-path fallback is handed part lists (#10092)."""
+ import os
+ import sys
+
+ import pytest as _pytest
+
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import test_sf_client_tools_passthrough as passthrough
+
+ truncated = '<tool_call>{"name": "lookup"'
+
+ def responder(messages, tools):
+ nudged = any(
+ "native tool-call format" in (m.get("content") or "")
+ for m in messages
+ if m.get("role") == "user" and isinstance(m.get("content"), str)
+ )
+ return (
+ ['<tool_call>{"name": "lookup", "arguments": {}}</tool_call>']
+ if nudged
+ else [truncated]
+ )
+
+ backend = passthrough._ScriptedBackend(responder)
+ backend.models["sf-model"]["is_vision"] = True
+ backend.models["sf-model"]["chat_template_info"] = {"template": _CHATML_WITH_TOOLS}
+ payload = _image_request(tools = [passthrough.LOOKUP_TOOL], stream = False, nudge_tool_calls = True)
+
+ monkeypatch = _pytest.MonkeyPatch()
+ try:
+ passthrough._call(payload, monkeypatch, backend)
+ finally:
+ monkeypatch.undo()
+
+ assert len(backend.calls) == 2, "the nudge retry did not run"
+ for call in backend.calls:
+ for message in call["messages"]:
+ body = message.get("content")
+ if isinstance(body, list):
+ assert not any(p.get("type") == "image" for p in body), message