From 92c806dc4d01a1e295c9ee701bb1839f704036be Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Wed, 14 Oct 2026 20:23:46 +0400 Subject: [PATCH 1/2] Omit empty text from message content parts `contentParts(for:layout:)` always appended a text part, so an assistant tool call without text became `[{"type": "text", "text": ""}]`. Chat templates test `message.content` for truth: the empty string a text model receives is false, but a list holding an empty part is true. Qwen3-VL's template then renders the call as `\n\n` instead of the `\n` the model generated. The cache no longer matches the prompt, and a rewind is refused because the model carries M-RoPE state, so every tool follow-up pass prefilled the whole conversation. Empty text now gives no part. An empty list is false, as the empty string is, so the re-rendered prompt extends the cache again. Checked against the chat templates of every registered model that uses content parts (Qwen2-VL, Qwen2.5-VL, Qwen3-VL, Qwen3.5, Qwen3.8, Muse-Glimmer, Gemma 3, Gemma 4, LFM2-VL, Ministral 3, FastVLM, GLM-OCR): only the Qwen3-VL template changes output, and it now renders the same as with string content. --- Libraries/MLXLMCommon/Chat.swift | 3 +++ .../MLXLMTests/MessageContentPartsTests.swift | 27 ++++++++++++++----- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/Libraries/MLXLMCommon/Chat.swift b/Libraries/MLXLMCommon/Chat.swift index 684c80ca22..9c0c0842cd 100644 --- a/Libraries/MLXLMCommon/Chat.swift +++ b/Libraries/MLXLMCommon/Chat.swift @@ -187,12 +187,15 @@ extension MessageGenerator { } } + /// Empty text gives no part: templates test `content` for truth, and a list + /// holding an empty text part is true where the empty string is false. package func contentParts( for message: Chat.Message, layout: MessageContentLayout ) -> [[String: String]] { var parts: [[String: String]] = [] func appendText(_ text: String) { + guard !text.isEmpty else { return } parts.append(["type": "text", "text": text]) } diff --git a/Tests/MLXLMTests/MessageContentPartsTests.swift b/Tests/MLXLMTests/MessageContentPartsTests.swift index 72a46b6d2c..3b7747900d 100644 --- a/Tests/MLXLMTests/MessageContentPartsTests.swift +++ b/Tests/MLXLMTests/MessageContentPartsTests.swift @@ -2,6 +2,7 @@ import Foundation import MLXLMCommon +import MLXVLM import Testing @Suite("Message content parts") @@ -163,14 +164,28 @@ struct MessageContentPartsTests { ]) } - @Test("Empty text still gives a text part") - func emptyTextStillGivesAPart() { + @Test("Empty text gives no part") + func emptyTextGivesNoPart() { let message = Chat.Message.user("", images: [image(nil)]) #expect( generator.contentParts(for: message, layout: .imagesThenText) - == [ - ["type": "image"], - ["type": "text", "text": ""], - ]) + == [["type": "image"]]) + } + + @Test("A tool call without text has empty content in every content-parts generator") + func toolCallWithoutTextHasEmptyContent() { + let call = ToolCall( + function: .init(name: "get_weather", arguments: ["city": .string("Rome")])) + let generators: [any MessageGenerator] = [ + Qwen2VLMessageGenerator(), Qwen3VLMessageGenerator(), Gemma4MessageGenerator(), + Mistral3MessageGenerator(), FastVLMMessageGenerator(), GlmOcrMessageGenerator(), + ] + for generator in generators { + let message = generator.generate(message: .assistant("", toolCalls: [call])) + #expect( + (message["content"] as? [[String: String]])?.isEmpty == true, + "\(type(of: generator)) gave \(String(describing: message["content"]))") + #expect(message["tool_calls"] != nil, "\(type(of: generator)) lost the tool call") + } } } From e9bccdc0222c7974064bb06fdaf5514ebaff3542 Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Thu, 15 Oct 2026 03:22:59 +0400 Subject: [PATCH 2/2] Limit empty text omission to assistant tool calls --- ...EmptyToolCallContentIntegrationTests.swift | 70 ++++++++++++++++ Libraries/MLXLMCommon/Chat.swift | 10 ++- .../MLXLMTests/MessageContentPartsTests.swift | 80 ++++++++++++++++++- 3 files changed, 153 insertions(+), 7 deletions(-) create mode 100644 IntegrationTesting/IntegrationTestingTests/EmptyToolCallContentIntegrationTests.swift diff --git a/IntegrationTesting/IntegrationTestingTests/EmptyToolCallContentIntegrationTests.swift b/IntegrationTesting/IntegrationTestingTests/EmptyToolCallContentIntegrationTests.swift new file mode 100644 index 0000000000..e8a842eca9 --- /dev/null +++ b/IntegrationTesting/IntegrationTestingTests/EmptyToolCallContentIntegrationTests.swift @@ -0,0 +1,70 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import HuggingFace +import MLXHuggingFace +import MLXLMCommon +import MLXVLM +import Testing +import Tokenizers + +struct EmptyToolCallContentIntegrationTests { + private func tokenizer(id: String, revision: String) async throws -> any MLXLMCommon.Tokenizer { + let downloader: any Downloader = #hubDownloader() + let loader: any TokenizerLoader = #huggingFaceTokenizerLoader() + let directory = try await downloader.download( + id: id, revision: revision, matching: ["*.json", "*.jinja"], + useLatest: false, progressHandler: { _ in }) + return try await loader.load(from: directory) + } + + @Test func ministral3AcceptsEmptyMessagesAndToolCalls() async throws { + let tokenizer = try await tokenizer( + id: "mlx-community/Ministral-3-3B-Instruct-2512-4bit", + revision: "a962dcb09eee4169c890e544c9eb938f1113fdee") + let generator = Mistral3MessageGenerator() + let user = generator.generate(message: .user("Hello")) + for role in ["user", "assistant"] { + let empty: MLXLMCommon.Message = ["role": role, "content": [[String: String]]()] + #expect(throws: (any Error).self) { + try tokenizer.applyChatTemplate(messages: role == "user" ? [empty] : [user, empty]) + } + } + for assistant: Chat.Message in [.assistant(""), .assistant("", toolCalls: [])] { + let messages = generator.generate(messages: [.user(""), assistant]) + let tokens = try tokenizer.applyChatTemplate(messages: messages) + let prompt = tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) + #expect(prompt.contains("[INST][/INST]")) + } + let call = ToolCall(function: .init(name: "get_weather", arguments: [:])) + let messages = generator.generate(messages: [ + .user("Weather in Rome?"), .assistant("", toolCalls: [call]), + ]) + let tokens = try tokenizer.applyChatTemplate(messages: messages) + let prompt = tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) + #expect(prompt.contains("[TOOL_CALLS]get_weather[ARGS]{}")) + } + + @Test func qwen3VLToolCallRendersLikeEmptyStringContent() async throws { + let tokenizer = try await tokenizer( + id: "mlx-community/Qwen3-VL-2B-Instruct-4bit", + revision: "9c4f5209e57b31f4b9dfba735de3fb983739c9cc") + let call = ToolCall( + function: .init(name: "get_weather", arguments: ["city": .string("Rome")])) + let generator = Qwen3VLMessageGenerator() + let user = generator.generate(message: .user("Weather in Rome?")) + let assistant = generator.generate(message: .assistant("", toolCalls: [call])) + let tokens = try tokenizer.applyChatTemplate(messages: [user, assistant]) + var stringAssistant = assistant + stringAssistant["content"] = "" + let reference = try tokenizer.applyChatTemplate(messages: [user, stringAssistant]) + #expect(tokens == reference) + let prompt = tokenizer.decode(tokenIds: tokens, skipSpecialTokens: false) + #expect(prompt.contains("\n")) + #expect(!prompt.contains("\n\n")) + var legacyAssistant = assistant + legacyAssistant["content"] = [["type": "text", "text": ""]] + let legacy = try tokenizer.applyChatTemplate(messages: [user, legacyAssistant]) + #expect(legacy != reference) + } +} diff --git a/Libraries/MLXLMCommon/Chat.swift b/Libraries/MLXLMCommon/Chat.swift index 9c0c0842cd..1ddce449c7 100644 --- a/Libraries/MLXLMCommon/Chat.swift +++ b/Libraries/MLXLMCommon/Chat.swift @@ -187,15 +187,19 @@ extension MessageGenerator { } } - /// Empty text gives no part: templates test `content` for truth, and a list - /// holding an empty text part is true where the empty string is false. + /// Avoid truthy empty text parts on assistant tool calls. + /// Keep empty text parts elsewhere for templates that require nonempty lists. package func contentParts( for message: Chat.Message, layout: MessageContentLayout ) -> [[String: String]] { var parts: [[String: String]] = [] func appendText(_ text: String) { - guard !text.isEmpty else { return } + if text.isEmpty, message.role == .assistant, let calls = message.tool?.calls, + !calls.isEmpty + { + return + } parts.append(["type": "text", "text": text]) } diff --git a/Tests/MLXLMTests/MessageContentPartsTests.swift b/Tests/MLXLMTests/MessageContentPartsTests.swift index 3b7747900d..6faebeb80f 100644 --- a/Tests/MLXLMTests/MessageContentPartsTests.swift +++ b/Tests/MLXLMTests/MessageContentPartsTests.swift @@ -164,15 +164,80 @@ struct MessageContentPartsTests { ]) } - @Test("Empty text gives no part") - func emptyTextGivesNoPart() { + @Test("Empty text still gives a text part") + func emptyTextStillGivesAPart() { let message = Chat.Message.user("", images: [image(nil)]) #expect( generator.contentParts(for: message, layout: .imagesThenText) - == [["type": "image"]]) + == [["type": "image"], ["type": "text", "text": ""]]) } - @Test("A tool call without text has empty content in every content-parts generator") + @Test("Empty messages without tool calls keep a text part in every layout") + func emptyMessagesWithoutToolCallsKeepText() { + for role: Chat.Message.Role in [.user, .assistant, .system, .tool] { + for tool: Chat.Message.Tool? in [nil, .calls([]), .result(id: "call_1")] { + let message = Chat.Message(role: role, content: "", tool: tool) + for layout: MessageContentLayout in [ + .imagesThenVideosThenText, .imagesThenText, .textThenImages, + ] { + #expect( + generator.contentParts(for: message, layout: layout) + == [["type": "text", "text": ""]]) + } + } + } + } + + @Test("Only assistant tool calls omit empty text, and nonempty text is preserved") + func toolCallTextByRole() { + let call = ToolCall(function: .init(name: "get_weather", arguments: [:])) + for role: Chat.Message.Role in [.user, .assistant, .system, .tool] { + for text in ["", " ", "Checking the weather."] { + let message = Chat.Message(role: role, content: text, tool: .calls([call])) + for layout: MessageContentLayout in [ + .imagesThenVideosThenText, .imagesThenText, .textThenImages, + ] { + let expected = + role == .assistant && text.isEmpty + ? [] : [["type": "text", "text": text]] + #expect(generator.contentParts(for: message, layout: layout) == expected) + } + } + } + } + + @Test("Omitting tool-call text preserves image labels and media") + func toolCallsKeepMedia() { + let call = ToolCall(function: .init(name: "get_weather", arguments: [:])) + let message = Chat.Message.assistant( + "", images: [image("A"), image(nil)], + videos: [.url(URL(fileURLWithPath: "/tmp/example.mov"))], toolCalls: [call]) + for layout: MessageContentLayout in [ + .imagesThenVideosThenText, .imagesThenText, .textThenImages, + ] { + var expected = [ + ["type": "text", "text": "[A]"], ["type": "image"], ["type": "image"], + ] + if case .imagesThenVideosThenText = layout { + expected.append(["type": "video"]) + } + #expect(generator.contentParts(for: message, layout: layout) == expected) + } + } + + @Test("Qwen reasoning with no answer omits text only when tool calls are present") + func reasoningOnlyAssistantContent() { + let call = ToolCall(function: .init(name: "get_weather", arguments: [:])) + for calls: [ToolCall]? in [nil, [], [call]] { + let message = Qwen3VLMessageGenerator().generate( + message: .assistant("Check the weather.", toolCalls: calls)) + #expect(message["reasoning_content"] as? String == "Check the weather.") + let expected = calls?.isEmpty == false ? [] : [["type": "text", "text": ""]] + #expect(message["content"] as? [[String: String]] == expected) + } + } + + @Test("Content-parts generators omit empty text only for actual tool calls") func toolCallWithoutTextHasEmptyContent() { let call = ToolCall( function: .init(name: "get_weather", arguments: ["city": .string("Rome")])) @@ -181,6 +246,13 @@ struct MessageContentPartsTests { Mistral3MessageGenerator(), FastVLMMessageGenerator(), GlmOcrMessageGenerator(), ] for generator in generators { + for input: Chat.Message in [.user(""), .assistant(""), .assistant("", toolCalls: [])] { + let message = generator.generate(message: input) + #expect( + (message["content"] as? [[String: String]]) + == [["type": "text", "text": ""]], + "\(type(of: generator)) changed an empty message without tool calls") + } let message = generator.generate(message: .assistant("", toolCalls: [call])) #expect( (message["content"] as? [[String: String]])?.isEmpty == true,