Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Escape reserved image markers from Qwen prompts
JoaoFaycd83f885e66e
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex 51fedb9..8ea72fe 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -285,21 +285,65 @@ def extract_images(messages: list[dict[str, Any]]) -> list[str]:content = m.get("content")if isinstance(content, list):for part in content:- if isinstance(part, dict) and (part.get("type") in ("image_url", "image") or "image_url" in part):+ if _is_image_part(part):iu = part.get("image_url", part.get("image"))urls.append(iu.get("url") if isinstance(iu, dict) else iu)return urls+def _escape_image_pad(text: str) -> str:+ """Keep a textual mention from being interpreted as an image placeholder by validation."""+ return text.replace(IMAGE_PAD, IMAGE_PAD[:1] + "\\" + IMAGE_PAD[1:])+++def _escape_render_text(value: Any) -> Any:+ """Escape marker-like text in arbitrary values supplied to the chat template."""+ if isinstance(value, str):+ return _escape_image_pad(value)+ if isinstance(value, list):+ return [_escape_render_text(item) for item in value]+ if isinstance(value, tuple):+ return tuple(_escape_render_text(item) for item in value)+ if isinstance(value, dict):+ escaped = {}+ for key, item in value.items():+ escaped_key = _escape_render_text(key) if isinstance(key, str) else key+ if escaped_key in escaped:+ raise BadRequest("sanitization collision between dictionary keys")+ escaped[escaped_key] = _escape_render_text(item)+ return escaped+ return value+++def _is_image_part(part: Any) -> bool:+ """Match the image-part shape accepted by extract_images."""+ return (+ isinstance(part, dict)+ and (part.get("type") in ("image_url", "image") or "image_url" in part or "image" in part)+ )+++def _sanitize_message_content(content: Any) -> Any:+ """Escape text content, preserving only image parts in the content list."""+ if isinstance(content, str):+ return _escape_image_pad(content)+ if isinstance(content, list):+ return [part if _is_image_part(part) else _escape_render_text(part) for part in content]+ return _escape_render_text(content)++def normalize_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:out = []for m in messages:if not isinstance(m, dict) or "role" not in m:raise BadRequest("each message needs a role")- if m.get("content") is None:- m = dict(m, content="")+ content = _sanitize_message_content(m.get("content"))+ m = {key: _escape_render_text(value) for key, value in m.items() if key != "content"}+ if content is None:+ content = ""+ m["content"] = contentif m["role"] == "developer": # OpenAI's newer name for the system role- m = dict(m, role="system")+ m["role"] = "system"out.append(m)return out@@ -1335,7 +1379,8 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anmessages = normalize_messages(body["messages"])kwargs = resolve_template_kwargs(body, defaults)try:- prompt = render_prompt(template, messages, body.get("tools"), **kwargs)+ prompt = render_prompt(template, messages, _escape_render_text(body.get("tools")),+ **_escape_render_text(kwargs))except (ValueError, TypeError, KeyError, AttributeError, jinja2.TemplateError) as exc:raise BadRequest(f"chat template: {exc}") from excimages = extract_images(messages)@@ -1528,8 +1573,9 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anbody = await request.json()if not isinstance(body, dict) or not isinstance(body.get("messages"), list) or not body["messages"]:raise BadRequest("messages must be a non-empty array")- prompt = render_prompt(template, normalize_messages(body["messages"]), body.get("tools"),- **resolve_template_kwargs(body, defaults))+ prompt = render_prompt(template, normalize_messages(body["messages"]),+ _escape_render_text(body.get("tools")),+ **_escape_render_text(resolve_template_kwargs(body, defaults)))except json.JSONDecodeError as exc:return err(400, f"invalid JSON: {exc}")except (BadRequest, ValueError, TypeError, KeyError, AttributeError, jinja2.TemplateError) as exc:@@ -1554,8 +1600,9 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anraise BadRequest("messages must be a non-empty array")if extract_images(body["messages"]):raise BadRequest("images cannot be tokenized here")- text = render_prompt(template, normalize_messages(body["messages"]), body.get("tools"),- **resolve_template_kwargs(body, defaults))+ text = render_prompt(template, normalize_messages(body["messages"]),+ _escape_render_text(body.get("tools")),+ **_escape_render_text(resolve_template_kwargs(body, defaults)))add_special = bool(add_special) # a rendered chat prompt carries its own special tokenselse:text = body.get("prompt")diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.pyindex 54968fa..2ddf1ec 100644--- a/tools/qwen/test_serve.py+++ b/tools/qwen/test_serve.py@@ -204,11 +204,11 @@ class RoleTests(unittest.TestCase):class HttpTests(unittest.TestCase):- def chat(self, engine, payload, stream=False):+ def chat(self, engine, payload, stream=False, template=THINK_TEMPLATE):async def fn(client):r = await client.post("/v1/chat/completions", json={"stream": stream, "model": "m"} | payload)return r.status, (await r.text() if stream else await r.json())- return with_client(engine, fn)+ return with_client(engine, fn, template=template)def test_models_and_health(self):async def fn(client):@@ -340,8 +340,116 @@ class HttpTests(unittest.TestCase):st, body = self.chat(eng, {"messages": msgs})self.assertIn("vision", body["error"]["message"])+ def test_tool_text_matching_image_placeholder_is_not_an_image(self):+ eng = FakeEngine("x")+ marker = serve.IMAGE_PAD+ st, body = self.chat(eng, {"messages": [{"role": "tool", "content": "tool output: " + marker}]})+ self.assertEqual(st, 200, body)+ self.assertEqual(len(eng.calls), 1)+ self.assertEqual(eng.calls[0][1]["images"], [])++ def test_tool_call_argument_image_url_key_is_escaped(self):+ marker = serve.IMAGE_PAD+ tpl = THINK_TEMPLATE.replace("{{ m.content }}", "{{ m.tool_calls[0].function.arguments.image_url }}")+ eng = FakeEngine("x")+ messages = [{"role": "assistant", "content": "", "tool_calls": [{+ "id": "call_1", "type": "function", "function": {+ "name": "f", "arguments": {"image_url": marker}}}]}]+ st, body = self.chat(eng, {"messages": messages}, template=tpl)+ self.assertEqual(st, 200, body)+ self.assertEqual(eng.calls[0][1]["images"], [])+ self.assertNotIn(marker, eng.calls[0][0])++ def test_input_text_part_matching_image_placeholder_is_not_an_image(self):+ marker = serve.IMAGE_PAD+ eng = FakeEngine("x")+ st, body = self.chat(eng, {"messages": [{"role": "user", "content": [+ {"type": "input_text", "text": marker}]}]}, template=THINK_TEMPLATE.replace(+ "{{ m.content }}", "{{ m.content[0].text }}"))+ self.assertEqual(st, 200, body)+ self.assertEqual(eng.calls[0][1]["images"], [])++ def test_tool_schema_property_key_matching_image_placeholder_is_not_an_image(self):+ marker = serve.IMAGE_PAD+ tpl = THINK_TEMPLATE.replace("TOOLS={{ tools|length }}", "TOOLS={{ tools|tojson }}")+ eng = FakeEngine("x")+ tools = [{"type": "function", "function": {"name": "f", "parameters": {+ "type": "object", "properties": {marker: {"type": "string"}}}}}]+ original_tools = json.loads(json.dumps(tools))+ st, body = self.chat(eng, {"messages": [{"role": "user", "content": "hi"}], "tools": tools},+ template=tpl)+ self.assertEqual(st, 200, body)+ self.assertEqual(eng.calls[0][1]["images"], [])+ self.assertIn(marker, tools[0]["function"]["parameters"]["properties"])+ self.assertEqual(tools, original_tools)++ def test_tool_schema_description_matching_image_placeholder_is_not_an_image(self):+ marker = serve.IMAGE_PAD+ tpl = THINK_TEMPLATE.replace("TOOLS={{ tools|length }}", "TOOLS={{ tools[0].function.description }}")+ eng = FakeEngine("x")+ tools = [{"type": "function", "function": {"name": "f", "description": marker,+ "parameters": {"type": "object", "properties": {}}}}]+ st, body = self.chat(eng, {"messages": [{"role": "user", "content": "hi"}], "tools": tools},+ template=tpl)+ self.assertEqual(st, 200, body)+ self.assertEqual(eng.calls[0][1]["images"], [])++ def test_reasoning_matching_image_placeholder_is_not_an_image(self):+ marker = serve.IMAGE_PAD+ tpl = THINK_TEMPLATE.replace("{{ m.content }}", "{{ m.reasoning_content }}")+ eng = FakeEngine("x")+ messages = [{"role": "assistant", "content": "", "reasoning_content": marker}]+ st, body = self.chat(eng, {"messages": messages}, template=tpl)+ self.assertEqual(st, 200, body)+ self.assertEqual(eng.calls[0][1]["images"], [])++ def test_image_part_count_ignores_placeholder_in_tool_text(self):+ marker = serve.IMAGE_PAD+ tpl = THINK_TEMPLATE.replace("{{ m.content }}", "{{ m.content if m.content is string else '" + marker + "' }}")+ eng = FakeEngine("x")++ async def fn(client):+ msgs = [{"role": "tool", "content": marker},+ {"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:image"}},+ {"type": "input_text", "text": "note: " + marker}]}]+ r = await client.post("/v1/chat/completions", json={"model": "m", "messages": msgs})+ return r.status++ self.assertEqual(with_client(eng, fn, template=tpl), 200)+ self.assertEqual(eng.calls[0][1]["images"], ["data:image"])++ def test_image_field_only_parts_are_counted_and_passed_in_order(self):+ marker = serve.IMAGE_PAD+ tpl = THINK_TEMPLATE.replace("{{ m.content }}", "{{ m.content if m.content is string else '" + marker * 2 + "' }}")+ eng = FakeEngine("ok")+ image_urls = ["https://example.test/first.png", "data:second"]+ messages = [{"role": "user", "content": [+ {"image": image_urls[0]},+ {"type": "image_url", "image_url": {"url": image_urls[1]}},+ ]}]+ st, body = self.chat(eng, {"messages": messages}, template=tpl)+ self.assertEqual(st, 200, body)+ self.assertEqual(eng.calls[0][1]["images"], image_urls)++ def test_tool_property_sanitization_collision_is_rejected_without_mutation(self):+ marker = serve.IMAGE_PAD+ escaped_marker = marker[:1] + "\\" + marker[1:]+ tpl = THINK_TEMPLATE.replace("TOOLS={{ tools|length }}", "TOOLS={{ tools|tojson }}")+ eng = FakeEngine("x")+ tools = [{"type": "function", "function": {"name": "f", "parameters": {+ "type": "object", "properties": {marker: {"type": "string"},+ escaped_marker: {"type": "integer"}}}}}]+ original_tools = json.loads(json.dumps(tools))+ st, body = self.chat(eng, {"messages": [{"role": "user", "content": "hi"}], "tools": tools},+ template=tpl)+ self.assertEqual(st, 400, body)+ self.assertIn("collision", body["error"]["message"].lower())+ self.assertEqual(eng.calls, [])+ self.assertEqual(tools, original_tools)+def test_images_reach_the_engine_in_order(self):- tpl = THINK_TEMPLATE.replace("{{ m.content }}", "{{ m.content if m.content is string else '<|image_pad|>' }}")+ marker = serve.IMAGE_PAD+ tpl = THINK_TEMPLATE.replace("{{ m.content }}", "{{ m.content if m.content is string else '" + marker + "' }}")eng = FakeEngine("ok")async def fn(client):