129 lines
5.6 KiB
Swift
129 lines
5.6 KiB
Swift
import Foundation
|
|
import MLXLLM
|
|
import MLXLMCommon
|
|
|
|
actor MLXProvider: InferenceProvider {
|
|
private var loaded: (directory: String, container: ModelContainer)?
|
|
|
|
func unload() { loaded = nil }
|
|
|
|
nonisolated func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
|
|
streaming { continuation in
|
|
try await self.generate(request, continuation: continuation)
|
|
}
|
|
}
|
|
|
|
private func generate(_ request: InferenceRequest, continuation: AsyncThrowingStream<Delta, Error>.Continuation) async throws {
|
|
let directory = request.model
|
|
let model: ModelContainer
|
|
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.")
|
|
}
|
|
model = try await LLMModelFactory.shared.loadContainer(configuration: .init(directory: url))
|
|
try Task.checkCancellation()
|
|
loaded = (directory, model)
|
|
}
|
|
let history: [Chat.Message] = 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)
|
|
var context: [String: any Sendable]?
|
|
if supportsThinking {
|
|
switch request.thinking {
|
|
case .off: context = ["enable_thinking": false]
|
|
case .on: context = ["enable_thinking": true]
|
|
case .automatic, .low, .medium, .high: break
|
|
}
|
|
}
|
|
var thinkingOutput = MLXThinking()
|
|
let input = try await model.prepare(input: UserInput(chat: history, additionalContext: context))
|
|
let output = try await model.generate(input: input, parameters: GenerateParameters(maxTokens: 1024))
|
|
continuation.yield(.backend("MLX · \(URL(fileURLWithPath: directory).lastPathComponent)"))
|
|
var finished = false
|
|
for await event in output {
|
|
try Task.checkCancellation()
|
|
switch event {
|
|
case .chunk(let text):
|
|
if supportsThinking {
|
|
for delta in thinkingOutput.append(text) { continuation.yield(delta) }
|
|
} else {
|
|
continuation.yield(.answer(text))
|
|
}
|
|
case .info(let info):
|
|
finished = true
|
|
continuation.yield(.metrics(ProviderMetrics(tokens: info.generationTokenCount, seconds: info.generateTime)))
|
|
case .toolCall:
|
|
continuation.yield(.committed)
|
|
throw StudioError("The MLX model returned a tool call, but no tools are configured.")
|
|
}
|
|
}
|
|
try Task.checkCancellation()
|
|
guard finished else { throw StudioError("MLX generation ended without completion information.") }
|
|
for delta in thinkingOutput.finish() { continuation.yield(delta) }
|
|
}
|
|
}
|
|
|
|
struct MLXThinking {
|
|
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 {
|
|
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,
|
|
size < 2_000_000,
|
|
let data = try? Data(contentsOf: url, options: .mappedIfSafe),
|
|
let config = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
|
|
let template = config["chat_template"] as? String else { return false }
|
|
return template.contains("enable_thinking") && template.contains(start) && template.contains(end)
|
|
}
|
|
|
|
mutating func append(_ text: String) -> [Delta] {
|
|
buffer += text
|
|
if !decided {
|
|
let candidate = buffer.drop(while: \.isWhitespace)
|
|
if candidate.isEmpty && buffer.count < 32 { return [] }
|
|
if candidate.hasPrefix(Self.start) {
|
|
buffer = String(candidate.dropFirst(Self.start.count))
|
|
readingThinking = true
|
|
} else if Self.start.hasPrefix(candidate) && !candidate.isEmpty {
|
|
return []
|
|
}
|
|
decided = true
|
|
}
|
|
if !readingThinking { return drain(asThinking: false) }
|
|
if let close = buffer.range(of: Self.end) {
|
|
let reasoning = String(buffer[..<close.lowerBound])
|
|
buffer = String(buffer[close.upperBound...])
|
|
readingThinking = false
|
|
return (reasoning.isEmpty ? [] : [.thinking(reasoning)]) + drain(asThinking: false)
|
|
}
|
|
let length = (1..<Self.end.count).reversed().first { size in
|
|
Self.end.hasPrefix(buffer.suffix(size)) && buffer.count >= size
|
|
} ?? 0
|
|
let complete = String(buffer.dropLast(length))
|
|
buffer = String(buffer.suffix(length))
|
|
return complete.isEmpty ? [] : [.thinking(complete)]
|
|
}
|
|
|
|
mutating func finish() -> [Delta] { drain(asThinking: readingThinking) }
|
|
|
|
private mutating func drain(asThinking: Bool) -> [Delta] {
|
|
guard !buffer.isEmpty else { return [] }
|
|
defer { buffer = "" }
|
|
return [asThinking ? .thinking(buffer) : .answer(buffer)]
|
|
}
|
|
}
|