new features
This commit is contained in:
+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