diff --git a/Applications/MLXChatExample/Models/LMModel.swift b/Applications/MLXChatExample/Models/LMModel.swift index 23353d43..d3b1285d 100644 --- a/Applications/MLXChatExample/Models/LMModel.swift +++ b/Applications/MLXChatExample/Models/LMModel.swift @@ -10,9 +10,12 @@ import MLXLMCommon /// Represents a language model configuration with its associated properties and type. /// Can represent either a large language model (LLM) or a vision-language model (VLM). struct LMModel { - /// Name of the model + /// Identifier for the model, used for cache keys and equality. let name: String + /// User-facing label shown in the model picker. + let displayName: String + /// Configuration settings for model initialization let configuration: ModelConfiguration @@ -31,15 +34,6 @@ struct LMModel { // MARK: - Helpers extension LMModel { - /// Display name with additional "(Vision)" suffix for vision models - var displayName: String { - if isVisionModel { - "\(name) (Vision)" - } else { - name - } - } - /// Whether the model is a large language model var isLanguageModel: Bool { type == .llm diff --git a/Applications/MLXChatExample/Models/Message.swift b/Applications/MLXChatExample/Models/Message.swift index 68132692..40899e3f 100644 --- a/Applications/MLXChatExample/Models/Message.swift +++ b/Applications/MLXChatExample/Models/Message.swift @@ -17,8 +17,11 @@ class Message: Identifiable { /// The role of the message sender (user, assistant, or system) let role: Role - /// The text content of the message - var content: String + /// On-screen regions in arrival order. User/system messages have a + /// single ``MessageSegment/content(_:)`` holding the whole text. + /// Assistant messages grow as the parser surfaces reasoning runs, + /// tool-call items, and content runs, interleaved. + var segments: [MessageSegment] /// Array of image URLs attached to the message var images: [URL] @@ -29,6 +32,17 @@ class Message: Identifiable { /// Timestamp when the message was created let timestamp: Date + /// Concatenated text from every ``MessageSegment/content(_:)`` segment. + /// Used for user/system rendering and for re-seeding assistant turns + /// into a `Chat.Message` history – the model only needs to see what + /// it actually said, not its reasoning or tool-call wire syntax. + var content: String { + segments.compactMap { + if case let .content(segment) = $0 { return segment.text } + return nil + }.joined() + } + /// Creates a new message with the specified role, content, and optional media attachments /// - Parameters: /// - role: The role of the message sender @@ -38,7 +52,9 @@ class Message: Identifiable { init(role: Role, content: String, images: [URL] = [], videos: [URL] = []) { self.id = UUID() self.role = role - self.content = content + self.segments = content.isEmpty + ? [] + : [.content(TextSegment(itemId: "_initial", text: content))] self.images = images self.videos = videos self.timestamp = .now diff --git a/Applications/MLXChatExample/Models/MessageSegment.swift b/Applications/MLXChatExample/Models/MessageSegment.swift new file mode 100644 index 00000000..19cf3451 --- /dev/null +++ b/Applications/MLXChatExample/Models/MessageSegment.swift @@ -0,0 +1,42 @@ +// +// MessageSegment.swift +// MLXChatExample +// + +import Foundation + +/// One on-screen region inside an assistant ``Message``: a run of content +/// text, a run of reasoning text, or a tool call. Stored in arrival order +/// so the UI renders reasoning, tool-call cards, and answer text +/// interleaved as the parser surfaced them. +enum MessageSegment: Identifiable { + case content(TextSegment) + case reasoning(TextSegment) + case toolCall(ToolCall) + + var id: String { + switch self { + case .content(let segment), .reasoning(let segment): + return segment.id.uuidString + case .toolCall(let toolCall): + return toolCall.id + } + } +} + +/// A growable text run inside a ``MessageSegment``. `itemId` is the +/// parser's `msg_…` / `rs_…` id, used to merge consecutive deltas of +/// the same item into one segment. `id` is a stable UUID for SwiftUI +/// `Identifiable` – distinct from `itemId` to stay safe if the parser +/// ever reuses an id across non-contiguous spans. +@Observable +class TextSegment: Identifiable { + let id = UUID() + let itemId: String + var text: String + + init(itemId: String, text: String = "") { + self.itemId = itemId + self.text = text + } +} diff --git a/Applications/MLXChatExample/Models/ToolCall.swift b/Applications/MLXChatExample/Models/ToolCall.swift new file mode 100644 index 00000000..f7b6aef1 --- /dev/null +++ b/Applications/MLXChatExample/Models/ToolCall.swift @@ -0,0 +1,40 @@ +// +// ToolCall.swift +// MLXChatExample +// + +import Foundation + +/// One assistant-issued tool call surfaced in the UI. `argumentsRaw` +/// accumulates as `functionCallArgumentsDelta` events arrive; `result` +/// fills in when the matching `functionCallOutput` lands. +@Observable +class ToolCall: Identifiable { + /// Parser-minted `fc_…` id. Used for `Identifiable` and for matching + /// `functionCallArgumentsDelta.itemId`. + let id: String + + /// Parser-minted `call_…` id used to match the eventual + /// `functionCallOutput` back to this call. + let callId: String + + /// Function name the model wants to invoke. + let name: String + + /// Raw JSON arguments string, growing one delta at a time. + var argumentsRaw: String + + /// Tool result once dispatch returns; `nil` while in flight. + var result: String? + + init( + id: String, callId: String, name: String, + argumentsRaw: String = "", result: String? = nil + ) { + self.id = id + self.callId = callId + self.name = name + self.argumentsRaw = argumentsRaw + self.result = result + } +} diff --git a/Applications/MLXChatExample/Services/MLXService.swift b/Applications/MLXChatExample/Services/MLXService.swift index b73f7b81..97779e5a 100644 --- a/Applications/MLXChatExample/Services/MLXService.swift +++ b/Applications/MLXChatExample/Services/MLXService.swift @@ -7,6 +7,7 @@ import Foundation import HuggingFace +import LMResponseParserMLX import MLX import MLXHuggingFace import MLXLLM @@ -15,120 +16,245 @@ import MLXVLM import Tokenizers /// A service class that manages machine learning models for text and vision-language tasks. -/// This class handles model loading, caching, and text generation using various LLM and VLM models. +/// Holds a single active `ResponseChatSession` so KV-cache state is reused across turns +/// without re-feeding the visible message array. When the selected model changes, +/// the session is rebuilt and seeded with the current visible chat history so the +/// new model can continue the conversation. @Observable +@MainActor class MLXService { /// List of available models that can be used for generation. /// Includes both language models (LLM) and vision-language models (VLM). + /// `qwen3:4b` is listed first so it is the default selection on a fresh launch. static let availableModels: [LMModel] = [ - LMModel(name: "llama3.2:1b", configuration: LLMRegistry.llama3_2_1B_4bit, type: .llm), - LMModel(name: "qwen2.5:1.5b", configuration: LLMRegistry.qwen2_5_1_5b, type: .llm), - LMModel(name: "smolLM:135m", configuration: LLMRegistry.smolLM_135M_4bit, type: .llm), - LMModel(name: "qwen3:0.6b", configuration: LLMRegistry.qwen3_0_6b_4bit, type: .llm), - LMModel(name: "qwen3:1.7b", configuration: LLMRegistry.qwen3_1_7b_4bit, type: .llm), - LMModel(name: "qwen3:4b", configuration: LLMRegistry.qwen3_4b_4bit, type: .llm), - LMModel(name: "qwen3:8b", configuration: LLMRegistry.qwen3_8b_4bit, type: .llm), - LMModel( - name: "qwen2.5VL:3b", configuration: VLMRegistry.qwen2_5VL3BInstruct4Bit, type: .vlm), - LMModel(name: "qwen2VL:2b", configuration: VLMRegistry.qwen2VL2BInstruct4Bit, type: .vlm), - LMModel(name: "smolVLM", configuration: VLMRegistry.smolvlminstruct4bit, type: .vlm), - LMModel(name: "acereason:7B", configuration: LLMRegistry.acereason_7b_4bit, type: .llm), - LMModel(name: "gemma3n:E2B", configuration: LLMRegistry.gemma3n_E2B_it_lm_4bit, type: .llm), - LMModel(name: "gemma3n:E4B", configuration: LLMRegistry.gemma3n_E4B_it_lm_4bit, type: .llm), + LMModel( + name: "qwen3:4b", displayName: "Qwen 3 (4B)", + configuration: LLMRegistry.qwen3_4b_4bit, type: .llm), + LMModel( + name: "llama3.2:1b", displayName: "Llama 3.2 (1B)", + configuration: LLMRegistry.llama3_2_1B_4bit, type: .llm), + LMModel( + name: "qwen2.5:1.5b", displayName: "Qwen 2.5 (1.5B)", + configuration: LLMRegistry.qwen2_5_1_5b, type: .llm), + LMModel( + name: "smolLM:135m", displayName: "SmolLM (135M)", + configuration: LLMRegistry.smolLM_135M_4bit, type: .llm), + LMModel( + name: "qwen3:0.6b", displayName: "Qwen 3 (0.6B)", + configuration: LLMRegistry.qwen3_0_6b_4bit, type: .llm), + LMModel( + name: "qwen3:1.7b", displayName: "Qwen 3 (1.7B)", + configuration: LLMRegistry.qwen3_1_7b_4bit, type: .llm), + LMModel( + name: "qwen3:8b", displayName: "Qwen 3 (8B)", + configuration: LLMRegistry.qwen3_8b_4bit, type: .llm), + LMModel( + name: "qwen2.5VL:3b", displayName: "Qwen 2.5 VL (3B)", + configuration: VLMRegistry.qwen2_5VL3BInstruct4Bit, type: .vlm), + LMModel( + name: "qwen2VL:2b", displayName: "Qwen 2 VL (2B)", + configuration: VLMRegistry.qwen2VL2BInstruct4Bit, type: .vlm), + LMModel( + name: "smolVLM", displayName: "SmolVLM", + configuration: VLMRegistry.smolvlminstruct4bit, type: .vlm), + LMModel( + name: "acereason:7B", displayName: "AceReason (7B)", + configuration: LLMRegistry.acereason_7b_4bit, type: .llm), + LMModel( + name: "gemma3n:E2B", displayName: "Gemma 3n (E2B)", + configuration: LLMRegistry.gemma3n_E2B_it_lm_4bit, type: .llm), + LMModel( + name: "gemma3n:E4B", displayName: "Gemma 3n (E4B)", + configuration: LLMRegistry.gemma3n_E4B_it_lm_4bit, type: .llm), + LMModel( + name: "gpt-oss:20b", displayName: "GPT-OSS (20B, MXFP4 Q8)", + configuration: LLMRegistry.gpt_oss_20b_MXFP4_Q8, type: .llm), + LMModel( + name: "granite4:tiny", displayName: "Granite 4.0 H Tiny (4-bit DWQ)", + configuration: LLMRegistry.granite_4_0_h_tiny_4bit_dwq, type: .llm), + LMModel( + name: "gemma4:E2B", displayName: "Gemma 4 (E2B)", + configuration: LLMRegistry.gemma4_e2b_it_4bit, type: .llm), + LMModel( + name: "lfm2:1.2b", displayName: "LFM2 (1.2B)", + configuration: LLMRegistry.lfm2_1_2b_4bit, type: .llm), ] - /// Cache to store loaded model containers to avoid reloading. + /// System prompt applied to each new `ResponseChatSession` (as `instructions`) + /// and shown in the chat as the system message. + static let systemPrompt = "You are a helpful assistant." + + /// Generation parameters applied to each new `ResponseChatSession`. + private let generateParameters = GenerateParameters(temperature: 0.7) + + /// Cache of loaded model containers, keyed by `LMModel.name`. private let modelCache = NSCache() + /// The currently active session, owning the KV cache for `currentModel`. + /// Rebuilt with seeded history whenever the selected model changes. + private var currentSession: ResponseChatSession? + + /// The model that `currentSession` was built for. Used to detect a model + /// switch on the next call to ``generate(history:prompt:images:videos:model:)``. + private var currentModel: LMModel? + + /// Output token count from the most recent finalized turn, used by + /// `ChatViewModel` to derive the toolbar's tokens-per-second readout. + /// `nil` until the first turn finalizes; `nil` again after a turn + /// that was cancelled or threw, since `ResponseChatSession.lastResponse` + /// only updates on clean completion. + var lastResponseOutputTokens: Int? { + currentSession?.lastResponse?.usage?.outputTokens + } + /// Tracks the current model download progress. - /// Access this property to monitor model download status. - @MainActor + /// Non-nil only while bytes are actively flowing from the network. private(set) var modelDownloadProgress: Progress? + /// Whether a model is currently being initialized into memory. + /// True for the entire `loadContainer` call, including the disk → memory phase + /// after any network download has finished. + private(set) var isLoadingModel = false + /// Loads a model from the hub or retrieves it from cache. - /// - Parameter model: The model configuration to load - /// - Returns: A ModelContainer instance containing the loaded model - /// - Throws: Errors that might occur during model loading private func load(model: LMModel) async throws -> ModelContainer { // Set GPU memory limit to prevent out of memory issues Memory.cacheLimit = 20 * 1024 * 1024 - // Return cached model if available to avoid reloading if let container = modelCache.object(forKey: model.name as NSString) { return container - } else { - // Select appropriate factory based on model type - let factory: ModelFactory = - switch model.type { - case .llm: - LLMModelFactory.shared - case .vlm: - VLMModelFactory.shared - } - - let downloader = #hubDownloader() - let loader = #huggingFaceTokenizerLoader() + } - // Load model and track download progress - let container = try await factory.loadContainer( - from: downloader, - using: loader, - configuration: model.configuration - ) { progress in - Task { @MainActor in - self.modelDownloadProgress = progress - } + let factory: any ModelFactory = + switch model.type { + case .llm: + LLMModelFactory.shared + case .vlm: + VLMModelFactory.shared } - // Cache the loaded model for future use - modelCache.setObject(container, forKey: model.name as NSString) + let downloader = #hubDownloader() + let loader = #huggingFaceTokenizerLoader() - return container + isLoadingModel = true + defer { + modelDownloadProgress = nil + isLoadingModel = false } - } - /// Generates text based on the provided messages using the specified model. - /// - Parameters: - /// - messages: Array of chat messages including user, assistant, and system messages - /// - model: The language model to use for generation - /// - Returns: An AsyncStream of generated text tokens - /// - Throws: Errors that might occur during generation - func generate(messages: [Message], model: LMModel) async throws -> AsyncStream { - // Load or retrieve model from cache - let modelContainer = try await load(model: model) - - // Map app-specific Message type to Chat.Message for model input - let chat = messages.map { message in - let role: Chat.Message.Role = - switch message.role { - case .assistant: - .assistant - case .user: - .user - case .system: - .system + let container = try await factory.loadContainer( + from: downloader, + using: loader, + configuration: model.configuration + ) { progress in + Task { @MainActor in + guard self.isLoadingModel else { return } + if progress.isFinished { + self.modelDownloadProgress = nil + } else { + self.modelDownloadProgress = progress } + } + } - // Process any attached media for VLM models - let images: [UserInput.Image] = message.images.map { imageURL in .url(imageURL) } - let videos: [UserInput.Video] = message.videos.map { videoURL in .url(videoURL) } + modelCache.setObject(container, forKey: model.name as NSString) + return container + } - return Chat.Message( - role: role, content: message.content, images: images, videos: videos) + /// Returns the active `ResponseChatSession`, rebuilding it (seeded with `history`) + /// whenever the selected model changes or no session is yet active. + /// + /// `history` is only consumed on a rebuild; for follow-up turns on the same + /// model the existing session is reused so KV-cache state is preserved. + private func session( + for model: LMModel, + history: [Chat.Message] + ) async throws -> ResponseChatSession { + if let currentSession, currentModel?.id == model.id { + return currentSession } + let container = try await load(model: model) + let (modelType, modelConfig) = try await readModelTypeAndConfig(from: container) + // Infer the format up here using the LMModel's pre-load HF repo + // name. `LLMModelFactory._load` rewrites the loaded `ModelContext`'s + // configuration to a `.directory(snapshotURL)` id, so the name + // `ResponseChatSession` would otherwise read becomes + // `snapshots/` and stops matching any name-prefix entry + // in the parser library's table. + let format = ResponseFormat.infer( + modelName: model.configuration.name, + modelType: modelType ?? "", + modelConfig: modelConfig ?? [:] + ) + let session = ResponseChatSession( + container, + modelType: modelType, + modelConfig: modelConfig, + instructions: Self.systemPrompt, + history: history, + generateParameters: generateParameters, + processing: .init(resize: .init(width: 1024, height: 1024)), + tools: ToolRegistry.allSpecs, + toolDispatch: { call in + .string(await ToolRegistry.dispatch(call)) + }, + format: format + ) + currentSession = session + currentModel = model + return session + } - // Prepare input for model processing - let userInput = UserInput( - chat: chat, processing: .init(resize: .init(width: 1024, height: 1024))) + /// Reads `config.json` from the loaded container's snapshot directory + /// for the `model_type` and raw config dict that `ResponseFormat.infer` + /// needs. + /// + /// - TODO: Drop this helper (and the matching `modelType` / + /// `modelConfig` arguments to `ResponseChatSession`) once + /// `MLXLMCommon.ModelConfiguration` or `ModelContainer` exposes + /// the decoded `model_type` and raw config dict directly – the + /// loader already decodes both during `loadContainer` and + /// discards them. + private func readModelTypeAndConfig( + from container: ModelContainer + ) async throws -> (modelType: String?, modelConfig: [String: any Sendable]?) { + let directory = try await container.modelDirectory + let configURL = directory.appending(path: "config.json") + let data = try Data(contentsOf: configURL) + let json = try JSONSerialization.jsonObject(with: data) + guard let dict = json as? [String: any Sendable] else { return (nil, nil) } + return (dict["model_type"] as? String, dict) + } - // Generate response using the model - return try await modelContainer.perform { (context: ModelContext) in - let lmInput = try await context.processor.prepare(input: userInput) - // Set temperature for response randomness (0.7 provides good balance) - let parameters = GenerateParameters(temperature: 0.7) + /// Streams the model's response to the next prompt/media turn as a + /// sequence of Responses-API events. + /// + /// `history` carries the prior conversation (excluding the system prompt and + /// the new turn being submitted). It is used to seed a fresh session when the + /// selected model has changed since the previous call; otherwise the existing + /// session already knows the prior turns and `history` is ignored. + func generate( + history: [Chat.Message], + prompt: String, + images: [URL] = [], + videos: [URL] = [], + model: LMModel + ) async throws -> AsyncThrowingStream { + let session = try await session(for: model, history: history) + let userImages = images.map { UserInput.Image.url($0) } + let userVideos = videos.map { UserInput.Video.url($0) } - return try MLXLMCommon.generate( - input: lmInput, parameters: parameters, context: context) - } + return session.streamResponseEvents( + prompt: prompt, + images: userImages, + videos: userVideos + ) + } + + /// Drops the active session so the next call to ``generate(history:prompt:images:videos:model:)`` + /// builds a fresh one (with whatever history the caller passes at that time). + func clearSession() { + currentSession = nil + currentModel = nil } } diff --git a/Applications/MLXChatExample/Services/ToolRegistry.swift b/Applications/MLXChatExample/Services/ToolRegistry.swift new file mode 100644 index 00000000..288c11f4 --- /dev/null +++ b/Applications/MLXChatExample/Services/ToolRegistry.swift @@ -0,0 +1,80 @@ +// +// ToolRegistry.swift +// MLXChatExample +// + +import Foundation +import LMResponseParserMLX + +/// Tool palette advertised to `ResponseChatSession`. Both tools are +/// side-effect-free: `get_current_datetime` returns the formatted current +/// time, and `save_file` is a no-op stub whose long `content` parameter +/// gives the streaming-arguments view something substantial to render +/// token-by-token. Replace the `save_file` body with real I/O if you +/// want persistence; ``dispatch(_:)`` is the natural place to add +/// argument validation and policy checks. +@MainActor +struct ToolRegistry { + static let getCurrentDatetime: ToolSpec = [ + "type": "function", + "function": [ + "name": "get_current_datetime", + "description": "Get the current date and time as a formatted string.", + "parameters": [ + "type": "object", + "properties": [:] as [String: any Sendable], + "required": [] as [String], + ] as [String: any Sendable], + ] as [String: any Sendable], + ] + + static let saveFile: ToolSpec = [ + "type": "function", + "function": [ + "name": "save_file", + "description": + "Save a file with the given name and content. Returns a confirmation string.", + "parameters": [ + "type": "object", + "properties": [ + "name": [ + "type": "string", + "description": "File name to save under.", + ] as [String: any Sendable], + "content": [ + "type": "string", + "description": "Full text content of the file.", + ] as [String: any Sendable], + ] as [String: any Sendable], + "required": ["name", "content"] as [String], + ] as [String: any Sendable], + ] as [String: any Sendable], + ] + + static let allSpecs: [ToolSpec] = [getCurrentDatetime, saveFile] + + /// Dispatch a model-issued call. Unknown names and decode failures + /// return model-visible error strings so the next pass can correct, + /// rather than aborting the response. + static func dispatch(_ call: ResponseFunctionToolCall) async -> String { + switch call.name { + case "get_current_datetime": + return Date.now.formatted() + + case "save_file": + struct Args: Decodable { + let name: String + let content: String + } + do { + let args = try call.decodedArguments(as: Args.self) + return "Saved \(args.name) (\(args.content.count) characters)" + } catch { + return "Error: could not decode save_file arguments: \(error.localizedDescription)" + } + + default: + return "Error: unknown tool '\(call.name)'." + } + } +} diff --git a/Applications/MLXChatExample/ViewModels/ChatViewModel.swift b/Applications/MLXChatExample/ViewModels/ChatViewModel.swift index 893edb79..17129108 100644 --- a/Applications/MLXChatExample/ViewModels/ChatViewModel.swift +++ b/Applications/MLXChatExample/ViewModels/ChatViewModel.swift @@ -6,6 +6,7 @@ // import Foundation +import LMResponseParserMLX import MLXLMCommon import UniformTypeIdentifiers @@ -24,9 +25,14 @@ class ChatViewModel { /// Current user input text var prompt: String = "" - /// Chat history containing system, user, and assistant messages + /// Chat history containing system, user, and assistant messages. + /// + /// `messages` is the on-screen transcript and the source of truth for what + /// the model sees. ``MLXService`` reuses its active session as long as the + /// selected model does not change; when it does, the session is rebuilt and + /// seeded from this array so the new model continues the conversation. var messages: [Message] = [ - .system("You are a helpful assistant!") + .system(MLXService.systemPrompt) ] /// Currently selected language model for generation @@ -41,12 +47,14 @@ class ChatViewModel { /// Current generation task, used for cancellation private var generateTask: Task? - /// Stores performance metrics from the current generation - private var generateCompletionInfo: GenerateCompletionInfo? + /// Tokens per second for the most recently finalized turn, derived + /// from `ResponseChatSession`'s output token count and the turn's + /// wall-clock duration. `nil` until the first turn finalizes. + private(set) var tokensPerSecond: Double? - /// Current generation speed in tokens per second - var tokensPerSecond: Double { - generateCompletionInfo?.tokensPerSecond ?? 0 + /// Whether there is any user-visible chat history that can be cleared. + var canClearChat: Bool { + messages.contains { $0.role != .system } } /// Progress of the current model download, if any @@ -54,12 +62,16 @@ class ChatViewModel { mlxService.modelDownloadProgress } + /// Whether a model is currently being initialized into memory. + var isLoadingModel: Bool { + mlxService.isLoadingModel + } + /// Most recent error message, if any var errorMessage: String? /// Generates response for the current prompt and media attachments func generate() async { - // Cancel any existing generation task if let existingTask = generateTask { existingTask.cancel() generateTask = nil @@ -67,48 +79,121 @@ class ChatViewModel { isGenerating = true - // Add user message with any media attachments - messages.append(.user(prompt, images: mediaSelection.images, videos: mediaSelection.videos)) - // Add empty assistant message that will be filled during generation + // Capture the prompt/media before clearing the input. + let userPrompt = prompt + let userImages = mediaSelection.images + let userVideos = mediaSelection.videos + let model = selectedModel + + // Prior conversation excluding the system prompt (the session sets + // it via `instructions`). Only consumed when the service rebuilds + // its session after a model switch; otherwise ignored. + let history: [Chat.Message] = messages.compactMap { message in + switch message.role { + case .user: + return .user( + message.content, + images: message.images.map { .url($0) }, + videos: message.videos.map { .url($0) } + ) + case .assistant: + return .assistant(message.content) + case .system: + return nil + } + } + + messages.append(.user(userPrompt, images: userImages, videos: userVideos)) messages.append(.assistant("")) - // Clear the input after sending clear(.prompt) generateTask = Task { - // Process generation chunks and update UI - for await generation in try await mlxService.generate( - messages: messages, model: selectedModel) - { - switch generation { - case .chunk(let chunk): - // Append new text to the current assistant message - if let assistantMessage = messages.last { - assistantMessage.content += chunk + let stream = try await mlxService.generate( + history: history, + prompt: userPrompt, + images: userImages, + videos: userVideos, + model: model + ) + let startTime = Date.now + for try await event in stream { + guard let assistantMessage = messages.last else { continue } + switch event { + case .outputTextDelta(let delta): + appendText(.content, itemId: delta.itemId, delta: delta.delta, + to: assistantMessage) + + case .reasoningTextDelta(let delta): + appendText(.reasoning, itemId: delta.itemId, delta: delta.delta, + to: assistantMessage) + + case .outputItemAdded(let added): + switch added.item { + case .functionCall(let call): + assistantMessage.segments.append( + .toolCall( + ToolCall( + id: call.id, + callId: call.callId, + name: call.name, + argumentsRaw: call.arguments + ) + ) + ) + case .functionCallOutput(let output): + if let toolCall = findToolCall(callId: output.callId, + in: assistantMessage) { + toolCall.result = output.output.stringValue ?? "" + } + case .message, .reasoning: + break } - case .info(let info): - // Update performance metrics - generateCompletionInfo = info - case .toolCall(let call): + + case .functionCallArgumentsDelta(let delta): + if let toolCall = findToolCall(itemId: delta.itemId, + in: assistantMessage) { + toolCall.argumentsRaw += delta.delta + } + + default: break } } + if let outputTokens = mlxService.lastResponseOutputTokens { + let elapsed = Date.now.timeIntervalSince(startTime) + if elapsed > 0 { + tokensPerSecond = Double(outputTokens) / elapsed + } + } } do { - // Handle task completion and cancellation try await withTaskCancellationHandler { try await generateTask?.value } onCancel: { Task { @MainActor in generateTask?.cancel() - // Mark message as cancelled if let assistantMessage = messages.last { - assistantMessage.content += "\n[Cancelled]" + assistantMessage.segments.append( + .content(TextSegment(itemId: "_cancelled", text: "\n[Cancelled]")) + ) } + + // Drop the session so the next turn rebuilds from + // the visible history. The KV cache holds a partial + // assistant response with no end-of-turn marker; + // reusing it would feed the next call a malformed + // transcript. + mlxService.clearSession() } } + } catch is CancellationError { + // Stop, dismiss, or chat-clear mid-generation – not surfaced. + } catch let error as URLError where error.code == .cancelled { + // Same intent, raised from an in-flight URLSession (e.g. + // model download interrupted). } catch { errorMessage = error.localizedDescription } @@ -117,6 +202,52 @@ class ChatViewModel { generateTask = nil } + private enum TextSegmentKind { case content, reasoning } + + /// Append a delta to the latest segment if it matches kind and + /// itemId; otherwise open a new segment. Drives the interleaving of + /// reasoning, tool calls, and content in arrival order. + private func appendText( + _ kind: TextSegmentKind, + itemId: String, + delta: String, + to message: Message + ) { + if case let .reasoning(segment) = message.segments.last, + kind == .reasoning, segment.itemId == itemId + { + segment.text += delta + return + } + if case let .content(segment) = message.segments.last, + kind == .content, segment.itemId == itemId + { + segment.text += delta + return + } + let new = TextSegment(itemId: itemId, text: delta) + switch kind { + case .content: + message.segments.append(.content(new)) + case .reasoning: + message.segments.append(.reasoning(new)) + } + } + + private func findToolCall(itemId: String, in message: Message) -> ToolCall? { + for segment in message.segments { + if case let .toolCall(call) = segment, call.id == itemId { return call } + } + return nil + } + + private func findToolCall(callId: String, in message: Message) -> ToolCall? { + for segment in message.segments { + if case let .toolCall(call) = segment, call.callId == callId { return call } + } + return nil + } + /// Processes and adds media attachments to the current message func addMedia(_ result: Result) { do { @@ -143,12 +274,13 @@ class ChatViewModel { } if options.contains(.chat) { - messages = [] generateTask?.cancel() + messages = [.system(MLXService.systemPrompt)] + mlxService.clearSession() } if options.contains(.meta) { - generateCompletionInfo = nil + tokensPerSecond = nil } errorMessage = nil diff --git a/Applications/MLXChatExample/Views/MessageView.swift b/Applications/MLXChatExample/Views/MessageView.swift index cb5ba629..295faa97 100644 --- a/Applications/MLXChatExample/Views/MessageView.swift +++ b/Applications/MLXChatExample/Views/MessageView.swift @@ -58,25 +58,104 @@ struct MessageView: View { } case .assistant: - // Assistant messages are left-aligned without background - // LocalizedStringKey used to trigger default handling of markdown content. + // Segments are rendered in arrival order so reasoning runs, + // tool calls, and content interleave exactly as the parser + // surfaced them. Empty-after-trim text segments are skipped + // so VStack spacing doesn't reserve a row for them. HStack { - Text(LocalizedStringKey(message.content)) - .textSelection(.enabled) + VStack(alignment: .leading, spacing: 8) { + ForEach(message.segments) { segment in + switch segment { + case .reasoning(let textSegment): + let trimmed = textSegment.text.trimmingCharacters( + in: .whitespacesAndNewlines) + if !trimmed.isEmpty { + Text(trimmed) + .font(.callout.italic()) + .foregroundStyle(.secondary) + .textSelection(.enabled) + } + case .toolCall(let toolCall): + ToolCallCard(toolCall: toolCall) + case .content(let textSegment): + let trimmed = textSegment.text.trimmingCharacters( + in: .whitespacesAndNewlines) + if !trimmed.isEmpty { + // LocalizedStringKey triggers markdown rendering. + Text(LocalizedStringKey(trimmed)) + .textSelection(.enabled) + } + } + } + } Spacer() } case .system: - // System messages are centered with computer icon - Label(message.content, systemImage: "desktopcomputer") - .font(.headline) + // System messages are centered, prefixed for clarity + Text("\(Text("System prompt: ").font(.headline))\(message.content)") .foregroundColor(.secondary) .frame(maxWidth: .infinity, alignment: .center) } } } +/// Card showing one tool call's name, arguments, and result. Arguments +/// pretty-print once the streaming JSON parses; until then the raw +/// partial buffer is shown so the buildup is visible. +private struct ToolCallCard: View { + let toolCall: ToolCall + + /// `nil` when the call has no arguments (don't render the row). + private var formattedArguments: String? { + let raw = toolCall.argumentsRaw.trimmingCharacters(in: .whitespacesAndNewlines) + if raw.isEmpty || raw == "{}" || raw == "[]" { return nil } + guard let data = raw.data(using: .utf8), + let object = try? JSONSerialization.jsonObject(with: data), + let pretty = try? JSONSerialization.data( + withJSONObject: object, + options: [.prettyPrinted, .sortedKeys] + ), + let string = String(data: pretty, encoding: .utf8) + else { + return raw + } + return string + } + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 6) { + Text("Tool call:") + .font(.headline) + Text(toolCall.name) + .font(.subheadline.bold()) + } + + if let formattedArguments { + Text(formattedArguments) + .font(.caption.monospaced()) + .textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + } + + if let result = toolCall.result { + HStack(alignment: .firstTextBaseline, spacing: 6) { + Text("Result:") + .font(.headline) + Text(result) + .font(.caption) + .foregroundStyle(.secondary) + .textSelection(.enabled) + } + } + } + .padding(10) + .glassEffect(.regular, in: .rect(cornerRadius: 10)) + } +} + #Preview { VStack(spacing: 20) { MessageView(.system("You are a helpful assistant.")) diff --git a/Applications/MLXChatExample/Views/PromptField.swift b/Applications/MLXChatExample/Views/PromptField.swift index 7b3e465c..51f1a11e 100644 --- a/Applications/MLXChatExample/Views/PromptField.swift +++ b/Applications/MLXChatExample/Views/PromptField.swift @@ -19,7 +19,10 @@ struct PromptField: View { if let mediaButtonAction { Button(action: mediaButtonAction) { Image(systemName: "photo.badge.plus") + .padding(4) } + .buttonStyle(.glass) + .buttonBorderShape(.circle) } TextField("Prompt", text: $prompt) @@ -36,8 +39,12 @@ struct PromptField: View { } } } label: { - Image(systemName: isRunning ? "stop.circle.fill" : "paperplane.fill") + Image(systemName: isRunning ? "stop.fill" : "arrow.up") + .fontWeight(.bold) + .padding(4) } + .buttonStyle(.glassProminent) + .buttonBorderShape(.circle) .keyboardShortcut(isRunning ? .cancelAction : .defaultAction) } } diff --git a/Applications/MLXChatExample/Views/Toolbar/ChatToolbarView.swift b/Applications/MLXChatExample/Views/Toolbar/ChatToolbarView.swift index 06012eb3..7b4ece90 100644 --- a/Applications/MLXChatExample/Views/Toolbar/ChatToolbarView.swift +++ b/Applications/MLXChatExample/Views/Toolbar/ChatToolbarView.swift @@ -7,37 +7,68 @@ import SwiftUI -/// Toolbar view for the chat interface that displays error messages, download progress, +/// Toolbar content for the chat interface that displays error messages, download progress, /// generation statistics, and model selection controls. -struct ChatToolbarView: View { +struct ChatToolbarView: ToolbarContent { /// View model containing the chat state and controls @Bindable var vm: ChatViewModel - var body: some View { + var body: some ToolbarContent { // Display error message if present if let errorMessage = vm.errorMessage { - ErrorView(errorMessage: errorMessage) + ToolbarItem { + ErrorView(errorMessage: errorMessage) + } + } + + // Show download progress while bytes are flowing from the network + if let progress = vm.modelDownloadProgress { + ToolbarItem { + DownloadProgressView(progress: progress) + } + } else if vm.isLoadingModel { + // Otherwise, show a generic loading indicator while weights are + // being initialized into memory. + ToolbarItem { + ProgressView() + .controlSize(.small) + .help("Loading model") + } + .sharedBackgroundVisibility(.hidden) } - // Show download progress for model loading - if let progress = vm.modelDownloadProgress, !progress.isFinished { - DownloadProgressView(progress: progress) + // Generation statistics indicator (only shown after a generation has completed) + if let tokensPerSecond = vm.tokensPerSecond { + ToolbarItem { + GenerationInfoView( + tokensPerSecond: tokensPerSecond + ) + } + .sharedBackgroundVisibility(.hidden) } - // Button to clear chat history, displays generation statistics - Button { - vm.clear([.chat, .meta]) - } label: { - GenerationInfoView( - tokensPerSecond: vm.tokensPerSecond - ) + ToolbarSpacer(.fixed) + + // Button to clear chat history (only shown when there's something to clear) + if vm.canClearChat { + ToolbarItem { + Button { + vm.clear([.chat, .meta]) + } label: { + Image(systemName: "trash") + } + .help("Clear chat") + .disabled(vm.isGenerating) + } } // Model selection picker - Picker("Model", selection: $vm.selectedModel) { - ForEach(MLXService.availableModels) { model in - Text(model.displayName) - .tag(model) + ToolbarItem { + Picker("Model", selection: $vm.selectedModel) { + ForEach(MLXService.availableModels) { model in + Text(model.displayName) + .tag(model) + } } } } diff --git a/Applications/MLXChatExample/Views/Toolbar/DownloadProgressView.swift b/Applications/MLXChatExample/Views/Toolbar/DownloadProgressView.swift index d85e3e24..a5296421 100644 --- a/Applications/MLXChatExample/Views/Toolbar/DownloadProgressView.swift +++ b/Applications/MLXChatExample/Views/Toolbar/DownloadProgressView.swift @@ -12,25 +12,35 @@ struct DownloadProgressView: View { @State private var isShowingDownload = false + private var bytesText: String { + let completed = progress.completedUnitCount.formatted(.byteCount(style: .file)) + let total = progress.totalUnitCount.formatted(.byteCount(style: .file)) + return "\(completed) of \(total)" + } + + private var percentText: String { + progress.fractionCompleted.formatted(.percent.precision(.fractionLength(0))) + } + var body: some View { Button { isShowingDownload = true } label: { - Image(systemName: "arrow.down.square") + Image(systemName: "arrow.down") .foregroundStyle(.tint) } .popover(isPresented: $isShowingDownload, arrowEdge: .bottom) { VStack { ProgressView(value: progress.fractionCompleted) { HStack { - Text(progress.localizedAdditionalDescription) + Text(bytesText) .bold() Spacer() - Text(progress.localizedDescription) + Text(percentText) } } - Text("The model is downloading") + Text("Downloading...") .padding(.horizontal, 32) } .padding() diff --git a/mlx-swift-examples.xcodeproj/project.pbxproj b/mlx-swift-examples.xcodeproj/project.pbxproj index 648e81c0..e1b8ce9b 100644 --- a/mlx-swift-examples.xcodeproj/project.pbxproj +++ b/mlx-swift-examples.xcodeproj/project.pbxproj @@ -12,6 +12,7 @@ 0F5AD8002DB70E6300745C06 /* MLXLLM in Frameworks */ = {isa = PBXBuildFile; productRef = C32A17FC2CFFB98A0092A5B6 /* MLXLLM */; }; 0F5AD8012DB70E6300745C06 /* MLXVLM in Frameworks */ = {isa = PBXBuildFile; productRef = C32A17FE2CFFB98A0092A5B6 /* MLXVLM */; }; 81695B412BA373D300F260D8 /* MarkdownUI in Frameworks */ = {isa = PBXBuildFile; productRef = 81695B402BA373D300F260D8 /* MarkdownUI */; }; + 929AC89A2FA50D6C00618F9C /* LMResponseParserMLX in Frameworks */ = {isa = PBXBuildFile; productRef = 929AC8992FA50D6C00618F9C /* LMResponseParserMLX */; }; C3132C2E2DFB317C00270E8E /* MLXVLM in Frameworks */ = {isa = PBXBuildFile; productRef = C3132C2D2DFB317C00270E8E /* MLXVLM */; }; C3132C302DFB317C00270E8E /* MLXLLM in Frameworks */ = {isa = PBXBuildFile; productRef = C3132C2F2DFB317C00270E8E /* MLXLLM */; }; C3208E762DB1945D006AE6CA /* MLX in Frameworks */ = {isa = PBXBuildFile; productRef = C3208E752DB1945D006AE6CA /* MLX */; }; @@ -320,7 +321,10 @@ MLXChatExample/MLXChatExampleApp.swift, MLXChatExample/Models/LMModel.swift, MLXChatExample/Models/Message.swift, + MLXChatExample/Models/MessageSegment.swift, + MLXChatExample/Models/ToolCall.swift, MLXChatExample/Services/MLXService.swift, + MLXChatExample/Services/ToolRegistry.swift, MLXChatExample/Support/Assets.xcassets, "MLXChatExample/Support/HubApi+default.swift", "MLXChatExample/Support/Preview Content/Preview Assets.xcassets", @@ -411,6 +415,7 @@ 0F5AD8002DB70E6300745C06 /* MLXLLM in Frameworks */, C3EA7F732F8445EE0054AEA3 /* HuggingFace in Frameworks */, C3EA7F752F8445EE0054AEA3 /* Tokenizers in Frameworks */, + 929AC89A2FA50D6C00618F9C /* LMResponseParserMLX in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -632,6 +637,7 @@ C3EA7F722F8445EE0054AEA3 /* HuggingFace */, C3EA7F742F8445EE0054AEA3 /* Tokenizers */, C33944FC2F8970620054D57D /* MLXHuggingFace */, + 929AC8992FA50D6C00618F9C /* LMResponseParserMLX */, ); productName = MLXChatExample; productReference = 0F5AD7412DB70C0300745C06 /* MLXChatExample.app */; @@ -978,6 +984,7 @@ C3EA7F522F8431BE0054AEA3 /* XCRemoteSwiftPackageReference "swift-huggingface" */, C3EA7F532F8432080054AEA3 /* XCRemoteSwiftPackageReference "swift-transformers" */, C36941322F8F489800810A49 /* XCRemoteSwiftPackageReference "mlx-swift-lm" */, + 929AC8982FA50D6B00618F9C /* XCRemoteSwiftPackageReference "swift-lm-response-parser" */, ); productRefGroup = C39273752B606A0A00368D5D /* Products */; projectDirPath = ""; @@ -1274,13 +1281,13 @@ INFOPLIST_KEY_UILaunchScreen_Generation = YES; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; - IPHONEOS_DEPLOYMENT_TARGET = 18.0; + IPHONEOS_DEPLOYMENT_TARGET = 26.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); LOCALIZATION_PREFERS_STRING_CATALOGS = YES; - MACOSX_DEPLOYMENT_TARGET = 15.0; + MACOSX_DEPLOYMENT_TARGET = 26.0; MARKETING_VERSION = 1.0; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; @@ -1297,7 +1304,7 @@ SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2,7"; - XROS_DEPLOYMENT_TARGET = 2.0; + XROS_DEPLOYMENT_TARGET = 26.0; }; name = Debug; }; @@ -1335,13 +1342,13 @@ INFOPLIST_KEY_UILaunchScreen_Generation = YES; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; - IPHONEOS_DEPLOYMENT_TARGET = 18.0; + IPHONEOS_DEPLOYMENT_TARGET = 26.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); LOCALIZATION_PREFERS_STRING_CATALOGS = YES; - MACOSX_DEPLOYMENT_TARGET = 15.0; + MACOSX_DEPLOYMENT_TARGET = 26.0; MARKETING_VERSION = 1.0; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; @@ -1358,7 +1365,7 @@ SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2,7"; VALIDATE_PRODUCT = YES; - XROS_DEPLOYMENT_TARGET = 2.0; + XROS_DEPLOYMENT_TARGET = 26.0; }; name = Release; }; @@ -3302,6 +3309,14 @@ minimumVersion = 3.31.3; }; }; + 929AC8982FA50D6B00618F9C /* XCRemoteSwiftPackageReference "swift-lm-response-parser" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/DePasqualeOrg/swift-lm-response-parser"; + requirement = { + branch = main; + kind = branch; + }; + }; C36BEFF02BC32A8C002D4AFE /* XCRemoteSwiftPackageReference "Progress" */ = { isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/jkandzi/Progress.swift"; @@ -3356,6 +3371,11 @@ package = 81695B3F2BA373D300F260D8 /* XCRemoteSwiftPackageReference "swift-markdown-ui" */; productName = MarkdownUI; }; + 929AC8992FA50D6C00618F9C /* LMResponseParserMLX */ = { + isa = XCSwiftPackageProductDependency; + package = 929AC8982FA50D6B00618F9C /* XCRemoteSwiftPackageReference "swift-lm-response-parser" */; + productName = LMResponseParserMLX; + }; C3132C2D2DFB317C00270E8E /* MLXVLM */ = { isa = XCSwiftPackageProductDependency; package = C397D8F22CD2F60B00B87EE2 /* XCLocalSwiftPackageReference "Libraries/.." */; diff --git a/mlx-swift-examples.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/mlx-swift-examples.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index c895efc9..54a3f27a 100644 --- a/mlx-swift-examples.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/mlx-swift-examples.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "e538f345418093ec944f6af6ff98e1b0c1e736fb7c1f52379fbcf33a8ac26084", + "originHash" : "84fa6559ca7591a75da94453e25a70460565ddaafd4726a186dde27114c8caa8", "pins" : [ { "identity" : "eventsource", @@ -31,10 +31,10 @@ { "identity" : "mlx-swift-lm", "kind" : "remoteSourceControl", - "location" : "https://github.com/ml-explore/mlx-swift-lm.git", + "location" : "https://github.com/ml-explore/mlx-swift-lm", "state" : { - "revision" : "1c05248bb0899e2a7a4962b84d319cf12f4e12aa", - "version" : "3.31.3" + "branch" : "main", + "revision" : "7e2b7107be52ffbfe488f3c7987d3f52c1858b4b" } }, { @@ -127,6 +127,15 @@ "version" : "2.3.1" } }, + { + "identity" : "swift-lm-response-parser", + "kind" : "remoteSourceControl", + "location" : "https://github.com/DePasqualeOrg/swift-lm-response-parser", + "state" : { + "branch" : "main", + "revision" : "d6f2cad458762111e5b73579f4acc29afe530c3c" + } + }, { "identity" : "swift-markdown-ui", "kind" : "remoteSourceControl",