Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: a template refusal answers 400 (#365); the temporary image goes when the encoder's pipe fails (#352)

Niko1221318d74d9d2db
diff --git a/serve/frontend.py b/serve/frontend.py
index e832be996..9e73ae0a2 100644
--- a/serve/frontend.py
+++ b/serve/frontend.py
@@ -25,12 +25,17 @@ from jinja2.sandbox import ImmutableSandboxedEnvironment
# ------------------------------------------------------------------------------------------------ template
+class TemplateRequestError(jinja2.exceptions.TemplateError, ValueError):
+ """The template refused the request's messages (e.g. "No user query found in messages."): a ValueError, so the
+ client gets a 400 with the template's message instead of a dropped connection (#365)."""
+
+
class ChatTemplate:
"""The model's chat template, rendered with the same Jinja settings as transformers' apply_chat_template."""
def __init__(self, path: str | Path):
def raise_exception(message):
- raise jinja2.exceptions.TemplateError(message)
+ raise TemplateRequestError(message)
def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False):
return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys)
diff --git a/serve/server.py b/serve/server.py
index f13cf0399..0b02e7295 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -585,10 +585,12 @@ class Vision:
return self.cache[key]
img, out = self.dir / f"{key}.img", self.dir / f"{key}.sve"
img.write_bytes(data)
- self.proc.stdin.write(f"ENC {img} {out}\n")
- self.proc.stdin.flush()
- line = self.proc.stdout.readline().strip()
- img.unlink(missing_ok=True)
+ try:
+ self.proc.stdin.write(f"ENC {img} {out}\n")
+ self.proc.stdin.flush()
+ line = self.proc.stdout.readline().strip()
+ finally: # #352: also when the encoder's pipe is gone
+ img.unlink(missing_ok=True)
if not line.startswith("OK"):
raise ValueError("the image could not be read: " + (line[4:] if line.startswith("ERR") else
"the vision encoder stopped"))
diff --git a/serve/test_server.py b/serve/test_server.py
index 90781f7a6..c52b095e1 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -455,6 +455,43 @@ class ClientShapes(unittest.TestCase):
for part in ("Be brief.", "Now use digits.", "Also this.", "1+1?"):
self.assertIn(part, text)
+ def test_no_user_turn_is_a_400(self):
+ # #365: the template's own refusal (Qwen's "No user query found in messages." when no turn is a user's query)
+ # answers 400, not a dropped connection
+ with tempfile.TemporaryDirectory() as d:
+ tpl = Path(d) / "chat_template.jinja"
+ tpl.write_text("{% if messages[-1].role != 'user' %}{{ raise_exception('No user query found in messages.') }}"
+ "{% endif %}{{ messages[-1].content }}", encoding="utf-8")
+ template, self.svc.template = self.svc.template, ChatTemplate(tpl)
+ try:
+ status, b = self.post("/v1/chat/completions", {
+ "model": "x", "max_tokens": 20, "messages": [{"role": "system", "content": "Only a system."}]})
+ self.assertEqual(status, 400, b)
+ self.assertIn("No user query found", b["error"]["message"])
+ finally:
+ self.svc.template = template
+ status, b = self.post("/v1/chat/completions", {"model": "x", "max_tokens": 20,
+ "messages": [{"role": "user", "content": "hi"}]})
+ self.assertEqual(status, 200, b) # the server goes on
+
+ def test_vision_temp_image_removed_when_the_pipe_fails(self):
+ # #352: the temporary image goes even when the encoder's pipe raises
+ from serve.server import Vision
+
+ class Gone:
+ def write(self, _):
+ raise BrokenPipeError("the encoder is gone")
+
+ v = Vision.__new__(Vision)
+ v.dir, v.lock, v.cache = Path(tempfile.mkdtemp(prefix="strata-vision-test-")), threading.Lock(), {}
+ v.proc = mock.Mock(stdin=Gone())
+ with mock.patch.object(Vision, "load", return_value=b""), mock.patch.object(Vision, "normalize",
+ return_value=b"png"):
+ with self.assertRaises(BrokenPipeError):
+ v.encode("x")
+ self.assertEqual(list(v.dir.iterdir()), [])
+ v.dir.rmdir()
+
def test_leading_system_unchanged(self):
from serve.frontend import anthropic_to_messages, openai_to_messages
msgs, _, _ = openai_to_messages({"messages": [{"role": "developer", "content": "D"}, {"role": "user", "content": "u"}]})