From 636e48ce9301525526c40e799e1e10e997cde722 Mon Sep 17 00:00:00 2001 From: Mikei386 <44135113+Mikei386@users.noreply.github.com> Date: Tue, 8 Sep 2026 08:37:53 +0200 Subject: [PATCH] Merge restoration policy into system message --- dev/test_router_support.py | 15 +++++++++++++++ router/ai_profile_router.py | 13 ++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/dev/test_router_support.py b/dev/test_router_support.py index 872b54e..f5691fd 100644 --- a/dev/test_router_support.py +++ b/dev/test_router_support.py @@ -294,6 +294,21 @@ class RestorationSystemPolicyTests(unittest.TestCase): self.assertIn("Photo-restoration mode", normalized["instructions"]) self.assertTrue(normalized["instructions"].endswith("Client policy.")) + def test_chat_policy_merges_with_existing_leading_system_message(self) -> None: + request = {"messages": [ + {"role": "system", "content": "Global policy."}, + {"role": "user", "content": "Mach schöner"}, + ]} + normalized = _inject_restoration_system_policy( + request, "/v1/chat/completions") + system_messages = [ + message for message in normalized["messages"] + if message.get("role") == "system" + ] + self.assertEqual(len(system_messages), 1) + self.assertIn("Photo-restoration mode", system_messages[0]["content"]) + self.assertTrue(system_messages[0]["content"].endswith("Global policy.")) + class RetentionTests(unittest.TestCase): def test_oldest_pairs_are_removed(self) -> None: diff --git a/router/ai_profile_router.py b/router/ai_profile_router.py index 095b8e1..ffd0edf 100755 --- a/router/ai_profile_router.py +++ b/router/ai_profile_router.py @@ -1396,7 +1396,18 @@ def _inject_restoration_system_policy(data: dict, path: str) -> dict: if path == "/v1/chat/completions": messages = data.get("messages") if isinstance(messages, list): - messages.insert(0, {"role": "system", "content": policy}) + # Qwen's chat template permits exactly one system message and it + # must be the first message. The global router policy may already + # have created that message, so extend it instead of inserting a + # second system message in front of it. + if (messages and isinstance(messages[0], dict) + and messages[0].get("role") == "system" + and isinstance(messages[0].get("content"), str)): + existing = messages[0]["content"] + if policy not in existing: + messages[0]["content"] = f"{policy}\n\n{existing}" + else: + messages.insert(0, {"role": "system", "content": policy}) elif path == "/v1/responses": instructions = data.get("instructions") data["instructions"] = (