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 mid-conversation Anthropic system messages in place so new sessions reuse the prompt cache (#13727)

Daniel Han8611f1846cbe
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 7f9c4032152..178850992de 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -4108,6 +4108,41 @@ def _merge_anthropic_system(system: Any, additions: list[str]) -> Any:
return system
+def _block_type(block: Any) -> Any:
+ return block.get("type") if isinstance(block, dict) else getattr(block, "type", None)
+
+
+def _system_note(text: str) -> str:
+ if text.lstrip().startswith("<system-reminder>"):
+ return text
+ return f"<system-reminder>\n{text}\n</system-reminder>"
+
+
+def _as_blocks(content: Any) -> Optional[list]:
+ if isinstance(content, str):
+ return [{"type": "text", "text": content}] if content else []
+ return list(content) if isinstance(content, list) else None
+
+
+def _with_user_note(message: dict, note: str, *, first: bool) -> Optional[dict]:
+ """Copy of a user turn with a text block added; None for malformed content, left for validation to reject."""
+ blocks = _as_blocks(message.get("content"))
+ if blocks is None:
+ return None
+ block = {"type": "text", "text": note}
+ if blocks and all(_block_type(b) == "tool_result" for b in blocks):
+ # As a text block it would start a new user query (templates drop the reasoning before it); MCP image envelopes stay last.
+ index = 0 if first else len(blocks) - 1
+ result = blocks[index] if isinstance(blocks[index], dict) else blocks[index].model_dump()
+ inner = result.get("content")
+ inner = [] if inner is None else _as_blocks(inner)
+ if inner is None:
+ return None
+ blocks[index] = {**result, "content": [block, *inner]}
+ return {**message, "content": blocks}
+ return {**message, "content": [block, *blocks] if first else [*blocks, block]}
+
+
_CLAUDE_STYLE_REMINDER_SUFFIX = (
" output style is active. Remember to follow the specific guidelines for this style."
)
@@ -4310,21 +4345,45 @@ class AnthropicMessagesRequest(BaseModel):
normalized_messages: list[Any] = []
system_additions: list[str] = []
retained_system = [_anthropic_content_to_system_text(data.get("system"))]
+ pending: list[str] = []
changed = False
for message in messages:
if isinstance(message, dict) and message.get("role") == "system":
text = _anthropic_content_to_system_text(message.get("content", ""))
- if not _is_repeated_claude_style_reminder(text, retained_system):
- system_additions.append(text)
- retained_system.append(text)
changed = True
+ if _is_repeated_claude_style_reminder(text, retained_system):
+ continue
+ retained_system.append(text)
+ previous = normalized_messages[-1] if normalized_messages else None
+ if previous is None or not text.strip():
+ system_additions.append(text)
+ elif isinstance(previous, dict) and previous.get("role") == "user":
+ # Hoisted, it renders above the tools: claude's per-session env message broke every new session's cache.
+ folded = _with_user_note(previous, _system_note(text), first = False)
+ if folded is None:
+ system_additions.append(text)
+ else:
+ normalized_messages[-1] = folded
+ else:
+ pending.append(text)
continue
+ if pending and isinstance(message, dict) and message.get("role") == "user":
+ note = "\n".join(_system_note(text) for text in pending)
+ folded = _with_user_note(message, note, first = True)
+ if folded is None:
+ system_additions.extend(pending)
+ else:
+ message = folded
+ pending = []
normalized_messages.append(message)
if not changed:
return data
+ # A trailing assistant turn is a prefill; a user turn after it would replace it.
+ system_additions.extend(pending)
+
normalized = dict(data)
normalized["messages"] = normalized_messages
normalized["system"] = _merge_anthropic_system(normalized.get("system"), system_additions)
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index 01554635e48..d5f47cf9f08 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -724,7 +724,7 @@ class TestAnthropicModels:
assert len(req.messages) == 1
assert req.messages[0].role == "user"
- def test_system_role_message_merges_with_existing_system_field(self):
+ def test_later_system_role_message_stays_in_the_user_turn_it_follows(self):
req = AnthropicMessagesRequest(
max_tokens = 50,
system = "Base instructions.",
@@ -734,8 +734,163 @@ class TestAnthropicModels:
{"role": "assistant", "content": "Hello."},
],
)
+ assert req.system == "Base instructions."
+ assert [msg.role for msg in req.messages] == ["user", "assistant"]
+ assert [block.text for block in req.messages[0].content] == [
+ "Hi",
+ "<system-reminder>\nAdditional instructions.\n</system-reminder>",
+ ]
+
+ def test_leading_system_role_message_still_joins_the_system_field(self):
+ req = AnthropicMessagesRequest(
+ max_tokens = 50,
+ system = "Base instructions.",
+ messages = [
+ {"role": "system", "content": "Additional instructions."},
+ {"role": "user", "content": "Hi"},
+ ],
+ )
assert req.system == "Base instructions.\n\nAdditional instructions."
+ assert req.messages[0].content == "Hi"
+
+ def test_system_role_message_after_an_assistant_turn_opens_the_next_user_turn(self):
+ req = AnthropicMessagesRequest(
+ max_tokens = 50,
+ messages = [
+ {"role": "user", "content": "Hi"},
+ {"role": "assistant", "content": "Hello."},
+ {"role": "system", "content": "Note."},
+ {"role": "user", "content": [{"type": "text", "text": "Next."}]},
+ ],
+ )
+ assert [msg.role for msg in req.messages] == ["user", "assistant", "user"]
+ assert [block.text for block in req.messages[2].content] == [
+ "<system-reminder>\nNote.\n</system-reminder>",
+ "Next.",
+ ]
+
+ def test_system_role_message_after_a_trailing_prefill_keeps_the_prefill_last(self):
+ req = AnthropicMessagesRequest(
+ max_tokens = 50,
+ messages = [
+ {"role": "user", "content": "Hi"},
+ {"role": "assistant", "content": "Hello."},
+ {"role": "system", "content": "Note."},
+ ],
+ )
assert [msg.role for msg in req.messages] == ["user", "assistant"]
+ assert req.system == "Note."
+
+ @pytest.mark.parametrize(
+ "messages",
+ [
+ [{"role": "user", "content": 5}, {"role": "system", "content": "env"}],
+ [{"role": "user", "content": None}, {"role": "system", "content": "env"}],
+ [
+ {"role": "user", "content": "Hi"},
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "t", "name": "R", "input": {}}],
+ },
+ {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": "t", "content": {"a": 1}}],
+ },
+ {"role": "system", "content": "env"},
+ ],
+ ],
+ )
+ def test_malformed_turns_are_still_rejected_with_a_system_message_after_them(self, messages):
+ from pydantic import ValidationError
+ with pytest.raises(ValidationError):
+ AnthropicMessagesRequest(max_tokens = 50, messages = messages)
+
+ def test_claude_environment_message_leaves_system_and_tools_identical_across_sessions(self):
+ def converted(cwd):
+ req = AnthropicMessagesRequest(
+ max_tokens = 50,
+ system = "Static instructions.",
+ tools = [{"name": "Read", "input_schema": {"type": "object"}}],
+ messages = [
+ {"role": "user", "content": "Fix the bug."},
+ {
+ "role": "system",
+ "content": f"# Environment\n - Primary working directory: {cwd}",
+ },
+ ],
+ ).model_dump()
+ return anthropic_messages_to_openai(req["messages"], req["system"]), req["tools"]
+
+ first, first_tools = converted("/work/a")
+ second, second_tools = converted("/work/b")
+ assert first[0] == second[0] == {"role": "system", "content": "Static instructions."}
+ assert first_tools == second_tools
+ assert first[1]["content"].startswith("Fix the bug.\n<system-reminder>\n# Environment")
+ assert "/work/a" in first[1]["content"] and "/work/b" in second[1]["content"]
+
+ def test_per_round_system_reminders_only_append(self):
+ base = [
+ {"role": "user", "content": "Read it."},
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "r1", "name": "Read", "input": {}}],
+ },
+ {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": "r1", "content": "data"}],
+ },
+ {"role": "system", "content": "<total_tokens>900 tokens left</total_tokens>"},
+ ]
+ later = [
+ *base,
+ {
+ "role": "assistant",
+ "content": [{"type": "tool_use", "id": "r2", "name": "Read", "input": {}}],
+ },
+ {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": "r2", "content": "more"}],
+ },
+ {"role": "system", "content": "<total_tokens>800 tokens left</total_tokens>"},
+ ]
+
+ def converted(messages):
+ req = AnthropicMessagesRequest(
+ max_tokens = 50, system = "Base.", messages = messages
+ ).model_dump()
+ return anthropic_messages_to_openai(req["messages"], req["system"])
+
+ before, after = converted(base), converted(later)
+ assert after[: len(before)] == before
+ assert after[0] == {"role": "system", "content": "Base."}
+ assert after[-1]["role"] == "tool"
+ assert "800 tokens left" in after[-1]["content"]
+
+ def test_a_reminder_after_a_tool_result_keeps_the_turn_and_its_thinking(self):
+ req = AnthropicMessagesRequest(
+ max_tokens = 50,
+ messages = [
+ {"role": "user", "content": "Read it."},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "thinking": "I should read it.", "signature": "s"},
+ {"type": "tool_use", "id": "r1", "name": "Read", "input": {}},
+ ],
+ },
+ {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": "r1", "content": "data"}],
+ },
+ {"role": "system", "content": "<total_tokens>900 tokens left</total_tokens>"},
+ ],
+ ).model_dump()
+ result = anthropic_messages_to_openai(req["messages"], req.get("system"))
+ assert [m["role"] for m in result] == ["user", "assistant", "tool"]
+ assert result[1].get("reasoning_content") == "I should read it."
+ assert result[2]["content"] == (
+ "<system-reminder>\n<total_tokens>900 tokens left</total_tokens>\n</system-reminder>\ndata"
+ )
def test_system_role_message_with_null_content_ignored(self):
req = AnthropicMessagesRequest(
diff --git a/studio/backend/tests/test_claude_style_reminder_cache.py b/studio/backend/tests/test_claude_style_reminder_cache.py
index 9eca73de15e..059ac2fda54 100644
--- a/studio/backend/tests/test_claude_style_reminder_cache.py
+++ b/studio/backend/tests/test_claude_style_reminder_cache.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-"""Claude's later system reminders must not invalidate a stable style prefix."""
+"""Claude's later system messages must not invalidate a stable system prefix."""
import copy
import os
@@ -21,6 +21,10 @@ REMINDER = (
STYLE = f"# Output Style: Concise\nUse short answers.\n\n{REMINDER}\n\nToday's date is fixed."
+def note(text):
+ return f"<system-reminder>\n{text}\n</system-reminder>"
+
+
def converted(payload):
request = AnthropicMessagesRequest.model_validate(payload).model_dump()
return anthropic_messages_to_openai(request["messages"], request["system"])
@@ -91,7 +95,8 @@ def test_nonredundant_system_instructions_are_preserved(initial, addition):
],
}
)
- assert result[0]["content"] == initial + "\n\n" + addition
+ assert result[0]["content"] == initial
+ assert result[1] == {"role": "user", "content": f"Hello\n{note(addition)}"}
@pytest.mark.parametrize("role", ["user", "assistant"])
@@ -105,8 +110,12 @@ def test_conversation_text_cannot_suppress_a_system_instruction(role):
],
}
)
- assert result[0]["content"] == "Base instructions.\n\n" + REMINDER
- assert result[1] == {"role": role, "content": STYLE}
+ if role == "user":
+ assert result[0]["content"] == "Base instructions."
+ assert result[1] == {"role": "user", "content": f"{STYLE}\n{note(REMINDER)}"}
+ else:
+ assert result[0]["content"] == "Base instructions.\n\n" + REMINDER
+ assert result[1:] == [{"role": "assistant", "content": STYLE}]
def test_changed_style_definition_is_preserved():
@@ -121,4 +130,5 @@ def test_changed_style_definition_is_preserved():
],
}
)
- assert result[0]["content"] == STYLE + "\n\n" + updated
+ assert result[0]["content"] == STYLE
+ assert result[1] == {"role": "user", "content": f"Hello\n{note(updated)}"}