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 content part the server does not read is a 400 on chat and messages, as on responses
midagedev5804094b2f1c
diff --git a/serve/frontend.py b/serve/frontend.pyindex 685b8d840..c7b0d63aa 100644--- a/serve/frontend.py+++ b/serve/frontend.py@@ -112,13 +112,17 @@ class ChatTemplate:# ------------------------------------------------------------------------------------------------ requests+# The content-part types the readers take as text (a part with no type that has a "text" field reads as text too)+TEXT_PARTS = ("text", "input_text", None)++def _text_of(content) -> str:if content is None:return ""if isinstance(content, str):return contentreturn "".join(part.get("text", "") for part in content if isinstance(part, dict) and part.get("type") in- ("text", "input_text", None))+ TEXT_PARTS)IMAGE_PARTS = ("image_url", "input_image", "image")@@ -182,11 +186,42 @@ def _parts_of(content):continueif part.get("type") in IMAGE_PARTS:items.append({"type": "image", "source": _image_source(part)})- elif part.get("type") in ("text", "input_text", None) and "text" in part:+ elif part.get("type") in TEXT_PARTS and "text" in part:items.append({"type": "text", "text": part.get("text", "")})return items+# The blocks a messages request may carry: text, the image parts, thinking, tool_use and tool_result.+# redacted_thinking is allowed only to be dropped without an error: another server's encrypted reasoning, which+# carries nothing this server can read - the same reason responses.py's _reasoning_text gives for another server's+# encrypted_content.+ANTHROPIC_BLOCKS = ("text",) + IMAGE_PARTS + ("thinking", "tool_use", "tool_result", "redacted_thinking")+++def _check_parts(content, path: str, kinds):+ """A request's content parts (on chat) or content blocks (on messages), checked while the request is converted:+ a part whose type this server does not read - a file, audio, a document - raises a ValueError naming the type+ and where it sits, which the server answers with a 400, as /v1/responses does; these two paths used to drop the+ part without a word, and the model answered about a file it had never seen. `kinds` is the types the place+ reads. A "refusal" part is read as its text, as /v1/responses does. Content that is not a list, and a part+ that is not an object, passes through: the readers skip it as they always did."""+ if not isinstance(content, list):+ return content+ out = content+ for j, part in enumerate(content):+ if not isinstance(part, dict):+ continue+ kind = part.get("type")+ if kind == "refusal":+ if out is content:+ out = list(content)+ out[j] = {"type": "text", "text": part.get("refusal") or ""}+ elif kind not in kinds:+ read = "text and images are" if set(kinds) & set(IMAGE_PARTS) else "text is"+ raise ValueError(f"{path}[{j}].type: content parts of type {kind!r} are not supported ({read})")+ return out++def images_of(messages: list[dict]) -> list[str]:"""The image sources of the rendered conversation, in prompt order (the template renders one<|vision_start|><|image_pad|><|vision_end|> per image item, message by message)."""@@ -365,11 +400,15 @@ def tool_arguments(raw) -> dict:def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:"""OpenAI Chat Completions -> (template messages, template tools, template kwargs)."""messages = []- for m in _object_list(req.get("messages"), "messages"):+ for i, m in enumerate(_object_list(req.get("messages"), "messages")):role = m.get("role")if role == "developer":role = "system"- out = {"role": role, "content": _parts_of(m.get("content")) if role in ("user", "tool", "assistant") else _text_of(m.get("content"))}+ # an image is read in a user, tool or assistant message; the system prompt takes text only, as _text_of reads+ images = role in ("user", "tool", "assistant")+ content = _check_parts(m.get("content"), f"messages[{i}].content",+ TEXT_PARTS + IMAGE_PARTS if images else TEXT_PARTS)+ out = {"role": role, "content": _parts_of(content) if images else _text_of(content)}if m.get("reasoning_content"):out["reasoning_content"] = m["reasoning_content"]if m.get("tool_calls"):@@ -432,9 +471,10 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[dmessages = []system = req.get("system")if system:- messages.append({"role": "system", "content": pin_billing_stamp(_text_of(system))})- for m in _object_list(req.get("messages"), "messages"):- content = m.get("content")+ messages.append({"role": "system",+ "content": pin_billing_stamp(_text_of(_check_parts(system, "system", TEXT_PARTS)))})+ for i, m in enumerate(_object_list(req.get("messages"), "messages")):+ content = _check_parts(m.get("content"), f"messages[{i}].content", ANTHROPIC_BLOCKS)if isinstance(content, str):messages.append({"role": m["role"], "content": content})continue@@ -443,7 +483,7 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[dmessages.append({"role": "user", "content": _parts_of(content)})continuetext, reasoning, calls, parts = [], [], [], []- for block in content or []:+ for j, block in enumerate(content or []):kind = block.get("type")if kind == "text":text.append(block.get("text", ""))@@ -457,7 +497,8 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[delif kind == "tool_result":# A tool's image (Claude Code's Read of a picture) reaches the encoder like a user's, as the OpenAI# path's tool messages already do; a text-only result is one string, as before.- messages.append({"role": "tool", "content": _parts_of(block.get("content"))})+ messages.append({"role": "tool", "content": _parts_of(_check_parts(+ block.get("content"), f"messages[{i}].content[{j}].content", TEXT_PARTS + IMAGE_PARTS))})if text or calls or reasoning or parts:# an image sent beside tool results stays in this turn instead of being droppedout = {"role": m["role"], "content": _parts_of(parts) if _has_image(parts) else "".join(text)}diff --git a/serve/test_frontend.py b/serve/test_frontend.pyindex 8d4b80df2..9320c5117 100644--- a/serve/test_frontend.py+++ b/serve/test_frontend.py@@ -77,6 +77,107 @@ class EmptyAssistantHistory(unittest.TestCase):self.assertIn("<tool_response>\n\n</tool_response>", prompt)+class UnreadContentParts(unittest.TestCase):+ """A content part the server does not read is refused naming it and where it sits, as /v1/responses does; chat+ and messages used to drop it without a word, and the model answered about a file it had never seen."""++ def setUp(self):+ self.template = ChatTemplate(Path(__file__).with_name("chat_template.jinja"))+ tok = ByteTokenizer()+ self.service = Service(MockEngine(tok, "ok"), tok, self.template)++ def test_chat_file_and_audio_parts_are_refused(self):+ parts = ({"type": "file", "file": {"filename": "a.pdf", "file_data": "data:application/pdf;base64,AA"}},+ {"type": "input_audio", "input_audio": {"data": "AA", "format": "wav"}})+ for part in parts:+ with self.subTest(kind=part["type"]):+ with self.assertRaises(ValueError) as raised:+ openai_to_messages({"messages": [+ {"role": "user", "content": "summarize the attached file"},+ {"role": "assistant", "content": "which file?"},+ {"role": "user", "content": [{"type": "text", "text": "this one"}, part]}]})+ self.assertEqual(str(raised.exception),+ f"messages[2].content[1].type: content parts of type {part['type']!r} are not "+ "supported (text and images are)")++ def test_messages_document_block_is_refused(self):+ with self.assertRaises(ValueError) as raised:+ anthropic_to_messages({"messages": [+ {"role": "user", "content": "summarize the attached file"},+ {"role": "assistant", "content": "which file?"},+ {"role": "user", "content": [+ {"type": "text", "text": "this one"},+ {"type": "document", "source": {"type": "base64", "media_type": "application/pdf",+ "data": "AA"}}]}]})+ self.assertEqual(str(raised.exception),+ "messages[2].content[1].type: content parts of type 'document' are not supported "+ "(text and images are)")++ def test_messages_document_in_a_tool_result_is_refused(self):+ with self.assertRaises(ValueError) as raised:+ anthropic_to_messages({"messages": [+ {"role": "user", "content": "read the pdf"},+ {"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "read", "input": {}}]},+ {"role": "user", "content": [+ {"type": "tool_result", "tool_use_id": "t1", "content": [+ {"type": "text", "text": "page 1"},+ {"type": "document", "source": {"type": "base64", "media_type": "application/pdf",+ "data": "AA"}}]}]}]})+ self.assertEqual(str(raised.exception),+ "messages[2].content[0].content[1].type: content parts of type 'document' are not "+ "supported (text and images are)")++ def test_a_system_prompt_takes_text_only(self):+ with self.assertRaises(ValueError) as raised:+ openai_to_messages({"messages": [+ {"role": "system", "content": [{"type": "text", "text": "be brief"},+ {"type": "image_url", "image_url": "image.png"}]},+ {"role": "user", "content": "hi"}]})+ self.assertEqual(str(raised.exception),+ "messages[0].content[1].type: content parts of type 'image_url' are not supported (text is)")++ def test_messages_redacted_thinking_is_dropped(self):+ msgs = {"messages": [+ {"role": "user", "content": "haz un ls"},+ {"role": "assistant", "content": [{"type": "redacted_thinking", "data": "ZW50cnk="},+ {"type": "text", "text": "Running ls."}]},+ {"role": "user", "content": "thanks"}]}+ without = copy.deepcopy(msgs)+ del without["messages"][1]["content"][0]+ with_block = anthropic_to_messages(msgs)+ without_block = anthropic_to_messages(without)+ self.assertEqual(with_block[0], without_block[0])+ self.assertEqual(self.service.encode_prompt(with_block[0], with_block[1], with_block[2]),+ self.service.encode_prompt(without_block[0], without_block[1], without_block[2]))++ def test_chat_refusal_part_is_read_as_its_text(self):+ messages, tools, kwargs = openai_to_messages({"messages": [+ {"role": "user", "content": "do a thing"},+ {"role": "assistant", "content": [{"type": "refusal", "refusal": "I cannot do that."}]},+ {"role": "user", "content": "ok"}]})+ self.assertEqual(messages[1]["content"], "I cannot do that.")+ self.assertIn("I cannot do that.", self.template.render(messages, tools=tools, **kwargs))++ def test_text_and_image_requests_render_as_before(self):+ parts = [{"role": "user", "content": [{"type": "text", "text": "haz un ls"}]},+ {"role": "assistant", "content": [{"type": "text", "text": "file.txt"}]}]+ plain = [{"role": "user", "content": "haz un ls"}, {"role": "assistant", "content": "file.txt"}]+ for convert in (openai_to_messages, anthropic_to_messages):+ with self.subTest(convert=convert.__name__):+ self.assertEqual(self.service.encode_prompt(*convert({"messages": parts})),+ self.service.encode_prompt(*convert({"messages": plain})))+ chat = openai_to_messages({"messages": [+ {"role": "user", "content": [{"type": "text", "text": "describe"},+ {"type": "image_url", "image_url": "image.png"}]}]})+ self.assertIn("<|vision_start|><|image_pad|><|vision_end|>",+ self.template.render(chat[0], tools=chat[1], **chat[2]))+ msgs = anthropic_to_messages({"messages": [+ {"role": "user", "content": [{"type": "text", "text": "describe"},+ {"type": "image", "source": {"type": "url", "url": "image.png"}}]}]})+ self.assertIn("<|vision_start|><|image_pad|><|vision_end|>",+ self.template.render(msgs[0], tools=msgs[1], **msgs[2]))++if __name__ == "__main__":unittest.main()