new features
This commit is contained in:
+253
-56
@@ -41,6 +41,7 @@ struct AIStudioApp: App {
|
||||
.task {
|
||||
await Task.yield()
|
||||
studio.open()
|
||||
try? await studio.refreshLocalMLXModels()
|
||||
}
|
||||
}
|
||||
.defaultSize(width: 1000, height: 700)
|
||||
@@ -53,6 +54,12 @@ struct AIStudioApp: App {
|
||||
Button("Cycle Workspace Mode") { mode = nextValue(mode) }.keyboardShortcut(StudioShortcut.workspaceMode.shortcut(in: shortcutData))
|
||||
}
|
||||
}
|
||||
Window("Training & Images", id: "creativeWorkspace") {
|
||||
CreativeWorkspace()
|
||||
.preferredColorScheme(theme.colorScheme)
|
||||
.tint(StudioCustomTheme.selected(customThemeID, in: customThemesData)?.accentColor ?? accent.color)
|
||||
}
|
||||
.defaultSize(width: 990, height: 690)
|
||||
Settings {
|
||||
StudioSettingsView(studio: studio)
|
||||
.preferredColorScheme(theme.colorScheme)
|
||||
@@ -67,6 +74,9 @@ struct AIStudioApp: App {
|
||||
}
|
||||
|
||||
struct ChatView: View {
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
@State private var checkedThinkingModel: ChatModelChoice?
|
||||
@State private var inspectedThinkingSupport = false
|
||||
@ObservedObject var studio: StudioModel
|
||||
@AppStorage("endpoint") private var endpoint = "http://127.0.0.1:11434"
|
||||
@AppStorage("ollamaModel") private var model = ""
|
||||
@@ -89,6 +99,8 @@ struct ChatView: View {
|
||||
@AppStorage("mlxPath") private var mlxPath = ""
|
||||
@AppStorage("thinking") private var thinking = Thinking.automatic
|
||||
@AppStorage("failover") private var failover = true
|
||||
@AppStorage("defaultCoreMLPath") private var defaultCoreMLPath = ""
|
||||
@AppStorage("defaultGGUFPath") private var defaultGGUFPath = ""
|
||||
@AppStorage("mlxOnly") private var mlxOnly = false
|
||||
@AppStorage("compatibleEnabled") private var compatibleEnabled = false
|
||||
@AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1"
|
||||
@@ -127,10 +139,13 @@ struct ChatView: View {
|
||||
@State private var newTitle = ""
|
||||
|
||||
@AppStorage(ChatModelChoice.settingsKey) private var chatModelData = Data()
|
||||
@AppStorage(GGUFModelMetadata.libraryKey) private var registeredGGUF = Data()
|
||||
@AppStorage("mlxRegisteredPaths") private var registeredMLX = Data()
|
||||
@AppStorage("managedMLXModels") private var managedMLX = Data()
|
||||
|
||||
private var defaultChatModel: ChatModelChoice {
|
||||
if !defaultCoreMLPath.isEmpty { return ChatModelChoice(backend: .coreML, model: defaultCoreMLPath) }
|
||||
if !defaultGGUFPath.isEmpty { return ChatModelChoice(backend: .gguf, model: defaultGGUFPath) }
|
||||
if mlxOnly { return ChatModelChoice(backend: .mlx, model: mlxPath) }
|
||||
if compatibleEnabled { return ChatModelChoice(backend: .compatible, model: compatibleModel) }
|
||||
return ChatModelChoice(backend: .ollama, model: model)
|
||||
@@ -138,6 +153,29 @@ struct ChatView: View {
|
||||
|
||||
private var chatChoices: [UUID: ChatModelChoice] { ChatModelChoice.read(chatModelData) }
|
||||
private var chatModel: ChatModelChoice { modelForChat(studio.selected) }
|
||||
private var thinkingModes: [Thinking] {
|
||||
let choice = chatModel
|
||||
let registered = choice.backend == .gguf && GGUFModelMetadata.library(in: registeredGGUF).contains {
|
||||
$0.path == choice.model && $0.supportsThinking
|
||||
}
|
||||
return ChatThinkingControl.options(backend: choice.backend,
|
||||
supportsLocalThinking: registered || (checkedThinkingModel == choice && inspectedThinkingSupport))
|
||||
}
|
||||
|
||||
private func inspectThinking(_ choice: ChatModelChoice) async {
|
||||
let supported = await Task.detached(priority: .utility) {
|
||||
guard !choice.model.isEmpty else { return false }
|
||||
switch choice.backend {
|
||||
case .mlx: return ThinkingOutput.supportsMLX(choice.model)
|
||||
case .gguf:
|
||||
return (try? GGUFModelMetadata.read(URL(fileURLWithPath: choice.model)).supportsThinking) == true
|
||||
case .ollama, .compatible, .coreML: return false
|
||||
}
|
||||
}.value
|
||||
guard !Task.isCancelled, chatModel == choice else { return }
|
||||
inspectedThinkingSupport = supported
|
||||
checkedThinkingModel = choice
|
||||
}
|
||||
private var backendName: String { chatModel.backend.rawValue }
|
||||
|
||||
private func modelForChat(_ id: UUID?) -> ChatModelChoice {
|
||||
@@ -159,9 +197,11 @@ struct ChatView: View {
|
||||
private var mlxChoices: [String] {
|
||||
let registered = (try? JSONDecoder().decode([String].self, from: registeredMLX)) ?? []
|
||||
let managed = (try? JSONDecoder().decode([CatalogModel].self, from: managedMLX)) ?? []
|
||||
let paths = (managed + CatalogModel.all).map { $0.localFolder.path } + registered + [mlxPath]
|
||||
let installed = paths.filter { !$0.isEmpty && MLXLibrary.isModel(at: URL(fileURLWithPath: $0)) }
|
||||
return Array(Set(installed)).sorted { $0.localizedStandardCompare($1) == .orderedAscending }
|
||||
let saved = (managed + CatalogModel.all).map { $0.localFolder.path } + registered + [mlxPath]
|
||||
let installed = saved.filter { !$0.isEmpty && MLXLibrary.isModel(at: URL(fileURLWithPath: $0)) }
|
||||
return Set((installed + studio.discoveredMLXPaths).map {
|
||||
URL(fileURLWithPath: $0).resolvingSymlinksInPath().path
|
||||
}).sorted { $0.localizedStandardCompare($1) == .orderedAscending }
|
||||
}
|
||||
|
||||
private func modelPicker(for id: UUID?, running: Bool) -> some View {
|
||||
@@ -204,15 +244,25 @@ struct ChatView: View {
|
||||
@State private var replacingFile = false
|
||||
@AppStorage("chatFileAccessFolder") private var chatFileScope = ""
|
||||
@AppStorage("chatFileWriteEnabled") private var chatFileWriteEnabled = false
|
||||
@State private var filePreview: ChatFilePreview?
|
||||
private struct PendingAttachment: Identifiable {
|
||||
let preview: ChatFilePreview
|
||||
let target: StudioModel
|
||||
let conversation: UUID?
|
||||
var id: UUID { preview.id }
|
||||
}
|
||||
@State private var filePreview: PendingAttachment?
|
||||
@State private var preparingFilePreview = false
|
||||
@State private var fileError = ""
|
||||
@State private var splitFileError = ""
|
||||
|
||||
var body: some View {
|
||||
NavigationSplitView(columnVisibility: $columns) {
|
||||
List(visibleChats, selection: $studio.selected) { chat in
|
||||
Label(chat.title, systemImage: "bubble.left").tag(chat.id)
|
||||
.contextMenu {
|
||||
Button("Export Chat as Markdown…", systemImage: "square.and.arrow.up") {
|
||||
exportChat(chat)
|
||||
}
|
||||
Button("Delete Chat", systemImage: "trash", role: .destructive) {
|
||||
chatToDelete = chat
|
||||
confirmDelete = true
|
||||
@@ -223,6 +273,9 @@ struct ChatView: View {
|
||||
.disabled(studio.running || splitStudio.running)
|
||||
.navigationSplitViewColumnWidth(min: 180, ideal: 235)
|
||||
.toolbar {
|
||||
Button("Training & Images", systemImage: "slider.horizontal.3") {
|
||||
openWindow(id: "creativeWorkspace")
|
||||
}
|
||||
Button("New Chat", systemImage: "square.and.pencil") {
|
||||
search = ""
|
||||
studio.newChat()
|
||||
@@ -233,6 +286,12 @@ struct ChatView: View {
|
||||
renaming = true
|
||||
}
|
||||
.disabled(studio.running || splitStudio.running || studio.selected == nil)
|
||||
Button("Export Chat as Markdown…", systemImage: "square.and.arrow.up") {
|
||||
if let chat = studio.conversations.first(where: { $0.id == studio.selected }) {
|
||||
exportChat(chat)
|
||||
}
|
||||
}
|
||||
.disabled(studio.running || splitStudio.running || studio.selected == nil)
|
||||
Button("Delete Chat", systemImage: "trash") {
|
||||
chatToDelete = studio.conversations.first { $0.id == studio.selected }
|
||||
confirmDelete = chatToDelete != nil
|
||||
@@ -286,7 +345,9 @@ struct ChatView: View {
|
||||
.sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) }
|
||||
.sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) }
|
||||
.sheet(isPresented: $showingWorkspace) { WorkspaceResourcesView(studio: studio) }
|
||||
.sheet(item: $filePreview) { preview in
|
||||
.sheet(item: $filePreview) { pending in
|
||||
let preview = pending.preview
|
||||
let target = pending.target
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text(preview.name).font(.headline)
|
||||
ScrollView {
|
||||
@@ -295,7 +356,7 @@ struct ChatView: View {
|
||||
.frame(maxWidth: 520, maxHeight: 260)
|
||||
.accessibilityLabel("Attachment preview")
|
||||
}
|
||||
if preview.imagePNG == nil || chatModel.backend == .mlx {
|
||||
if preview.imagePNG == nil || modelForChat(target.selected).backend == .mlx {
|
||||
Text(preview.text.isEmpty && preview.imagePNG != nil
|
||||
? "No readable text detected. Choose a vision-capable model to analyze this image."
|
||||
: preview.text)
|
||||
@@ -306,8 +367,10 @@ struct ChatView: View {
|
||||
Spacer()
|
||||
Button("Cancel") { filePreview = nil }.keyboardShortcut(.cancelAction)
|
||||
Button("Attach to Next Message") {
|
||||
studio.attachToolResult(name: preview.name, output: preview.text,
|
||||
isDocument: true, isPDF: preview.isPDF, imagePNG: preview.imagePNG)
|
||||
if target.selected == pending.conversation {
|
||||
target.attachToolResult(name: preview.name, output: preview.text,
|
||||
isDocument: true, isPDF: preview.isPDF, imagePNG: preview.imagePNG)
|
||||
}
|
||||
filePreview = nil
|
||||
}.keyboardShortcut(.defaultAction)
|
||||
}
|
||||
@@ -328,6 +391,8 @@ struct ChatView: View {
|
||||
}
|
||||
.onChange(of: studio.modelSelectionRevision) {
|
||||
let defaults = UserDefaults.standard
|
||||
defaultCoreMLPath = defaults.string(forKey: "defaultCoreMLPath") ?? ""
|
||||
defaultGGUFPath = defaults.string(forKey: "defaultGGUFPath") ?? ""
|
||||
mlxPath = defaults.string(forKey: "mlxPath") ?? ""
|
||||
model = defaults.string(forKey: "ollamaModel") ?? ""
|
||||
mlxOnly = defaults.bool(forKey: "mlxOnly")
|
||||
@@ -411,11 +476,13 @@ struct ChatView: View {
|
||||
.font(chatFont.font(size: chatSize))
|
||||
Divider()
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
let feedback = [showDebugOutput ? "" : splitStudio.webStatus, splitStudio.status]
|
||||
attachmentLabel(for: splitStudio)
|
||||
let feedback = [splitFileError, showDebugOutput ? "" : splitStudio.webStatus, splitStudio.status]
|
||||
.filter { !$0.isEmpty }.joined(separator: " · ")
|
||||
if !feedback.isEmpty { Text(feedback).font(.caption).foregroundStyle(.secondary) }
|
||||
ChatComposerInput(text: $splitStudio.prompt, canSend: !splitStudio.running, spellCheck: spellCheck,
|
||||
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendSplitMessage)
|
||||
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendSplitMessage,
|
||||
pasteAttachment: { pasteAttachment($0, into: splitStudio) })
|
||||
.frame(height: 54)
|
||||
HStack {
|
||||
resourceMenu(for: splitStudio)
|
||||
@@ -474,18 +541,7 @@ struct ChatView: View {
|
||||
.font(.caption)
|
||||
.disabled(studio.running)
|
||||
}
|
||||
if let attachment = studio.toolAttachment {
|
||||
HStack {
|
||||
Label("\(attachment.name) attached to next message", systemImage: "paperclip")
|
||||
if attachment.imagePNG != nil && chatModel.backend == .mlx {
|
||||
Text("Extracted text only").foregroundStyle(.secondary)
|
||||
}
|
||||
if chatModel.backend != .mlx { Text("Sent to \(backendName)").foregroundStyle(.secondary) }
|
||||
Spacer()
|
||||
Button("Remove", systemImage: "xmark.circle") { studio.removeToolAttachment() }
|
||||
}
|
||||
.font(.caption)
|
||||
}
|
||||
attachmentLabel(for: studio)
|
||||
let activity = [preparingFilePreview ? "Preparing attachment preview…" : fileError,
|
||||
showDebugOutput ? "" : studio.webStatus, studio.status].filter { !$0.isEmpty }
|
||||
if !activity.isEmpty {
|
||||
@@ -496,7 +552,8 @@ struct ChatView: View {
|
||||
Link("Open in Browser", destination: link).font(.caption)
|
||||
}
|
||||
ChatComposerInput(text: $studio.prompt, canSend: !studio.running, spellCheck: spellCheck,
|
||||
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendMessage)
|
||||
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendMessage,
|
||||
pasteAttachment: { pasteAttachment($0, into: studio) })
|
||||
.frame(height: 62)
|
||||
.padding(5)
|
||||
.background(.background, in: RoundedRectangle(cornerRadius: 8))
|
||||
@@ -541,16 +598,17 @@ struct ChatView: View {
|
||||
HStack(spacing: 10) {
|
||||
modelPicker(for: studio.selected, running: studio.running)
|
||||
Spacer()
|
||||
if chatModel.backend == .ollama || (chatModel.backend == .mlx && MLXThinking.supports(chatModel.model)) {
|
||||
let modes: [Thinking] = chatModel.backend == .mlx ? [.automatic, .off, .on] : Thinking.allCases
|
||||
Picker("Thinking", selection: Binding(
|
||||
get: { modes.contains(thinking) ? thinking : .automatic },
|
||||
set: { thinking = $0 }
|
||||
)) {
|
||||
ForEach(modes) { Text($0.rawValue.capitalized).tag($0) }
|
||||
}
|
||||
.fixedSize().disabled(studio.running)
|
||||
let modes = thinkingModes
|
||||
Picker("Thinking", selection: Binding(
|
||||
get: { modes.contains(thinking) ? thinking : .automatic },
|
||||
set: { thinking = $0 }
|
||||
)) {
|
||||
ForEach(modes) { Text($0.rawValue.capitalized).tag($0) }
|
||||
}
|
||||
.fixedSize()
|
||||
.disabled(studio.running || modes.count == 1)
|
||||
.help(modes.count == 1 ? "This backend controls its own thinking mode." : "Set thinking for the selected model.")
|
||||
.task(id: chatModel) { await inspectThinking(chatModel) }
|
||||
Toggle("Agents", isOn: $agentWorkflowEnabled)
|
||||
.toggleStyle(.checkbox)
|
||||
.fixedSize()
|
||||
@@ -572,6 +630,38 @@ struct ChatView: View {
|
||||
}
|
||||
.padding(16)
|
||||
}
|
||||
@ViewBuilder private func attachmentLabel(for target: StudioModel) -> some View {
|
||||
if let attachment = target.toolAttachment {
|
||||
let backend = modelForChat(target.selected).backend
|
||||
HStack {
|
||||
Label("\(attachment.name) attached to next message", systemImage: "paperclip")
|
||||
if backend != .mlx { Text("Sent to \(backend.rawValue)").foregroundStyle(.secondary) }
|
||||
else if attachment.imagePNG != nil { Text("Extracted text only").foregroundStyle(.secondary) }
|
||||
Spacer()
|
||||
Button("Remove", systemImage: "xmark.circle") { target.removeToolAttachment() }
|
||||
}
|
||||
.font(.caption)
|
||||
}
|
||||
}
|
||||
|
||||
private func exportChat(_ chat: Conversation) {
|
||||
let panel = NSSavePanel()
|
||||
panel.allowedContentTypes = [UTType(filenameExtension: "md") ?? .plainText]
|
||||
panel.canCreateDirectories = true
|
||||
let name = chat.title.components(separatedBy: CharacterSet.controlCharacters.union(CharacterSet(charactersIn: "/:")))
|
||||
.joined(separator: " ").trimmingCharacters(in: .whitespacesAndNewlines.union(CharacterSet(charactersIn: ".")))
|
||||
panel.nameFieldStringValue = (name.isEmpty ? "Chat" : String(name.prefix(80))) + ".md"
|
||||
panel.begin { response in
|
||||
guard response == .OK, let url = panel.url else { return }
|
||||
do {
|
||||
try studio.exportChat(chat.id, to: url)
|
||||
fileError = "Exported \(url.lastPathComponent)."
|
||||
} catch {
|
||||
fileError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func pickLocalFile() {
|
||||
let panel = NSOpenPanel()
|
||||
panel.canChooseFiles = true
|
||||
@@ -580,16 +670,27 @@ struct ChatView: View {
|
||||
panel.prompt = "Preview"
|
||||
panel.begin { response in
|
||||
guard response == .OK, let url = panel.url else { return }
|
||||
Task { @MainActor in
|
||||
let conversation = studio.selected
|
||||
preparingFilePreview = true
|
||||
fileError = ""
|
||||
defer { preparingFilePreview = false }
|
||||
do {
|
||||
let preview = try await Task.detached { try ChatFilePreview.read(url) }.value
|
||||
guard studio.selected == conversation, !studio.running else { return }
|
||||
filePreview = preview
|
||||
} catch { fileError = error.localizedDescription }
|
||||
pasteAttachment(.files([url]), into: studio)
|
||||
}
|
||||
}
|
||||
|
||||
private func pasteAttachment(_ item: ComposerPaste, into target: StudioModel) {
|
||||
guard !target.running, !preparingFilePreview, filePreview == nil else { return }
|
||||
let conversation = target.selected
|
||||
let isMain = target === studio
|
||||
preparingFilePreview = true
|
||||
if isMain { fileError = "" }
|
||||
else { splitFileError = "Preparing attachment preview…" }
|
||||
Task { @MainActor in
|
||||
defer { preparingFilePreview = false }
|
||||
do {
|
||||
let preview = try await Task.detached { try item.preview() }.value
|
||||
if !isMain { splitFileError = "" }
|
||||
guard target.selected == conversation, !target.running else { return }
|
||||
filePreview = PendingAttachment(preview: preview, target: target, conversation: conversation)
|
||||
} catch {
|
||||
if isMain { fileError = error.localizedDescription }
|
||||
else { splitFileError = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -632,7 +733,7 @@ struct ChatView: View {
|
||||
recall: recall, useDocuments: useDocuments, instructions: promptMode.instructions(custom: customPrompt),
|
||||
settings: GenerationSettings.read(generationSettings), agents: selectedAgents, agentTools: allowAgentTools,
|
||||
ragEnabled: ragEnabled, lmStudioPlugins: pluginsEnabled && pluginEndpoint == compatibleEndpoint
|
||||
? CompatibleEndpoint.pluginIDs(pluginIDs) : [])
|
||||
? CompatibleEndpoint.pluginIDs(pluginIDs) : [], gguf: choice.backend == .gguf, coreML: choice.backend == .coreML)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -750,6 +851,7 @@ private struct ChatModelPicker: View {
|
||||
let compatibleDefault: String
|
||||
let select: (ChatModelChoice?) -> Void
|
||||
|
||||
@AppStorage(CoreMLLibrary.key) private var coreMLLibrary = Data()
|
||||
@State private var showing = false
|
||||
@State private var compatibleModels: [String] = []
|
||||
@State private var compatibleStatus = ""
|
||||
@@ -759,11 +861,17 @@ private struct ChatModelPicker: View {
|
||||
Button {
|
||||
showing.toggle()
|
||||
} label: {
|
||||
Label(choice.displayName, systemImage: choice.backend == .mlx ? "cpu" : "server.rack")
|
||||
.lineLimit(1)
|
||||
HStack(spacing: 6) {
|
||||
Label(choice.displayName, systemImage: [.mlx, .gguf, .coreML].contains(choice.backend) ? "cpu" : "server.rack")
|
||||
.lineLimit(1)
|
||||
Text(choice.backend.rawValue)
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(.secondary)
|
||||
.fixedSize()
|
||||
}
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.accessibilityLabel("Chat model: " + choice.displayName)
|
||||
.accessibilityLabel("Chat model: \(choice.displayName), \(choice.backend.rawValue)")
|
||||
.help("Switch models for this conversation")
|
||||
.popover(isPresented: $showing) {
|
||||
Form {
|
||||
@@ -774,6 +882,14 @@ private struct ChatModelPicker: View {
|
||||
optionLabel("Use Default · " + defaultChoice.displayName, selected: !hasOverride)
|
||||
}
|
||||
}
|
||||
GGUFModels(selection: choice.backend == .gguf ? choice.model : nil) {
|
||||
choose(ChatModelChoice(backend: .gguf, model: $0))
|
||||
}
|
||||
if #available(macOS 15, *), !CoreMLLibrary.read(coreMLLibrary).isEmpty {
|
||||
Section("Core ML") {
|
||||
ForEach(CoreMLLibrary.read(coreMLLibrary)) { model in modelButton(.coreML, model.path) }
|
||||
}
|
||||
}
|
||||
Section("Ollama") {
|
||||
let installed = studio.modelListEndpoint == endpoint ? studio.models.map(\.name) : []
|
||||
ForEach(names(installed + [ollamaDefault]), id: \.self) { name in
|
||||
@@ -808,7 +924,7 @@ private struct ChatModelPicker: View {
|
||||
.formStyle(.grouped)
|
||||
.frame(width: 340, height: 420)
|
||||
.task {
|
||||
if studio.modelListEndpoint != endpoint { studio.refresh(endpoint: endpoint) }
|
||||
if choice.backend == .ollama && studio.modelListEndpoint != endpoint { studio.refresh(endpoint: endpoint) }
|
||||
}
|
||||
.onChange(of: compatibleEndpoint) {
|
||||
compatibleModels = []
|
||||
@@ -976,6 +1092,8 @@ struct BackendSettings: View {
|
||||
@AppStorage("ollamaModel") private var model = ""
|
||||
@AppStorage("mlxPath") private var mlxPath = ""
|
||||
@AppStorage("failover") private var failover = true
|
||||
@AppStorage("defaultCoreMLPath") private var defaultCoreMLPath = ""
|
||||
@AppStorage("defaultGGUFPath") private var defaultGGUFPath = ""
|
||||
@AppStorage("mlxOnly") private var mlxOnly = false
|
||||
@AppStorage("compatibleEnabled") private var compatibleEnabled = false
|
||||
@AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1"
|
||||
@@ -990,8 +1108,10 @@ struct BackendSettings: View {
|
||||
Form {
|
||||
Section("Inference") {
|
||||
Picker("Backend", selection: Binding(
|
||||
get: { mlxOnly ? "mlx" : (compatibleEnabled ? "compatible" : "ollama") },
|
||||
get: { !defaultCoreMLPath.isEmpty ? "coreML" : !defaultGGUFPath.isEmpty ? "gguf" : mlxOnly ? "mlx" : (compatibleEnabled ? "compatible" : "ollama") },
|
||||
set: { mode in
|
||||
if mode != "gguf" { defaultGGUFPath = "" }
|
||||
if mode != "coreML" { defaultCoreMLPath = "" }
|
||||
mlxOnly = mode == "mlx"
|
||||
compatibleEnabled = mode == "compatible"
|
||||
}
|
||||
@@ -999,11 +1119,14 @@ struct BackendSettings: View {
|
||||
Text("Prefer Ollama").tag("ollama")
|
||||
Text("OpenAI-compatible").tag("compatible")
|
||||
Text("MLX only").tag("mlx")
|
||||
if !defaultCoreMLPath.isEmpty { Text("Core ML").tag("coreML") }
|
||||
if !defaultGGUFPath.isEmpty { Text("Local GGUF").tag("gguf") }
|
||||
}
|
||||
Toggle("Fall back to MLX before output begins", isOn: $failover)
|
||||
.disabled(mlxOnly)
|
||||
.disabled(mlxOnly || !defaultGGUFPath.isEmpty || !defaultCoreMLPath.isEmpty)
|
||||
Toggle("Recall older matching messages in this conversation", isOn: $recall)
|
||||
}
|
||||
GGUFModels(selection: defaultGGUFPath, selectionDisabled: studio.running) { studio.selectGGUFModel($0) }
|
||||
Section("Ollama") {
|
||||
TextField("Server URL", text: $endpoint)
|
||||
.disabled(studio.managing)
|
||||
@@ -1030,11 +1153,13 @@ struct BackendSettings: View {
|
||||
Spacer()
|
||||
Text(ModelLibrarySize.label(entry.size))
|
||||
.foregroundStyle(.secondary).font(.caption)
|
||||
Button(model == entry.name && !mlxOnly && !compatibleEnabled ? "Selected" : "Use Model") {
|
||||
Button(defaultCoreMLPath.isEmpty && defaultGGUFPath.isEmpty && model == entry.name && !mlxOnly && !compatibleEnabled ? "Selected" : "Use Model") {
|
||||
model = entry.name
|
||||
defaultCoreMLPath = ""
|
||||
defaultGGUFPath = ""
|
||||
mlxOnly = false
|
||||
compatibleEnabled = false
|
||||
}.disabled(model == entry.name && !mlxOnly && !compatibleEnabled)
|
||||
}.disabled(defaultCoreMLPath.isEmpty && defaultGGUFPath.isEmpty && model == entry.name && !mlxOnly && !compatibleEnabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1066,7 +1191,7 @@ struct BackendSettings: View {
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.onAppear {
|
||||
if !mlxOnly && !compatibleEnabled && studio.modelListEndpoint != endpoint {
|
||||
if defaultCoreMLPath.isEmpty && defaultGGUFPath.isEmpty && !mlxOnly && !compatibleEnabled && studio.modelListEndpoint != endpoint {
|
||||
studio.refresh(endpoint: endpoint)
|
||||
}
|
||||
}
|
||||
@@ -1074,8 +1199,8 @@ struct BackendSettings: View {
|
||||
.fileImporter(isPresented: $pickingFolder, allowedContentTypes: [.folder]) { result in
|
||||
do {
|
||||
let url = try result.get()
|
||||
guard FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) else {
|
||||
throw StudioError("This folder does not contain an MLX config.json.")
|
||||
guard MLXLibrary.isModel(at: url) else {
|
||||
throw StudioError("Choose a complete model folder with a readable config.json and all safetensors weight files.")
|
||||
}
|
||||
mlxPath = url.path
|
||||
folderError = ""
|
||||
@@ -1973,6 +2098,68 @@ struct RuntimeSettingsView: View {
|
||||
}
|
||||
}
|
||||
|
||||
enum ComposerPaste: Equatable, Sendable {
|
||||
case files([URL])
|
||||
case image(Data)
|
||||
|
||||
@MainActor static func read(_ pasteboard: NSPasteboard) -> Self? {
|
||||
if pasteboard.types?.contains(.fileURL) == true,
|
||||
let urls = pasteboard.readObjects(forClasses: [NSURL.self],
|
||||
options: [.urlReadingFileURLsOnly: true]) as? [URL],
|
||||
!urls.isEmpty {
|
||||
return .files(urls)
|
||||
}
|
||||
if let type = imageType(on: pasteboard), let data = pasteboard.data(forType: type) {
|
||||
return .image(data)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@MainActor private static func imageType(on pasteboard: NSPasteboard) -> NSPasteboard.PasteboardType? {
|
||||
let types = pasteboard.types ?? []
|
||||
if let preferred = [NSPasteboard.PasteboardType.png, .tiff].first(where: types.contains) {
|
||||
return preferred
|
||||
}
|
||||
return types.first { UTType($0.rawValue)?.conforms(to: .image) == true }
|
||||
}
|
||||
|
||||
@MainActor static func isAvailable(on pasteboard: NSPasteboard) -> Bool {
|
||||
pasteboard.types?.contains(.fileURL) == true || imageType(on: pasteboard) != nil
|
||||
}
|
||||
|
||||
func preview() throws -> ChatFilePreview {
|
||||
switch self {
|
||||
case .files(let urls):
|
||||
guard urls.count == 1, let url = urls.first else {
|
||||
throw StudioError("Paste one file at a time.")
|
||||
}
|
||||
return try ChatFilePreview.read(url)
|
||||
case .image(let data):
|
||||
return try ChatFilePreview.pastedImage(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final class ComposerTextView: NSTextView {
|
||||
var pasteAttachment: ((ComposerPaste) -> Void)?
|
||||
|
||||
override func paste(_ sender: Any?) {
|
||||
if let pasteAttachment, let item = ComposerPaste.read(.general) {
|
||||
pasteAttachment(item)
|
||||
} else {
|
||||
super.paste(sender)
|
||||
}
|
||||
}
|
||||
|
||||
override func validateUserInterfaceItem(_ item: any NSValidatedUserInterfaceItem) -> Bool {
|
||||
if item.action == #selector(paste(_:)), isEditable, pasteAttachment != nil,
|
||||
ComposerPaste.isAvailable(on: .general) {
|
||||
return true
|
||||
}
|
||||
return super.validateUserInterfaceItem(item)
|
||||
}
|
||||
}
|
||||
|
||||
struct ChatComposerInput: NSViewRepresentable {
|
||||
@Binding var text: String
|
||||
var canSend: Bool
|
||||
@@ -1980,15 +2167,25 @@ struct ChatComposerInput: NSViewRepresentable {
|
||||
var autoCorrect: Bool
|
||||
var font: NSFont
|
||||
var send: () -> Void
|
||||
var pasteAttachment: (ComposerPaste) -> Void
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll = NSTextView.scrollableTextView()
|
||||
guard let editor = scroll.documentView as? NSTextView else { return scroll }
|
||||
let scroll = NSScrollView()
|
||||
scroll.hasVerticalScroller = true
|
||||
let editor = ComposerTextView(frame: scroll.contentView.bounds)
|
||||
editor.isVerticallyResizable = true
|
||||
editor.isHorizontallyResizable = false
|
||||
editor.autoresizingMask = [.width]
|
||||
editor.textContainer?.widthTracksTextView = true
|
||||
scroll.documentView = editor
|
||||
editor.isRichText = false
|
||||
editor.font = font
|
||||
editor.delegate = context.coordinator
|
||||
editor.pasteAttachment = { [weak coordinator = context.coordinator] item in
|
||||
coordinator?.parent.pasteAttachment(item)
|
||||
}
|
||||
editor.drawsBackground = false
|
||||
scroll.drawsBackground = false
|
||||
editor.setAccessibilityLabel("Message")
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
import Metal
|
||||
import CryptoKit
|
||||
|
||||
enum ModelMemoryBudget {
|
||||
static let gpu = MTLCreateSystemDefaultDevice().map { Int64($0.recommendedMaxWorkingSetSize) }
|
||||
static let system = Int64(ProcessInfo.processInfo.physicalMemory)
|
||||
|
||||
static func exceeds(bytes: Int64?, budget: Int64?) -> Bool {
|
||||
guard let bytes, let budget, budget > 0 else { return false }
|
||||
return bytes > budget
|
||||
}
|
||||
}
|
||||
|
||||
struct ModelMemoryWarning: View {
|
||||
let bytes: Int64?
|
||||
var coreML = false
|
||||
var mlx = false
|
||||
@AppStorage(MLXRuntimeLimits.weightKey) private var mlxGiB = 0
|
||||
|
||||
var body: some View {
|
||||
let configured = mlxGiB > 0 && mlxGiB <= Int64.max / 1_073_741_824 ? Int64(mlxGiB) * 1_073_741_824 : nil
|
||||
let overMLXLimit = mlx && ModelMemoryBudget.exceeds(bytes: bytes, budget: configured)
|
||||
if overMLXLimit || ModelMemoryBudget.exceeds(bytes: bytes, budget: coreML ? ModelMemoryBudget.system : ModelMemoryBudget.gpu) {
|
||||
Label(overMLXLimit ? "Exceeds MLX weight limit" : coreML ? "Exceeds Mac memory" : "Exceeds GPU memory budget",
|
||||
systemImage: "exclamationmark.triangle.fill")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(.red)
|
||||
.help("The model files alone exceed this budget. Generation also uses memory for context.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CoreMLLibrary: Codable, Identifiable, Sendable {
|
||||
static let key = "coreMLLibrary"
|
||||
let path: String
|
||||
let bytes: Int64
|
||||
var id: String { path }
|
||||
|
||||
static func read(_ data: Data) -> [Self] { (try? JSONDecoder().decode([Self].self, from: data)) ?? [] }
|
||||
|
||||
static func inspect(_ source: URL) throws -> Self {
|
||||
let extensions = ["mlpackage", "mlmodelc", "mlmodel"]
|
||||
var package = source.resolvingSymlinksInPath()
|
||||
guard package.isFileURL else { throw StudioError("Choose a local Core ML model.") }
|
||||
if !extensions.contains(package.pathExtension.lowercased()) {
|
||||
let entries = try FileManager.default.contentsOfDirectory(at: package, includingPropertiesForKeys: nil)
|
||||
.filter { extensions.contains($0.pathExtension.lowercased()) }
|
||||
guard entries.count == 1, let match = entries.first else {
|
||||
throw StudioError("Choose a Core ML model or a folder containing one model package.")
|
||||
}
|
||||
package = match
|
||||
}
|
||||
let tokenizer = package.deletingLastPathComponent()
|
||||
guard MLXLibrary.hasFile("tokenizer.json", in: tokenizer), MLXLibrary.hasFile("tokenizer_config.json", in: tokenizer) else {
|
||||
throw StudioError("Put the matching tokenizer.json and tokenizer_config.json beside the Core ML model.")
|
||||
}
|
||||
let manager = FileManager.default
|
||||
let properties: Set<URLResourceKey> = [.isRegularFileKey, .fileSizeKey]
|
||||
let values = try package.resourceValues(forKeys: properties)
|
||||
var size = Int64(values.fileSize ?? 0)
|
||||
if values.isRegularFile != true {
|
||||
size = 0
|
||||
if let entries = manager.enumerator(at: package, includingPropertiesForKeys: Array(properties)) {
|
||||
for case let file as URL in entries {
|
||||
let attributes = try file.resourceValues(forKeys: properties)
|
||||
if attributes.isRegularFile == true { size += Int64(attributes.fileSize ?? 0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
guard size > 0 else { throw StudioError("The Core ML package is empty.") }
|
||||
return Self(path: package.path, bytes: size)
|
||||
}
|
||||
}
|
||||
|
||||
struct CoreMLDownloads {
|
||||
static let repository = "apple/mistral-coreml"
|
||||
static let modelBytes: Int64 = 4_078_518_656
|
||||
static let package = "StatefulMistral7BInstructInt4.mlpackage"
|
||||
private static let hashes = [
|
||||
"model.mlmodel": "aa0d5b06e1fe50cbdb095b846c1f30fb69aef08550db309ef6fc48d43ea51ad6",
|
||||
"weight.bin": "1fa5158e6a1c5d3d131a1b08cb8dd3a4030c682a5fefa625e37a289f34d7a7ff"
|
||||
]
|
||||
|
||||
static func install(in destination: URL, progress: @escaping HubGGUFAsset.ProgressUpdate) async throws -> CoreMLLibrary {
|
||||
let checkpoint = destination.appending(path: package)
|
||||
if let installed = try? CoreMLLibrary.inspect(checkpoint) { return installed }
|
||||
let fileManager = FileManager.default
|
||||
let parent = destination.deletingLastPathComponent()
|
||||
try fileManager.createDirectory(at: parent, withIntermediateDirectories: true)
|
||||
let stage = parent.appending(path: ".download-" + UUID().uuidString)
|
||||
defer { try? fileManager.removeItem(at: stage) }
|
||||
let hf = URL(string: "https://huggingface.co")!
|
||||
let weights = hf.appending(path: "apple/mistral-coreml/resolve/ef561211ae2c829934011eec8b396776bf24df9b")
|
||||
let tokenizer = hf.appending(path: "mistralai/Mistral-7B-Instruct-v0.3/resolve/c170c708c41dac9275d15a8fff4eca08d52bab71")
|
||||
let files: [(URL, String, Int64)] = [
|
||||
(weights, package + "/Manifest.json", 617),
|
||||
(weights, package + "/Data/com.apple.CoreML/model.mlmodel", 984_023),
|
||||
(weights, package + "/Data/com.apple.CoreML/weights/weight.bin", 4_077_534_016),
|
||||
(tokenizer, "tokenizer.json", 1_961_548),
|
||||
(tokenizer, "tokenizer_config.json", 140_874),
|
||||
(tokenizer, "config.json", 601)
|
||||
]
|
||||
let total = files.reduce(0) { $0 + $1.2 }
|
||||
var written: Int64 = 0
|
||||
for (base, path, bytes) in files {
|
||||
try Task.checkCancellation()
|
||||
let file = stage.appending(path: path)
|
||||
try fileManager.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
let offset = written
|
||||
try await HubGGUFTransfer.download(base.appending(path: path), file) { count, _ in progress(offset + count, total) }
|
||||
guard try file.resourceValues(forKeys: [.fileSizeKey]).fileSize.map(Int64.init) == bytes else {
|
||||
throw StudioError("The Core ML download returned an unexpected file size.")
|
||||
}
|
||||
if let expected = hashes[file.lastPathComponent] {
|
||||
let handle = try FileHandle(forReadingFrom: file)
|
||||
defer { try? handle.close() }
|
||||
var hash = SHA256()
|
||||
while let chunk = try handle.read(upToCount: 1_048_576), !chunk.isEmpty {
|
||||
try Task.checkCancellation()
|
||||
hash.update(data: chunk)
|
||||
}
|
||||
guard hash.finalize().map({ String(format: "%02x", $0) }).joined() == expected else {
|
||||
throw StudioError("The Core ML download checksum does not match Hugging Face.")
|
||||
}
|
||||
}
|
||||
written += bytes
|
||||
}
|
||||
_ = try CoreMLLibrary.inspect(stage.appending(path: package))
|
||||
try Task.checkCancellation()
|
||||
try fileManager.moveItem(at: stage, to: destination)
|
||||
return try CoreMLLibrary.inspect(checkpoint)
|
||||
}
|
||||
}
|
||||
|
||||
struct CoreMLModels: View {
|
||||
let selection: String
|
||||
let disabled: Bool
|
||||
let select: (String) -> Void
|
||||
@AppStorage(CoreMLLibrary.key) private var stored = Data()
|
||||
@State private var importing = false
|
||||
@State private var status = ""
|
||||
@State private var search = ""
|
||||
@State private var searching = false
|
||||
@State private var results: [HubGGUFAsset.RepositoryResult] = []
|
||||
@State private var download: Task<Void, Never>?
|
||||
@State private var received: Int64 = 0
|
||||
@State private var total: Int64?
|
||||
|
||||
var body: some View {
|
||||
Section("Core ML") {
|
||||
if #available(macOS 15, *) {
|
||||
Button("Import Core ML Model…", systemImage: "plus") { importing = true }.disabled(disabled)
|
||||
ForEach(CoreMLLibrary.read(stored)) { model in
|
||||
HStack {
|
||||
VStack(alignment: .leading) {
|
||||
Text(URL(fileURLWithPath: model.path).deletingPathExtension().lastPathComponent)
|
||||
Text("Core ML · " + ModelLibrarySize.label(model.bytes)).font(.caption).foregroundStyle(.secondary)
|
||||
ModelMemoryWarning(bytes: model.bytes, coreML: true)
|
||||
}
|
||||
Spacer()
|
||||
Button(selection == model.path ? "Active" : "Use") { select(model.path) }
|
||||
.disabled(disabled || selection == model.path || !FileManager.default.fileExists(atPath: model.path))
|
||||
if selection != model.path {
|
||||
Button("Remove", systemImage: "minus.circle") {
|
||||
do { stored = try JSONEncoder().encode(CoreMLLibrary.read(stored).filter { $0.path != model.path }) }
|
||||
catch { status = error.localizedDescription }
|
||||
}.labelStyle(.iconOnly)
|
||||
}
|
||||
}
|
||||
}
|
||||
HStack {
|
||||
VStack(alignment: .leading) {
|
||||
Text("Apple Mistral 7B Instruct")
|
||||
Text("Core ML · Int4 · " + ModelLibrarySize.label(CoreMLDownloads.modelBytes))
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
ModelMemoryWarning(bytes: CoreMLDownloads.modelBytes, coreML: true)
|
||||
}
|
||||
Spacer()
|
||||
if let download { Button("Cancel") { download.cancel() } }
|
||||
else { Button("Download from Hugging Face", action: startDownload) }
|
||||
}
|
||||
if download != nil {
|
||||
if let total { ProgressView(value: Double(min(total, received)), total: Double(total)) }
|
||||
else { ProgressView("Starting download…") }
|
||||
}
|
||||
HStack {
|
||||
TextField("Search Hugging Face", text: $search, prompt: Text("Core ML text-generation models"))
|
||||
.onSubmit(find)
|
||||
Button(search.isEmpty ? "Browse" : "Search", action: find).disabled(searching)
|
||||
if searching { ProgressView().controlSize(.small) }
|
||||
}
|
||||
ForEach(results) { result in
|
||||
Link(result.id, destination: URL(string: "https://huggingface.co")!.appending(path: result.id))
|
||||
}
|
||||
if !status.isEmpty { Text(status).font(.caption).foregroundStyle(.secondary) }
|
||||
} else {
|
||||
Text("Core ML chat requires macOS 15 or later.").foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.fileImporter(isPresented: $importing, allowedContentTypes: [.folder] + ["mlpackage", "mlmodel", "mlmodelc"].compactMap { UTType(filenameExtension: $0) }) { result in
|
||||
do {
|
||||
let url = try result.get()
|
||||
let access = url.startAccessingSecurityScopedResource()
|
||||
defer { if access { url.stopAccessingSecurityScopedResource() } }
|
||||
try register(CoreMLLibrary.inspect(url))
|
||||
} catch { status = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
private func register(_ model: CoreMLLibrary) throws {
|
||||
stored = try JSONEncoder().encode(CoreMLLibrary.read(stored).filter { $0.path != model.path } + [model])
|
||||
status = "Core ML model added."
|
||||
}
|
||||
|
||||
private func find() {
|
||||
guard !searching else { return }
|
||||
searching = true
|
||||
status = ""
|
||||
Task {
|
||||
defer { searching = false }
|
||||
do {
|
||||
results = try await HubGGUFAsset.search(search.trimmingCharacters(in: .whitespaces), format: "coreml")
|
||||
if results.isEmpty { status = "No public Core ML text-generation models found." }
|
||||
} catch { status = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
private func startDownload() {
|
||||
received = 0
|
||||
total = nil
|
||||
status = ""
|
||||
download = Task {
|
||||
defer { download = nil }
|
||||
do {
|
||||
let path = URL.applicationSupportDirectory.appending(path: "AIStudio/Models/CoreML/Apple-Mistral-7B")
|
||||
let model = try await CoreMLDownloads.install(in: path) { written, expected in
|
||||
Task { @MainActor in
|
||||
guard download != nil, written >= received else { return }
|
||||
received = written
|
||||
total = expected
|
||||
}
|
||||
}
|
||||
try register(model)
|
||||
} catch {
|
||||
status = Task.isCancelled ? "Download cancelled." : error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import Foundation
|
||||
import CoreML
|
||||
import Tokenizers
|
||||
|
||||
enum CoreMLInputs {
|
||||
static func mask(queryCount: Int, pastCount: Int) -> [Float16] {
|
||||
let width = queryCount + pastCount
|
||||
return (0..<queryCount).flatMap { query in
|
||||
(0..<width).map { $0 > pastCount + query ? -Float16.greatestFiniteMagnitude : 0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CoreMLProvider: InferenceProvider {
|
||||
private static let engine = CoreMLEngine()
|
||||
|
||||
func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
|
||||
streaming { output in
|
||||
guard #available(macOS 15, *) else { throw StudioError("Core ML chat requires macOS 15 or later.") }
|
||||
try await Self.engine.generate(request, output: output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private actor CoreMLEngine {
|
||||
@available(macOS 15, *)
|
||||
func generate(_ request: InferenceRequest, output: AsyncThrowingStream<Delta, Error>.Continuation) async throws {
|
||||
guard !request.messages.contains(where: { $0.imagePNG != nil }), !request.parameters.json else {
|
||||
throw StudioError("Use text input and turn off JSON mode for this Core ML model.")
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
output.yield(.backend("Core ML"))
|
||||
let entry = try CoreMLLibrary.inspect(URL(fileURLWithPath: request.model))
|
||||
let package = URL(fileURLWithPath: entry.path)
|
||||
let compiled = package.pathExtension.lowercased() == "mlmodelc" ? package : try await MLModel.compileModel(at: package)
|
||||
defer { if compiled != package { try? FileManager.default.removeItem(at: compiled) } }
|
||||
let config = MLModelConfiguration()
|
||||
config.computeUnits = .cpuAndGPU
|
||||
let model = try await MLModel.load(contentsOf: compiled, configuration: config)
|
||||
let description = model.modelDescription
|
||||
let ids = description.inputDescriptionsByName["inputIds"]?.multiArrayConstraint
|
||||
let mask = description.inputDescriptionsByName["causalMask"]?.multiArrayConstraint
|
||||
let logits = description.outputDescriptionsByName["logits"]?.multiArrayConstraint
|
||||
guard Set(description.inputDescriptionsByName.keys) == ["inputIds", "causalMask"],
|
||||
ids?.dataType == .int32, mask?.dataType == .float16, logits != nil,
|
||||
!description.stateDescriptionsByName.isEmpty,
|
||||
let width = mask?.shapeConstraint.sizeRangeForDimension.last as? NSRange,
|
||||
width.location == 1, width.length > 1 else {
|
||||
throw StudioError("This package does not match the supported stateful Core ML chat model inputs.")
|
||||
}
|
||||
let tokenizer = try await AutoTokenizer.from(modelFolder: package.deletingLastPathComponent())
|
||||
let context = min(width.length, request.parameters.context ?? width.length)
|
||||
let outputReserve = min(request.parameters.maxTokens ?? 256, max(1, context / 4))
|
||||
let tokens = try preparePrompt(request.messages, tokenizer: tokenizer, capacity: context - outputReserve)
|
||||
let state = model.makeState()
|
||||
let limit = min(request.parameters.maxTokens ?? 256, context - tokens.count)
|
||||
var scores: MLMultiArray?
|
||||
for offset in stride(from: 0, to: tokens.count, by: 256) {
|
||||
try Task.checkCancellation()
|
||||
scores = try await predict(model, state: state, tokens: Array(tokens[offset..<min(tokens.count, offset + 256)]), past: offset)
|
||||
}
|
||||
var generated: [Int] = []
|
||||
var decoded = ""
|
||||
var stop = StopMatcher(sequences: request.parameters.stop)
|
||||
let start = ContinuousClock.now
|
||||
for index in 0..<limit {
|
||||
try Task.checkCancellation()
|
||||
if stop.stopped { break }
|
||||
guard let currentScores = scores else { throw StudioError("Core ML did not return token scores.") }
|
||||
let next = try choose(currentScores, parameters: request.parameters)
|
||||
if next == tokenizer.eosTokenId { break }
|
||||
generated.append(next)
|
||||
let text = tokenizer.decode(tokens: generated, skipSpecialTokens: true)
|
||||
let valid = String(text.reversed().drop(while: { $0 == "�" }).reversed())
|
||||
if valid.hasPrefix(decoded) {
|
||||
let visible = stop.append(String(valid.dropFirst(decoded.count)))
|
||||
decoded = valid
|
||||
if !visible.isEmpty { output.yield(.answer(visible)) }
|
||||
}
|
||||
if index + 1 < limit && !stop.stopped {
|
||||
scores = try await predict(model, state: state, tokens: [next], past: tokens.count + index)
|
||||
}
|
||||
}
|
||||
let remainder = stop.finish()
|
||||
if !remainder.isEmpty { output.yield(.answer(remainder)) }
|
||||
let elapsed = (ContinuousClock.now - start).components
|
||||
output.yield(.metrics(.init(tokens: generated.count, seconds: Double(elapsed.seconds) + Double(elapsed.attoseconds) / 1e18)))
|
||||
}
|
||||
|
||||
private func preparePrompt(_ messages: [Message], tokenizer: any Tokenizer, capacity: Int) throws -> [Int] {
|
||||
func encode(_ messages: [Message]) throws -> [Int] {
|
||||
do {
|
||||
return try tokenizer.applyChatTemplate(messages: messages.map {
|
||||
["role": $0.role.rawValue, "content": $0.content]
|
||||
})
|
||||
} catch {
|
||||
throw StudioError("The Core ML tokenizer could not render this chat. Check that its chat template matches the model.")
|
||||
}
|
||||
}
|
||||
|
||||
let normalized = LocalChatHistory.prepare(messages)
|
||||
var system = Array(normalized.prefix(while: { $0.role == .system }))
|
||||
var turns = Array(normalized.dropFirst(system.count))
|
||||
var tokens = try encode(system + turns)
|
||||
while tokens.count > capacity && turns.count > 1 {
|
||||
turns.removeFirst(min(2, turns.count - 1))
|
||||
tokens = try encode(system + turns)
|
||||
}
|
||||
if tokens.count > capacity, let instructions = system.first {
|
||||
let userTokens = try encode(turns)
|
||||
guard userTokens.count <= capacity else {
|
||||
throw StudioError("The latest message needs \(userTokens.count) tokens. This Core ML model has \(capacity) prompt tokens available.")
|
||||
}
|
||||
let characters = Array(instructions.content)
|
||||
var low = 0
|
||||
var high = characters.count
|
||||
tokens = userTokens
|
||||
while low < high {
|
||||
let length = low + (high - low + 1) / 2
|
||||
system[0].content = String(characters.prefix(length))
|
||||
let candidate = try encode(system + turns)
|
||||
if candidate.count <= capacity {
|
||||
tokens = candidate
|
||||
low = length
|
||||
} else {
|
||||
high = length - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
guard !tokens.isEmpty, tokens.count <= capacity else {
|
||||
throw StudioError("The Core ML prompt uses \(tokens.count) tokens. The available prompt budget is \(capacity).")
|
||||
}
|
||||
return tokens
|
||||
}
|
||||
|
||||
@available(macOS 15, *)
|
||||
private func predict(_ model: MLModel, state: MLState, tokens: [Int], past: Int) async throws -> MLMultiArray {
|
||||
let input = try MLMultiArray(shape: [1, NSNumber(value: tokens.count)], dataType: .int32)
|
||||
for (index, token) in tokens.enumerated() { input[index] = NSNumber(value: token) }
|
||||
let attention = try MLMultiArray(shape: [1, 1, NSNumber(value: tokens.count), NSNumber(value: past + tokens.count)], dataType: .float16)
|
||||
let values = CoreMLInputs.mask(queryCount: tokens.count, pastCount: past)
|
||||
attention.withUnsafeMutableBytes { buffer, _ in
|
||||
_ = buffer.bindMemory(to: Float16.self).update(from: values)
|
||||
}
|
||||
let features = try MLDictionaryFeatureProvider(dictionary: ["inputIds": input, "causalMask": attention])
|
||||
let result = try await model.prediction(from: features, using: state)
|
||||
guard let logits = result.featureValue(for: "logits")?.multiArrayValue else { throw StudioError("Core ML returned no logits.") }
|
||||
return logits
|
||||
}
|
||||
|
||||
private func choose(_ logits: MLMultiArray, parameters: GenerationParameters) throws -> Int {
|
||||
let dimensions = logits.shape.map(\.intValue)
|
||||
guard dimensions.count == 3, dimensions[0] == 1, dimensions[1] > 0, dimensions[2] > 0 else {
|
||||
throw StudioError("Core ML returned an unsupported logits shape.")
|
||||
}
|
||||
let position = NSNumber(value: dimensions[1] - 1)
|
||||
let scores = (0..<dimensions[2]).map { index in logits[[0, position, NSNumber(value: index)]].doubleValue }
|
||||
let temperature = parameters.temperature ?? 0
|
||||
guard let best = scores.indices.filter({ scores[$0].isFinite }).max(by: { scores[$0] < scores[$1] }) else {
|
||||
throw StudioError("Core ML returned invalid token scores.")
|
||||
}
|
||||
guard temperature > 0 else { return best }
|
||||
let candidates = scores.indices.filter { scores[$0].isFinite }.sorted { scores[$0] > scores[$1] }
|
||||
let top = candidates.prefix(max(1, parameters.topK.flatMap { $0 > 0 ? $0 : nil } ?? 50))
|
||||
let weights = top.map { exp((scores[$0] - scores[best]) / temperature) }
|
||||
let total = weights.reduce(0, +)
|
||||
let cutoff = total * (parameters.topP ?? 1)
|
||||
var mass = 0.0
|
||||
let retained = weights.prefix { weight in
|
||||
guard mass == 0 || mass < cutoff else { return false }
|
||||
mass += weight
|
||||
return true
|
||||
}
|
||||
var draw = Double.random(in: 0..<mass)
|
||||
for (token, weight) in zip(top, retained) {
|
||||
draw -= weight
|
||||
if draw <= 0 { return token }
|
||||
}
|
||||
return best
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import AppKit
|
||||
import ImageIO
|
||||
import ImagePlayground
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct StudioImagePreview: Sendable {
|
||||
let name: String
|
||||
let width: Int
|
||||
let height: Int
|
||||
let png: Data
|
||||
|
||||
init(data: Data, name: String, maxDimension: Int = 2048) throws {
|
||||
guard let source = CGImageSourceCreateWithData(data as CFData, nil),
|
||||
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
|
||||
let width = properties[kCGImagePropertyPixelWidth] as? Int,
|
||||
let height = properties[kCGImagePropertyPixelHeight] as? Int,
|
||||
let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [
|
||||
kCGImageSourceCreateThumbnailFromImageAlways: true,
|
||||
kCGImageSourceCreateThumbnailWithTransform: true,
|
||||
kCGImageSourceThumbnailMaxPixelSize: max(1, maxDimension)
|
||||
] as CFDictionary) else {
|
||||
throw StudioError("This file could not be opened as an image.")
|
||||
}
|
||||
let output = NSMutableData()
|
||||
guard let destination = CGImageDestinationCreateWithData(output, UTType.png.identifier as CFString, 1, nil) else {
|
||||
throw StudioError("Could not create the PNG preview.")
|
||||
}
|
||||
CGImageDestinationAddImage(destination, image, nil)
|
||||
guard CGImageDestinationFinalize(destination) else { throw StudioError("Could not encode the PNG preview.") }
|
||||
self.name = name
|
||||
self.width = width
|
||||
self.height = height
|
||||
self.png = output as Data
|
||||
}
|
||||
}
|
||||
|
||||
struct CreativeWorkspace: View {
|
||||
private enum Area: String, CaseIterable, Identifiable {
|
||||
case training = "Training"
|
||||
case images = "Images"
|
||||
var id: Self { self }
|
||||
var icon: String { self == .training ? "cpu" : "photo" }
|
||||
}
|
||||
|
||||
@State private var area: Area = .training
|
||||
@AppStorage("mlxRegisteredPaths") private var registered = Data()
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 0) {
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
ForEach(Area.allCases) { item in
|
||||
Button { area = item } label: {
|
||||
Label(item.rawValue, systemImage: item.icon)
|
||||
.font(.headline)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.horizontal, 12)
|
||||
.padding(.vertical, 9)
|
||||
.background(area == item ? Color.accentColor.opacity(0.15) : .clear,
|
||||
in: RoundedRectangle(cornerRadius: 8))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityAddTraits(area == item ? .isSelected : [])
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
.padding(12)
|
||||
.frame(width: 158)
|
||||
.background(.regularMaterial)
|
||||
Divider()
|
||||
ZStack {
|
||||
ModelWorkshopView(workshop: ModelWorkshop(base: nil), embedded: true, register: register)
|
||||
.opacity(area == .training ? 1 : 0)
|
||||
.allowsHitTesting(area == .training)
|
||||
.accessibilityHidden(area != .training)
|
||||
ImageWorkspace()
|
||||
.opacity(area == .images ? 1 : 0)
|
||||
.allowsHitTesting(area == .images)
|
||||
.accessibilityHidden(area != .images)
|
||||
}
|
||||
}
|
||||
.frame(minWidth: 835, minHeight: 560)
|
||||
}
|
||||
|
||||
private func register(_ url: URL) {
|
||||
let paths = (try? JSONDecoder().decode([String].self, from: registered)) ?? []
|
||||
let updated = Set(paths + [url.resolvingSymlinksInPath().path]).sorted()
|
||||
if let data = try? JSONEncoder().encode(updated) { registered = data }
|
||||
}
|
||||
}
|
||||
|
||||
private struct ImageWorkspace: View {
|
||||
@State private var prompt = ""
|
||||
@State private var preview: StudioImagePreview?
|
||||
@State private var importing = false
|
||||
@State private var status = ""
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 0) {
|
||||
VStack(alignment: .leading, spacing: 14) {
|
||||
Text("Images").font(.largeTitle.weight(.semibold))
|
||||
Text("Image description").font(.headline)
|
||||
TextField("Describe the image to generate", text: $prompt, axis: .vertical)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.lineLimit(3...6)
|
||||
if #available(macOS 15.1, *) {
|
||||
PlaygroundAction(prompt: prompt) { receive($0) }
|
||||
} else {
|
||||
Label("Image generation requires Image Playground.", systemImage: "info.circle")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
Divider()
|
||||
Button("Open Image…", systemImage: "folder") { importing = true }
|
||||
Button("Export Preview PNG…", systemImage: "square.and.arrow.up", action: export)
|
||||
.disabled(preview == nil)
|
||||
if !status.isEmpty {
|
||||
Text(status).font(.callout).foregroundStyle(.secondary).textSelection(.enabled)
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
.padding(24)
|
||||
.frame(width: 280)
|
||||
Divider()
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
Text("Preview").font(.headline)
|
||||
Spacer()
|
||||
if let preview {
|
||||
Text("\(preview.width) × \(preview.height) px")
|
||||
.monospacedDigit().foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
if let preview, let image = NSImage(data: preview.png) {
|
||||
Image(nsImage: image).resizable().scaledToFit()
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.accessibilityLabel(preview.name)
|
||||
} else {
|
||||
ContentUnavailableView("No image selected", systemImage: "photo.on.rectangle",
|
||||
description: Text("Generate an image or open one to preview."))
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
.padding(24)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(Color(nsColor: .controlBackgroundColor))
|
||||
}
|
||||
.fileImporter(isPresented: $importing, allowedContentTypes: [.image]) {
|
||||
switch $0 {
|
||||
case .success(let url): receive(url)
|
||||
case .failure(let error): status = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func receive(_ url: URL) {
|
||||
let access = url.startAccessingSecurityScopedResource()
|
||||
defer { if access { url.stopAccessingSecurityScopedResource() } }
|
||||
do {
|
||||
preview = try StudioImagePreview(data: Data(contentsOf: url, options: .mappedIfSafe),
|
||||
name: url.deletingPathExtension().lastPathComponent)
|
||||
status = ""
|
||||
} catch { status = error.localizedDescription }
|
||||
}
|
||||
|
||||
private func export() {
|
||||
guard let preview else { return }
|
||||
let panel = NSSavePanel()
|
||||
panel.allowedContentTypes = [.png]
|
||||
panel.nameFieldStringValue = preview.name + "-preview.png"
|
||||
guard panel.runModal() == .OK, let url = panel.url else { return }
|
||||
do {
|
||||
try preview.png.write(to: url, options: .atomic)
|
||||
status = "Saved \(url.lastPathComponent)"
|
||||
} catch { status = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 15.1, *)
|
||||
private struct PlaygroundAction: View {
|
||||
let prompt: String
|
||||
let completion: (URL) -> Void
|
||||
@Environment(\.supportsImagePlayground) private var supported
|
||||
@State private var showing = false
|
||||
|
||||
var body: some View {
|
||||
let description = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if supported {
|
||||
Button("Generate Image", systemImage: "sparkles") { showing = true }
|
||||
.buttonStyle(.borderedProminent)
|
||||
.disabled(description.isEmpty)
|
||||
.imagePlaygroundSheet(isPresented: $showing, concepts: [.text(description)], onCompletion: completion)
|
||||
} else {
|
||||
Label("Image Playground is unavailable on this Mac.", systemImage: "info.circle")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
import CryptoKit
|
||||
|
||||
struct HubGGUFAsset: Identifiable, Equatable, Sendable {
|
||||
let repository: String
|
||||
let revision: String
|
||||
let filename: String
|
||||
let bytes: Int64?
|
||||
let sha256: String?
|
||||
|
||||
var id: String { repository + "@" + revision + "/" + filename }
|
||||
|
||||
var url: URL {
|
||||
URL(string: "https://huggingface.co")!
|
||||
.appending(path: repository).appending(path: "resolve/\(revision)/\(filename)")
|
||||
}
|
||||
|
||||
var destination: URL {
|
||||
URL.applicationSupportDirectory
|
||||
.appending(path: "AIStudio/Models/GGUF/\(repository)/\(revision)/\(filename)")
|
||||
}
|
||||
|
||||
struct RepositoryResult: Decodable, Identifiable {
|
||||
let id: String
|
||||
let downloads: Int?
|
||||
let gated: CatalogModel.HubGating?
|
||||
let isPrivate: Bool?
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, downloads, gated
|
||||
case isPrivate = "private"
|
||||
}
|
||||
}
|
||||
|
||||
static func search(_ query: String, format: String = "gguf") async throws -> [RepositoryResult] {
|
||||
var parts = URLComponents()
|
||||
parts.scheme = "https"
|
||||
parts.host = "huggingface.co"
|
||||
parts.path = "/api/models"
|
||||
parts.queryItems = [
|
||||
.init(name: "filter", value: format), .init(name: "pipeline_tag", value: "text-generation"),
|
||||
.init(name: "sort", value: "downloads"), .init(name: "direction", value: "-1"),
|
||||
.init(name: "limit", value: "25"), .init(name: "search", value: query),
|
||||
.init(name: "expand", value: "downloads"), .init(name: "expand", value: "gated"),
|
||||
.init(name: "expand", value: "private")
|
||||
]
|
||||
guard let url = parts.url else { throw StudioError("Invalid Hugging Face search.") }
|
||||
let response = try await WebFetch.load(url, types: ["application/json"])
|
||||
return try decodeSearch(response.data)
|
||||
}
|
||||
|
||||
static func decodeSearch(_ data: Data) throws -> [RepositoryResult] {
|
||||
var seen = Set<String>()
|
||||
return try JSONDecoder().decode([RepositoryResult].self, from: data).filter {
|
||||
CatalogModel.repositoryParts($0.id) != nil && $0.gated != .restricted &&
|
||||
$0.isPrivate != true && seen.insert($0.id.lowercased()).inserted
|
||||
}
|
||||
}
|
||||
|
||||
static func resolve(_ repository: String) async throws -> [Self] {
|
||||
guard CatalogModel.repositoryParts(repository) != nil else {
|
||||
throw StudioError("Enter a Hugging Face model ID in owner/model format.")
|
||||
}
|
||||
var parts = URLComponents()
|
||||
parts.scheme = "https"
|
||||
parts.host = "huggingface.co"
|
||||
parts.path = "/api/models/" + repository
|
||||
parts.queryItems = [.init(name: "blobs", value: "true")]
|
||||
guard let url = parts.url else { throw StudioError("Invalid Hugging Face model ID.") }
|
||||
let response = try await WebFetch.load(url, types: ["application/json"])
|
||||
return try decodeRepository(response.data, requested: repository)
|
||||
}
|
||||
|
||||
static func decodeRepository(_ data: Data, requested: String) throws -> [Self] {
|
||||
struct Repository: Decodable {
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, sha, gated, siblings
|
||||
case isPrivate = "private"
|
||||
}
|
||||
|
||||
let id: String
|
||||
let sha: String
|
||||
let isPrivate: Bool?
|
||||
let gated: CatalogModel.HubGating?
|
||||
let siblings: [HubModelMetadata.File]
|
||||
}
|
||||
|
||||
let info = try JSONDecoder().decode(Repository.self, from: data)
|
||||
guard info.id.caseInsensitiveCompare(requested) == .orderedSame,
|
||||
CatalogModel.repositoryParts(info.id) != nil, isHex(info.sha, count: 40),
|
||||
info.isPrivate != true, info.gated != .restricted else {
|
||||
throw StudioError("Select a public Hugging Face GGUF repository.")
|
||||
}
|
||||
|
||||
var seen = Set<String>()
|
||||
let models: [Self] = info.siblings.compactMap { file in
|
||||
let name = file.rfilename
|
||||
let lowercase = name.lowercased()
|
||||
guard CatalogModel.safeComponent(name), lowercase.hasSuffix(".gguf"),
|
||||
!lowercase.hasPrefix("mmproj"), !lowercase.contains("adapter"),
|
||||
lowercase.range(of: #"-[0-9]{5}-of-[0-9]{5}\.gguf$"#, options: .regularExpression) == nil,
|
||||
seen.insert(name).inserted else { return nil }
|
||||
let bytes = file.lfs?.size ?? file.size
|
||||
let sha = file.lfs?.sha256.flatMap { isHex($0, count: 64) ? $0.lowercased() : nil }
|
||||
return Self(repository: info.id, revision: info.sha, filename: name,
|
||||
bytes: bytes.flatMap { $0 > 0 ? $0 : nil }, sha256: sha)
|
||||
}
|
||||
guard !models.isEmpty else { throw StudioError("This repository has no standalone GGUF model files.") }
|
||||
return models.sorted { $0.filename.localizedStandardCompare($1.filename) == .orderedAscending }
|
||||
}
|
||||
|
||||
private static func isHex(_ text: String, count: Int) -> Bool {
|
||||
text.count == count && text.allSatisfy { $0.isASCII && $0.isHexDigit }
|
||||
}
|
||||
|
||||
typealias ProgressUpdate = @Sendable (Int64, Int64?) -> Void
|
||||
typealias Transfer = @Sendable (URL, URL, @escaping ProgressUpdate) async throws -> Void
|
||||
|
||||
func install(to destination: URL, progress: @escaping ProgressUpdate,
|
||||
transfer: Transfer = HubGGUFTransfer.download) async throws -> GGUFModelMetadata {
|
||||
let manager = FileManager.default
|
||||
let parent = destination.deletingLastPathComponent()
|
||||
try manager.createDirectory(at: parent, withIntermediateDirectories: true)
|
||||
if manager.fileExists(atPath: destination.path) {
|
||||
return try validatedModel(at: destination)
|
||||
}
|
||||
|
||||
let staging = parent.appending(path: ".download-\(UUID())")
|
||||
defer { try? manager.removeItem(at: staging) }
|
||||
try await transfer(url, staging, { written, expected in progress(written, self.bytes ?? expected) })
|
||||
try Task.checkCancellation()
|
||||
let model = try validatedModel(at: staging)
|
||||
try Task.checkCancellation()
|
||||
try manager.moveItem(at: staging, to: destination)
|
||||
return GGUFModelMetadata(path: destination.resolvingSymlinksInPath().path, version: model.version,
|
||||
tensorFormat: model.tensorFormat, architecture: model.architecture,
|
||||
hasThinkingTemplate: model.hasThinkingTemplate)
|
||||
}
|
||||
|
||||
private func validatedModel(at file: URL) throws -> GGUFModelMetadata {
|
||||
let fileSize = try file.resourceValues(forKeys: [.fileSizeKey]).fileSize.map(Int64.init)
|
||||
if let bytes, fileSize != bytes {
|
||||
throw StudioError("The downloaded file size does not match the repository metadata.")
|
||||
}
|
||||
if let sha256 {
|
||||
let handle = try FileHandle(forReadingFrom: file)
|
||||
defer { try? handle.close() }
|
||||
var digest = SHA256()
|
||||
while let chunk = try handle.read(upToCount: 1_048_576), !chunk.isEmpty {
|
||||
try Task.checkCancellation()
|
||||
digest.update(data: chunk)
|
||||
}
|
||||
let actual = digest.finalize().map { String(format: "%02x", $0) }.joined()
|
||||
guard actual == sha256 else { throw StudioError("The download checksum does not match Hugging Face.") }
|
||||
}
|
||||
return try GGUFModelMetadata.read(file)
|
||||
}
|
||||
}
|
||||
|
||||
enum HubGGUFTransfer {
|
||||
static let download: HubGGUFAsset.Transfer = { source, destination, progress in
|
||||
let config = URLSessionConfiguration.ephemeral
|
||||
config.timeoutIntervalForRequest = 60
|
||||
config.timeoutIntervalForResource = 3600
|
||||
let result = AsyncThrowingStream<Void, Error>.makeStream()
|
||||
let observer = Observer(destination: destination, progress: progress, result: result.continuation)
|
||||
let session = URLSession(configuration: config, delegate: observer, delegateQueue: nil)
|
||||
defer { session.finishTasksAndInvalidate() }
|
||||
|
||||
let task = session.downloadTask(with: source)
|
||||
// Wait for the delegate to release the temporary file even if the caller cancels.
|
||||
let completion = Task.detached { for try await _ in result.stream {} }
|
||||
try await withTaskCancellationHandler {
|
||||
task.resume()
|
||||
try await completion.value
|
||||
} onCancel: {
|
||||
task.cancel()
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
}
|
||||
|
||||
private final class Observer: NSObject, URLSessionDownloadDelegate {
|
||||
let destination: URL
|
||||
let progress: HubGGUFAsset.ProgressUpdate
|
||||
let result: AsyncThrowingStream<Void, Error>.Continuation
|
||||
|
||||
init(destination: URL, progress: @escaping HubGGUFAsset.ProgressUpdate,
|
||||
result: AsyncThrowingStream<Void, Error>.Continuation) {
|
||||
self.destination = destination
|
||||
self.progress = progress
|
||||
self.result = result
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
|
||||
didFinishDownloadingTo location: URL) {
|
||||
guard let http = downloadTask.response as? HTTPURLResponse,
|
||||
http.statusCode == 200, http.url?.scheme == "https" else {
|
||||
let status = (downloadTask.response as? HTTPURLResponse).map { " (HTTP \($0.statusCode))" } ?? ""
|
||||
result.finish(throwing: StudioError("Could not download the GGUF file\(status)."))
|
||||
return
|
||||
}
|
||||
do { try FileManager.default.moveItem(at: location, to: destination) }
|
||||
catch { result.finish(throwing: error) }
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
|
||||
result.finish(throwing: error)
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
|
||||
totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
|
||||
progress(totalBytesWritten, totalBytesExpectedToWrite > 0 ? totalBytesExpectedToWrite : nil)
|
||||
}
|
||||
|
||||
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
|
||||
newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
|
||||
completionHandler(request.url?.scheme == "https" ? request : nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct HubGGUFDownloads: View {
|
||||
@AppStorage(GGUFModelMetadata.libraryKey) private var stored = Data()
|
||||
@State private var repository = ""
|
||||
@State private var repositories: [HubGGUFAsset.RepositoryResult] = []
|
||||
@State private var assets: [HubGGUFAsset] = []
|
||||
@State private var lookupInProgress = false
|
||||
@State private var download: Task<Void, Never>?
|
||||
@State private var downloadingID: String?
|
||||
@State private var written: Int64 = 0
|
||||
@State private var expected: Int64?
|
||||
@State private var notice: String?
|
||||
@State private var failure: String?
|
||||
|
||||
var body: some View {
|
||||
Section("Hugging Face · GGUF") {
|
||||
HStack {
|
||||
TextField("Search Hugging Face", text: $repository, prompt: Text("Model name or owner/model"))
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.onSubmit(lookup)
|
||||
Button(repository.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? "Browse" : "Search", action: lookup)
|
||||
.disabled(lookupInProgress || download != nil)
|
||||
if lookupInProgress { ProgressView().controlSize(.small) }
|
||||
}
|
||||
ForEach(repositories) { result in
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text(result.id).lineLimit(1).help(result.id)
|
||||
if let downloads = result.downloads {
|
||||
Text("\(downloads.formatted()) downloads").font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
Button("View Files") { lookup(result.id) }.disabled(lookupInProgress || download != nil)
|
||||
}
|
||||
}
|
||||
ForEach(assets) { asset in
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text(asset.filename).fontWeight(.medium).lineLimit(1).help(asset.filename)
|
||||
Text("GGUF · " + ModelLibrarySize.label(asset.bytes))
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
ModelMemoryWarning(bytes: asset.bytes)
|
||||
}
|
||||
Spacer()
|
||||
if downloadingID == asset.id {
|
||||
Button("Cancel") { download?.cancel() }
|
||||
} else if isRegistered(asset) {
|
||||
Label("Installed", systemImage: "checkmark.circle.fill").foregroundStyle(.secondary)
|
||||
} else {
|
||||
Button("Download") { start(asset) }.disabled(download != nil)
|
||||
}
|
||||
}
|
||||
if downloadingID == asset.id {
|
||||
let label = ByteCountFormatter.string(fromByteCount: written, countStyle: .file)
|
||||
if let expected, expected > 0 {
|
||||
ProgressView(label, value: Double(min(written, expected)), total: Double(expected))
|
||||
.accessibilityLabel("Downloading " + asset.filename)
|
||||
} else {
|
||||
ProgressView("Downloading · " + label)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 3)
|
||||
}
|
||||
if let notice { Label(notice, systemImage: "checkmark.circle").foregroundStyle(.secondary) }
|
||||
if let failure { Label(failure, systemImage: "exclamationmark.triangle").foregroundStyle(.orange) }
|
||||
}
|
||||
}
|
||||
|
||||
private func isRegistered(_ asset: HubGGUFAsset) -> Bool {
|
||||
let path = asset.destination.resolvingSymlinksInPath().path
|
||||
return GGUFModelMetadata.library(in: stored).contains { $0.path == path } &&
|
||||
FileManager.default.fileExists(atPath: path)
|
||||
}
|
||||
|
||||
private func lookup() { lookup(repository) }
|
||||
|
||||
private func lookup(_ term: String) {
|
||||
let query = term.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !lookupInProgress, download == nil else { return }
|
||||
lookupInProgress = true
|
||||
failure = nil
|
||||
notice = nil
|
||||
assets = []
|
||||
repositories = []
|
||||
Task {
|
||||
defer { lookupInProgress = false }
|
||||
do {
|
||||
if query.contains("/") {
|
||||
repository = query
|
||||
assets = try await HubGGUFAsset.resolve(query)
|
||||
} else {
|
||||
repositories = try await HubGGUFAsset.search(query)
|
||||
if repositories.isEmpty { notice = "No public GGUF repositories found." }
|
||||
}
|
||||
} catch { failure = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
private func start(_ asset: HubGGUFAsset) {
|
||||
guard download == nil else { return }
|
||||
downloadingID = asset.id
|
||||
written = 0
|
||||
expected = asset.bytes
|
||||
notice = nil
|
||||
failure = nil
|
||||
download = Task {
|
||||
defer {
|
||||
download = nil
|
||||
downloadingID = nil
|
||||
}
|
||||
do {
|
||||
let model = try await asset.install(to: asset.destination, progress: { bytes, expectedBytes in
|
||||
Task { @MainActor in
|
||||
guard downloadingID == asset.id, bytes >= written else { return }
|
||||
written = bytes
|
||||
expected = expectedBytes
|
||||
}
|
||||
})
|
||||
stored = try GGUFModelMetadata.register([model], in: stored)
|
||||
notice = "Installed \(asset.filename)"
|
||||
} catch {
|
||||
if Task.isCancelled { notice = "Download cancelled" }
|
||||
else { failure = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import Foundation
|
||||
|
||||
enum GGUFHeader {
|
||||
enum ValidationError: LocalizedError {
|
||||
case invalidMagic
|
||||
case unsupportedVersion(UInt32)
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidMagic: "The file does not have a valid GGUF header."
|
||||
case .unsupportedVersion(let version): "GGUF version \(version) is unsupported."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static func version(in data: Data) throws -> UInt32 {
|
||||
guard data.count >= 8, data.prefix(4).elementsEqual("GGUF".utf8) else {
|
||||
throw ValidationError.invalidMagic
|
||||
}
|
||||
let version = data.withUnsafeBytes { bytes in
|
||||
UInt32(littleEndian: bytes.loadUnaligned(fromByteOffset: 4, as: UInt32.self))
|
||||
}
|
||||
guard version == 2 || version == 3 else {
|
||||
throw ValidationError.unsupportedVersion(version)
|
||||
}
|
||||
return version
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
import Metal
|
||||
import llama
|
||||
|
||||
struct GGUFModelMetadata: Codable, Equatable, Sendable {
|
||||
static let libraryKey = "ggufLibrary"
|
||||
|
||||
let path: String
|
||||
let version: UInt32
|
||||
let tensorFormat: String
|
||||
let architecture: String
|
||||
var hasThinkingTemplate: Bool? = nil
|
||||
|
||||
var supportsThinking: Bool {
|
||||
hasThinkingTemplate ?? ["qwen35", "qwen35moe"].contains(architecture)
|
||||
}
|
||||
|
||||
var architectureName: String {
|
||||
switch architecture {
|
||||
case "llama": "Llama"
|
||||
case "qwen35", "qwen35moe": "Qwen3.5"
|
||||
case "mpt": "MPT"
|
||||
case "openelm": "OpenELM"
|
||||
default: architecture
|
||||
}
|
||||
}
|
||||
|
||||
static func library(in data: Data) -> [Self] {
|
||||
(try? JSONDecoder().decode([Self].self, from: data)) ?? []
|
||||
}
|
||||
|
||||
static func register(_ additions: [Self], in data: Data) throws -> Data {
|
||||
var entries = library(in: data)
|
||||
for model in additions {
|
||||
entries.removeAll { $0.path == model.path }
|
||||
entries.append(model)
|
||||
}
|
||||
return try JSONEncoder().encode(entries.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending })
|
||||
}
|
||||
|
||||
static func read(_ url: URL) throws -> Self {
|
||||
let file = try FileHandle(forReadingFrom: url)
|
||||
defer { try? file.close() }
|
||||
let version = try GGUFHeader.version(in: file.read(upToCount: 8) ?? Data())
|
||||
guard let model = gguf_init_from_file(url.path, .init(no_alloc: true, ctx: nil)) else {
|
||||
throw StudioError("Could not read the GGUF metadata.")
|
||||
}
|
||||
defer { gguf_free(model) }
|
||||
|
||||
let architectureKey = gguf_find_key(model, "general.architecture")
|
||||
let tensorCount = gguf_get_n_tensors(model)
|
||||
guard tensorCount > 0, architectureKey >= 0, gguf_get_kv_type(model, architectureKey) == GGUF_TYPE_STRING,
|
||||
let architecture = gguf_get_val_str(model, architectureKey) else {
|
||||
throw StudioError("This GGUF file does not contain model weights and architecture metadata.")
|
||||
}
|
||||
let templateKey = gguf_find_key(model, "tokenizer.chat_template")
|
||||
guard templateKey >= 0, gguf_get_kv_type(model, templateKey) == GGUF_TYPE_STRING,
|
||||
let template = gguf_get_val_str(model, templateKey), template.pointee != 0 else {
|
||||
throw StudioError("This model has no embedded chat template. Choose a GGUF chat or instruct model.")
|
||||
}
|
||||
let fileSize = try file.seekToEnd()
|
||||
let dataOffset = UInt64(gguf_get_data_offset(model))
|
||||
guard dataOffset < fileSize else { throw StudioError("This GGUF file is incomplete.") }
|
||||
let dataSize = fileSize - dataOffset
|
||||
var bytesByType: [String: UInt64] = [:]
|
||||
for index in 0..<tensorCount {
|
||||
let type = String(cString: ggml_type_name(gguf_get_tensor_type(model, index))).uppercased()
|
||||
let offset = UInt64(gguf_get_tensor_offset(model, index))
|
||||
let size = UInt64(gguf_get_tensor_size(model, index))
|
||||
guard offset <= dataSize, size <= dataSize - offset,
|
||||
bytesByType[type, default: 0] <= dataSize - size else {
|
||||
throw StudioError("This GGUF file contains incomplete tensor data.")
|
||||
}
|
||||
bytesByType[type, default: 0] += size
|
||||
}
|
||||
let primary = bytesByType.sorted {
|
||||
$0.value == $1.value ? $0.key < $1.key : $0.value > $1.value
|
||||
}.first?.key ?? "Unknown"
|
||||
return Self(path: url.path, version: version, tensorFormat: primary, architecture: String(cString: architecture),
|
||||
hasThinkingTemplate: GGUFThinking.supports(String(cString: template)))
|
||||
}
|
||||
}
|
||||
|
||||
enum LocalModelImport: Equatable, Sendable {
|
||||
case mlx(String)
|
||||
case gguf(GGUFModelMetadata)
|
||||
|
||||
static var lmStudioFolder: URL { URL.homeDirectory.appending(path: ".lmstudio/models") }
|
||||
|
||||
static func discover(in folder: URL) throws -> [Self] {
|
||||
let files = FileManager.default
|
||||
guard let entries = files.enumerator(at: folder, includingPropertiesForKeys: [.isDirectoryKey],
|
||||
options: [.skipsHiddenFiles, .skipsPackageDescendants]) else {
|
||||
throw StudioError("Could not open the model library folder.")
|
||||
}
|
||||
var models: [Self] = []
|
||||
for case let url as URL in entries {
|
||||
try Task.checkCancellation()
|
||||
if (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true {
|
||||
if MLXLibrary.isModel(at: url) {
|
||||
models.append(.mlx(url.resolvingSymlinksInPath().path))
|
||||
entries.skipDescendants()
|
||||
}
|
||||
} else if url.pathExtension.lowercased() == "gguf",
|
||||
!url.lastPathComponent.lowercased().hasPrefix("mmproj"),
|
||||
let model = try? inspect(url) {
|
||||
models.append(model)
|
||||
}
|
||||
}
|
||||
return models
|
||||
}
|
||||
|
||||
static func inspect(_ source: URL) throws -> Self {
|
||||
guard source.isFileURL else { throw StudioError("Choose a local model file or folder.") }
|
||||
let scoped = source.startAccessingSecurityScopedResource()
|
||||
defer { if scoped { source.stopAccessingSecurityScopedResource() } }
|
||||
let url = source.resolvingSymlinksInPath().standardizedFileURL
|
||||
let values = try url.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey])
|
||||
if values.isDirectory == true {
|
||||
guard MLXLibrary.isModel(at: url) else {
|
||||
throw StudioError("Choose a complete MLX folder with a readable configuration and all safetensors weights.")
|
||||
}
|
||||
return .mlx(url.path)
|
||||
}
|
||||
guard values.isRegularFile == true else {
|
||||
throw StudioError("Choose a regular GGUF file or an MLX model folder.")
|
||||
}
|
||||
return .gguf(try GGUFModelMetadata.read(url))
|
||||
}
|
||||
}
|
||||
|
||||
struct GGUFModels: View {
|
||||
let selection: String?
|
||||
var inUse = false
|
||||
var filter = ""
|
||||
var selectionDisabled = false
|
||||
let select: (String) -> Void
|
||||
@AppStorage(GGUFModelMetadata.libraryKey) private var stored = Data()
|
||||
@State private var showingImporter = false
|
||||
@State private var inspecting = false
|
||||
@State private var error: String?
|
||||
@State private var notice: String?
|
||||
|
||||
private var models: [GGUFModelMetadata] {
|
||||
GGUFModelMetadata.library(in: stored)
|
||||
}
|
||||
|
||||
private var filteredModels: [GGUFModelMetadata] {
|
||||
let query = filter.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return models.filter { model in
|
||||
query.isEmpty || [URL(fileURLWithPath: model.path).lastPathComponent,
|
||||
model.architectureName, model.tensorFormat, "GGUF"].contains {
|
||||
$0.localizedStandardContains(query)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Section {
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Label("Local GGUF", systemImage: "cpu")
|
||||
.font(.headline)
|
||||
memorySummary
|
||||
}
|
||||
Spacer()
|
||||
Button("Import…", systemImage: "plus") { showingImporter = true }
|
||||
.disabled(inspecting)
|
||||
.accessibilityLabel("Import GGUF model")
|
||||
}
|
||||
if models.isEmpty && !inspecting {
|
||||
Text("Import a GGUF chat model to run it on this Mac.")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
if !models.isEmpty && filteredModels.isEmpty {
|
||||
Text("No matching GGUF models").foregroundStyle(.secondary)
|
||||
}
|
||||
ForEach(filteredModels, id: \.path) { model in
|
||||
modelRow(model)
|
||||
}
|
||||
if inspecting {
|
||||
ProgressView("Inspecting model…").controlSize(.small)
|
||||
} else if let error {
|
||||
Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.orange)
|
||||
} else if let notice {
|
||||
Label(notice, systemImage: "checkmark.circle").foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.fileImporter(isPresented: $showingImporter, allowedContentTypes: [UTType(filenameExtension: "gguf") ?? .data]) {
|
||||
switch $0 {
|
||||
case .success(let url): Task { await importModel(url) }
|
||||
case .failure(let failure): error = failure.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var memorySummary: some View {
|
||||
let systemMemory = ByteCountFormatter.string(fromByteCount: Int64(ProcessInfo.processInfo.physicalMemory), countStyle: .memory)
|
||||
let recommended = MTLCreateSystemDefaultDevice().map {
|
||||
ByteCountFormatter.string(fromByteCount: Int64($0.recommendedMaxWorkingSetSize), countStyle: .memory)
|
||||
}
|
||||
return Text(recommended.map { "Metal budget \($0) · Unified memory \(systemMemory)" } ?? "Metal unavailable")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.help("Metal budget is the GPU’s recommended working set. Model weights and the context cache share system memory.")
|
||||
}
|
||||
|
||||
private func importModel(_ url: URL) async {
|
||||
inspecting = true
|
||||
error = nil
|
||||
notice = nil
|
||||
defer { inspecting = false }
|
||||
do {
|
||||
let metadata = try await Task.detached(priority: .userInitiated) {
|
||||
guard case .gguf(let model) = try LocalModelImport.inspect(url) else {
|
||||
throw StudioError("Choose a GGUF chat model file.")
|
||||
}
|
||||
return model
|
||||
}.value
|
||||
stored = try GGUFModelMetadata.register([metadata], in: stored)
|
||||
notice = "Added \(url.lastPathComponent)"
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private func modelRow(_ model: GGUFModelMetadata) -> some View {
|
||||
let url = URL(fileURLWithPath: model.path)
|
||||
let name = url.deletingPathExtension().lastPathComponent
|
||||
let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize
|
||||
let active = selection.map {
|
||||
URL(fileURLWithPath: $0).resolvingSymlinksInPath().standardizedFileURL.path ==
|
||||
url.resolvingSymlinksInPath().standardizedFileURL.path
|
||||
} ?? false
|
||||
return HStack(spacing: 11) {
|
||||
Image(systemName: active ? "checkmark.circle.fill" : "shippingbox")
|
||||
.font(.title3)
|
||||
.foregroundStyle(active ? Color.accentColor : Color.secondary)
|
||||
.frame(width: 24)
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(name).fontWeight(active ? .semibold : .regular).lineLimit(1)
|
||||
Text([
|
||||
"GGUF v\(model.version)", model.architectureName, model.tensorFormat,
|
||||
size.map { ByteCountFormatter.string(fromByteCount: Int64($0), countStyle: .file) } ?? "File missing"
|
||||
].joined(separator: " · "))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.help("Architecture: \(model.architecture). Quantisation shows the tensor format that accounts for the most weight bytes.")
|
||||
ModelMemoryWarning(bytes: size.map(Int64.init))
|
||||
}
|
||||
Spacer()
|
||||
if active {
|
||||
Text(inUse ? "In use" : "Active")
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(Color.accentColor)
|
||||
.padding(.horizontal, 8)
|
||||
.padding(.vertical, 4)
|
||||
.background(Color.accentColor.opacity(0.12), in: Capsule())
|
||||
} else {
|
||||
Button("Use") { select(model.path) }.disabled(size == nil || selectionDisabled)
|
||||
Button {
|
||||
do { stored = try JSONEncoder().encode(models.filter { $0.path != model.path }) }
|
||||
catch { self.error = error.localizedDescription }
|
||||
} label: {
|
||||
Image(systemName: "minus.circle")
|
||||
}
|
||||
.buttonStyle(.borderless)
|
||||
.disabled(selectionDisabled)
|
||||
.accessibilityLabel("Remove \(name) from library")
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 6)
|
||||
.listRowBackground(active ? Color.accentColor.opacity(0.10) : nil)
|
||||
.help(model.path)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import Foundation
|
||||
import llama
|
||||
|
||||
struct GGUFProvider: InferenceProvider {
|
||||
private static let engine = GGUFEngine()
|
||||
|
||||
func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
|
||||
streaming { continuation in
|
||||
try await Self.engine.generate(request, continuation)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private actor GGUFEngine {
|
||||
init() { llama_backend_init() }
|
||||
|
||||
func generate(_ request: InferenceRequest, _ output: AsyncThrowingStream<Delta, Error>.Continuation) throws {
|
||||
try Task.checkCancellation()
|
||||
guard !request.messages.contains(where: { $0.imagePNG != nil }) else {
|
||||
throw StudioError("This GGUF backend supports text input.")
|
||||
}
|
||||
guard !request.parameters.json else {
|
||||
throw StudioError("JSON mode is unavailable for local GGUF chat. Turn it off in Generation settings.")
|
||||
}
|
||||
guard ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU) != nil else { throw StudioError("Metal acceleration is unavailable.") }
|
||||
let file = URL(fileURLWithPath: request.model)
|
||||
guard FileManager.default.isReadableFile(atPath: file.path) else {
|
||||
throw StudioError("Cannot read \(file.lastPathComponent). Import the model again if it was moved.")
|
||||
}
|
||||
var modelSettings = llama_model_default_params()
|
||||
modelSettings.n_gpu_layers = .max
|
||||
guard let model = llama_model_load_from_file(request.model, modelSettings) else {
|
||||
throw StudioError("llama.cpp could not load \(file.lastPathComponent). Check that the download is complete and the file contains chat model weights.")
|
||||
}
|
||||
defer { llama_model_free(model) }
|
||||
try Task.checkCancellation()
|
||||
let vocab = llama_model_get_vocab(model)
|
||||
let formatted = try format(LocalChatHistory.prepare(request.messages), model: model)
|
||||
let thinking = GGUFThinking.prepare(formatted.prompt, template: formatted.template, mode: request.thinking)
|
||||
let prompt = thinking.prompt
|
||||
var thinkingOutput = ThinkingOutput(prefilled: thinking.prefilled)
|
||||
func emit(_ text: String) {
|
||||
if thinking.supported {
|
||||
for delta in thinkingOutput.append(text) { output.yield(delta) }
|
||||
} else if !text.isEmpty {
|
||||
output.yield(.answer(text))
|
||||
}
|
||||
}
|
||||
var tokens = [llama_token](repeating: 0, count: prompt.utf8.count + 32)
|
||||
var count = tokenize(prompt, vocab: vocab, tokens: &tokens)
|
||||
if count < 0 {
|
||||
tokens = [llama_token](repeating: 0, count: -Int(count))
|
||||
count = tokenize(prompt, vocab: vocab, tokens: &tokens)
|
||||
}
|
||||
|
||||
let settings = request.parameters
|
||||
var contextSettings = llama_context_default_params()
|
||||
contextSettings.n_ctx = UInt32(min(settings.context ?? 4096, Int(llama_model_n_ctx_train(model))))
|
||||
contextSettings.n_batch = min(512, contextSettings.n_ctx)
|
||||
contextSettings.n_ubatch = min(contextSettings.n_ubatch, contextSettings.n_batch)
|
||||
guard count > 0, UInt32(count) < contextSettings.n_ctx else {
|
||||
throw StudioError("The prompt exceeds the GGUF model’s context window.")
|
||||
}
|
||||
guard let context = llama_init_from_model(model, contextSettings) else {
|
||||
throw StudioError("llama.cpp could not allocate the GGUF context.")
|
||||
}
|
||||
defer { llama_free(context) }
|
||||
|
||||
let sampler = llama_sampler_chain_init(llama_sampler_chain_default_params())
|
||||
defer { llama_sampler_free(sampler) }
|
||||
llama_sampler_chain_add(sampler, llama_sampler_init_penalties(
|
||||
llama_vocab_n_tokens(vocab), Int32(settings.repeatLastN ?? 64), Float(settings.repeatPenalty ?? 1),
|
||||
Float(settings.frequencyPenalty ?? 0), Float(settings.presencePenalty ?? 0)))
|
||||
if settings.temperature == 0 {
|
||||
llama_sampler_chain_add(sampler, llama_sampler_init_greedy())
|
||||
} else {
|
||||
llama_sampler_chain_add(sampler, llama_sampler_init_top_k(Int32(settings.topK ?? 40)))
|
||||
llama_sampler_chain_add(sampler, llama_sampler_init_top_p(Float(settings.topP ?? 0.95), 1))
|
||||
llama_sampler_chain_add(sampler, llama_sampler_init_min_p(Float(settings.minP ?? 0), 1))
|
||||
llama_sampler_chain_add(sampler, llama_sampler_init_temp(Float(settings.temperature ?? 0.8)))
|
||||
llama_sampler_chain_add(sampler, llama_sampler_init_dist(settings.seed.map { UInt32(truncatingIfNeeded: $0) } ?? UInt32.max))
|
||||
}
|
||||
|
||||
output.yield(.backend("GGUF · Metal"))
|
||||
try tokens.withUnsafeMutableBufferPointer { buffer in
|
||||
for offset in stride(from: 0, to: Int(count), by: Int(contextSettings.n_batch)) {
|
||||
try Task.checkCancellation()
|
||||
let length = min(Int(contextSettings.n_batch), Int(count) - offset)
|
||||
try decode(context, buffer.baseAddress?.advanced(by: offset), count: Int32(length))
|
||||
}
|
||||
}
|
||||
|
||||
var pending = Data()
|
||||
var produced = 0
|
||||
var heldText = ""
|
||||
let stops = settings.stop.filter { !$0.isEmpty }
|
||||
let start = ContinuousClock.now
|
||||
let limit = min(settings.maxTokens ?? 1024, Int(contextSettings.n_ctx) - Int(count))
|
||||
for index in 0..<limit {
|
||||
try Task.checkCancellation()
|
||||
var token = llama_sampler_sample(sampler, context, -1)
|
||||
if llama_vocab_is_eog(vocab, token) { break }
|
||||
produced += 1
|
||||
var bytes = [Int8](repeating: 0, count: 128)
|
||||
var size = llama_token_to_piece(vocab, token, &bytes, Int32(bytes.count), 0, false)
|
||||
if size < 0 {
|
||||
bytes = [Int8](repeating: 0, count: -Int(size))
|
||||
size = llama_token_to_piece(vocab, token, &bytes, Int32(bytes.count), 0, false)
|
||||
}
|
||||
if size > 0 {
|
||||
pending.append(contentsOf: bytes.prefix(Int(size)).map { UInt8(bitPattern: $0) })
|
||||
}
|
||||
if let text = String(data: pending, encoding: .utf8), !text.isEmpty {
|
||||
pending.removeAll(keepingCapacity: true)
|
||||
heldText += text
|
||||
if let end = stops.compactMap({ heldText.range(of: $0)?.lowerBound }).min() {
|
||||
let visible = String(heldText[..<end])
|
||||
if !visible.isEmpty { emit(visible) }
|
||||
heldText = ""
|
||||
break
|
||||
}
|
||||
let maxPrefix = stops.map(\.count).max() ?? 1
|
||||
let keep = min(heldText.count, maxPrefix - 1)
|
||||
let visible = String(heldText.dropLast(keep))
|
||||
heldText = String(heldText.suffix(keep))
|
||||
if !visible.isEmpty { emit(visible) }
|
||||
}
|
||||
if index + 1 < limit { try decode(context, &token, count: 1) }
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
heldText += String(decoding: pending, as: UTF8.self)
|
||||
if !heldText.isEmpty { emit(heldText) }
|
||||
if thinking.supported {
|
||||
for delta in thinkingOutput.finish() { output.yield(delta) }
|
||||
}
|
||||
let elapsed = (ContinuousClock.now - start).components
|
||||
let seconds = Double(elapsed.seconds) + Double(elapsed.attoseconds) / 1e18
|
||||
output.yield(.metrics(.init(tokens: produced, seconds: seconds)))
|
||||
}
|
||||
|
||||
private func decode(_ context: OpaquePointer, _ tokens: UnsafeMutablePointer<llama_token>?, count: Int32) throws {
|
||||
guard llama_decode(context, llama_batch_get_one(tokens, count)) == 0 else {
|
||||
throw StudioError("llama.cpp could not decode the GGUF prompt or response.")
|
||||
}
|
||||
}
|
||||
|
||||
private func tokenize(_ prompt: String, vocab: OpaquePointer?, tokens: inout [llama_token]) -> Int32 {
|
||||
llama_tokenize(vocab, prompt, Int32(prompt.utf8.count), &tokens, Int32(tokens.count), true, true)
|
||||
}
|
||||
|
||||
private func format(_ messages: [Message], model: OpaquePointer) throws -> (prompt: String, template: String) {
|
||||
let roles = messages.map { strdup($0.role.rawValue) }
|
||||
let contents = messages.map { strdup($0.content.replacingOccurrences(of: "\0", with: "�")) }
|
||||
defer {
|
||||
roles.forEach { free($0) }
|
||||
contents.forEach { free($0) }
|
||||
}
|
||||
let chat = zip(roles, contents).map { llama_chat_message(role: UnsafePointer($0), content: UnsafePointer($1)) }
|
||||
guard let template = llama_model_chat_template(model, nil) else {
|
||||
throw StudioError("This GGUF file has no chat template. Import an instruct or chat model.")
|
||||
}
|
||||
let size = llama_chat_apply_template(template, chat, chat.count, true, nil, 0)
|
||||
guard size > 0 else { throw StudioError("llama.cpp does not support this GGUF chat template.") }
|
||||
var buffer = [CChar](repeating: 0, count: Int(size) + 1)
|
||||
let written = llama_chat_apply_template(template, chat, chat.count, true, &buffer, Int32(buffer.count))
|
||||
guard written == size else { throw StudioError("llama.cpp could not format the chat.") }
|
||||
return (String(cString: buffer), String(cString: template))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
enum GGUFThinking {
|
||||
private static let assistantMarker = "<|im_start|>assistant\n"
|
||||
|
||||
static func supports(_ template: String) -> Bool {
|
||||
["enable_thinking", "<think>", "</think>", "<|im_start|>assistant"].allSatisfy { template.contains($0) }
|
||||
}
|
||||
|
||||
static func prepare(_ prompt: String, template: String, mode: Thinking) -> (prompt: String, supported: Bool, prefilled: Bool) {
|
||||
let supported = supports(template)
|
||||
guard supported, prompt.hasSuffix(assistantMarker) else {
|
||||
return (prompt, supported, supported && prompt.hasSuffix("<think>\n"))
|
||||
}
|
||||
switch mode {
|
||||
case .on: return (prompt + "<think>\n", true, true)
|
||||
case .off: return (prompt + "<think>\n\n</think>\n\n", true, false)
|
||||
default: return (prompt, true, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
+90
-4
@@ -12,6 +12,8 @@ struct ChatModelChoice: Equatable, Codable {
|
||||
enum Backend: String, Codable {
|
||||
case ollama = "Ollama"
|
||||
case mlx = "MLX"
|
||||
case gguf = "GGUF"
|
||||
case coreML = "Core ML"
|
||||
case compatible = "Compatible API"
|
||||
}
|
||||
|
||||
@@ -20,7 +22,8 @@ struct ChatModelChoice: Equatable, Codable {
|
||||
|
||||
var displayName: String {
|
||||
guard !model.isEmpty else { return "Choose Model" }
|
||||
return backend == .mlx ? URL(fileURLWithPath: model).lastPathComponent : model
|
||||
if [.gguf, .coreML].contains(backend) { return URL(fileURLWithPath: model).deletingPathExtension().lastPathComponent }
|
||||
return backend == .mlx ? MLXLibrary.displayName(for: URL(fileURLWithPath: model)) : model
|
||||
}
|
||||
|
||||
static func read(_ data: Data) -> [UUID: Self] {
|
||||
@@ -28,11 +31,21 @@ struct ChatModelChoice: Equatable, Codable {
|
||||
}
|
||||
|
||||
func thinkingMode(_ mode: Thinking) -> Thinking {
|
||||
if backend == .mlx && ![Thinking.automatic, .off, .on].contains(mode) { return .automatic }
|
||||
if [.mlx, .gguf].contains(backend) && ![Thinking.automatic, .off, .on].contains(mode) { return .automatic }
|
||||
return mode
|
||||
}
|
||||
}
|
||||
|
||||
enum ChatThinkingControl {
|
||||
static func options(backend: ChatModelChoice.Backend, supportsLocalThinking: Bool) -> [Thinking] {
|
||||
switch backend {
|
||||
case .ollama: Thinking.allCases
|
||||
case .gguf, .mlx: supportsLocalThinking ? [.automatic, .off, .on] : [.automatic]
|
||||
case .compatible, .coreML: [.automatic]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Role: String, Codable, Sendable { case system, user, assistant }
|
||||
|
||||
struct WebReplySource: Identifiable, Equatable, Codable, Sendable {
|
||||
@@ -59,12 +72,38 @@ struct Message: Identifiable, Equatable, Sendable {
|
||||
var documentNames: [String] = []
|
||||
var documentCitations: [DocumentCitation] = []
|
||||
var imagePNG: Data? = nil
|
||||
var performance: GenerationMeasurement? = nil
|
||||
|
||||
var imageDataURL: String? {
|
||||
imagePNG.map { "data:image/png;base64," + $0.base64EncodedString() }
|
||||
}
|
||||
}
|
||||
|
||||
enum LocalChatHistory {
|
||||
static func prepare(_ messages: [Message]) -> [Message] {
|
||||
var system: [String] = []
|
||||
var earlierReplies: [String] = []
|
||||
var turns: [Message] = []
|
||||
for message in messages {
|
||||
if message.role == .system {
|
||||
system.append(message.inferenceContent)
|
||||
} else if turns.isEmpty && message.role == .assistant {
|
||||
earlierReplies.append(message.inferenceContent)
|
||||
} else if turns.last?.role == message.role, let last = turns.indices.last {
|
||||
turns[last].content += "\n\n" + message.inferenceContent
|
||||
} else {
|
||||
turns.append(.init(role: message.role, content: message.inferenceContent))
|
||||
}
|
||||
}
|
||||
if !earlierReplies.isEmpty, let first = turns.indices.first {
|
||||
let context = earlierReplies.joined(separator: "\n\n")
|
||||
turns[first].content = "Earlier assistant replies:\n" + context + "\n\nUser messages:\n" + turns[first].content
|
||||
}
|
||||
if !system.isEmpty { turns.insert(.init(role: .system, content: system.joined(separator: "\n\n")), at: 0) }
|
||||
return turns
|
||||
}
|
||||
}
|
||||
|
||||
private extension Message {
|
||||
var inferenceContent: String {
|
||||
guard !documentCitations.isEmpty else { return content }
|
||||
@@ -196,18 +235,30 @@ enum Router {
|
||||
continuation.yield(delta)
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
if !committed { throw StudioError("The model returned an empty response.") }
|
||||
} catch {
|
||||
try Task.checkCancellation()
|
||||
guard !committed, !(error is CancellationError), (error as? URLError)?.code != .cancelled,
|
||||
let fallback else { throw error }
|
||||
do {
|
||||
var producedOutput = false
|
||||
for try await delta in fallback() {
|
||||
try Task.checkCancellation()
|
||||
switch delta {
|
||||
case .answer(let text), .thinking(let text):
|
||||
producedOutput = producedOutput || !text.isEmpty
|
||||
case .committed: producedOutput = true
|
||||
case .backend, .metrics: break
|
||||
}
|
||||
continuation.yield(delta)
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
if !producedOutput { throw StudioError("The model returned an empty response.") }
|
||||
} catch let fallbackError {
|
||||
try Task.checkCancellation()
|
||||
if fallbackError is CancellationError { throw fallbackError }
|
||||
if fallbackError is CancellationError || (fallbackError as? URLError)?.code == .cancelled {
|
||||
throw fallbackError
|
||||
}
|
||||
throw StudioError("\(primaryName): \(error.localizedDescription) MLX: \(fallbackError.localizedDescription)")
|
||||
}
|
||||
}
|
||||
@@ -226,7 +277,7 @@ struct ProviderMetrics: Codable, Equatable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
struct GenerationMeasurement: Codable, Identifiable {
|
||||
struct GenerationMeasurement: Codable, Identifiable, Equatable, Sendable {
|
||||
var id = UUID()
|
||||
static let key = "generationMeasurements"
|
||||
let backend: String
|
||||
@@ -235,6 +286,13 @@ struct GenerationMeasurement: Codable, Identifiable {
|
||||
let characters: Int
|
||||
let provider: ProviderMetrics?
|
||||
let outcome: String
|
||||
var model: String? = nil
|
||||
var recordedAt: Date? = nil
|
||||
var benchmark: Bool? = nil
|
||||
|
||||
static func history(_ data: Data) -> [Self] {
|
||||
(try? JSONDecoder().decode([Self].self, from: data)) ?? []
|
||||
}
|
||||
|
||||
var charactersPerSecond: Double? {
|
||||
guard let firstOutput, seconds > firstOutput, characters > 0 else { return nil }
|
||||
@@ -243,6 +301,34 @@ struct GenerationMeasurement: Codable, Identifiable {
|
||||
}
|
||||
}
|
||||
|
||||
struct GenerationCapture {
|
||||
let start: Double
|
||||
private(set) var firstOutput: Double?
|
||||
private(set) var characters = 0
|
||||
private var backend: String?
|
||||
private var provider: ProviderMetrics?
|
||||
|
||||
mutating func observe(_ delta: Delta, at time: Double) {
|
||||
switch delta {
|
||||
case .answer(let text), .thinking(let text):
|
||||
if !text.isEmpty {
|
||||
if firstOutput == nil { firstOutput = max(0, time - start) }
|
||||
characters += text.count
|
||||
}
|
||||
case .backend(let name): backend = name
|
||||
case .metrics(let metrics): provider = metrics
|
||||
case .committed: break
|
||||
}
|
||||
}
|
||||
|
||||
func finish(at time: Double, requested: String, model: String?, outcome: String,
|
||||
benchmark: Bool = false) -> GenerationMeasurement {
|
||||
GenerationMeasurement(backend: backend ?? requested, firstOutput: firstOutput,
|
||||
seconds: max(0, time - start), characters: characters, provider: provider, outcome: outcome,
|
||||
model: model, recordedAt: Date(), benchmark: benchmark)
|
||||
}
|
||||
}
|
||||
|
||||
enum PromptMode: String, CaseIterable, Identifiable {
|
||||
case standard = "Default"
|
||||
case concise = "Concise"
|
||||
|
||||
+16
-6
@@ -783,9 +783,10 @@ enum GiteaRepositoryLookup {
|
||||
|
||||
static func entries(client: any MCPToolClient) async throws -> [String] {
|
||||
let data = try await client.callTool("list_repositories", argumentsJSON: Data("{}".utf8))
|
||||
guard let result = try JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
result["isError"] as? Bool != true else {
|
||||
throw StudioError("The connected Gitea server could not list its repositories.")
|
||||
try MCPToolResponse.check(data, tool: "list_repositories")
|
||||
let result = try JSONSerialization.jsonObject(with: data)
|
||||
guard result is [String: Any] || result is [Any] else {
|
||||
throw StudioError("Gitea returned an unexpected repository response.")
|
||||
}
|
||||
var entries: [String] = []
|
||||
var seen: Set<String> = []
|
||||
@@ -796,7 +797,7 @@ enum GiteaRepositoryLookup {
|
||||
let link = object["html_url"] as? String
|
||||
entries.append(link.map { "\(name) — \($0)" } ?? name)
|
||||
} else {
|
||||
for field in ["result", "structuredContent", "content", "text"] {
|
||||
for field in ["structuredContent", "result", "data", "repositories", "content", "text"] {
|
||||
if let nested = object[field] { collect(nested) }
|
||||
}
|
||||
}
|
||||
@@ -955,7 +956,16 @@ struct ChatFilePreview: Identifiable, Sendable {
|
||||
guard values.isRegularFile == true, let size = values.fileSize, size <= 20_000_000 else {
|
||||
throw StudioError("Choose an image file up to 20 MB.")
|
||||
}
|
||||
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
|
||||
return try imagePreview(source: CGImageSourceCreateWithURL(url as CFURL, nil), name: url.lastPathComponent)
|
||||
}
|
||||
|
||||
static func pastedImage(_ data: Data) throws -> Self {
|
||||
guard data.count <= 20_000_000 else { throw StudioError("Choose an image up to 20 MB.") }
|
||||
return try imagePreview(source: CGImageSourceCreateWithData(data as CFData, nil), name: "Pasted Image.png")
|
||||
}
|
||||
|
||||
private static func imagePreview(source: CGImageSource?, name: String) throws -> Self {
|
||||
guard let source,
|
||||
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
|
||||
let width = properties[kCGImagePropertyPixelWidth] as? Int,
|
||||
let height = properties[kCGImagePropertyPixelHeight] as? Int, width > 0, height > 0 else {
|
||||
@@ -983,7 +993,7 @@ struct ChatFilePreview: Identifiable, Sendable {
|
||||
throw StudioError("The image exceeds 20 MB when converted to PNG.")
|
||||
}
|
||||
let text = (try? recognizeText(in: image)) ?? ""
|
||||
return Self(name: url.lastPathComponent, text: text, imagePNG: png as Data)
|
||||
return Self(name: name, text: text, imagePNG: png as Data)
|
||||
}
|
||||
|
||||
private static func pdfText(at url: URL) throws -> String {
|
||||
|
||||
@@ -850,6 +850,17 @@ struct RemoteKnowledgeStack: Identifiable {
|
||||
let supportsInventory: Bool
|
||||
}
|
||||
|
||||
enum MCPToolResponse {
|
||||
static func check(_ data: Data, tool: String) throws {
|
||||
guard let result = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
|
||||
result["isError"] as? Bool == true else { return }
|
||||
let content = result["content"] as? [[String: Any]] ?? []
|
||||
let details = content.compactMap { $0["text"] as? String }.joined(separator: "\n")
|
||||
let message = details.isEmpty ? "The server reported a tool error." : String(details.prefix(4_000))
|
||||
throw StudioError("\(tool) failed. \(message)")
|
||||
}
|
||||
}
|
||||
|
||||
struct MCPConnectionState {
|
||||
var toolset: ActiveToolset? = nil
|
||||
var progress: String? = nil
|
||||
|
||||
+60
-12
@@ -1,6 +1,7 @@
|
||||
import Foundation
|
||||
import MLXLLM
|
||||
import MLXLMCommon
|
||||
import Tokenizers
|
||||
|
||||
actor MLXProvider: InferenceProvider {
|
||||
private var loaded: (directory: String, container: ModelContainer)?
|
||||
@@ -20,6 +21,8 @@ actor MLXProvider: InferenceProvider {
|
||||
loaded.map { URL(fileURLWithPath: $0.directory).lastPathComponent }
|
||||
}
|
||||
|
||||
func modelDirectory() -> String? { loaded?.directory }
|
||||
|
||||
func unload() {
|
||||
guard !active else { return }
|
||||
eviction?.cancel()
|
||||
@@ -59,15 +62,15 @@ actor MLXProvider: InferenceProvider {
|
||||
if let loaded, loaded.directory == directory {
|
||||
model = loaded.container
|
||||
} else {
|
||||
loaded = nil
|
||||
let url = URL(fileURLWithPath: directory, isDirectory: true)
|
||||
guard FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) else {
|
||||
throw StudioError("Select an MLX model folder containing config.json and model weights.")
|
||||
guard MLXLibrary.isModel(at: url) else {
|
||||
throw StudioError("Select a complete MLX model folder with a readable config.json and all safetensors weight files.")
|
||||
}
|
||||
if let weightLimit, try MLXRuntimeLimits.weightBytes(in: url) > weightLimit {
|
||||
throw StudioError("The model’s weight files exceed the configured MLX weight limit.")
|
||||
}
|
||||
model = try await LLMModelFactory.shared.loadContainer(configuration: .init(directory: url))
|
||||
loaded = nil
|
||||
model = try await LLMModelFactory.shared.loadContainer(from: url, using: StudioMLXTokenizerLoader())
|
||||
try Task.checkCancellation()
|
||||
loaded = (directory, model)
|
||||
}
|
||||
@@ -92,14 +95,14 @@ actor MLXProvider: InferenceProvider {
|
||||
}
|
||||
let directory = request.model
|
||||
let model = try await container(for: directory)
|
||||
let history: [Chat.Message] = request.messages.map {
|
||||
let history: [Chat.Message] = LocalChatHistory.prepare(request.messages).map {
|
||||
switch $0.role {
|
||||
case .system: .system($0.content)
|
||||
case .user: .user($0.content)
|
||||
case .assistant: .assistant($0.content)
|
||||
}
|
||||
}
|
||||
let supportsThinking = MLXThinking.supports(directory)
|
||||
let supportsThinking = ThinkingOutput.supportsMLX(directory)
|
||||
var context: [String: any Sendable]?
|
||||
if supportsThinking {
|
||||
switch request.thinking {
|
||||
@@ -108,15 +111,20 @@ actor MLXProvider: InferenceProvider {
|
||||
case .automatic, .low, .medium, .high: break
|
||||
}
|
||||
}
|
||||
var thinkingOutput = MLXThinking()
|
||||
let input = try await model.prepare(input: UserInput(chat: history, additionalContext: context))
|
||||
var thinkingOutput = ThinkingOutput()
|
||||
let input: LMInput
|
||||
do {
|
||||
input = try await model.prepare(input: UserInput(chat: history, additionalContext: context))
|
||||
} catch let error where (error as NSError).domain == "Jinja.TemplateException" {
|
||||
throw StudioError("The MLX model’s chat template rejected this conversation. Try sending the message in a new chat.")
|
||||
}
|
||||
let config = request.parameters
|
||||
let parameters = GenerateParameters(maxTokens: config.maxTokens ?? 1024, maxKVSize: config.mlxCache,
|
||||
temperature: Float(config.temperature ?? 0.6),
|
||||
topP: Float(config.topP ?? 1),
|
||||
repetitionPenalty: config.repeatPenalty.map(Float.init),
|
||||
repetitionContextSize: config.repeatLastN ?? 20,
|
||||
prefillStepSize: config.mlxPrefill ?? 512)
|
||||
prefill: .init(stepSize: config.mlxPrefill ?? 512, chunking: .remainder))
|
||||
let output = try await model.generate(input: input, parameters: parameters)
|
||||
var stopMatcher = StopMatcher(sequences: config.stop)
|
||||
continuation.yield(.backend("MLX · \(URL(fileURLWithPath: directory).lastPathComponent)"))
|
||||
@@ -138,7 +146,7 @@ actor MLXProvider: InferenceProvider {
|
||||
case .info(let info):
|
||||
finished = true
|
||||
continuation.yield(.metrics(ProviderMetrics(tokens: info.generationTokenCount, seconds: info.generateTime)))
|
||||
case .toolCall:
|
||||
case .toolCall, .rejectedToolCall:
|
||||
continuation.yield(.committed)
|
||||
throw StudioError("The MLX model returned a tool call, but no tools are configured.")
|
||||
}
|
||||
@@ -176,14 +184,19 @@ enum MLXRuntimeLimits {
|
||||
}
|
||||
}
|
||||
|
||||
struct MLXThinking {
|
||||
struct ThinkingOutput {
|
||||
private static let start = "<think>"
|
||||
private static let end = "</think>"
|
||||
private var buffer = ""
|
||||
private var readingThinking = false
|
||||
private var decided = false
|
||||
|
||||
static func supports(_ folder: String) -> Bool {
|
||||
init(prefilled: Bool = false) {
|
||||
readingThinking = prefilled
|
||||
decided = prefilled
|
||||
}
|
||||
|
||||
static func supportsMLX(_ folder: String) -> Bool {
|
||||
guard !folder.isEmpty else { return false }
|
||||
let url = URL(fileURLWithPath: folder).appending(path: "tokenizer_config.json")
|
||||
guard let size = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize,
|
||||
@@ -230,3 +243,38 @@ struct MLXThinking {
|
||||
return [asThinking ? .thinking(buffer) : .answer(buffer)]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private struct StudioMLXTokenizerLoader: TokenizerLoader {
|
||||
func load(from directory: URL) async throws -> any MLXLMCommon.Tokenizer {
|
||||
StudioMLXTokenizer(base: try await AutoTokenizer.from(modelFolder: directory))
|
||||
}
|
||||
}
|
||||
|
||||
private struct StudioMLXTokenizer: MLXLMCommon.Tokenizer {
|
||||
let base: any Tokenizers.Tokenizer
|
||||
|
||||
var bosToken: String? { base.bosToken }
|
||||
var eosToken: String? { base.eosToken }
|
||||
var unknownToken: String? { base.unknownToken }
|
||||
|
||||
func encode(text: String, addSpecialTokens: Bool) -> [Int] {
|
||||
base.encode(text: text, addSpecialTokens: addSpecialTokens)
|
||||
}
|
||||
|
||||
func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String {
|
||||
base.decode(tokens: tokenIds, skipSpecialTokens: skipSpecialTokens)
|
||||
}
|
||||
|
||||
func convertTokenToId(_ token: String) -> Int? { base.convertTokenToId(token) }
|
||||
func convertIdToToken(_ id: Int) -> String? { base.convertIdToToken(id) }
|
||||
|
||||
func applyChatTemplate(messages: [[String: any Sendable]], tools: [[String: any Sendable]]?,
|
||||
additionalContext: [String: any Sendable]?) throws -> [Int] {
|
||||
do {
|
||||
return try base.applyChatTemplate(messages: messages, tools: tools, additionalContext: additionalContext)
|
||||
} catch Tokenizers.TokenizerError.missingChatTemplate {
|
||||
throw MLXLMCommon.TokenizerError.missingChatTemplate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+88
-51
@@ -95,6 +95,8 @@ final class TrainingOperation: ObservableObject {
|
||||
process.standardInput = FileHandle.nullDevice
|
||||
var environment = ProcessInfo.processInfo.environment
|
||||
environment["PYTHONUNBUFFERED"] = "1"
|
||||
environment["NO_COLOR"] = "1"
|
||||
environment["TERM"] = "dumb"
|
||||
environment["PATH"] = executable.deletingLastPathComponent().path + ":" + (environment["PATH"] ?? "/usr/bin:/bin")
|
||||
process.environment = environment
|
||||
let pipe = Pipe()
|
||||
@@ -118,7 +120,7 @@ final class TrainingOperation: ObservableObject {
|
||||
}
|
||||
|
||||
private func append(_ text: String) {
|
||||
log += text
|
||||
log += text.replacingOccurrences(of: "\u{001B}\\[[0-?]*[ -/]*[@-~]", with: "", options: .regularExpression)
|
||||
if log.count > 80_000 { log = String(log.suffix(60_000)) }
|
||||
}
|
||||
}
|
||||
@@ -133,6 +135,14 @@ struct ModelWorkshop: Identifiable {
|
||||
struct ModelWorkshopView: View {
|
||||
let workshop: ModelWorkshop
|
||||
let register: (URL) -> Void
|
||||
let embedded: Bool
|
||||
|
||||
private enum Stage: String, CaseIterable, Identifiable {
|
||||
case setup = "Tools", convert = "Convert", train = "Train"
|
||||
var id: Self { self }
|
||||
}
|
||||
|
||||
@State private var stage: Stage = .train
|
||||
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@AppStorage("trainingInstallerPython") private var installerPython = ""
|
||||
@@ -147,9 +157,10 @@ struct ModelWorkshopView: View {
|
||||
@State private var iterations = 50
|
||||
@State private var layers = 4
|
||||
|
||||
init(workshop: ModelWorkshop, register: @escaping (URL) -> Void) {
|
||||
init(workshop: ModelWorkshop, embedded: Bool = false, register: @escaping (URL) -> Void) {
|
||||
self.workshop = workshop
|
||||
self.register = register
|
||||
self.embedded = embedded
|
||||
_base = State(initialValue: workshop.base)
|
||||
}
|
||||
|
||||
@@ -167,56 +178,76 @@ struct ModelWorkshopView: View {
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
Form {
|
||||
Section("MLX Tools") {
|
||||
LabeledContent("Environment", value: toolsInstalled ? "Installed" : "Setup required")
|
||||
HStack {
|
||||
Button(toolsInstalled ? "Reinstall MLX Tools" : "Install MLX Tools", action: install)
|
||||
Button("Choose Python…") {
|
||||
if let url = selectURL(folders: false) { installerPython = url.path }
|
||||
}
|
||||
}
|
||||
Text(installerPython.isEmpty ? "Uses a local Python 3.11 or newer to set up a dedicated environment." : installerPython)
|
||||
if embedded {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
Text("Training").font(.largeTitle.weight(.semibold))
|
||||
Label(toolsInstalled ? "MLX tools ready" : "MLX tools setup required",
|
||||
systemImage: toolsInstalled ? "checkmark.circle.fill" : "info.circle")
|
||||
.foregroundStyle(.secondary)
|
||||
Picker("Training stage", selection: $stage) {
|
||||
ForEach(Stage.allCases) { Text($0.rawValue).tag($0) }
|
||||
}.pickerStyle(.segmented).labelsHidden().frame(maxWidth: 340)
|
||||
}
|
||||
Section("Convert to MLX") {
|
||||
if let name = workshop.modelName {
|
||||
Text("For \(name), select its original Hugging Face checkpoint. Ollama GGUF files cannot be converted by MLX LM.")
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(20)
|
||||
Divider()
|
||||
}
|
||||
Form {
|
||||
if !embedded || stage == .setup {
|
||||
Section("MLX Tools") {
|
||||
LabeledContent("Environment", value: toolsInstalled ? "Installed" : "Setup required")
|
||||
HStack {
|
||||
Button(toolsInstalled ? "Reinstall MLX Tools" : "Install MLX Tools", action: install)
|
||||
Button("Choose Python…") {
|
||||
if let url = selectURL(folders: false) { installerPython = url.path }
|
||||
}
|
||||
}
|
||||
Text(installerPython.isEmpty ? "Uses a local Python 3.11 or newer to set up a dedicated environment." : installerPython)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
if let sourceFolder {
|
||||
LabeledContent("Checkpoint", value: sourceFolder.path)
|
||||
} else {
|
||||
TextField("Hugging Face repository", text: $repository, prompt: Text("owner/model"))
|
||||
TextField("Revision", text: $revision, prompt: Text("Optional commit or tag"))
|
||||
}
|
||||
HStack {
|
||||
Button("Choose Checkpoint Folder…") { if let url = selectURL() { sourceFolder = url } }
|
||||
if sourceFolder != nil { Button("Use Hugging Face Repository") { sourceFolder = nil } }
|
||||
if !embedded || stage == .convert {
|
||||
Section("Convert to MLX") {
|
||||
if let name = workshop.modelName {
|
||||
Text("For \(name), select its original Hugging Face checkpoint. Ollama GGUF files cannot be converted by MLX LM.")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
if let sourceFolder {
|
||||
LabeledContent("Checkpoint", value: sourceFolder.path)
|
||||
} else {
|
||||
TextField("Hugging Face repository", text: $repository, prompt: Text("owner/model"))
|
||||
TextField("Revision", text: $revision, prompt: Text("Optional commit or tag"))
|
||||
}
|
||||
HStack {
|
||||
Button("Choose Checkpoint Folder…") { if let url = selectURL() { sourceFolder = url } }
|
||||
if sourceFolder != nil { Button("Use Hugging Face Repository") { sourceFolder = nil } }
|
||||
}
|
||||
Toggle("Quantize to 4-bit", isOn: $quantize)
|
||||
Button("Convert and Register…", action: convert)
|
||||
.disabled(!toolsInstalled || (sourceFolder == nil && repository.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty))
|
||||
}
|
||||
Toggle("Quantize to 4-bit", isOn: $quantize)
|
||||
Button("Convert and Register…", action: convert)
|
||||
.disabled(!toolsInstalled || (sourceFolder == nil && repository.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty))
|
||||
}
|
||||
Section("Clone and Train") {
|
||||
LabeledContent("Base checkpoint", value: base?.path ?? "Choose a converted MLX folder")
|
||||
HStack {
|
||||
Button("Choose Base…") { if let url = selectURL() { base = url } }
|
||||
Button("Clone Base…", action: clone).disabled(base == nil)
|
||||
}
|
||||
LabeledContent("Dataset", value: datasetPath.isEmpty ? "No folder selected" : datasetPath)
|
||||
Button("Choose Dataset…") { if let url = selectURL() { datasetPath = url.path } }
|
||||
Text("Use a folder containing train.jsonl, valid.jsonl and test.jsonl with text chat examples.")
|
||||
.foregroundStyle(.secondary)
|
||||
LabeledContent("Run folder", value: projectPath.isEmpty ? "No folder selected" : projectPath)
|
||||
Button("Choose Run Folder…") { if let url = selectURL(create: true) { projectPath = url.path } }
|
||||
Stepper("Training iterations: \(iterations)", value: $iterations, in: 1...100_000)
|
||||
Stepper("Adapted layers: \(layers)", value: $layers, in: 1...256)
|
||||
HStack {
|
||||
Button("Validate Dataset") { train(.validate) }.disabled(!toolsInstalled || datasetPath.isEmpty)
|
||||
Button("Train Adapter") { train(.train) }.disabled(!ready || datasetPath.isEmpty)
|
||||
Button("Evaluate") { train(.evaluate) }.disabled(!ready || datasetPath.isEmpty)
|
||||
Button("Fuse and Register") { train(.fuse) }.disabled(!ready)
|
||||
if !embedded || stage == .train {
|
||||
Section("Clone and Train") {
|
||||
LabeledContent("Base checkpoint", value: base?.path ?? "Choose a converted MLX folder")
|
||||
HStack {
|
||||
Button("Choose Base…") { if let url = selectURL() { base = url } }
|
||||
Button("Clone Base…", action: clone).disabled(base == nil)
|
||||
}
|
||||
LabeledContent("Dataset", value: datasetPath.isEmpty ? "No folder selected" : datasetPath)
|
||||
Button("Choose Dataset…") { if let url = selectURL() { datasetPath = url.path } }
|
||||
Text("Use a folder containing train.jsonl, valid.jsonl and test.jsonl with text chat examples.")
|
||||
.foregroundStyle(.secondary)
|
||||
LabeledContent("Run folder", value: projectPath.isEmpty ? "No folder selected" : projectPath)
|
||||
Button("Choose Run Folder…") { if let url = selectURL(create: true) { projectPath = url.path } }
|
||||
Stepper("Training iterations: \(iterations)", value: $iterations, in: 1...100_000)
|
||||
Stepper("Adapted layers: \(layers)", value: $layers, in: 1...256)
|
||||
HStack {
|
||||
Button("Validate Dataset") { train(.validate) }.disabled(!toolsInstalled || datasetPath.isEmpty)
|
||||
Button("Train Adapter") { train(.train) }.disabled(!ready || datasetPath.isEmpty)
|
||||
Button("Evaluate") { train(.evaluate) }.disabled(!ready || datasetPath.isEmpty)
|
||||
Button("Fuse and Register") { train(.fuse) }.disabled(!ready)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -224,11 +255,16 @@ struct ModelWorkshopView: View {
|
||||
.disabled(busy)
|
||||
Divider()
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
if embedded { Text("Run output").font(.headline) }
|
||||
if !operation.log.isEmpty {
|
||||
ScrollView {
|
||||
Text(operation.log).font(.system(.caption, design: .monospaced))
|
||||
.textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
|
||||
}.frame(height: 112)
|
||||
ScrollViewReader { proxy in
|
||||
ScrollView {
|
||||
Text(operation.log).font(.system(.caption, design: .monospaced))
|
||||
.textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
|
||||
.id("run-end")
|
||||
}
|
||||
.onChange(of: operation.log) { proxy.scrollTo("run-end", anchor: .bottom) }
|
||||
}.frame(height: embedded ? 145 : 112)
|
||||
}
|
||||
HStack {
|
||||
if let active = operation.active {
|
||||
@@ -239,13 +275,14 @@ struct ModelWorkshopView: View {
|
||||
Text(operation.status).textSelection(.enabled)
|
||||
}
|
||||
Spacer()
|
||||
Button("Done") { dismiss() }.disabled(busy)
|
||||
if !embedded { Button("Done") { dismiss() }.disabled(busy) }
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
}
|
||||
.frame(width: 660, height: 585)
|
||||
.frame(width: embedded ? nil : 660, height: embedded ? nil : 585)
|
||||
.interactiveDismissDisabled(busy)
|
||||
.onAppear { if embedded && !toolsInstalled { stage = .setup } }
|
||||
}
|
||||
|
||||
private var ready: Bool { toolsInstalled && base != nil && !projectPath.isEmpty }
|
||||
|
||||
+398
-103
@@ -32,7 +32,7 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
|
||||
url.host = "huggingface.co"
|
||||
url.path = "/api/models"
|
||||
url.queryItems = [
|
||||
.init(name: "author", value: "mlx-community"),
|
||||
.init(name: "filter", value: "mlx"),
|
||||
.init(name: "pipeline_tag", value: "text-generation"),
|
||||
.init(name: "search", value: query),
|
||||
.init(name: "limit", value: "25"),
|
||||
@@ -45,46 +45,94 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
|
||||
return try decodeSearch(response.data)
|
||||
}
|
||||
|
||||
static func decodeSearch(_ data: Data) throws -> [Self] {
|
||||
struct Entry: Decodable {
|
||||
struct File: Decodable { let rfilename: String }
|
||||
let id: String
|
||||
let sha: String?
|
||||
let siblings: [File]?
|
||||
let downloads: Int?
|
||||
let likes: Int?
|
||||
enum HubGating: Decodable {
|
||||
case open, restricted
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let value = try decoder.singleValueContainer()
|
||||
self = (try? value.decode(Bool.self)) == false ? .open : .restricted
|
||||
}
|
||||
return try JSONDecoder().decode([Entry].self, from: data).compactMap { entry in
|
||||
let prefix = "mlx-community/"
|
||||
guard entry.id.hasPrefix(prefix), let revision = entry.sha, revision.count == 40,
|
||||
revision.allSatisfy({ $0.isASCII && $0.isHexDigit }) else { return nil }
|
||||
let name = String(entry.id.dropFirst(prefix.count))
|
||||
let safe = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.")
|
||||
guard !name.isEmpty, name.unicodeScalars.allSatisfy(safe.contains) else { return nil }
|
||||
let files = (entry.siblings ?? []).map(\.rfilename).filter { file in
|
||||
!file.hasPrefix(".") && file.unicodeScalars.allSatisfy(safe.contains) &&
|
||||
(file.hasSuffix(".safetensors") || file.hasSuffix(".json") || file.hasSuffix(".txt") ||
|
||||
file.hasSuffix(".model") || file.hasSuffix(".jinja") || file.hasSuffix(".tiktoken"))
|
||||
}
|
||||
}
|
||||
|
||||
private struct HubEntry: Decodable {
|
||||
struct File: Decodable { let rfilename: String }
|
||||
let id: String
|
||||
let sha: String?
|
||||
let siblings: [File]?
|
||||
let downloads: Int?
|
||||
let likes: Int?
|
||||
let library_name: String?
|
||||
let tags: [String]?
|
||||
let privateModel: Bool?
|
||||
let gated: HubGating?
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, sha, siblings, downloads, likes, library_name, tags, gated
|
||||
case privateModel = "private"
|
||||
}
|
||||
|
||||
func catalogModel() -> CatalogModel? {
|
||||
guard let (owner, name) = CatalogModel.repositoryParts(id),
|
||||
let revision = sha, revision.count == 40,
|
||||
revision.allSatisfy({ $0.isASCII && $0.isHexDigit }),
|
||||
privateModel != true, gated != .restricted else { return nil }
|
||||
let declaresMLX = library_name == "mlx" || tags?.contains("mlx") == true
|
||||
guard declaresMLX || (owner == "mlx-community" && library_name == nil) else { return nil }
|
||||
let files = Set((siblings ?? []).map(\.rfilename).filter { file in
|
||||
CatalogModel.safeComponent(file) &&
|
||||
[".safetensors", ".json", ".txt", ".model", ".jinja", ".tiktoken"].contains { file.hasSuffix($0) }
|
||||
})
|
||||
guard files.contains("config.json"), files.contains(where: { $0.hasSuffix(".safetensors") }),
|
||||
!files.contains("adapter_config.json"), !files.contains("adapter_model.safetensors") else { return nil }
|
||||
return Self(id: "hf-" + name, title: name, size: "", repository: entry.id, revision: revision,
|
||||
files: Array(Set(files)).sorted(), downloads: entry.downloads, likes: entry.likes)
|
||||
// Keep the existing installation key for mlx-community models.
|
||||
let key = owner == "mlx-community" ? "hf-" + name : "hf--" + owner + "/" + name
|
||||
return CatalogModel(id: key, title: name, size: "", repository: id, revision: revision,
|
||||
files: files.sorted(), downloads: downloads, likes: likes)
|
||||
}
|
||||
}
|
||||
|
||||
static func safeComponent(_ value: String) -> Bool {
|
||||
let safe = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.")
|
||||
return !value.isEmpty && !value.hasPrefix(".") && value.unicodeScalars.allSatisfy(safe.contains)
|
||||
}
|
||||
|
||||
static func repositoryParts(_ id: String) -> (String, String)? {
|
||||
let parts = id.split(separator: "/", omittingEmptySubsequences: false).map(String.init)
|
||||
guard parts.count == 2, parts.allSatisfy(safeComponent) else { return nil }
|
||||
return (parts[0], parts[1])
|
||||
}
|
||||
|
||||
static func decodeSearch(_ data: Data) throws -> [Self] {
|
||||
try JSONDecoder().decode([HubEntry].self, from: data).compactMap { $0.catalogModel() }
|
||||
}
|
||||
|
||||
static func resolve(_ repository: String) async throws -> Self {
|
||||
guard repositoryParts(repository) != nil else {
|
||||
throw StudioError("Enter a Hugging Face model ID in owner/model format.")
|
||||
}
|
||||
let endpoint = URL(string: "https://huggingface.co/api/models/")!.appending(path: repository)
|
||||
let response = try await WebFetch.load(endpoint, types: ["application/json"])
|
||||
return try decodeRepository(response.data, requested: repository)
|
||||
}
|
||||
|
||||
static func decodeRepository(_ data: Data, requested: String) throws -> Self {
|
||||
let entry = try JSONDecoder().decode(HubEntry.self, from: data)
|
||||
guard entry.id.caseInsensitiveCompare(requested) == .orderedSame,
|
||||
let model = entry.catalogModel() else {
|
||||
throw StudioError("The repository does not expose a public MLX checkpoint with safetensors weights.")
|
||||
}
|
||||
return model
|
||||
}
|
||||
|
||||
var source: URL { URL(string: "https://huggingface.co/" + repository)! }
|
||||
var metadataKey: String { "mlx:" + repository + "@" + revision }
|
||||
var localFolder: URL {
|
||||
URL.applicationSupportDirectory.appending(path: "AIStudio/Models", directoryHint: .isDirectory)
|
||||
.appending(path: id, directoryHint: .isDirectory)
|
||||
.appending(path: id.contains("/") ? "Custom/" + repository : id, directoryHint: .isDirectory)
|
||||
}
|
||||
|
||||
func installed(at folder: URL) -> Bool {
|
||||
files.allSatisfy {
|
||||
let file = folder.appending(path: $0)
|
||||
return ((try? file.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0) > 0
|
||||
}
|
||||
!files.isEmpty && files.allSatisfy { MLXLibrary.hasFile($0, in: folder) } && MLXLibrary.isModel(at: folder)
|
||||
}
|
||||
|
||||
func install(
|
||||
@@ -96,7 +144,9 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
|
||||
if manager.fileExists(atPath: destination.path) {
|
||||
throw StudioError("Remove the incomplete managed model before reinstalling.")
|
||||
}
|
||||
let staging = URL.temporaryDirectory.appending(path: "AIStudio-model-\(UUID())", directoryHint: .isDirectory)
|
||||
let parent = destination.deletingLastPathComponent()
|
||||
try manager.createDirectory(at: parent, withIntermediateDirectories: true)
|
||||
let staging = parent.appending(path: ".download-\(UUID())", directoryHint: .isDirectory)
|
||||
try manager.createDirectory(at: staging, withIntermediateDirectories: false)
|
||||
defer { try? manager.removeItem(at: staging) }
|
||||
|
||||
@@ -113,14 +163,15 @@ struct CatalogModel: Identifiable, Hashable, Sendable, Codable {
|
||||
defer { try? manager.removeItem(at: download) }
|
||||
guard let http = response as? HTTPURLResponse, http.statusCode == 200,
|
||||
http.url?.scheme == "https" else {
|
||||
throw StudioError("Could not download \(file).")
|
||||
let code = (response as? HTTPURLResponse).map { " (HTTP \($0.statusCode))" } ?? ""
|
||||
throw StudioError("Could not download \(file)\(code).")
|
||||
}
|
||||
try manager.moveItem(at: download, to: staging.appending(path: file))
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
guard installed(at: staging) else { throw StudioError("The download was incomplete.") }
|
||||
try manager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try manager.moveItem(at: staging, to: destination)
|
||||
await progress("Download complete.", 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,7 +203,7 @@ struct MLXModelConfiguration: Decodable {
|
||||
|
||||
struct HubModelMetadata: Decodable {
|
||||
struct File: Decodable {
|
||||
struct LFS: Decodable { let size: Int64 }
|
||||
struct LFS: Decodable { let size: Int64; let sha256: String? }
|
||||
let rfilename: String
|
||||
let size: Int64?
|
||||
let lfs: LFS?
|
||||
@@ -295,15 +346,30 @@ struct ModelLibrarySelection {
|
||||
let compatible: Bool
|
||||
let mlxPath: String
|
||||
let ollamaModel: String
|
||||
let ggufPath: String
|
||||
|
||||
init(mlxOnly: Bool, compatible: Bool, mlxPath: String, ollamaModel: String, ggufPath: String = "") {
|
||||
self.mlxOnly = mlxOnly
|
||||
self.compatible = compatible
|
||||
self.mlxPath = mlxPath
|
||||
self.ollamaModel = ollamaModel
|
||||
self.ggufPath = ggufPath
|
||||
}
|
||||
|
||||
func isGGUF(_ path: String) -> Bool {
|
||||
!ggufPath.isEmpty && canonicalPath(ggufPath) == canonicalPath(path)
|
||||
}
|
||||
|
||||
private func canonicalPath(_ path: String) -> String {
|
||||
URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path
|
||||
}
|
||||
|
||||
func isMLX(_ path: String) -> Bool {
|
||||
mlxOnly && !mlxPath.isEmpty &&
|
||||
URL(fileURLWithPath: mlxPath).resolvingSymlinksInPath().standardizedFileURL.path ==
|
||||
URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path
|
||||
ggufPath.isEmpty && mlxOnly && !mlxPath.isEmpty && canonicalPath(mlxPath) == canonicalPath(path)
|
||||
}
|
||||
|
||||
func isOllama(_ name: String) -> Bool {
|
||||
guard !mlxOnly, !compatible, !ollamaModel.isEmpty else { return false }
|
||||
guard ggufPath.isEmpty, !mlxOnly, !compatible, !ollamaModel.isEmpty else { return false }
|
||||
func tag(_ value: String) -> String {
|
||||
let value = value.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return value.split(separator: "/").last?.contains(":") == true ? value : value + ":latest"
|
||||
@@ -314,6 +380,8 @@ struct ModelLibrarySelection {
|
||||
|
||||
struct ModelCatalogView: View {
|
||||
@ObservedObject var studio: StudioModel
|
||||
@AppStorage("defaultCoreMLPath") private var defaultCoreMLPath = ""
|
||||
@AppStorage("defaultGGUFPath") private var defaultGGUFPath = ""
|
||||
@AppStorage("mlxPath") private var mlxPath = ""
|
||||
@AppStorage("mlxOnly") private var mlxOnly = false
|
||||
@State private var downloads: [String: Task<Void, Never>] = [:]
|
||||
@@ -324,11 +392,15 @@ struct ModelCatalogView: View {
|
||||
let fraction: Double?
|
||||
}
|
||||
@AppStorage("mlxRegisteredPaths") private var registered = Data()
|
||||
@AppStorage(GGUFModelMetadata.libraryKey) private var ggufLibrary = Data()
|
||||
@State private var dropTargeted = false
|
||||
@State private var pickingLibrary = false
|
||||
@State private var scanningLibrary = false
|
||||
@State private var scanRequested = false
|
||||
@State private var libraryStatus = ""
|
||||
|
||||
@State private var loadedPath: String?
|
||||
@State private var cacheScan = 0
|
||||
|
||||
private var library: [String] { (try? JSONDecoder().decode([String].self, from: registered)) ?? [] }
|
||||
@State private var removing: CatalogModel?
|
||||
@State private var status = ""
|
||||
@@ -340,12 +412,9 @@ struct ModelCatalogView: View {
|
||||
@State private var loadingPath: String?
|
||||
@AppStorage("favoriteModelKeys") private var favoriteData = Data()
|
||||
|
||||
@State private var libraryBackend: String?
|
||||
@State private var libraryBackend = "Local"
|
||||
@State private var localQuery = ""
|
||||
|
||||
private var backend: Binding<String> {
|
||||
Binding(get: { libraryBackend ?? (selection.mlxOnly ? "MLX" : "Ollama") },
|
||||
set: { libraryBackend = $0 })
|
||||
}
|
||||
@AppStorage("endpoint") private var ollamaEndpoint = "http://127.0.0.1:11434"
|
||||
@AppStorage("ollamaModel") private var ollamaModel = ""
|
||||
@AppStorage("compatibleEnabled") private var compatibleEnabled = false
|
||||
@@ -368,12 +437,15 @@ struct ModelCatalogView: View {
|
||||
@State private var catalogBytes: [String: Int64] = [:]
|
||||
|
||||
private func mlxPreview(model: CatalogModel?, folder: URL?) -> ModelPreview {
|
||||
let title = model?.title ?? folder?.lastPathComponent ?? "MLX model"
|
||||
let title = model?.title ?? folder.map(MLXLibrary.displayName(for:)) ?? "MLX model"
|
||||
let cached = model.flatMap { catalogBytes[$0.metadataKey] }
|
||||
let size = folder.map { ModelLibrarySize.mlx($0.path) } ?? cached.map { ModelLibrarySize.label($0) }
|
||||
return ModelPreview(title: title, fields: [
|
||||
("Backend", "MLX"), ("Weights", size), ("Repository", model?.repository),
|
||||
("Revision", model?.revision), ("Local folder", folder?.path)
|
||||
("Revision", model?.revision), ("Local folder", folder?.path),
|
||||
("Compatibility", folder.map {
|
||||
MLXLibrary.isModel(at: $0) ? "Checkpoint files present · runtime checked on load" : "Missing or invalid checkpoint files"
|
||||
} ?? "MLX checkpoint · runtime checked on load")
|
||||
], source: model?.source, load: {
|
||||
if let folder {
|
||||
let data = try Data(contentsOf: folder.appending(path: "config.json"))
|
||||
@@ -426,11 +498,12 @@ struct ModelCatalogView: View {
|
||||
return ModelLibrarySelection(
|
||||
mlxOnly: studio.inferenceBackend.hasPrefix("MLX · "),
|
||||
compatible: !studio.inferenceBackend.hasPrefix("Ollama · ") || run.endpoint != ollamaEndpoint,
|
||||
mlxPath: run.path, ollamaModel: run.tag
|
||||
mlxPath: run.path, ollamaModel: run.tag,
|
||||
ggufPath: studio.inferenceBackend.hasPrefix("GGUF · ") ? run.tag : ""
|
||||
)
|
||||
}
|
||||
return ModelLibrarySelection(mlxOnly: mlxOnly, compatible: compatibleEnabled,
|
||||
mlxPath: mlxPath, ollamaModel: ollamaModel)
|
||||
return ModelLibrarySelection(mlxOnly: mlxOnly && defaultCoreMLPath.isEmpty, compatible: compatibleEnabled || !defaultCoreMLPath.isEmpty,
|
||||
mlxPath: mlxPath, ollamaModel: ollamaModel, ggufPath: defaultGGUFPath)
|
||||
}
|
||||
|
||||
private func activeBadge(_ runtime: String) -> some View {
|
||||
@@ -496,17 +569,17 @@ struct ModelCatalogView: View {
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
Picker("Model runtime", selection: backend) {
|
||||
Text("MLX").tag("MLX")
|
||||
Picker("Model library", selection: $libraryBackend) {
|
||||
Text("On This Mac").tag("Local")
|
||||
Text("Ollama").tag("Ollama")
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
.frame(width: 260)
|
||||
.padding()
|
||||
if backend.wrappedValue == "Ollama" {
|
||||
if libraryBackend == "Ollama" {
|
||||
ollamaLibrary
|
||||
} else {
|
||||
mlxLibrary
|
||||
localLibrary
|
||||
}
|
||||
}
|
||||
.sheet(item: $preview) { ModelPreviewSheet(preview: $0) }
|
||||
@@ -526,30 +599,120 @@ struct ModelCatalogView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private var mlxLibrary: some View {
|
||||
private func matchesLocal(_ name: String) -> Bool {
|
||||
let query = localQuery.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return query.isEmpty || [name, "MLX"].contains { $0.localizedStandardContains(query) }
|
||||
}
|
||||
|
||||
private func registerLocalModels(_ models: [LocalModelImport]) throws {
|
||||
let gguf = models.compactMap { if case .gguf(let model) = $0 { return model }; return nil }
|
||||
let mlx = models.compactMap { if case .mlx(let path) = $0 { return path }; return nil }
|
||||
if !gguf.isEmpty { ggufLibrary = try GGUFModelMetadata.register(gguf, in: ggufLibrary) }
|
||||
if !mlx.isEmpty { registered = try JSONEncoder().encode(Array(Set(library + mlx)).sorted()) }
|
||||
}
|
||||
|
||||
private func importLMStudioLibrary() {
|
||||
scanningLibrary = true
|
||||
libraryStatus = ""
|
||||
Task {
|
||||
defer { scanningLibrary = false }
|
||||
do {
|
||||
let models = try await Task.detached(priority: .userInitiated) {
|
||||
try LocalModelImport.discover(in: LocalModelImport.lmStudioFolder)
|
||||
}.value
|
||||
try registerLocalModels(models)
|
||||
libraryStatus = models.isEmpty ? "No supported models found in the LM Studio library." :
|
||||
"Found \(models.count) models in the LM Studio library."
|
||||
} catch { libraryStatus = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
private func acceptModelDrop(_ providers: [NSItemProvider]) -> Bool {
|
||||
let files = providers.filter { $0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) }
|
||||
guard !files.isEmpty, !scanningLibrary, !studio.running else { return false }
|
||||
scanningLibrary = true
|
||||
Task {
|
||||
defer { scanningLibrary = false }
|
||||
var models: [LocalModelImport] = []
|
||||
var messages: [String] = []
|
||||
for provider in files {
|
||||
do {
|
||||
let url: URL = try await withCheckedThrowingContinuation { continuation in
|
||||
_ = provider.loadDataRepresentation(forTypeIdentifier: UTType.fileURL.identifier) { data, error in
|
||||
if let error { continuation.resume(throwing: error) }
|
||||
else if let data, let url = URL(dataRepresentation: data, relativeTo: nil), url.isFileURL {
|
||||
continuation.resume(returning: url)
|
||||
} else {
|
||||
continuation.resume(throwing: StudioError("Finder did not provide a local file URL."))
|
||||
}
|
||||
}
|
||||
}
|
||||
let model = try await Task.detached(priority: .userInitiated) { try LocalModelImport.inspect(url) }.value
|
||||
models.append(model)
|
||||
} catch {
|
||||
messages.append(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
do {
|
||||
try registerLocalModels(models)
|
||||
let count = models.count
|
||||
if count > 0 { messages.insert("Registered \(count) model(s).", at: 0) }
|
||||
} catch { messages.append(error.localizedDescription) }
|
||||
libraryStatus = messages.joined(separator: " ")
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private var localLibrary: some View {
|
||||
Form {
|
||||
Section {
|
||||
TextField("Filter installed models", text: $localQuery, prompt: Text("Name, architecture, or format"))
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.accessibilityLabel("Filter installed models")
|
||||
Label(dropTargeted ? "Release to import" : "Drop GGUF files or MLX folders here",
|
||||
systemImage: "square.and.arrow.down")
|
||||
.font(.callout)
|
||||
.foregroundStyle(dropTargeted ? Color.accentColor : Color.secondary)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(10)
|
||||
.background(dropTargeted ? Color.accentColor.opacity(0.12) : Color.secondary.opacity(0.07),
|
||||
in: RoundedRectangle(cornerRadius: 8))
|
||||
.onDrop(of: [.fileURL], isTargeted: $dropTargeted, perform: acceptModelDrop)
|
||||
Button("Import LM Studio Library", systemImage: "folder.badge.plus", action: importLMStudioLibrary)
|
||||
.disabled(scanningLibrary || studio.running)
|
||||
if scanningLibrary { ProgressView("Checking model files…").controlSize(.small) }
|
||||
if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) }
|
||||
}
|
||||
GGUFModels(selection: selection.ggufPath, inUse: studio.inferenceBackend.hasPrefix("GGUF · "),
|
||||
filter: localQuery, selectionDisabled: studio.running) {
|
||||
studio.selectGGUFModel($0)
|
||||
}
|
||||
|
||||
Section("Installed MLX Models") {
|
||||
HStack {
|
||||
Button("Register Model Folder…") { scanRequested = false; pickingLibrary = true }
|
||||
Button("Scan Folder for Models…") { scanRequested = true; pickingLibrary = true }
|
||||
Button("Import MLX Models…") { pickingLibrary = true }
|
||||
Button("Refresh Local Models") { cacheScan += 1 }
|
||||
Button("MLX Tools…") { workshop = ModelWorkshop(base: nil) }
|
||||
if scanningLibrary { ProgressView().controlSize(.small) }
|
||||
}
|
||||
.disabled(studio.running || scanningLibrary)
|
||||
if library.isEmpty && readyModels.isEmpty && (!selection.mlxOnly || selection.mlxPath.isEmpty) {
|
||||
if library.isEmpty && studio.discoveredMLXPaths.isEmpty && readyModels.isEmpty && (!selection.mlxOnly || selection.mlxPath.isEmpty) {
|
||||
Text("Register an existing MLX folder, scan a model library, or download a catalog model below.")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
ForEach(favoriteFirst(readyModels) { "mlx:" + $0.id }) { model in modelRow(model) }
|
||||
ForEach(favoriteFirst(readyModels.filter { matchesLocal($0.id) }) { "mlx:" + $0.id }) { model in modelRow(model) }
|
||||
let selectedPath = selection.mlxOnly && !selection.mlxPath.isEmpty ? [selection.mlxPath] : []
|
||||
let paths = Array(Set(library + selectedPath)).sorted().filter { path in
|
||||
!readyModels.contains { $0.localFolder.standardizedFileURL.path == URL(fileURLWithPath: path).standardizedFileURL.path }
|
||||
}
|
||||
ForEach(favoriteFirst(paths) { "folder:" + $0 }, id: \.self) { path in
|
||||
let managedPaths = Set(readyModels.map { $0.localFolder.resolvingSymlinksInPath().path })
|
||||
let paths = Set((library + studio.discoveredMLXPaths + selectedPath).map {
|
||||
URL(fileURLWithPath: $0).resolvingSymlinksInPath().path
|
||||
}).subtracting(managedPaths).sorted()
|
||||
ForEach(favoriteFirst(paths.filter { matchesLocal(MLXLibrary.displayName(for: URL(fileURLWithPath: $0))) }) { "folder:" + $0 }, id: \.self) { path in
|
||||
HStack {
|
||||
let title = URL(fileURLWithPath: path).lastPathComponent
|
||||
let title = MLXLibrary.displayName(for: URL(fileURLWithPath: path))
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(title).help(path)
|
||||
Text("MLX · Safetensors").font(.caption).foregroundStyle(.secondary)
|
||||
ModelMemoryWarning(bytes: (try? MLXRuntimeLimits.weightBytes(in: URL(fileURLWithPath: path))).flatMap { Int64(exactly: $0) }, mlx: true)
|
||||
popularityBadge(title)
|
||||
}
|
||||
favoriteButton("folder:" + path)
|
||||
@@ -557,13 +720,11 @@ struct ModelCatalogView: View {
|
||||
Text(ModelLibrarySize.mlx(path))
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
.help("Size of local model weights")
|
||||
if selection.isMLX(path) { activeBadge("MLX") }
|
||||
mlxStatus(path)
|
||||
Button("Preview") {
|
||||
preview = mlxPreview(model: nil, folder: URL(fileURLWithPath: path))
|
||||
}
|
||||
Button("Load Model") { load(path) }
|
||||
.disabled(studio.running || loadingPath != nil || selection.isMLX(path) ||
|
||||
!MLXLibrary.isModel(at: URL(fileURLWithPath: path)))
|
||||
mlxLoadButton(path)
|
||||
Menu("Tools") {
|
||||
Button("Clone & Train…") { workshop = ModelWorkshop(base: URL(fileURLWithPath: path)) }
|
||||
Button("Reveal") {
|
||||
@@ -572,20 +733,23 @@ struct ModelCatalogView: View {
|
||||
}
|
||||
.fixedSize()
|
||||
if library.contains(path) {
|
||||
Button("Unregister") {
|
||||
registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data()
|
||||
}.disabled(studio.running)
|
||||
if library.contains(path) {
|
||||
Button("Unregister") {
|
||||
registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data()
|
||||
}.disabled(studio.running)
|
||||
}
|
||||
}
|
||||
}
|
||||
.listRowBackground(selection.isMLX(path) ? Color.accentColor.opacity(0.12) : nil)
|
||||
}
|
||||
if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) }
|
||||
}
|
||||
Section("Hugging Face") {
|
||||
CoreMLModels(selection: defaultCoreMLPath, disabled: studio.running) { studio.selectCoreMLModel($0) }
|
||||
HubGGUFDownloads()
|
||||
Section("Hugging Face · MLX") {
|
||||
HStack {
|
||||
TextField("Search MLX models", text: $query, prompt: Text("e.g. Qwen, Gemma"))
|
||||
TextField("Search MLX models", text: $query, prompt: Text("Qwen, Gemma, or owner/model"))
|
||||
.labelsHidden().textFieldStyle(.roundedBorder).onSubmit(search)
|
||||
Button(query.isEmpty ? "Browse" : "Search", action: search).disabled(searching || hasMLXDownloads)
|
||||
Button(query.isEmpty ? "Browse" : (query.contains("/") ? "Find Model ID" : "Search"), action: search).disabled(searching || hasMLXDownloads)
|
||||
if searching { ProgressView().controlSize(.small) }
|
||||
}
|
||||
if !searchStatus.isEmpty { Text(searchStatus).foregroundStyle(.secondary) }
|
||||
@@ -605,26 +769,41 @@ struct ModelCatalogView: View {
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.onAppear { if matches.isEmpty && searchStatus.isEmpty { search() } }
|
||||
.task(id: cacheScan) {
|
||||
do {
|
||||
try await studio.refreshLocalMLXModels()
|
||||
} catch is CancellationError {
|
||||
return
|
||||
} catch {
|
||||
libraryStatus = "Could not scan local models. \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
.task {
|
||||
while !Task.isCancelled {
|
||||
await refreshLoadedPath()
|
||||
do { try await Task.sleep(for: .seconds(2)) }
|
||||
catch { return }
|
||||
}
|
||||
}
|
||||
.fileImporter(isPresented: $pickingLibrary, allowedContentTypes: [.folder]) { result in
|
||||
do {
|
||||
let url = try result.get()
|
||||
if scanRequested {
|
||||
scanningLibrary = true
|
||||
Task {
|
||||
defer { scanningLibrary = false }
|
||||
do {
|
||||
let found = try await Task.detached { try MLXLibrary.discover(in: url) }.value
|
||||
registered = try JSONEncoder().encode(Array(Set(library + found.map(\.path))).sorted())
|
||||
libraryStatus = "Found \(found.count) compatible MLX model folder(s)."
|
||||
} catch { libraryStatus = error.localizedDescription }
|
||||
}
|
||||
} else {
|
||||
guard MLXLibrary.isModel(at: url) else {
|
||||
throw StudioError("Choose an MLX folder with config.json and safetensors weights.")
|
||||
}
|
||||
registered = try JSONEncoder().encode(Array(Set(library + [url.resolvingSymlinksInPath().path])).sorted())
|
||||
libraryStatus = "Registered \(url.lastPathComponent)."
|
||||
scanningLibrary = true
|
||||
libraryStatus = ""
|
||||
Task {
|
||||
defer { scanningLibrary = false }
|
||||
do {
|
||||
let found = try await Task.detached(priority: .userInitiated) {
|
||||
let scoped = url.startAccessingSecurityScopedResource()
|
||||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||||
return try MLXLibrary.discover(in: url.resolvingSymlinksInPath())
|
||||
}.value
|
||||
guard !found.isEmpty else {
|
||||
throw StudioError("No complete MLX checkpoints found in \(url.lastPathComponent).")
|
||||
}
|
||||
try registerLocalModels(found.map { .mlx($0.path) })
|
||||
libraryStatus = "Registered \(found.count) MLX model(s)."
|
||||
} catch { libraryStatus = error.localizedDescription }
|
||||
}
|
||||
} catch { libraryStatus = error.localizedDescription }
|
||||
}
|
||||
@@ -647,6 +826,9 @@ struct ModelCatalogView: View {
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Label(model.name, systemImage: "cube")
|
||||
if let format = model.details?.format {
|
||||
Text(format.uppercased()).font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
popularityBadge(model.name)
|
||||
}
|
||||
favoriteButton("ollama:" + model.name)
|
||||
@@ -811,19 +993,22 @@ struct ModelCatalogView: View {
|
||||
popularityBadge(model.repository)
|
||||
}
|
||||
HStack {
|
||||
Text("MLX · Safetensors")
|
||||
Text(installed ? ModelLibrarySize.mlx(saved.localFolder.path) : ModelLibrarySize.label(catalogBytes[metadataKey]))
|
||||
.help(installed ? "Size of local model weights" : "Weight files at the listed Hugging Face revision")
|
||||
ModelMemoryWarning(bytes: installed
|
||||
? (try? MLXRuntimeLimits.weightBytes(in: saved.localFolder)).flatMap { Int64(exactly: $0) }
|
||||
: catalogBytes[metadataKey], mlx: true)
|
||||
if let count = model.downloads { Label(count.formatted(), systemImage: "arrow.down") }
|
||||
if let count = model.likes { Label(count.formatted(), systemImage: "heart") }
|
||||
if isActive { activeBadge("MLX") }
|
||||
if installed { mlxStatus(saved.localFolder.path) }
|
||||
}.font(.caption).foregroundStyle(.secondary)
|
||||
HStack {
|
||||
Button("Preview") { preview = mlxPreview(model: model, folder: installed ? saved.localFolder : nil) }
|
||||
Link("Model Card", destination: model.source)
|
||||
Spacer()
|
||||
if installed {
|
||||
Button("Load Model") { load(saved.localFolder.path) }
|
||||
.disabled(studio.running || loadingPath != nil || isActive)
|
||||
mlxLoadButton(saved.localFolder.path)
|
||||
Button("Clone & Train…") { workshop = ModelWorkshop(base: saved.localFolder) }
|
||||
.disabled(studio.running || loadingPath != nil)
|
||||
Button("Reveal") { NSWorkspace.shared.activateFileViewerSelecting([saved.localFolder]) }
|
||||
@@ -843,7 +1028,7 @@ struct ModelCatalogView: View {
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
.listRowBackground(isActive ? Color.accentColor.opacity(0.12) : nil)
|
||||
.task(id: installed) {
|
||||
.task(id: installed ? nil : metadataKey) {
|
||||
guard !installed, catalogBytes[metadataKey] == nil else { return }
|
||||
if let metadata = try? await HubModelMetadata.load(model), !Task.isCancelled {
|
||||
catalogBytes[metadataKey] = metadata.weightBytes(files: model.files)
|
||||
@@ -865,27 +1050,75 @@ struct ModelCatalogView: View {
|
||||
guard !searching, !hasMLXDownloads else { return }
|
||||
searching = true
|
||||
searchStatus = ""
|
||||
matches = []
|
||||
Task {
|
||||
defer { searching = false }
|
||||
do {
|
||||
matches = try await CatalogModel.search(term)
|
||||
if term.contains("/") {
|
||||
matches = [try await CatalogModel.resolve(term)]
|
||||
} else {
|
||||
matches = try await CatalogModel.search(term)
|
||||
}
|
||||
if matches.isEmpty { searchStatus = "No MLX checkpoints matched." }
|
||||
} catch { searchStatus = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
private func refreshLoadedPath() async {
|
||||
loadedPath = await studio.mlxLoadedPath().map {
|
||||
URL(fileURLWithPath: $0).resolvingSymlinksInPath().path
|
||||
}
|
||||
}
|
||||
|
||||
private func isLoaded(_ path: String) -> Bool {
|
||||
loadedPath == URL(fileURLWithPath: path).resolvingSymlinksInPath().path
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func mlxStatus(_ path: String) -> some View {
|
||||
if selection.isMLX(path) {
|
||||
Label("Selected", systemImage: "checkmark.circle.fill")
|
||||
.font(.caption.weight(.semibold)).foregroundStyle(Color.accentColor)
|
||||
}
|
||||
if isLoaded(path) {
|
||||
let inUse = studio.running && studio.inferenceBackend.hasPrefix("MLX")
|
||||
Label(inUse ? "In use" : "Loaded", systemImage: "memorychip")
|
||||
.font(.caption).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func mlxLoadButton(_ path: String) -> some View {
|
||||
if isLoaded(path) {
|
||||
Button("Unload") {
|
||||
Task {
|
||||
await studio.unloadMLXModel()
|
||||
await refreshLoadedPath()
|
||||
}
|
||||
}
|
||||
.disabled(studio.running || loadingPath != nil)
|
||||
if !selection.isMLX(path) {
|
||||
Button("Use Model") { studio.selectMLXModel(path) }.disabled(studio.running)
|
||||
}
|
||||
} else {
|
||||
Button("Load Model") { load(path) }
|
||||
.disabled(studio.running || loadingPath != nil || !MLXLibrary.isModel(at: URL(fileURLWithPath: path)))
|
||||
}
|
||||
}
|
||||
|
||||
private func load(_ path: String) {
|
||||
guard loadingPath == nil, !studio.running else { return }
|
||||
loadingPath = path
|
||||
let name = URL(fileURLWithPath: path).lastPathComponent
|
||||
let name = MLXLibrary.displayName(for: URL(fileURLWithPath: path))
|
||||
status = "Loading \(name)…"
|
||||
Task {
|
||||
defer { loadingPath = nil }
|
||||
do {
|
||||
try await studio.loadMLX(path)
|
||||
studio.selectMLXModel(path)
|
||||
status = "Loaded \(name)."
|
||||
} catch { status = error.localizedDescription }
|
||||
} catch { status = "Could not load \(name). \(error.localizedDescription)" }
|
||||
await refreshLoadedPath()
|
||||
loadingPath = nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -913,10 +1146,11 @@ struct ModelCatalogView: View {
|
||||
guard !studio.running, downloads["mlx:" + model.id] == nil else { return }
|
||||
do {
|
||||
try FileManager.default.removeItem(at: model.localFolder)
|
||||
if mlxPath == model.localFolder.path {
|
||||
if isLoaded(model.localFolder.path) { studio.unloadMLX() }
|
||||
if URL(fileURLWithPath: mlxPath).resolvingSymlinksInPath().path == model.localFolder.resolvingSymlinksInPath().path {
|
||||
mlxPath = ""
|
||||
studio.unloadMLX()
|
||||
}
|
||||
studio.forgetDiscoveredMLXModel(model.localFolder.resolvingSymlinksInPath().path)
|
||||
managed = try JSONEncoder().encode(installedModels.filter { $0.id != model.id && !CatalogModel.all.contains($0) })
|
||||
status = "Removed \(model.title)."
|
||||
} catch { status = error.localizedDescription }
|
||||
@@ -937,9 +1171,17 @@ enum MLXLibrary {
|
||||
offset += 1
|
||||
if isModel(at: folder) { found.append(folder); continue }
|
||||
guard depth < 4 else { continue }
|
||||
let children = try manager.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
|
||||
options: [.skipsHiddenFiles, .skipsPackageDescendants])
|
||||
let children: [URL]
|
||||
do {
|
||||
children = try manager.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
|
||||
options: [.skipsHiddenFiles, .skipsPackageDescendants])
|
||||
.sorted { $0.lastPathComponent < $1.lastPathComponent }
|
||||
} catch {
|
||||
if depth == 0 { throw error }
|
||||
continue
|
||||
}
|
||||
for child in children where queue.count < 2000 {
|
||||
if folder.lastPathComponent.hasPrefix("models--"), child.lastPathComponent != "snapshots" { continue }
|
||||
if let values = try? child.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]),
|
||||
values.isDirectory == true, values.isSymbolicLink != true {
|
||||
queue.append((child, depth + 1))
|
||||
@@ -949,9 +1191,62 @@ enum MLXLibrary {
|
||||
return found.sorted { $0.path < $1.path }
|
||||
}
|
||||
|
||||
static func discoverLocalModels() throws -> [URL] {
|
||||
let environment = ProcessInfo.processInfo.environment
|
||||
let home = URL.homeDirectory
|
||||
let defaultCache = home.appending(path: ".cache/huggingface/hub")
|
||||
var roots = [
|
||||
URL.applicationSupportDirectory.appending(path: "AIStudio/Models"),
|
||||
URL.documentsDirectory.appending(path: "huggingface/models"),
|
||||
defaultCache, LocalModelImport.lmStudioFolder
|
||||
]
|
||||
if let cache = environment["HF_HUB_CACHE"] ?? environment["HUGGINGFACE_HUB_CACHE"], !cache.isEmpty {
|
||||
roots.append(URL(fileURLWithPath: cache))
|
||||
}
|
||||
if let hfHome = environment["HF_HOME"], !hfHome.isEmpty {
|
||||
roots.append(URL(fileURLWithPath: hfHome).appending(path: "hub"))
|
||||
}
|
||||
if let cache = environment["XDG_CACHE_HOME"], !cache.isEmpty {
|
||||
roots.append(URL(fileURLWithPath: cache).appending(path: "huggingface/hub"))
|
||||
}
|
||||
var found: Set<URL> = []
|
||||
for root in Set(roots.map { $0.resolvingSymlinksInPath() }) where FileManager.default.fileExists(atPath: root.path) {
|
||||
found.formUnion(try discover(in: root))
|
||||
}
|
||||
return found.sorted { $0.path < $1.path }
|
||||
}
|
||||
|
||||
static func displayName(for folder: URL) -> String {
|
||||
let snapshots = folder.deletingLastPathComponent()
|
||||
let repository = snapshots.deletingLastPathComponent().lastPathComponent
|
||||
guard snapshots.lastPathComponent == "snapshots", repository.hasPrefix("models--") else {
|
||||
return folder.lastPathComponent
|
||||
}
|
||||
let name = repository.dropFirst("models--".count).replacingOccurrences(of: "--", with: "/")
|
||||
return "\(name) · \(folder.lastPathComponent.prefix(8))"
|
||||
}
|
||||
|
||||
static func hasFile(_ name: String, in folder: URL) -> Bool {
|
||||
let file = folder.appending(path: name).resolvingSymlinksInPath()
|
||||
guard let values = try? file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) else { return false }
|
||||
return values.isRegularFile == true && (values.fileSize ?? 0) > 0
|
||||
}
|
||||
|
||||
static func isModel(at url: URL) -> Bool {
|
||||
FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) &&
|
||||
((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0
|
||||
let config = url.appending(path: "config.json")
|
||||
guard hasFile("config.json", in: url),
|
||||
let data = try? Data(contentsOf: config),
|
||||
(try? MLXModelConfiguration.decode(data)) != nil,
|
||||
((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0 else { return false }
|
||||
let index = url.appending(path: "model.safetensors.index.json")
|
||||
guard FileManager.default.fileExists(atPath: index.path) else { return true }
|
||||
struct Index: Decodable { let weight_map: [String: String] }
|
||||
guard let data = try? Data(contentsOf: index),
|
||||
let map = try? JSONDecoder().decode(Index.self, from: data).weight_map,
|
||||
!map.isEmpty else { return false }
|
||||
return Set(map.values).allSatisfy {
|
||||
CatalogModel.safeComponent($0) && $0.hasSuffix(".safetensors") && hasFile($0, in: url)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+65
-3
@@ -86,6 +86,10 @@ final class Store {
|
||||
|
||||
private func prepareMessageSources() throws {
|
||||
try execute("""
|
||||
CREATE TABLE IF NOT EXISTS message_performance (
|
||||
message TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
|
||||
measurement TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS message_web_sources (
|
||||
message TEXT PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
|
||||
sources TEXT NOT NULL
|
||||
@@ -245,7 +249,7 @@ final class Store {
|
||||
[message.id.uuidString, chat.uuidString, message.role.rawValue, message.content, message.thinking, message.backend])
|
||||
}
|
||||
|
||||
guard !message.webSources.isEmpty || !message.documentNames.isEmpty || !message.documentCitations.isEmpty else {
|
||||
guard !message.webSources.isEmpty || !message.documentNames.isEmpty || !message.documentCitations.isEmpty || message.performance != nil else {
|
||||
try insertMessage()
|
||||
return
|
||||
}
|
||||
@@ -268,6 +272,11 @@ final class Store {
|
||||
try mutate("INSERT INTO message_document_citations(message,citations) VALUES(?,?)",
|
||||
[message.id.uuidString, String(decoding: citations, as: UTF8.self)])
|
||||
}
|
||||
if let timing = message.performance {
|
||||
let data = try encoder.encode(timing)
|
||||
try mutate("INSERT INTO message_performance(message,measurement) VALUES(?,?)",
|
||||
[message.id.uuidString, String(decoding: data, as: UTF8.self)])
|
||||
}
|
||||
try execute("RELEASE save_message_sources")
|
||||
} catch {
|
||||
try? execute("ROLLBACK TO save_message_sources")
|
||||
@@ -278,11 +287,12 @@ final class Store {
|
||||
|
||||
func messages(in chat: UUID) throws -> [Message] {
|
||||
try query("""
|
||||
SELECT m.id,m.role,m.content,m.thinking,m.backend,w.sources,d.names,c.citations
|
||||
SELECT m.id,m.role,m.content,m.thinking,m.backend,w.sources,d.names,c.citations,p.measurement
|
||||
FROM messages m
|
||||
LEFT JOIN message_web_sources w ON w.message=m.id
|
||||
LEFT JOIN message_documents d ON d.message=m.id
|
||||
LEFT JOIN message_document_citations c ON c.message=m.id
|
||||
LEFT JOIN message_performance p ON p.message=m.id
|
||||
WHERE m.chat=? ORDER BY m.rowid
|
||||
""", [chat.uuidString]) { row in
|
||||
guard let role = Role(rawValue: string(row, 1)) else { throw StudioError("Invalid stored message role.") }
|
||||
@@ -291,10 +301,62 @@ final class Store {
|
||||
let documents = (try? decoder.decode([String].self, from: Data(string(row, 6).utf8))) ?? []
|
||||
return Message(id: try uuid(row, 0), role: role, content: string(row, 2),
|
||||
thinking: string(row, 3), backend: string(row, 4), webSources: sources, documentNames: documents,
|
||||
documentCitations: decodeArray(string(row, 7)))
|
||||
documentCitations: decodeArray(string(row, 7)),
|
||||
performance: try? decoder.decode(GenerationMeasurement.self, from: Data(string(row, 8).utf8)))
|
||||
}
|
||||
}
|
||||
|
||||
func exportChat(_ chat: UUID, to url: URL) throws {
|
||||
guard let title = try query("SELECT title FROM chats WHERE id=?", [chat.uuidString], map: {
|
||||
string($0, 0)
|
||||
}).first else {
|
||||
throw StudioError("This conversation is no longer available.")
|
||||
}
|
||||
|
||||
func inline(_ text: String) -> String {
|
||||
let punctuation: Set<Character> = ["\\", "`", "*", "_", "[", "]", "<", ">", "#", "&", "~"]
|
||||
return text.components(separatedBy: .newlines).joined(separator: " ").map {
|
||||
punctuation.contains($0) ? "\\\($0)" : String($0)
|
||||
}.joined()
|
||||
}
|
||||
|
||||
func quote(_ text: String) -> String {
|
||||
text.components(separatedBy: "\n").map { "> " + $0 }.joined(separator: "\n")
|
||||
}
|
||||
|
||||
var sections = ["# \(inline(title))"]
|
||||
for message in try messages(in: chat) {
|
||||
switch message.role {
|
||||
case .user: sections.append("## You")
|
||||
case .assistant: sections.append("## Assistant")
|
||||
case .system: sections.append("## System")
|
||||
}
|
||||
if !message.backend.isEmpty { sections.append("*\(inline(message.backend))*") }
|
||||
if !message.content.isEmpty { sections.append(message.content) }
|
||||
if !message.thinking.isEmpty {
|
||||
sections.append("### Thinking\n\n" + quote(message.thinking))
|
||||
}
|
||||
if !message.documentNames.isEmpty {
|
||||
sections.append("### Attachments\n\n" + message.documentNames.map { "- " + inline($0) }.joined(separator: "\n"))
|
||||
}
|
||||
if !message.documentCitations.isEmpty {
|
||||
sections.append("### Document Sources")
|
||||
for source in message.documentCitations {
|
||||
sections.append("**\\[D\(source.number)\\] \(inline(source.title))**\n\n" + quote(source.excerpt))
|
||||
}
|
||||
}
|
||||
let webLinks = message.webSources.compactMap { source -> String? in
|
||||
guard let url = try? WebClipCapture.url(source.url.absoluteString) else { return nil }
|
||||
let label = source.title.isEmpty ? url.absoluteString : source.title
|
||||
return "- [\(inline(label))](<\(url.absoluteString)>)"
|
||||
}
|
||||
if !webLinks.isEmpty {
|
||||
sections.append("### Web Sources\n\n" + webLinks.joined(separator: "\n"))
|
||||
}
|
||||
}
|
||||
try (sections.joined(separator: "\n\n") + "\n").write(to: url, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
func memory(matching prompt: String, in chat: UUID, excluding: Set<UUID> = []) throws -> [String] {
|
||||
let terms = Array(Set(prompt.lowercased().split { !$0.isLetter && !$0.isNumber }
|
||||
.filter { $0.count >= 4 }.prefix(12).map(String.init))).sorted()
|
||||
|
||||
+155
-37
@@ -65,6 +65,10 @@ final class StudioModel: ObservableObject {
|
||||
}
|
||||
|
||||
@Published private(set) var measurements: [GenerationMeasurement] = []
|
||||
@Published var performanceModel: ChatModelChoice?
|
||||
@Published private(set) var benchmarkRunning = false
|
||||
@Published private(set) var benchmarkStatus = ""
|
||||
private var benchmarkTask: Task<Void, Never>?
|
||||
@Published private(set) var knowledgeStacks: [Conversation] = []
|
||||
@Published private(set) var snippets: [WorkspaceSnippet] = []
|
||||
@Published private(set) var mcpConnections: [MCPConnectionID: MCPConnectionState] = [:]
|
||||
@@ -75,6 +79,18 @@ final class StudioModel: ObservableObject {
|
||||
mcpConnections.compactMap { id, state in state.toolset.map { (id, $0) } }
|
||||
.sorted { $0.1.name.localizedStandardCompare($1.1.name) == .orderedAscending }
|
||||
}
|
||||
private var repositoryToolset: ActiveToolset? {
|
||||
let servers = activeToolsets.filter {
|
||||
$0.id != .web && $0.toolset.tools.contains { $0.name == "list_repositories" }
|
||||
}
|
||||
return (servers.first { entry in
|
||||
if case .profile(let profile) = entry.id, profile.localizedCaseInsensitiveContains("gitea") {
|
||||
return true
|
||||
}
|
||||
return entry.toolset.name.localizedCaseInsensitiveContains("gitea")
|
||||
} ?? servers.first)?.toolset
|
||||
}
|
||||
|
||||
@Published var activeStack: UUID?
|
||||
@Published var activeRemoteStack: RemoteStackChoice = .automatic
|
||||
@Published var activeSkill: UUID?
|
||||
@@ -122,6 +138,12 @@ final class StudioModel: ObservableObject {
|
||||
(try? store?.messages(in: id)) ?? []
|
||||
}
|
||||
|
||||
func exportChat(_ id: UUID, to url: URL) throws {
|
||||
let scoped = url.startAccessingSecurityScopedResource()
|
||||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||||
try database().exportChat(id, to: url)
|
||||
}
|
||||
|
||||
func searchConversations(_ term: String) -> [Conversation] {
|
||||
(try? store?.searchConversations(term)) ?? []
|
||||
}
|
||||
@@ -175,12 +197,16 @@ final class StudioModel: ObservableObject {
|
||||
|
||||
func send(endpoint: String, model: String, mlxPath: String, thinking: Thinking, failover: Bool,
|
||||
mlxOnly: Bool, compatible: Bool, recall: Bool, useDocuments: Bool, instructions: String, settings: GenerationSettings, agents: [AgentRole] = [], agentTools: Bool = false,
|
||||
ragEnabled: Bool = true, lmStudioPlugins: [String] = []) {
|
||||
ragEnabled: Bool = true, lmStudioPlugins: [String] = [], gguf: Bool = false, coreML: Bool = false) {
|
||||
let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let tag = model.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !running, !text.isEmpty else { return }
|
||||
guard !running, !benchmarkRunning, !text.isEmpty else { return }
|
||||
let attachment = toolAttachment
|
||||
let image = attachment?.imagePNG
|
||||
if (gguf || coreML) && image != nil {
|
||||
status = "This local model supports text. Remove the image attachment to continue."
|
||||
return
|
||||
}
|
||||
if image != nil && mlxOnly && attachment?.output.isEmpty == true {
|
||||
status = "MLX could not get readable text from this image. Choose a vision-capable model to analyze the image."
|
||||
return
|
||||
@@ -206,7 +232,7 @@ final class StudioModel: ObservableObject {
|
||||
do {
|
||||
let (name, generate) = try inferenceRoute(
|
||||
endpoint: endpoint, model: tag, mlxPath: mlxPath, mlxOnly: mlxOnly,
|
||||
compatible: compatible, failover: failover)
|
||||
compatible: compatible, failover: failover, gguf: gguf, coreML: coreML)
|
||||
let pluginClient = compatible && !mlxOnly && !lmStudioPlugins.isEmpty
|
||||
? try compatibleClient(endpoint: endpoint) : nil
|
||||
let parameters = try settings.parameters(mlxOnly: mlxOnly, compatible: compatible)
|
||||
@@ -420,9 +446,7 @@ final class StudioModel: ObservableObject {
|
||||
if wantsRepositories {
|
||||
webStatus = "Listing Gitea repositories…"
|
||||
do {
|
||||
guard let repositoryClient = activeToolsets.first(where: {
|
||||
$0.toolset.tools.contains { $0.name == "list_repositories" }
|
||||
})?.toolset.client else {
|
||||
guard let repositoryClient = repositoryToolset?.client else {
|
||||
throw StudioError("Enable the Gitea server in Toolbox → MCP Servers and check its connection.")
|
||||
}
|
||||
let repositories = try await GiteaRepositoryLookup.references(client: repositoryClient)
|
||||
@@ -500,6 +524,7 @@ final class StudioModel: ObservableObject {
|
||||
do {
|
||||
let data = try await connected.client.callTool(offer.tool.name, argumentsJSON: request.arguments)
|
||||
try Task.checkCancellation()
|
||||
try MCPToolResponse.check(data, tool: offer.tool.name)
|
||||
self.agentSteps.append("Tool completed · \(offer.tool.name)")
|
||||
return String(decoding: data.prefix(48_000), as: UTF8.self)
|
||||
} catch {
|
||||
@@ -510,7 +535,9 @@ final class StudioModel: ObservableObject {
|
||||
})
|
||||
}
|
||||
}
|
||||
await consume(stream, in: chat, start: start, requested: name)
|
||||
let requestedModel = mlxOnly ? MLXLibrary.displayName(for: URL(fileURLWithPath: mlxPath)) :
|
||||
(gguf || coreML ? URL(fileURLWithPath: tag).deletingPathExtension().lastPathComponent : tag)
|
||||
await consume(stream, in: chat, start: start, requested: name, model: requestedModel)
|
||||
}
|
||||
} catch { status = error.localizedDescription }
|
||||
}
|
||||
@@ -543,7 +570,16 @@ final class StudioModel: ObservableObject {
|
||||
private typealias Generate = @Sendable ([Message], Thinking, GenerationParameters) -> AsyncThrowingStream<Delta, Error>
|
||||
|
||||
private func inferenceRoute(endpoint: String, model: String, mlxPath: String, mlxOnly: Bool,
|
||||
compatible: Bool, failover: Bool) throws -> (String, Generate) {
|
||||
compatible: Bool, failover: Bool, gguf: Bool = false, coreML: Bool = false) throws -> (String, Generate) {
|
||||
if gguf || coreML {
|
||||
let provider: any InferenceProvider = coreML ? CoreMLProvider() : GGUFProvider()
|
||||
let name = coreML ? "Core ML" : "GGUF"
|
||||
return (name, { messages, thinking, parameters in
|
||||
Router.stream(primary: {
|
||||
provider.generate(.init(model: model, messages: messages, thinking: thinking, parameters: parameters))
|
||||
}, fallback: nil, primaryName: name)
|
||||
})
|
||||
}
|
||||
let provider: (any InferenceProvider)?
|
||||
let name: String
|
||||
if mlxOnly {
|
||||
@@ -567,11 +603,61 @@ final class StudioModel: ObservableObject {
|
||||
})
|
||||
}
|
||||
|
||||
static let benchmarkPrompt = "Write a numbered list of 20 practical tips for keeping a small garden healthy. Use one complete sentence per tip."
|
||||
|
||||
func benchmark(_ choice: ChatModelChoice, endpoint: String, repetitions: Int) {
|
||||
guard !running, !benchmarkRunning, !choice.model.isEmpty, (1...5).contains(repetitions) else { return }
|
||||
benchmarkRunning = true
|
||||
benchmarkStatus = "Preparing benchmark…"
|
||||
benchmarkTask = Task {
|
||||
defer {
|
||||
benchmarkRunning = false
|
||||
benchmarkTask = nil
|
||||
}
|
||||
do {
|
||||
let (backend, generate) = try inferenceRoute(endpoint: endpoint, model: choice.model,
|
||||
mlxPath: choice.model, mlxOnly: choice.backend == .mlx, compatible: choice.backend == .compatible,
|
||||
failover: false, gguf: choice.backend == .gguf, coreML: choice.backend == .coreML)
|
||||
var parameters = GenerationParameters()
|
||||
parameters.temperature = 0
|
||||
parameters.maxTokens = 128
|
||||
for run in 1...repetitions {
|
||||
try Task.checkCancellation()
|
||||
benchmarkStatus = "Running \(run) of \(repetitions)…"
|
||||
var capture = GenerationCapture(start: ProcessInfo.processInfo.systemUptime)
|
||||
do {
|
||||
for try await delta in generate([.init(role: .user, content: Self.benchmarkPrompt)], .automatic, parameters) {
|
||||
try Task.checkCancellation()
|
||||
capture.observe(delta, at: ProcessInfo.processInfo.systemUptime)
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
guard capture.characters > 0 else { throw StudioError("The model returned no text.") }
|
||||
record(capture.finish(at: ProcessInfo.processInfo.systemUptime, requested: backend,
|
||||
model: choice.displayName, outcome: "Complete", benchmark: true))
|
||||
} catch {
|
||||
record(capture.finish(at: ProcessInfo.processInfo.systemUptime, requested: backend,
|
||||
model: choice.displayName, outcome: Task.isCancelled ? "Stopped" : "Failed", benchmark: true))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
benchmarkStatus = repetitions == 1 ? "Benchmark complete." : "\(repetitions) benchmark runs complete."
|
||||
} catch {
|
||||
benchmarkStatus = Task.isCancelled ? "Benchmark stopped." : error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func stopBenchmark() { benchmarkTask?.cancel() }
|
||||
|
||||
func evaluatePrompt(_ template: PromptTemplate, input: String) async throws -> String {
|
||||
let defaults = UserDefaults.standard
|
||||
let mlxOnly = defaults.bool(forKey: "mlxOnly")
|
||||
let compatible = !mlxOnly && defaults.bool(forKey: "compatibleEnabled")
|
||||
let model = defaults.string(forKey: compatible ? "compatibleModel" : "ollamaModel") ?? ""
|
||||
let ggufPath = defaults.string(forKey: "defaultGGUFPath") ?? ""
|
||||
let coreMLPath = defaults.string(forKey: "defaultCoreMLPath") ?? ""
|
||||
let coreML = !coreMLPath.isEmpty
|
||||
let gguf = !coreML && !ggufPath.isEmpty
|
||||
let mlxOnly = !coreML && !gguf && defaults.bool(forKey: "mlxOnly")
|
||||
let compatible = !coreML && !gguf && !mlxOnly && defaults.bool(forKey: "compatibleEnabled")
|
||||
let model = coreML ? coreMLPath : gguf ? ggufPath : defaults.string(forKey: compatible ? "compatibleModel" : "ollamaModel") ?? ""
|
||||
let mlxPath = defaults.string(forKey: "mlxPath") ?? ""
|
||||
guard mlxOnly ? !mlxPath.isEmpty : !model.isEmpty else {
|
||||
throw StudioError("Choose a generation model in Settings before evaluating.")
|
||||
@@ -581,7 +667,7 @@ final class StudioModel: ObservableObject {
|
||||
: (defaults.string(forKey: "endpoint") ?? "http://127.0.0.1:11434")
|
||||
let (_, generate) = try inferenceRoute(
|
||||
endpoint: endpoint, model: model, mlxPath: mlxPath, mlxOnly: mlxOnly,
|
||||
compatible: compatible, failover: defaults.object(forKey: "failover") as? Bool ?? true)
|
||||
compatible: compatible, failover: defaults.object(forKey: "failover") as? Bool ?? true, gguf: gguf, coreML: coreML)
|
||||
let settings = GenerationSettings.read(defaults.data(forKey: GenerationSettings.key) ?? Data())
|
||||
let prepared = try StudioPromptRequest.prepare([Message(role: .user, content: input)], template: template,
|
||||
options: .init(), parameters: settings.parameters(mlxOnly: mlxOnly, compatible: compatible))
|
||||
@@ -848,18 +934,16 @@ final class StudioModel: ObservableObject {
|
||||
}
|
||||
for task in connecting { await task.value }
|
||||
try Task.checkCancellation()
|
||||
guard let server = activeToolsets.first(where: {
|
||||
$0.toolset.tools.contains { $0.name == "list_repositories" }
|
||||
}) else {
|
||||
guard let server = repositoryToolset else {
|
||||
throw StudioError("Connect your Gitea server in Settings → Toolbox to list repositories.")
|
||||
}
|
||||
let entries = try await GiteaRepositoryLookup.entries(client: server.toolset.client)
|
||||
let entries = try await GiteaRepositoryLookup.entries(client: server.client)
|
||||
try Task.checkCancellation()
|
||||
let shown = entries.prefix(limit)
|
||||
let summary = shown.isEmpty ? "Gitea returned no repositories for the connected account." :
|
||||
"Showing \(shown.count) of \(entries.count) repositories returned by Gitea.\n\n" +
|
||||
shown.enumerated().map { "\($0.offset + 1). \($0.element)" }.joined(separator: "\n")
|
||||
let reply = Message(role: .assistant, content: summary, backend: "Gitea · " + server.toolset.name)
|
||||
let reply = Message(role: .assistant, content: summary, backend: "Gitea · " + server.name)
|
||||
try store.save(reply, in: chat)
|
||||
if selected == chat { messages.append(reply) }
|
||||
} catch {
|
||||
@@ -939,8 +1023,37 @@ final class StudioModel: ObservableObject {
|
||||
} catch { status = error.localizedDescription }
|
||||
}
|
||||
|
||||
@Published private(set) var discoveredMLXPaths: [String] = []
|
||||
|
||||
func refreshLocalMLXModels() async throws {
|
||||
let scan = Task.detached(priority: .utility) { try MLXLibrary.discoverLocalModels() }
|
||||
let paths = try await withTaskCancellationHandler {
|
||||
try await scan.value.map(\.path)
|
||||
} onCancel: { scan.cancel() }
|
||||
try Task.checkCancellation()
|
||||
discoveredMLXPaths = paths
|
||||
}
|
||||
|
||||
func forgetDiscoveredMLXModel(_ path: String) {
|
||||
discoveredMLXPaths.removeAll { $0 == path }
|
||||
}
|
||||
|
||||
func selectCoreMLModel(_ path: String) {
|
||||
UserDefaults.standard.removeObject(forKey: "defaultGGUFPath")
|
||||
UserDefaults.standard.set(path, forKey: "defaultCoreMLPath")
|
||||
modelSelectionRevision += 1
|
||||
}
|
||||
|
||||
func selectGGUFModel(_ path: String) {
|
||||
UserDefaults.standard.removeObject(forKey: "defaultCoreMLPath")
|
||||
UserDefaults.standard.set(path, forKey: "defaultGGUFPath")
|
||||
modelSelectionRevision += 1
|
||||
}
|
||||
|
||||
func selectMLXModel(_ path: String) {
|
||||
let defaults = UserDefaults.standard
|
||||
defaults.removeObject(forKey: "defaultGGUFPath")
|
||||
defaults.removeObject(forKey: "defaultCoreMLPath")
|
||||
defaults.set(path, forKey: "mlxPath")
|
||||
defaults.set(true, forKey: "mlxOnly")
|
||||
modelSelectionRevision += 1
|
||||
@@ -948,6 +1061,8 @@ final class StudioModel: ObservableObject {
|
||||
|
||||
func selectOllamaModel(_ name: String) {
|
||||
let defaults = UserDefaults.standard
|
||||
defaults.removeObject(forKey: "defaultGGUFPath")
|
||||
defaults.removeObject(forKey: "defaultCoreMLPath")
|
||||
defaults.set(name, forKey: "ollamaModel")
|
||||
defaults.set(false, forKey: "compatibleEnabled")
|
||||
defaults.set(false, forKey: "mlxOnly")
|
||||
@@ -959,7 +1074,11 @@ final class StudioModel: ObservableObject {
|
||||
try await mlx.load(path)
|
||||
}
|
||||
|
||||
func unloadMLX() { Task { await mlx.unload() } }
|
||||
func unloadMLX() { Task { await unloadMLXModel() } }
|
||||
|
||||
func unloadMLXModel() async { await mlx.unload() }
|
||||
|
||||
func mlxLoadedPath() async -> String? { await mlx.modelDirectory() }
|
||||
|
||||
func mlxModelName() async -> String? { await mlx.modelName() }
|
||||
|
||||
@@ -992,25 +1111,22 @@ final class StudioModel: ObservableObject {
|
||||
}
|
||||
|
||||
private func consume(_ stream: AsyncThrowingStream<Delta, Error>, in chat: UUID,
|
||||
start: Double, requested: String) async {
|
||||
var firstOutput: Double?
|
||||
var provider: ProviderMetrics?
|
||||
start: Double, requested: String, model: String) async {
|
||||
var capture = GenerationCapture(start: start)
|
||||
defer { partial = nil; running = false; generation = nil }
|
||||
do {
|
||||
for try await delta in stream {
|
||||
try Task.checkCancellation()
|
||||
capture.observe(delta, at: ProcessInfo.processInfo.systemUptime)
|
||||
switch delta {
|
||||
case .answer(let text):
|
||||
if firstOutput == nil, !text.isEmpty { firstOutput = ProcessInfo.processInfo.systemUptime - start }
|
||||
partial?.content += text
|
||||
case .thinking(let text):
|
||||
if firstOutput == nil, !text.isEmpty { firstOutput = ProcessInfo.processInfo.systemUptime - start }
|
||||
partial?.thinking += text
|
||||
case .backend(let name):
|
||||
inferenceBackend = name
|
||||
partial?.backend = name
|
||||
case .metrics(let metrics): provider = metrics
|
||||
case .committed: break
|
||||
case .metrics, .committed: break
|
||||
}
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
@@ -1020,19 +1136,11 @@ final class StudioModel: ObservableObject {
|
||||
} catch {
|
||||
status = Task.isCancelled ? "Generation stopped." : error.localizedDescription
|
||||
}
|
||||
let backend = partial?.backend ?? ""
|
||||
measurements.insert(GenerationMeasurement(
|
||||
backend: backend.isEmpty ? requested : backend,
|
||||
firstOutput: firstOutput,
|
||||
seconds: ProcessInfo.processInfo.systemUptime - start,
|
||||
characters: (partial?.content.count ?? 0) + (partial?.thinking.count ?? 0),
|
||||
provider: provider, outcome: Task.isCancelled ? "Stopped" : (status.isEmpty ? "Complete" : "Failed")
|
||||
), at: 0)
|
||||
if measurements.count > 50 { measurements.removeLast() }
|
||||
if let history = try? JSONEncoder().encode(measurements) {
|
||||
UserDefaults.standard.set(history, forKey: GenerationMeasurement.key)
|
||||
}
|
||||
let measurement = capture.finish(at: ProcessInfo.processInfo.systemUptime, requested: requested,
|
||||
model: model, outcome: Task.isCancelled ? "Stopped" : (status.isEmpty ? "Complete" : "Failed"))
|
||||
record(measurement)
|
||||
if var reply = partial, !reply.content.isEmpty || !reply.thinking.isEmpty {
|
||||
reply.performance = measurement
|
||||
if !status.isEmpty { reply.backend += " · Interrupted" }
|
||||
do {
|
||||
try database().save(reply, in: chat)
|
||||
@@ -1044,6 +1152,15 @@ final class StudioModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
private func record(_ measurement: GenerationMeasurement) {
|
||||
let defaults = UserDefaults.standard
|
||||
let previous = GenerationMeasurement.history(defaults.data(forKey: GenerationMeasurement.key) ?? Data())
|
||||
measurements = Array(([measurement] + previous).prefix(50))
|
||||
if let data = try? JSONEncoder().encode(measurements) {
|
||||
defaults.set(data, forKey: GenerationMeasurement.key)
|
||||
}
|
||||
}
|
||||
|
||||
private func database() throws -> Store {
|
||||
guard let store else { throw StudioError("The chat database is unavailable.") }
|
||||
return store
|
||||
@@ -1129,6 +1246,7 @@ extension StudioModel {
|
||||
runMCP(id, progress: "Running \(tool)…") {
|
||||
let client: any MCPToolClient = id == .web ? BuiltInWebTools(searchEndpoint: searchEndpoint) : connected.client
|
||||
let response = try await client.callTool(tool, argumentsJSON: arguments)
|
||||
try MCPToolResponse.check(response, tool: tool)
|
||||
return MCPConnectionState(toolset: connected, output: String(decoding: response, as: UTF8.self),
|
||||
completedTool: tool)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user