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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: don't silently drop extra images from a message (#9719)
Nilay931194c82ec1
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex eb3054b9b9c..4a1cb4c1d20 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -25599,8 +25599,7 @@ class LlamaCppBackend:yield _evconversation.extend(_auto["messages"])_auto_satisfies_forced_choice = bool(_auto) and (- tool_choice == "required"- or forced_tool_name(tool_choice) == "search_knowledge_base"+ tool_choice == "required" or forced_tool_name(tool_choice) == "search_knowledge_base")_accumulated_completion_tokens = 0@@ -25816,9 +25815,7 @@ class LlamaCppBackend:requested_choice = "auto" if tool_choice is None else tool_choiceif _forced_choice_resolved and requested_choice not in ("auto", "none"):requested_choice = "auto"- requested_choice = (- reconciled_tool_choice(requested_choice, tools, safe_tools) or "auto"- )+ requested_choice = reconciled_tool_choice(requested_choice, tools, safe_tools) or "auto"forced_name = forced_tool_name(requested_choice)if forced_name:matching_tools = [diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 109bbaf6b03..721398a2de3 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -14385,6 +14385,57 @@ def _extract_content_parts(messages: list) -> tuple[str, list[dict], "Optional[s)+def _images_in_last_user_message(messages: list) -> int:+ """Image parts on the newest user turn.++ Per message, not per thread: only the turn being answered decides whether one+ call carries several.+ """+ for msg in reversed(messages):+ if msg.role != "user":+ continue+ if not isinstance(msg.content, list):+ return 0+ return sum(1 for part in msg.content if part.type == "image_url")+ return 0+++def _legacy_image_is_distinct(payload) -> bool:+ """Whether the top-level ``image_base64`` holds an image the messages do not.++ Studio fills that field from the thread, copying the same string the content+ part was built from, so an echo is byte-equal to the one value+ ``findLatestUserImageBase64`` could have sent. Anything else was attached to+ this request and a single-image path would drop it unannounced. Compare+ against that one value alone: matching any image in the thread let a client+ resend an older image, or an assistant's, and hid a real attachment.+ """+ if not payload.image_base64:+ return False+ return _latest_user_image_payload(payload.messages) != payload.image_base64+++def _latest_user_image_payload(messages: list) -> "Optional[str]":+ """The value ``findLatestUserImageBase64`` would put in ``image_base64``.++ Its scan order: newest turn first, user turns only, first image part, ``data:``+ prefix stripped the way :func:`_extract_content_parts` strips it. A part that+ yields nothing does not end the scan, since the frontend walks on past a falsy+ read; stopping on one refused Studio's echo of a valid earlier image.+ """+ for msg in reversed(messages):+ if msg.role != "user" or not isinstance(msg.content, list):+ continue+ for part in msg.content:+ if part.type != "image_url":+ continue+ url = part.image_url.url+ encoded = url.partition(",")[2] if url.startswith("data:") else url+ if encoded:+ return encoded+ return None++# ── External provider proxy ──────────────────────────────────────@@ -16175,6 +16226,17 @@ async def openai_chat_completions("request to a text model to use guided decoding.",)_reject_audio_output_continuation(payload)+ # Returns before every image check and speaks the newest user TEXT, so+ # an attached image would go unread. Nothing is running yet, so a bare+ # raise leaves nothing open.+ if _images_in_last_user_message(payload.messages) or _legacy_image_is_distinct(payload):+ raise HTTPException(+ status_code = 400,+ detail = (+ "This model generates speech and does not read images."+ " Load a vision model to send one."+ ),+ )return await _monitored_generate_audio(model_name,context_length = llama_backend.context_length,@@ -16209,6 +16271,17 @@ async def openai_chat_completions(if _wants_multiple_choices(payload):_raise_unsupported_n("non-GGUF audio chat completions")_reject_audio_output_continuation(payload)+ # Same as the GGUF branch above: generate_audio speaks the newest user+ # TEXT, so an attached image is dropped without a word, and this early+ # return is why the text-only check below never sees it. No row open yet.+ if _images_in_last_user_message(payload.messages) or _legacy_image_is_distinct(payload):+ raise HTTPException(+ status_code = 400,+ detail = (+ "This model generates speech and does not read images."+ " Load a vision model to send one."+ ),+ )return await _monitored_generate_audio(model_name)# ── Whisper without audio: return clear error ──@@ -16240,6 +16313,18 @@ async def openai_chat_completions(status_code = 400,detail = "continue_final_message is not supported with audio input.",)+ # Only the audio is forwarded, so an image on the turn is dropped on the+ # floor; one is discarded as silently as two. An image on an EARLIER turn+ # is deliberately allowed, since history images were never forwarded and+ # refusing would break asking by voice about a picture attached before.+ # api_monitor directly: _reject is not bound this early in the handler.+ if _images_in_last_user_message(payload.messages) or _legacy_image_is_distinct(payload):+ _audio_image_detail = (+ "This model takes audio or an image in one message, not both."+ " Send the image on its own turn."+ )+ api_monitor.fail(monitor_id, _audio_image_detail)+ raise HTTPException(status_code = 400, detail = _audio_image_detail)try:audio_array = _decode_audio_base64(payload.audio_base64)system_prompt, chat_messages, _ = _extract_content_parts(payload.messages)@@ -16473,7 +16558,6 @@ async def openai_chat_completions(def _reject_missing_forced_tool(tool_choice, selected_tools) -> None:from core.inference.chat_template_helpers import catalog_tool_names, forced_tool_name-forced_name = forced_tool_name(tool_choice)if forced_name and forced_name not in catalog_tool_names(selected_tools):raise _reject(@@ -18311,32 +18395,60 @@ async def openai_chat_completions(# Decode image (from content parts OR legacy field)image_b64 = extracted_image_b64 or payload.image_base64image = None+ # Image PARTS, not the ones extraction could decode: only a data URL yields+ # base64, so a turn holding several remote or empty image URLs has no image_b64+ # at all, and counting decoded images would let exactly those slip past. One+ # undecodable image is left alone, since it is not a multi-image call.+ images_on_turn = _images_in_last_user_message(payload.messages)- if image_b64:+ if image_b64 or images_on_turn > 1:try:model_info = backend.models.get(backend.active_model_name, {})if not model_info.get("is_vision"):- raise HTTPException(- status_code = 400,- detail = "Image provided but current model is text-only. Load a vision model.",+ # _reject, not a bare raise: the monitor row is open by here, and one+ # left running keeps Studio reporting the backend as generating after+ # the request has already been answered with a 400.+ raise _reject(+ 400,+ "Image provided but current model is text-only. Load a vision model.",)- image = await asyncio.to_thread(- _decode_and_resize_image,- backend,- image_b64,- )+ # A distinct legacy image is a second image the caller supplied, so it+ # joins the structural count. The second clause covers what the count+ # misses, a turn with no part while an earlier one has: selection is+ # `extracted_image_b64 or image_base64`, so the legacy one goes unread.+ _legacy_is_distinct = _legacy_image_is_distinct(payload)+ if images_on_turn + int(_legacy_is_distinct) > 1 or (+ extracted_image_b64 and _legacy_is_distinct+ ):+ raise _reject(+ 400,+ (+ "This model takes one image per message. Attach one, or load a"+ " GGUF build of it, which accepts several."+ ),+ )++ if image_b64:+ image = await asyncio.to_thread(+ _decode_and_resize_image,+ backend,+ image_b64,+ )except HTTPException:raiseexcept Exception as e:- raise log_and_http_error(+ # log_and_http_error knows nothing about the monitor row, so hand its+ # public detail to _reject and close the row like the refusals above.+ decode_error = log_and_http_error(e,400,"Failed to decode image",event = "inference.decode_image_failed",log = logger,)+ raise _reject(decode_error.status_code, decode_error.detail)# Classify capability flags from the loaded template._sf_model_info = backend.models.get(backend.active_model_name, {})@@ -23692,9 +23804,7 @@ async def anthropic_messages(server_tool_choice = openai_tool_choiceif isinstance(server_tool_choice, dict):forced_function = server_tool_choice.get("function")- forced_name = (- forced_function.get("name") if isinstance(forced_function, dict) else None- )+ forced_name = forced_function.get("name") if isinstance(forced_function, dict) else Nonecanonical_name = _STUDIO_ANTHROPIC_TOOL_ALIASES.get(forced_name)if canonical_name:server_tool_choice = {diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.pyindex d4e4502686e..e2ca7d6cb2f 100644--- a/studio/backend/tests/test_anthropic_messages.py+++ b/studio/backend/tests/test_anthropic_messages.py@@ -2733,10 +2733,7 @@ class TestAnthropicMessagesToolRouting:call_kind, kwargs = backend.calls[0]assert call_kind == "tools"- assert kwargs["tool_choice"] == {- "type": "function",- "function": {"name": "web_search"},- }+ assert kwargs["tool_choice"] == {"type": "function", "function": {"name": "web_search"}}assert [tool["function"]["name"] for tool in kwargs["tools"]] == ["web_search"]def test_server_tool_choice_must_be_in_the_selected_catalog(self, monkeypatch):diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.pyindex 02516c8f18b..0d0bbbf3af6 100644--- a/studio/backend/tests/test_llama_cpp_tool_loop.py+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py@@ -327,7 +327,7 @@ def test_forced_tool_choice_must_exist_in_the_catalog(monkeypatch):payloads: list[dict] = []backend = _make_backend(monkeypatch, [], payloads)- with pytest.raises(ValueError, match="Forced tool 'python' is not enabled"):+ with pytest.raises(ValueError, match = "Forced tool 'python' is not enabled"):list(backend.generate_chat_completion_with_tools(messages = [{"role": "user", "content": "run python"}],@@ -375,9 +375,9 @@ def test_forced_tool_choice_retries_after_other_structured_calls(monkeypatch):assert [tool["function"]["name"] for tool in payloads[1]["tools"]] == ["web_search"]assert payloads[2]["tool_choice"] == "auto"assert calls == [("web_search", {"query": "kernel version"})]- assert [- event.get("tool_name") for event in events if event.get("type") == "tool_start"- ] == ["web_search"]+ assert [event.get("tool_name") for event in events if event.get("type") == "tool_start"] == [+ "web_search"+ ]def test_none_tool_choice_never_executes_model_tool_calls(monkeypatch):@@ -3453,9 +3453,7 @@ def test_rag_autoinject_only_resolves_matching_forced_choices(monkeypatch):)return payloads[0]- matching = first_payload(- {"type": "function", "function": {"name": "search_knowledge_base"}}- )+ matching = first_payload({"type": "function", "function": {"name": "search_knowledge_base"}})required = first_payload("required")unrelated = first_payload({"type": "function", "function": {"name": "web_search"}})diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.pyindex 8c34ad727c7..3de093a2a83 100644--- a/studio/backend/tests/test_openai_tool_passthrough.py+++ b/studio/backend/tests/test_openai_tool_passthrough.py@@ -6,6 +6,7 @@import osimport sysimport asyncio+import base64import jsonimport threadingimport time@@ -52,6 +53,7 @@ from routes.inference import (_effective_openai_max_tokens,_effective_openai_max_tokens_from_values,_extract_content_parts,+ _images_in_last_user_message,_friendly_error,_friendly_upstream_error,_merge_user_content,@@ -81,6 +83,14 @@ from routes.inference import ()from state.tool_policy import reset_tool_policy, set_tool_policy+# 1x1 PNGs that Pillow can actually decode, for the paths that reach the decoder.+_RED_PNG_B64 = (+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"+)+_BLUE_PNG_B64 = (+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGNgYPgPAAEDAQAIicLsAAAAAElFTkSuQmCC"+)+@pytest.fixture(autouse = True)def _reset_admission_queues():@@ -571,164 +581,1142 @@ class TestChatCompletionRequestToolFields:class _UnusedBackend:is_loaded = False- client = self._v1_client(monkeypatch, _UnusedBackend())+ client = self._v1_client(monkeypatch, _UnusedBackend())+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [{"role": "user", "content": "hi"}],+ "provider_type": "openai",+ "top_logprobs": 3,+ },+ )+ self._assert_unsupported_param(resp, "top_logprobs")++ def test_n_rejected_for_gguf_streaming_path(self, monkeypatch):+ class _GGUFBackend:+ is_loaded = True+ model_identifier = "test-gguf"+ supports_tools = False+ is_vision = False+ _is_audio = False+ context_length = 4096++ client = self._v1_client(monkeypatch, _GGUFBackend())+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [{"role": "user", "content": "hi"}],+ "stream": True,+ "n": 2,+ },+ )+ self._assert_unsupported_n(resp)++ def test_n_rejected_for_gguf_tools_passthrough_path(self, monkeypatch):+ import routes.inference as inference_route++ class _GGUFBackend:+ is_loaded = True+ model_identifier = "test-gguf"+ supports_tools = True+ is_vision = False+ _is_audio = False+ context_length = 4096++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ client = self._v1_client(monkeypatch, _GGUFBackend())+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [{"role": "user", "content": "hi"}],+ "tools": [+ {+ "type": "function",+ "function": {+ "name": "lookup",+ "parameters": {"type": "object"},+ },+ }+ ],+ "n": 2,+ },+ )+ self._assert_unsupported_n(resp)+ [entry] = monitor.snapshot()+ assert entry["status"] == "error"+ assert "n > 1 is not supported" in entry["error"]+ assert monitor.active_count() == 0++ def test_a_no_op_response_format_keeps_a_gguf_request_off_the_passthrough(self):+ """The passthrough exists to reach llama-server's grammar engine, and+ ``{"type": "text"}`` names the default rather than a grammar: routing it+ there would withdraw what the ordinary path serves, n > 1 among them."""+ from routes.inference import _takes_tool_passthrough++ class _GGUFBackend:+ supports_tools = False++ backend = _GGUFBackend()+ assert _takes_tool_passthrough(self._make(response_format = {"type": "json_object"}), backend)+ # The field takes any object, and anything but the exact default -- an+ # unknown type, or a text format carrying members this build does not know+ # -- is a contract, so it keeps going where one can be answered or rejected.+ assert _takes_tool_passthrough(self._make(response_format = {"type": "later"}), backend)+ assert _takes_tool_passthrough(+ self._make(response_format = {"type": "text", "strict": True}), backend+ )+ assert not _takes_tool_passthrough(self._make(response_format = {"type": "text"}), backend)++ @pytest.mark.parametrize("enabled_tools", [None, []])+ def test_the_gguf_tool_loop_refuses_a_contract_it_cannot_forward(+ self, monkeypatch, enabled_tools+ ):+ """Unsloth's loop runs its own turns and never forwards response_format, so+ serving the request would answer with text that violates the contract while+ the client has no way to tell. A selection that resolves to no tool routes to+ the ordinary generator, which forwards it no more than the loop does, and the+ refusal lands after the monitor row opens, so it must close it."""+ import routes.inference as inference_route++ class _GGUFBackend:+ is_loaded = True+ model_identifier = "test-gguf"+ supports_tools = True+ is_vision = False+ _is_audio = False+ context_length = 4096++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ client = self._v1_client(monkeypatch, _GGUFBackend())+ body = {+ "messages": [{"role": "user", "content": "hi"}],+ "enable_tools": True,+ "response_format": {"type": "json_object"},+ }+ if enabled_tools is not None:+ body["enabled_tools"] = enabled_tools+ resp = client.post("/v1/chat/completions", json = body)+ self._assert_unsupported_param(resp, "response_format")+ assert monitor.active_count() == 0++ def test_client_tools_rejected_when_gguf_template_has_no_tool_support(self, monkeypatch):+ import routes.inference as inference_route++ class _GGUFBackend:+ is_loaded = True+ model_identifier = "test-gguf"+ supports_tools = False+ is_vision = False+ _is_audio = False+ context_length = 4096++ def generate_chat_completion(self, **_kwargs):+ raise AssertionError("client tools must not fall through to the standard GGUF path")++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ client = self._v1_client(monkeypatch, _GGUFBackend())+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [{"role": "user", "content": "hi"}],+ "tools": [+ {+ "type": "function",+ "function": {+ "name": "lookup",+ "parameters": {"type": "object"},+ },+ }+ ],+ },+ )++ self._assert_unsupported_param(resp, "tools")+ assert "does not advertise tools" in resp.json()["error"]["message"]+ [entry] = monitor.snapshot()+ assert entry["status"] == "error"+ assert "does not advertise tools" in entry["error"]+ assert monitor.active_count() == 0++ def test_a_multi_image_message_closes_the_monitor_row(self, monkeypatch):+ """The single-image refusal lands after the monitor row opens, so it must+ close it: a row left running keeps Studio reporting the backend as+ generating long after the request has been answered with a 400."""+ import routes.inference as inference_route++ class _LlamaOff:+ is_loaded = False+ supports_tools = False+ is_vision = False+ context_length = None++ class _VisionBackend:+ active_model_name = "vision-sf"+ models = {+ "vision-sf": {+ "is_vision": True,+ "chat_template_info": {"template": "chatml"},+ "context_length": 4096,+ }+ }++ def resize_image(self, image):+ return image++ def generate_chat_response(self, **kwargs):+ yield "ok"++ def reset_generation_state(self, cancel_event = None):+ pass++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ monkeypatch.setattr(+ inference_route,+ "_detect_safetensors_features",+ lambda *a, **k: {"supports_tools": False},+ )+ client = self._v1_client(monkeypatch, _LlamaOff(), _VisionBackend())+ image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {+ "role": "user",+ "content": [{"type": "text", "text": "compare these"}, image, image],+ }+ ]+ },+ )++ assert resp.status_code == 400+ assert "one image per message" in resp.text+ [entry] = monitor.snapshot()+ assert entry["status"] == "error"+ assert "one image per message" in entry["error"]+ assert monitor.active_count() == 0++ def _standard_vision_client(+ self,+ monkeypatch,+ monitor,+ is_vision = True,+ ):+ """A loaded safetensors backend on the standard path, recording generation."""+ import routes.inference as inference_route++ class _LlamaOff:+ is_loaded = False+ supports_tools = False+ is_vision = False+ context_length = None++ calls = []++ class _Backend:+ active_model_name = "vision-sf"+ models = {+ "vision-sf": {+ "is_vision": is_vision,+ "chat_template_info": {"template": "chatml"},+ "context_length": 4096,+ }+ }+ generated = calls++ def resize_image(self, image):+ return image++ def generate_chat_response(self, **kwargs):+ calls.append(kwargs)+ yield "ok"++ def reset_generation_state(self, cancel_event = None):+ pass++ backend = _Backend()+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ monkeypatch.setattr(+ inference_route,+ "_detect_safetensors_features",+ lambda *a, **k: {"supports_tools": False},+ )+ return self._v1_client(monkeypatch, _LlamaOff(), backend), backend++ def test_several_undecodable_images_on_one_message_are_still_refused(self, monkeypatch):+ """The count is of image PARTS, not of images extraction could decode.++ Only a data URL becomes base64, so several remote image URLs decode to+ nothing; gating on a decoded image would let exactly those be flattened+ away unannounced, which is the silent drop this guard exists to stop."""+ monitor = ApiMonitor(max_entries = 3)+ client, backend = self._standard_vision_client(monkeypatch, monitor)+ remote = {"type": "image_url", "image_url": {"url": "https://example.com/a.png"}}+ empty = {"type": "image_url", "image_url": {"url": "data:image/png;base64,"}}++ for parts in ([remote, remote], [empty, empty], [empty, remote]):+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {+ "role": "user",+ "content": [{"type": "text", "text": "compare these"}, *parts],+ }+ ]+ },+ )+ assert resp.status_code == 400, parts+ assert "one image per message" in resp.text++ assert backend.generated == []+ assert monitor.active_count() == 0+ assert all(e["status"] == "error" for e in monitor.snapshot())++ @pytest.mark.parametrize(+ "legacy,expected",+ [(_BLUE_PNG_B64, 400), (_RED_PNG_B64, 200)],+ ids = ["distinct_legacy_image_is_a_second_image", "echoed_legacy_image_is_the_same_one"],+ )+ def test_a_distinct_legacy_image_beside_a_message_image(self, legacy, expected, monkeypatch):+ """`extracted_image_b64 or image_base64` always picks the message image, so a+ DIFFERENT top-level image is a second one the caller never hears about.+ Studio's echo byte-matches the part, so it must not be counted twice."""+ monitor = ApiMonitor(max_entries = 3)+ client, backend = self._standard_vision_client(monkeypatch, monitor)+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "what is this?"},+ {+ "type": "image_url",+ "image_url": {"url": f"data:image/png;base64,{_RED_PNG_B64}"},+ },+ ],+ }+ ],+ "image_base64": legacy,+ },+ )++ assert resp.status_code == expected+ assert monitor.active_count() == 0+ if expected == 400:+ assert "one image per message" in resp.text+ assert backend.generated == []+ else:+ assert len(backend.generated) == 1++ @pytest.mark.parametrize(+ "bad_part",+ [+ {"type": "image_url", "image_url": {"url": "https://example.com/a.png"}},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,"}},+ ],+ ids = ["remote_url", "payloadless_data_url"],+ )+ def test_an_unreadable_part_plus_a_distinct_legacy_image_is_two_images(+ self, bad_part, monkeypatch+ ):+ """The count is structural, so a part the extractor cannot read still counts.+ With a distinct top-level image beside it the caller supplied two, and the+ part is the one that gets dropped."""+ monitor = ApiMonitor(max_entries = 3)+ client, backend = self._standard_vision_client(monkeypatch, monitor)+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {"role": "user", "content": [{"type": "text", "text": "x"}, bad_part]}+ ],+ "image_base64": _RED_PNG_B64,+ },+ )++ assert resp.status_code == 400+ assert "one image per message" in resp.text+ assert backend.generated == []+ assert monitor.active_count() == 0++ def test_an_unreadable_part_alone_is_still_answered(self, monkeypatch):+ """Control: one remote image and no top-level image is not a multi-image+ call, and clients relying on that text answer must keep it."""+ monitor = ApiMonitor(max_entries = 3)+ client, backend = self._standard_vision_client(monkeypatch, monitor)+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "x"},+ {"type": "image_url", "image_url": {"url": "https://e.com/a.png"}},+ ],+ }+ ]+ },+ )++ assert resp.status_code == 200+ assert len(backend.generated) == 1+ assert backend.generated[0]["image"] is None+ assert monitor.active_count() == 0++ @pytest.mark.parametrize("n_images,expected", [(2, 400), (1, 400), (0, 200)])+ def test_a_tts_model_refuses_an_image_instead_of_speaking_over_it(+ self, n_images, expected, monkeypatch+ ):+ """The TTS auto-route returns before the standard image path and speaks the+ newest user text, so an attached image is discarded. It is also why the+ text-only rejection never sees such a request."""+ import routes.inference as inference_route++ class _LlamaOff:+ is_loaded = False+ supports_tools = False+ is_vision = False+ context_length = None++ spoken = []++ class _TtsBackend:+ active_model_name = "tts"+ models = {+ "tts": {+ "is_vision": False,+ "is_audio": True,+ "audio_type": "csm",+ "chat_template_info": {"template": "chatml"},+ "context_length": 4096,+ }+ }++ def resize_image(self, image):+ return image++ def generate_audio_response(self, **kwargs):+ spoken.append(kwargs)+ import numpy as np+ return np.zeros(16000, dtype = "float32"), 16000++ def reset_generation_state(self, cancel_event = None):+ pass++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ monkeypatch.setattr(+ inference_route,+ "_detect_safetensors_features",+ lambda *a, **k: {"supports_tools": False},+ )+ client = self._v1_client(monkeypatch, _LlamaOff(), _TtsBackend())+ image = {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{_RED_PNG_B64}"}}+ content = [{"type": "text", "text": "say hi"}] + [image] * n_images++ resp = client.post(+ "/v1/chat/completions",+ json = {"messages": [{"role": "user", "content": content}]},+ )++ assert resp.status_code == expected+ assert monitor.active_count() == 0+ if expected == 400:+ assert "does not read images" in resp.text+ assert spoken == []+ else:+ assert len(spoken) == 1++ @pytest.mark.parametrize(+ "legacy_is_newest,expected",+ [(False, 400), (True, 200)],+ ids = ["older_user_image_is_not_the_echo", "newest_user_image_is_the_echo"],+ )+ def test_only_the_newest_user_image_counts_as_the_echo(+ self, legacy_is_newest, expected, monkeypatch+ ):+ """findLatestUserImageBase64 returns the first image on the newest user turn,+ so that one value is all the field could carry. Matching anywhere let a+ client resend an older image while the newest turn supplied its own."""+ monitor = ApiMonitor(max_entries = 3)+ client, backend = self._standard_vision_client(monkeypatch, monitor)+ older = {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{_RED_PNG_B64}"}}+ newest = {+ "type": "image_url",+ "image_url": {"url": f"data:image/png;base64,{_BLUE_PNG_B64}"},+ }++ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {"role": "user", "content": [{"type": "text", "text": "first"}, older]},+ {"role": "assistant", "content": "ok"},+ {"role": "user", "content": [{"type": "text", "text": "second"}, newest]},+ ],+ "image_base64": _BLUE_PNG_B64 if legacy_is_newest else _RED_PNG_B64,+ },+ )++ assert resp.status_code == expected+ assert monitor.active_count() == 0+ if expected == 400:+ assert "one image per message" in resp.text+ assert backend.generated == []+ else:+ assert len(backend.generated) == 1++ def test_a_comma_in_a_remote_url_is_not_an_echo(self, monkeypatch):+ """Only a data: URL carries an inline payload, the way _extract_content_parts+ reads it. Splitting every URL on its first comma let a remote URL that merely+ contains one pose as an echo of the top-level image, hiding a second image."""+ monitor = ApiMonitor(max_entries = 3)+ client, backend = self._standard_vision_client(monkeypatch, monitor)+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "x"},+ {+ "type": "image_url",+ "image_url": {"url": f"https://h.example/img,{_RED_PNG_B64}"},+ },+ ],+ }+ ],+ "image_base64": _RED_PNG_B64,+ },+ )++ assert resp.status_code == 400+ assert "one image per message" in resp.text+ assert backend.generated == []+ assert monitor.active_count() == 0++ def test_a_payloadless_newest_image_does_not_end_the_echo_scan(self, monkeypatch):+ """findLatestUserImageBase64 walks on past a falsy read, so an empty newest+ part is not the value the field carries. Stopping on it refused Studio's+ echo of a valid earlier image as a second attachment."""+ monitor = ApiMonitor(max_entries = 3)+ client, backend = self._standard_vision_client(monkeypatch, monitor)+ older = {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{_RED_PNG_B64}"}}+ empty = {"type": "image_url", "image_url": {"url": "data:image/png;base64,"}}++ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {"role": "user", "content": [{"type": "text", "text": "first"}, older]},+ {"role": "assistant", "content": "ok"},+ {"role": "user", "content": [{"type": "text", "text": "second"}, empty]},+ ],+ "image_base64": _RED_PNG_B64,+ },+ )++ assert resp.status_code == 200+ assert len(backend.generated) == 1+ assert monitor.active_count() == 0++ @pytest.mark.parametrize(+ "n_images,expected",+ [(1, 400), (0, 200)],+ ids = ["image_on_a_gguf_speech_model_is_refused", "no_image_still_speaks"],+ )+ def test_a_gguf_speech_model_refuses_an_image(self, n_images, expected, monkeypatch):+ """The GGUF audio branch returns before every image check, exactly as the+ safetensors audio branch does, and speaks the newest user TEXT. An attached+ image went unread and unmentioned."""+ import routes.inference as inference_route++ spoken = []++ class _LlamaTts:+ is_loaded = True+ model_identifier = "tts.gguf"+ supports_tools = False+ is_vision = False+ _is_audio = True+ _audio_type = "snac"+ context_length = 4096++ def generate_audio_response(self, **kwargs):+ spoken.append(kwargs)+ import numpy as np+ return np.zeros(16000, dtype = "float32"), 16000++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ client = self._v1_client(monkeypatch, _LlamaTts(), None)+ image = {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{_RED_PNG_B64}"}}++ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {+ "role": "user",+ "content": [{"type": "text", "text": "say hi"}] + [image] * n_images,+ }+ ]+ },+ )++ assert resp.status_code == expected+ assert monitor.active_count() == 0+ if expected == 400:+ assert "does not read images" in resp.text+ assert spoken == []+ else:+ assert len(spoken) == 1++ def test_a_legacy_image_alone_is_still_served(self, monkeypatch):+ """With nothing extracted from the messages the top-level image IS the one+ that gets used, so it must not be refused as a second image."""+ monitor = ApiMonitor(max_entries = 3)+ client, backend = self._standard_vision_client(monkeypatch, monitor)+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [{"role": "user", "content": "what is this?"}],+ "image_base64": _RED_PNG_B64,+ },+ )++ assert resp.status_code == 200+ assert len(backend.generated) == 1+ assert backend.generated[0]["image"] is not None+ assert monitor.active_count() == 0++ def test_a_single_undecodable_image_is_left_alone(self, monkeypatch):+ """One remote image is not a multi-image call. Clients that pass a remote+ URL today get a text answer, and this guard must not turn that into a 400."""+ monitor = ApiMonitor(max_entries = 3)+ client, backend = self._standard_vision_client(monkeypatch, monitor)+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "what is this?"},+ {+ "type": "image_url",+ "image_url": {"url": "https://example.com/a.png"},+ },+ ],+ }+ ]+ },+ )++ assert resp.status_code == 200+ assert len(backend.generated) == 1+ assert backend.generated[0]["image"] is None+ assert monitor.active_count() == 0++ def test_a_text_only_model_closes_the_monitor_row(self, monkeypatch):+ """Same defect as the multi-image refusal, one branch up: this rejection+ also lands after the monitor row opens and must finalize it."""+ monitor = ApiMonitor(max_entries = 3)+ client, backend = self._standard_vision_client(monkeypatch, monitor, is_vision = False)+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "what is this?"},+ {+ "type": "image_url",+ "image_url": {"url": "data:image/png;base64,AAAA"},+ },+ ],+ }+ ]+ },+ )++ assert resp.status_code == 400+ assert "text-only" in resp.text+ assert backend.generated == []+ [entry] = monitor.snapshot()+ assert entry["status"] == "error"+ assert "text-only" in entry["error"]+ assert monitor.active_count() == 0++ @pytest.mark.parametrize("n_images,expected", [(2, 400), (1, 400), (0, 200)])+ def test_an_image_with_audio_input_is_refused_not_dropped(+ self, n_images, expected, monkeypatch+ ):+ """The audio-input branch returns before the standard image path and forwards+ only the flattened messages plus the audio, so an attached image is+ discarded. Any count: one is dropped here as silently as two."""+ import numpy as np++ import routes.inference as inference_route++ class _LlamaOff:+ is_loaded = False+ supports_tools = False+ is_vision = False+ context_length = None++ calls = []++ class _OmniBackend:+ active_model_name = "omni-sf"+ models = {+ "omni-sf": {+ "is_vision": True,+ "has_audio_input": True,+ "audio_type": "audio_vlm",+ "chat_template_info": {"template": "chatml"},+ "context_length": 4096,+ }+ }+ generated = calls++ def resize_image(self, image):+ return image++ def generate_audio_input_response(self, **kwargs):+ calls.append(kwargs)+ yield "answered from the audio"++ def generate_chat_response(self, **kwargs):+ raise AssertionError("audio input should take the audio branch")++ def reset_generation_state(self, cancel_event = None):+ pass++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ monkeypatch.setattr(+ inference_route,+ "_detect_safetensors_features",+ lambda *a, **k: {"supports_tools": False},+ )+ monkeypatch.setattr(+ inference_route,+ "_decode_audio_base64",+ lambda *a, **k: np.zeros(16000, dtype = "float32"),+ )+ client = self._v1_client(monkeypatch, _LlamaOff(), _OmniBackend())+ image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}+ content = [{"type": "text", "text": "what is this?"}] + [image] * n_images++ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [{"role": "user", "content": content}],+ "audio_base64": base64.b64encode(b"RIFF....WAVEfmt ").decode(),+ },+ )++ assert resp.status_code == expected+ assert monitor.active_count() == 0+ if expected == 400:+ assert "audio or an image in one message" in resp.text+ assert calls == []+ [entry] = monitor.snapshot()+ assert entry["status"] == "error"+ assert "audio or an image in one message" in entry["error"]+ else:+ assert len(calls) == 1++ def test_a_legacy_image_field_with_audio_is_refused(self, monkeypatch):+ """A client attaching its image through the top-level image_base64+ extension, with no image parts anywhere, means that image for THIS+ request. The audio branch cannot forward it, so refuse rather than drop."""+ import numpy as np++ import routes.inference as inference_route++ class _LlamaOff:+ is_loaded = False+ supports_tools = False+ is_vision = False+ context_length = None++ calls = []++ class _OmniBackend:+ active_model_name = "omni-sf"+ models = {+ "omni-sf": {+ "is_vision": True,+ "has_audio_input": True,+ "chat_template_info": {"template": "chatml"},+ "context_length": 4096,+ }+ }++ def resize_image(self, image):+ return image++ def generate_audio_input_response(self, **kwargs):+ calls.append(kwargs)+ yield "answered from the audio"++ def reset_generation_state(self, cancel_event = None):+ pass++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ monkeypatch.setattr(+ inference_route,+ "_detect_safetensors_features",+ lambda *a, **k: {"supports_tools": False},+ )+ monkeypatch.setattr(+ inference_route,+ "_decode_audio_base64",+ lambda *a, **k: np.zeros(16000, dtype = "float32"),+ )+ client = self._v1_client(monkeypatch, _LlamaOff(), _OmniBackend())+resp = client.post("/v1/chat/completions",json = {- "messages": [{"role": "user", "content": "hi"}],- "provider_type": "openai",- "top_logprobs": 3,+ "messages": [{"role": "user", "content": "what is this?"}],+ "image_base64": "AAAA",+ "audio_base64": base64.b64encode(b"RIFF....WAVEfmt ").decode(),},)- self._assert_unsupported_param(resp, "top_logprobs")- def test_n_rejected_for_gguf_streaming_path(self, monkeypatch):- class _GGUFBackend:- is_loaded = True- model_identifier = "test-gguf"+ assert resp.status_code == 400+ assert "audio or an image in one message" in resp.text+ assert calls == []+ assert monitor.active_count() == 0++ def test_a_derived_legacy_image_field_does_not_block_a_voice_follow_up(self, monkeypatch):+ """Studio fills image_base64 from anywhere in the thread, so it is not a+ per-turn signal. When an earlier turn carries the image the parts decide,+ and the voice follow-up must still be answered."""+ import numpy as np++ import routes.inference as inference_route++ class _LlamaOff:+ is_loaded = Falsesupports_tools = Falseis_vision = False- _is_audio = False- context_length = 4096+ context_length = None++ calls = []++ class _OmniBackend:+ active_model_name = "omni-sf"+ models = {+ "omni-sf": {+ "is_vision": True,+ "has_audio_input": True,+ "chat_template_info": {"template": "chatml"},+ "context_length": 4096,+ }+ }++ def resize_image(self, image):+ return image++ def generate_audio_input_response(self, **kwargs):+ calls.append(kwargs)+ yield "answered from the audio"++ def reset_generation_state(self, cancel_event = None):+ pass++ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ monkeypatch.setattr(+ inference_route,+ "_detect_safetensors_features",+ lambda *a, **k: {"supports_tools": False},+ )+ monkeypatch.setattr(+ inference_route,+ "_decode_audio_base64",+ lambda *a, **k: np.zeros(16000, dtype = "float32"),+ )+ client = self._v1_client(monkeypatch, _LlamaOff(), _OmniBackend())+ image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}- client = self._v1_client(monkeypatch, _GGUFBackend())resp = client.post("/v1/chat/completions",json = {- "messages": [{"role": "user", "content": "hi"}],- "stream": True,- "n": 2,+ "messages": [+ {+ "role": "user",+ "content": [{"type": "text", "text": "what is this?"}, image],+ },+ {"role": "assistant", "content": "a square"},+ {"role": "user", "content": "and now by voice"},+ ],+ "image_base64": "AAAA",+ "audio_base64": base64.b64encode(b"RIFF....WAVEfmt ").decode(),},)- self._assert_unsupported_n(resp)- def test_n_rejected_for_gguf_tools_passthrough_path(self, monkeypatch):+ assert resp.status_code == 200+ assert len(calls) == 1+ assert monitor.active_count() == 0++ def test_a_new_legacy_image_is_refused_even_with_image_bearing_history(self, monkeypatch):+ """A direct client can attach a NEW image through the legacy field while the+ newest turn stays text-only. Studio's own field is copied out of the thread+ and byte-matches a part; one matching nothing came with this request."""+ import numpy as np+import routes.inference as inference_route- class _GGUFBackend:- is_loaded = True- model_identifier = "test-gguf"- supports_tools = True+ class _LlamaOff:+ is_loaded = False+ supports_tools = Falseis_vision = False- _is_audio = False- context_length = 4096+ context_length = None++ calls = []++ class _OmniBackend:+ active_model_name = "omni-sf"+ models = {+ "omni-sf": {+ "is_vision": True,+ "has_audio_input": True,+ "chat_template_info": {"template": "chatml"},+ "context_length": 4096,+ }+ }++ def resize_image(self, image):+ return image++ def generate_audio_input_response(self, **kwargs):+ calls.append(kwargs)+ yield "answered from the audio"++ def reset_generation_state(self, cancel_event = None):+ passmonitor = ApiMonitor(max_entries = 3)monkeypatch.setattr(inference_route, "api_monitor", monitor)- client = self._v1_client(monkeypatch, _GGUFBackend())+ monkeypatch.setattr(+ inference_route,+ "_detect_safetensors_features",+ lambda *a, **k: {"supports_tools": False},+ )+ monkeypatch.setattr(+ inference_route,+ "_decode_audio_base64",+ lambda *a, **k: np.zeros(16000, dtype = "float32"),+ )+ client = self._v1_client(monkeypatch, _LlamaOff(), _OmniBackend())+ old = {"type": "image_url", "image_url": {"url": "data:image/png;base64,T0xE"}}+resp = client.post("/v1/chat/completions",json = {- "messages": [{"role": "user", "content": "hi"}],- "tools": [- {- "type": "function",- "function": {- "name": "lookup",- "parameters": {"type": "object"},- },- }+ "messages": [+ {"role": "user", "content": [{"type": "text", "text": "this?"}, old]},+ {"role": "assistant", "content": "a square"},+ {"role": "user", "content": "and this one?"},],- "n": 2,+ "image_base64": "TkVX",+ "audio_base64": base64.b64encode(b"RIFF....WAVEfmt ").decode(),},)- self._assert_unsupported_n(resp)- [entry] = monitor.snapshot()- assert entry["status"] == "error"- assert "n > 1 is not supported" in entry["error"]++ assert resp.status_code == 400+ assert "audio or an image in one message" in resp.text+ assert calls == []assert monitor.active_count() == 0- def test_a_no_op_response_format_keeps_a_gguf_request_off_the_passthrough(self):- """The passthrough exists to reach llama-server's grammar engine, and- ``{"type": "text"}`` names the default rather than a grammar: routing it- there would withdraw what the ordinary path serves, n > 1 among them."""- from routes.inference import _takes_tool_passthrough+ def test_an_assistant_image_cannot_hide_a_top_level_attachment(self, monkeypatch):+ """findLatestUserImageBase64 derives the legacy field only from USER turns,+ so an image on an assistant turn is not something it could be an echo of.+ Matching any role let an explicitly attached image be discarded here."""+ import numpy as np- class _GGUFBackend:+ import routes.inference as inference_route++ class _LlamaOff:+ is_loaded = Falsesupports_tools = False+ is_vision = False+ context_length = None- backend = _GGUFBackend()- assert _takes_tool_passthrough(self._make(response_format = {"type": "json_object"}), backend)- # The field takes any object, and anything but the exact default -- an- # unknown type, or a text format carrying members this build does not know- # -- is a contract, so it keeps going where one can be answered or rejected.- assert _takes_tool_passthrough(self._make(response_format = {"type": "later"}), backend)- assert _takes_tool_passthrough(- self._make(response_format = {"type": "text", "strict": True}), backend- )- assert not _takes_tool_passthrough(self._make(response_format = {"type": "text"}), backend)+ calls = []- @pytest.mark.parametrize("enabled_tools", [None, []])- def test_the_gguf_tool_loop_refuses_a_contract_it_cannot_forward(- self, monkeypatch, enabled_tools- ):- """Unsloth's loop runs its own turns and never forwards response_format, so- serving the request would answer with text that violates the contract while- the client has no way to tell. A selection that resolves to no tool routes to- the ordinary generator, which forwards it no more than the loop does, and the- refusal lands after the monitor row opens, so it must close it."""- import routes.inference as inference_route+ class _OmniBackend:+ active_model_name = "omni-sf"+ models = {+ "omni-sf": {+ "is_vision": True,+ "has_audio_input": True,+ "chat_template_info": {"template": "chatml"},+ "context_length": 4096,+ }+ }- class _GGUFBackend:- is_loaded = True- model_identifier = "test-gguf"- supports_tools = True- is_vision = False- _is_audio = False- context_length = 4096+ def resize_image(self, image):+ return image++ def generate_audio_input_response(self, **kwargs):+ calls.append(kwargs)+ yield "answered from the audio"++ def reset_generation_state(self, cancel_event = None):+ passmonitor = ApiMonitor(max_entries = 3)monkeypatch.setattr(inference_route, "api_monitor", monitor)- client = self._v1_client(monkeypatch, _GGUFBackend())- body = {- "messages": [{"role": "user", "content": "hi"}],- "enable_tools": True,- "response_format": {"type": "json_object"},+ monkeypatch.setattr(+ inference_route,+ "_detect_safetensors_features",+ lambda *a, **k: {"supports_tools": False},+ )+ monkeypatch.setattr(+ inference_route,+ "_decode_audio_base64",+ lambda *a, **k: np.zeros(16000, dtype = "float32"),+ )+ client = self._v1_client(monkeypatch, _LlamaOff(), _OmniBackend())+ generated = {+ "type": "image_url",+ "image_url": {"url": f"data:image/png;base64,{_BLUE_PNG_B64}"},}- if enabled_tools is not None:- body["enabled_tools"] = enabled_tools- resp = client.post("/v1/chat/completions", json = body)- self._assert_unsupported_param(resp, "response_format")++ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {"role": "user", "content": "draw one"},+ {"role": "assistant", "content": [generated]},+ {"role": "user", "content": "describe it"},+ ],+ "image_base64": _BLUE_PNG_B64,+ "audio_base64": base64.b64encode(b"RIFF....WAVEfmt ").decode(),+ },+ )++ assert resp.status_code == 400+ assert "audio or an image in one message" in resp.text+ assert calls == []assert monitor.active_count() == 0- def test_client_tools_rejected_when_gguf_template_has_no_tool_support(self, monkeypatch):+ def test_an_image_on_an_earlier_turn_still_allows_a_voice_follow_up(self, monkeypatch):+ """The count is scoped to the newest user turn, so asking by voice about a+ picture attached on an earlier turn keeps working."""+ import numpy as np+import routes.inference as inference_route- class _GGUFBackend:- is_loaded = True- model_identifier = "test-gguf"+ class _LlamaOff:+ is_loaded = Falsesupports_tools = Falseis_vision = False- _is_audio = False- context_length = 4096+ context_length = None- def generate_chat_completion(self, **_kwargs):- raise AssertionError("client tools must not fall through to the standard GGUF path")+ calls = []++ class _OmniBackend:+ active_model_name = "omni-sf"+ models = {+ "omni-sf": {+ "is_vision": True,+ "has_audio_input": True,+ "chat_template_info": {"template": "chatml"},+ "context_length": 4096,+ }+ }++ def resize_image(self, image):+ return image++ def generate_audio_input_response(self, **kwargs):+ calls.append(kwargs)+ yield "answered from the audio"++ def reset_generation_state(self, cancel_event = None):+ passmonitor = ApiMonitor(max_entries = 3)monkeypatch.setattr(inference_route, "api_monitor", monitor)- client = self._v1_client(monkeypatch, _GGUFBackend())+ monkeypatch.setattr(+ inference_route,+ "_detect_safetensors_features",+ lambda *a, **k: {"supports_tools": False},+ )+ monkeypatch.setattr(+ inference_route,+ "_decode_audio_base64",+ lambda *a, **k: np.zeros(16000, dtype = "float32"),+ )+ client = self._v1_client(monkeypatch, _LlamaOff(), _OmniBackend())+ image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}+resp = client.post("/v1/chat/completions",json = {- "messages": [{"role": "user", "content": "hi"}],- "tools": [+ "messages": [{- "type": "function",- "function": {- "name": "lookup",- "parameters": {"type": "object"},- },- }+ "role": "user",+ "content": [{"type": "text", "text": "what is this?"}, image],+ },+ {"role": "assistant", "content": "a square"},+ {"role": "user", "content": "and now by voice"},],+ "audio_base64": base64.b64encode(b"RIFF....WAVEfmt ").decode(),},)- self._assert_unsupported_param(resp, "tools")- assert "does not advertise tools" in resp.json()["error"]["message"]+ assert resp.status_code == 200+ assert len(calls) == 1+ assert monitor.active_count() == 0++ def test_a_failed_image_decode_closes_the_monitor_row(self, monkeypatch):+ """A single image whose payload is not an image fails inside the decode,+ after the row opens. That rejection must finalize the row too."""+ monitor = ApiMonitor(max_entries = 3)+ client, backend = self._standard_vision_client(monkeypatch, monitor)+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "what is this?"},+ {+ "type": "image_url",+ "image_url": {"url": "data:image/png;base64,AAAA"},+ },+ ],+ }+ ]+ },+ )++ assert resp.status_code == 400+ assert "Failed to decode image" in resp.text+ assert backend.generated == [][entry] = monitor.snapshot()assert entry["status"] == "error"- assert "does not advertise tools" in entry["error"]+ assert "Failed to decode image" in entry["error"]assert monitor.active_count() == 0def test_client_tools_use_passthrough_capability_when_tool_loop_is_disabled(self, monkeypatch):@@ -1858,6 +2846,64 @@ class TestOpenAICompatibilityHelpers:assert chat_messages == [{"role": "user", "content": "hi"}]assert image_b64 is None+ def _turn(self, images: int):+ content = [{"type": "text", "text": "what is this?"}]+ for _ in range(images):+ content.append(+ {+ "type": "image_url",+ "image_url": {"url": "data:image/png;base64,AAAA"},+ }+ )+ return {"role": "user", "content": content}++ def test_two_images_on_one_turn_are_counted(self):+ payload = ChatCompletionRequest(messages = [self._turn(2)])+ assert _images_in_last_user_message(payload.messages) == 2++ def test_one_image_per_turn_is_not_a_multi_image_call(self):+ payload = ChatCompletionRequest(+ messages = [+ self._turn(1),+ {"role": "assistant", "content": "the first one"},+ self._turn(1),+ ]+ )+ assert _images_in_last_user_message(payload.messages) == 1++ def test_earlier_multi_image_turn_does_not_block_a_later_one(self):+ payload = ChatCompletionRequest(+ messages = [+ self._turn(2),+ {"role": "assistant", "content": "ok"},+ {"role": "user", "content": "and now just text"},+ ]+ )+ assert _images_in_last_user_message(payload.messages) == 0++ def test_undecodable_image_urls_still_count(self):+ """Structural count, not a decoded one: remote and empty data URLs are+ image parts the caller attached, whether or not extraction can read them."""+ payload = ChatCompletionRequest(+ messages = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "compare these"},+ {"type": "image_url", "image_url": {"url": "https://example.com/a.png"}},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,"}},+ ],+ }+ ]+ )+ assert _images_in_last_user_message(payload.messages) == 2++ def test_a_trailing_assistant_turn_does_not_change_which_turn_is_counted(self):+ payload = ChatCompletionRequest(+ messages = [self._turn(2), {"role": "assistant", "content": "partial"}]+ )+ assert _images_in_last_user_message(payload.messages) == 2+def test_latest_image_wins_over_earlier_turns(self):def turn(letter):return {