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 earlier messages in chats with images (#10944)

Nilay63a147aac341
diff --git a/studio/backend/core/inference/chat_template_helpers.py b/studio/backend/core/inference/chat_template_helpers.py
index f373eb9e963..035ab421fe1 100644
--- a/studio/backend/core/inference/chat_template_helpers.py
+++ b/studio/backend/core/inference/chat_template_helpers.py
@@ -2982,7 +2982,7 @@ def messages_with_attached_image(
for m in conversation
)
]
- if not parts:
+ if not parts and not fallback_user_text:
return conversation
for index in range(len(conversation) - 1, -1, -1):
message = conversation[index]
@@ -2993,9 +2993,11 @@ def messages_with_attached_image(
content = [{"type": "text", "text": content or fallback_user_text}]
elif not isinstance(content, list):
break
+ elif fallback_user_text and not last_user_text([message]):
+ content = [*content, {"type": "text", "text": fallback_user_text}]
conversation[index] = {**message, "content": parts + list(content)}
return conversation
- if fallback_user_text:
+ if parts and fallback_user_text:
conversation.append(
{"role": "user", "content": parts + [{"type": "text", "text": fallback_user_text}]}
)
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.py
index 7f566dc3b66..6ae5f896893 100644
--- a/studio/backend/core/inference/inference.py
+++ b/studio/backend/core/inference/inference.py
@@ -1511,23 +1511,21 @@ class InferenceBackend:
user_message = "Describe this image." if image else "Hello"
if image:
- # 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
)
+ # 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,
+ )
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,
- )
-
# The conversation the LAST render used, not the no-tools probe's (#10092).
rendered_with: dict = {"messages": vision_messages}
@@ -1594,50 +1592,21 @@ class InferenceBackend:
self.active_model_name,
)
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:
- 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.
+ # Processor's own template skips the choke point (#7066).
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):
+ def _render_plain_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)
+ input_text = _render_plain_vision(vision_messages)
except Exception as e:
# Safe here: no catalog and no tool history to hide a failure behind.
if system_prompt:
@@ -1646,7 +1615,7 @@ class InferenceBackend:
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)
+ input_text = _render_plain_vision(vision_messages)
else:
raise
inputs = processor(
diff --git a/studio/backend/tests/test_vision_client_tools.py b/studio/backend/tests/test_vision_client_tools.py
index 976dfb2f4cf..dd3a1816b8d 100644
--- a/studio/backend/tests/test_vision_client_tools.py
+++ b/studio/backend/tests/test_vision_client_tools.py
@@ -978,6 +978,123 @@ def test_a_historical_image_stays_on_the_turn_that_sent_it_without_tools():
assert later["content"] == "LATER_QUESTION unrelated to it"
+def test_an_image_turn_without_tools_keeps_the_earlier_turns():
+ backend, seen = _vision_probe()
+ _drain(
+ backend,
+ messages = [
+ {"role": "user", "content": "EARLIER"},
+ {"role": "assistant", "content": "ANSWER_ONE"},
+ {"role": "user", "content": "LATER"},
+ ],
+ )
+ rendered = json.dumps(seen["messages"])
+ assert "EARLIER" in rendered
+ assert "ANSWER_ONE" in rendered
+ assert [m["role"] for m in seen["messages"]] == ["user", "assistant", "user"]
+ assert [p["type"] for p in seen["messages"][-1]["content"]] == ["image", "text"]
+
+
+def test_an_image_turn_without_tools_leaves_the_image_on_the_turn_that_sent_it():
+ backend, seen = _vision_probe()
+ _drain(
+ backend,
+ system_prompt = "SYSTEM_RULE",
+ messages = [
+ {"role": "user", "content": "EARLIER"},
+ {"role": "assistant", "content": "ANSWER_ONE"},
+ {
+ "role": "user",
+ "content": [{"type": "image"}, {"type": "text", "text": "IMAGE_QUESTION"}],
+ },
+ {"role": "assistant", "content": "ANSWER_TWO"},
+ {"role": "user", "content": "LATER"},
+ ],
+ )
+ sent = seen["messages"]
+ assert [m["role"] for m in sent] == [
+ "system",
+ "user",
+ "assistant",
+ "user",
+ "assistant",
+ "user",
+ ]
+ assert [[p["type"] for p in m["content"]] for m in sent] == [
+ ["text"],
+ ["text"],
+ ["text"],
+ ["image", "text"],
+ ["text"],
+ ["text"],
+ ]
+
+
+def test_an_image_only_turn_still_asks_about_the_image():
+ backend, seen = _vision_probe()
+ _drain(
+ backend,
+ messages = [
+ {"role": "user", "content": "EARLIER"},
+ {"role": "assistant", "content": "ANSWER_ONE"},
+ {"role": "user", "content": [{"type": "image"}, {"type": "text", "text": ""}]},
+ ],
+ )
+ assert seen["messages"][0]["content"] == [{"type": "text", "text": "EARLIER"}]
+ assert seen["messages"][-1]["content"][-1] == {"type": "text", "text": "Describe this image."}
+
+
+def test_an_image_continuation_resumes_the_replayed_partial_after_the_no_system_retry():
+ backend, _ = _vision_probe()
+ renders = []
+
+ def apply_chat_template(messages, **kwargs):
+ renders.append((messages, kwargs))
+ if any(m["role"] == "system" for m in messages):
+ raise ValueError("system role not supported")
+ return "PROMPT"
+
+ backend.models["vision-tools"]["processor"].apply_chat_template = apply_chat_template
+ _drain(
+ backend,
+ system_prompt = "SYSTEM_RULE",
+ continue_final_message = True,
+ messages = [
+ {"role": "user", "content": "EARLIER"},
+ {"role": "assistant", "content": "ANSWER_ONE"},
+ {"role": "user", "content": "LATER"},
+ {"role": "assistant", "content": "PARTIAL_ANSWER"},
+ ],
+ )
+ assert len(renders) == 2
+ assert renders[0][0][0]["role"] == "system"
+ messages, kwargs = renders[1]
+ assert [m["role"] for m in messages] == ["user", "assistant", "user", "assistant"]
+ assert messages[-1]["content"] == [{"type": "text", "text": "PARTIAL_ANSWER"}]
+ assert [p["type"] for p in messages[-2]["content"]] == ["image", "text"]
+ assert kwargs["continue_final_message"] is True
+
+
+ "content, structured, expected",
+ [
+ ("", False, [{"type": "image"}, {"type": "text", "text": ""}]),
+ ("", True, [{"type": "image"}]),
+ (
+ [{"type": "image_url", "image_url": {"url": "x"}}],
+ True,
+ [{"type": "image_url", "image_url": {"url": "x"}}],
+ ),
+ ],
+)
+def test_an_image_only_turn_without_a_fallback_is_unchanged(content, structured, expected):
+ from core.inference.chat_template_helpers import messages_with_attached_image
+ out = messages_with_attached_image(
+ [{"role": "user", "content": content}], structured_content = structured
+ )
+ assert out == [{"role": "user", "content": expected}]
+
+
def test_no_image_marker_on_the_plain_route_when_renders_image_is_false():
"""``renders_image`` is the whole gate, and it is read with ``.get``, so a model whose
capability probe never reported one leaves the thread as strings.