Build AI Studio 1.1 for macOS #1
+9
-1
@@ -6,7 +6,8 @@
|
|||||||
| 2. Studio features | Complete | App icon and startup screen, MLX catalog, Qwen thinking, document retrieval, MCP Streamable HTTP tools |
|
| 2. Studio features | Complete | App icon and startup screen, MLX catalog, Qwen thinking, document retrieval, MCP Streamable HTTP tools |
|
||||||
| 3. Release readiness | Awaiting external checks | Authenticated gateway tests, archive verification, live remote interoperability and distribution signing |
|
| 3. Release readiness | Awaiting external checks | Authenticated gateway tests, archive verification, live remote interoperability and distribution signing |
|
||||||
| 4. Chat workspace | Complete | Chat search and rename, formatted answers, global prompt modes, prompt builder, performance dashboard |
|
| 4. Chat workspace | Complete | Chat search and rename, formatted answers, global prompt modes, prompt builder, performance dashboard |
|
||||||
| 5. MCP compatibility | Planned | Stdio transport and broader authentication and interaction support |
|
| 5. Generation and local tools | Awaiting Docker daemon check | Silent system instructions, runtime parameter overrides, confirmed Docker commands, Finder file actions |
|
||||||
|
| 6. Compatibility extensions | Planned | OpenAI-compatible endpoint, MCP stdio, broader desktop automation and runtime controls |
|
||||||
|
|
||||||
## Phase 3 checklist
|
## Phase 3 checklist
|
||||||
|
|
||||||
@@ -42,3 +43,10 @@ search and rename. The Debug build launched from `Scripts/build.sh`.
|
|||||||
**16 November 2026.** The release archive matched its SHA-256 checksum. The
|
**16 November 2026.** The release archive matched its SHA-256 checksum. The
|
||||||
extracted app passed strict signature verification and contained only the
|
extracted app passed strict signature verification and contained only the
|
||||||
arm64 executable slice. The package used ad-hoc signing for local testing.
|
arm64 executable slice. The package used ad-hoc signing for local testing.
|
||||||
|
|
||||||
|
**16 November 2026.** Generation settings and Local Tools built successfully.
|
||||||
|
24 tests passed and the opt-in catalog download was skipped. The live Ollama
|
||||||
|
and MLX checks used temperature and token-cap overrides. The new tests cover
|
||||||
|
the system-role request, option encoding, cross-chunk stop matching, and Docker
|
||||||
|
argument handling. Docker CLI discovery succeeded; the local daemon socket
|
||||||
|
was missing during the read-only test. Finder actions were compiled.
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ The client supports Streamable HTTP with current stateless discovery and legacy
|
|||||||
|
|
||||||
## 4. Customize prompts and review performance
|
## 4. Customize prompts and review performance
|
||||||
|
|
||||||
Choose a **Global Prompt** in the composer. Default, Concise, Coding, Study,
|
Choose a **Global preset** in **Settings → Generation**. Default, Concise, Coding, Study,
|
||||||
Creative, and Custom are available across conversations. **Prompt Builder**
|
Creative, and Custom are available across conversations. **Prompt Builder**
|
||||||
turns structured inputs into a prompt you can copy, put in the composer,
|
turns structured inputs into a prompt you can copy, put in the composer,
|
||||||
or save as the global system prompt. Global settings persist across launches.
|
or save as the global system prompt. Global settings persist across launches.
|
||||||
@@ -33,6 +33,23 @@ code blocks with copy controls. The **Performance** dashboard tracks the last
|
|||||||
50 generations in this session, including latency, duration, output size,
|
50 generations in this session, including latency, duration, output size,
|
||||||
backend, and tokens per second when the provider supplies it.
|
backend, and tokens per second when the provider supplies it.
|
||||||
|
|
||||||
|
## 5. Generation and local tools
|
||||||
|
|
||||||
|
**Settings → Generation** applies system instructions to future requests
|
||||||
|
without adding a transcript message. Save parameter overrides with **Apply
|
||||||
|
Parameters**. Blank fields inherit backend defaults, including AI Studio’s
|
||||||
|
1,024-token MLX cap. Shared settings include sampling temperature, top-p,
|
||||||
|
output token limit, repetition controls, and stop sequences. Ollama also accepts
|
||||||
|
context length, top-k, min-p, seed, frequency and presence penalties, keep-alive,
|
||||||
|
and JSON response mode. Native MLX exposes rolling KV-cache size and prefill
|
||||||
|
step size. On failover, MLX uses the supported shared and MLX settings.
|
||||||
|
|
||||||
|
**Settings → Local Tools** runs a confirmed command through the installed
|
||||||
|
Docker CLI. It captures up to 128 KiB of combined output; you can copy that
|
||||||
|
output or explicitly attach it to the active chat. The Finder section can open
|
||||||
|
or reveal a selected file or folder. Docker commands and Finder actions are
|
||||||
|
initiated from the settings panel.
|
||||||
|
|
||||||
## Build and test
|
## Build and test
|
||||||
|
|
||||||
From the project root, run `Scripts/build.sh` to build and open AI Studio. It defaults to Debug. Use `./build.sh Release` for a Release build, or add `--no-launch` after the configuration to build without opening the app. Run `Scripts/test.sh` for XCTest, including the local MCP and Ollama management fixture. It requires Python 3 for the fixture and keeps its logs and results in the temporary build directory.
|
From the project root, run `Scripts/build.sh` to build and open AI Studio. It defaults to Debug. Use `./build.sh Release` for a Release build, or add `--no-launch` after the configuration to build without opening the app. Run `Scripts/test.sh` for XCTest, including the local MCP and Ollama management fixture. It requires Python 3 for the fixture and keeps its logs and results in the temporary build directory.
|
||||||
|
|||||||
+240
-12
@@ -29,6 +29,10 @@ struct AIStudioApp: App {
|
|||||||
.tabItem { Label("Models", systemImage: "cpu") }
|
.tabItem { Label("Models", systemImage: "cpu") }
|
||||||
ModelCatalogView(studio: studio)
|
ModelCatalogView(studio: studio)
|
||||||
.tabItem { Label("MLX Catalog", systemImage: "arrow.down.circle") }
|
.tabItem { Label("MLX Catalog", systemImage: "arrow.down.circle") }
|
||||||
|
GenerationSettingsView()
|
||||||
|
.tabItem { Label("Generation", systemImage: "slider.horizontal.3") }
|
||||||
|
LocalToolsView(studio: studio)
|
||||||
|
.tabItem { Label("Local Tools", systemImage: "terminal") }
|
||||||
MCPSettings(studio: studio)
|
MCPSettings(studio: studio)
|
||||||
.tabItem { Label("MCP Tools", systemImage: "wrench.and.screwdriver") }
|
.tabItem { Label("MCP Tools", systemImage: "wrench.and.screwdriver") }
|
||||||
}
|
}
|
||||||
@@ -48,6 +52,7 @@ struct ChatView: View {
|
|||||||
@AppStorage("recall") private var recall = true
|
@AppStorage("recall") private var recall = true
|
||||||
@AppStorage("globalPromptMode") private var promptMode = PromptMode.standard
|
@AppStorage("globalPromptMode") private var promptMode = PromptMode.standard
|
||||||
@AppStorage("globalCustomPrompt") private var customPrompt = ""
|
@AppStorage("globalCustomPrompt") private var customPrompt = ""
|
||||||
|
@AppStorage(GenerationSettings.key) private var generationSettings = Data()
|
||||||
@State private var showingPromptBuilder = false
|
@State private var showingPromptBuilder = false
|
||||||
@State private var showingPerformance = false
|
@State private var showingPerformance = false
|
||||||
@State private var confirmDelete = false
|
@State private var confirmDelete = false
|
||||||
@@ -167,17 +172,6 @@ struct ChatView: View {
|
|||||||
.disabled(studio.running)
|
.disabled(studio.running)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
HStack {
|
|
||||||
Picker("Global Prompt", selection: $promptMode) {
|
|
||||||
ForEach(PromptMode.allCases) { Text($0.rawValue).tag($0) }
|
|
||||||
}
|
|
||||||
.fixedSize()
|
|
||||||
.disabled(studio.running)
|
|
||||||
Button("Edit Custom Prompt…") { showingPromptBuilder = true }
|
|
||||||
.buttonStyle(.borderless)
|
|
||||||
Spacer()
|
|
||||||
}
|
|
||||||
.font(.caption)
|
|
||||||
if !studio.documents.isEmpty {
|
if !studio.documents.isEmpty {
|
||||||
Toggle(mlxOnly ? "Include matching document excerpts" :
|
Toggle(mlxOnly ? "Include matching document excerpts" :
|
||||||
"Send matching document excerpts to Ollama", isOn: $useDocuments)
|
"Send matching document excerpts to Ollama", isOn: $useDocuments)
|
||||||
@@ -209,7 +203,8 @@ struct ChatView: View {
|
|||||||
Button("Send", systemImage: "arrow.up") {
|
Button("Send", systemImage: "arrow.up") {
|
||||||
studio.send(endpoint: endpoint, model: model, mlxPath: mlxPath, thinking: thinking,
|
studio.send(endpoint: endpoint, model: model, mlxPath: mlxPath, thinking: thinking,
|
||||||
failover: failover, mlxOnly: mlxOnly, recall: recall, useDocuments: useDocuments,
|
failover: failover, mlxOnly: mlxOnly, recall: recall, useDocuments: useDocuments,
|
||||||
instructions: promptMode.instructions(custom: customPrompt))
|
instructions: promptMode.instructions(custom: customPrompt),
|
||||||
|
settings: GenerationSettings.read(generationSettings))
|
||||||
}
|
}
|
||||||
.buttonStyle(.borderedProminent)
|
.buttonStyle(.borderedProminent)
|
||||||
.keyboardShortcut(.return, modifiers: .command)
|
.keyboardShortcut(.return, modifiers: .command)
|
||||||
@@ -644,3 +639,236 @@ struct PerformanceDashboard: View {
|
|||||||
value.map { $0.formatted(.number.precision(.fractionLength(2))) + " s" } ?? "—"
|
value.map { $0.formatted(.number.precision(.fractionLength(2))) + " s" } ?? "—"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct GenerationSettingsView: View {
|
||||||
|
@AppStorage("globalPromptMode") private var promptMode = PromptMode.standard
|
||||||
|
@AppStorage("globalCustomPrompt") private var prompt = ""
|
||||||
|
@AppStorage("thinking") private var thinking = Thinking.automatic
|
||||||
|
@AppStorage(GenerationSettings.key) private var stored = Data()
|
||||||
|
@State private var draft = GenerationSettings()
|
||||||
|
@State private var status = ""
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
Form {
|
||||||
|
Section("System Prompt") {
|
||||||
|
Picker("Global preset", selection: $promptMode) {
|
||||||
|
ForEach(PromptMode.allCases) { Text($0.rawValue).tag($0) }
|
||||||
|
}
|
||||||
|
if promptMode == .custom {
|
||||||
|
TextEditor(text: $prompt)
|
||||||
|
.font(.body).frame(minHeight: 88).accessibilityLabel("Global system instructions")
|
||||||
|
} else if promptMode != .standard {
|
||||||
|
Text(promptMode.instructions(custom: prompt)).foregroundStyle(.secondary).textSelection(.enabled)
|
||||||
|
}
|
||||||
|
Text("Applied automatically to new replies across chats. System instructions stay out of the transcript.")
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
Section("Shared Generation") {
|
||||||
|
Picker("Thinking", selection: $thinking) {
|
||||||
|
ForEach(Thinking.allCases) { Text($0.rawValue.capitalized).tag($0) }
|
||||||
|
}
|
||||||
|
field("Temperature", $draft.temperature)
|
||||||
|
field("Maximum output tokens", $draft.maxTokens)
|
||||||
|
field("Top P", $draft.topP)
|
||||||
|
field("Repeat penalty", $draft.repeatPenalty)
|
||||||
|
field("Repeat window", $draft.repeatLastN)
|
||||||
|
TextField("Stop sequences (one per line)", text: $draft.stop, axis: .vertical)
|
||||||
|
}
|
||||||
|
Section("Ollama") {
|
||||||
|
field("Context length", $draft.context)
|
||||||
|
field("Top K", $draft.topK)
|
||||||
|
field("Min P", $draft.minP)
|
||||||
|
field("Seed", $draft.seed)
|
||||||
|
field("Frequency penalty", $draft.frequencyPenalty)
|
||||||
|
field("Presence penalty", $draft.presencePenalty)
|
||||||
|
field("Keep alive (e.g. 5m or 0)", $draft.keepAlive)
|
||||||
|
Toggle("JSON output", isOn: $draft.json)
|
||||||
|
}
|
||||||
|
Section("MLX") {
|
||||||
|
field("Rolling KV cache tokens", $draft.mlxCache)
|
||||||
|
field("Prefill step size", $draft.mlxPrefill)
|
||||||
|
Text("MLX uses Default, Off, or On for supported thinking templates. Its default output cap is 1,024 tokens.")
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.formStyle(.grouped)
|
||||||
|
Divider()
|
||||||
|
HStack {
|
||||||
|
Text(status.isEmpty ? "Blank fields use backend defaults." : status)
|
||||||
|
.foregroundStyle(.secondary).font(.caption).textSelection(.enabled)
|
||||||
|
Spacer()
|
||||||
|
Button("Reset Overrides") {
|
||||||
|
draft = GenerationSettings()
|
||||||
|
save()
|
||||||
|
}
|
||||||
|
Button("Apply Parameters", action: save).buttonStyle(.borderedProminent)
|
||||||
|
}
|
||||||
|
.padding(12)
|
||||||
|
}
|
||||||
|
.onAppear { draft = GenerationSettings.read(stored) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func field(_ title: String, _ value: Binding<String>) -> some View {
|
||||||
|
TextField(title, text: value, prompt: Text("Default"))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func save() {
|
||||||
|
do {
|
||||||
|
_ = try draft.parameters(mlxOnly: false)
|
||||||
|
stored = try JSONEncoder().encode(draft)
|
||||||
|
status = "Parameters saved for future replies."
|
||||||
|
} catch { status = error.localizedDescription }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum DockerCommand {
|
||||||
|
static func arguments(_ line: String) throws -> [String] {
|
||||||
|
var arguments: [String] = []
|
||||||
|
var word = ""
|
||||||
|
var quote: Character?
|
||||||
|
var escaped = false
|
||||||
|
var started = false
|
||||||
|
for character in line {
|
||||||
|
if escaped {
|
||||||
|
word.append(character)
|
||||||
|
escaped = false
|
||||||
|
} else if character == "\\" && quote != "'" {
|
||||||
|
escaped = true
|
||||||
|
started = true
|
||||||
|
} else if let activeQuote = quote {
|
||||||
|
if character == activeQuote { quote = nil }
|
||||||
|
else { word.append(character) }
|
||||||
|
} else if character == "'" || character == "\"" {
|
||||||
|
quote = character
|
||||||
|
started = true
|
||||||
|
} else if character.isWhitespace {
|
||||||
|
if started { arguments.append(word); word = ""; started = false }
|
||||||
|
} else {
|
||||||
|
word.append(character)
|
||||||
|
started = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
guard quote == nil, !escaped else { throw StudioError("Close the quoted argument or remove the trailing backslash.") }
|
||||||
|
if started { arguments.append(word) }
|
||||||
|
if arguments.first == "docker" { arguments.removeFirst() }
|
||||||
|
guard let first = arguments.first, !first.isEmpty else { throw StudioError("Enter a Docker command.") }
|
||||||
|
return arguments
|
||||||
|
}
|
||||||
|
|
||||||
|
static var executable: URL? {
|
||||||
|
let paths = ["/usr/local/bin/docker", "/opt/homebrew/bin/docker",
|
||||||
|
FileManager.default.homeDirectoryForCurrentUser.appending(path: ".docker/bin/docker").path,
|
||||||
|
"/Applications/Docker.app/Contents/Resources/bin/docker"]
|
||||||
|
return paths.first(where: FileManager.default.isExecutableFile(atPath:)).map { URL(fileURLWithPath: $0) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct LocalToolsView: View {
|
||||||
|
@ObservedObject var studio: StudioModel
|
||||||
|
@State private var line = "docker ps"
|
||||||
|
@State private var pending: [String]?
|
||||||
|
@State private var output = ""
|
||||||
|
@State private var process: Process?
|
||||||
|
@State private var file: URL?
|
||||||
|
@State private var picking = false
|
||||||
|
@State private var status = ""
|
||||||
|
@State private var confirm = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Form {
|
||||||
|
Section("Docker") {
|
||||||
|
TextField("Command", text: $line, prompt: Text("docker ps --all"))
|
||||||
|
.font(.system(.body, design: .monospaced))
|
||||||
|
.disabled(process != nil)
|
||||||
|
Text("Commands run through the local Docker CLI. Interactive input is unavailable.")
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
HStack {
|
||||||
|
Button("Review Command…") {
|
||||||
|
do {
|
||||||
|
pending = try DockerCommand.arguments(line)
|
||||||
|
confirm = true
|
||||||
|
status = ""
|
||||||
|
} catch { status = error.localizedDescription }
|
||||||
|
}
|
||||||
|
.disabled(process != nil)
|
||||||
|
if let process { Button("Stop") { if process.isRunning { process.terminate() } } }
|
||||||
|
}
|
||||||
|
if !status.isEmpty { Text(status).foregroundStyle(.secondary) }
|
||||||
|
if !output.isEmpty {
|
||||||
|
ScrollView {
|
||||||
|
Text(output).font(.system(.caption, design: .monospaced)).textSelection(.enabled)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
}
|
||||||
|
.frame(height: 140)
|
||||||
|
HStack {
|
||||||
|
Button("Copy Output") { copyChatText(output) }
|
||||||
|
Button("Attach to Active Chat") { studio.attachToolResult(name: "Docker", output: output) }
|
||||||
|
.disabled(studio.selected == nil || studio.running)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Section("Finder") {
|
||||||
|
Button("Choose File or Folder…") { picking = true }
|
||||||
|
if let file {
|
||||||
|
Text(file.path).textSelection(.enabled)
|
||||||
|
HStack {
|
||||||
|
Button("Open") { NSWorkspace.shared.open(file) }
|
||||||
|
Button("Reveal in Finder") { NSWorkspace.shared.activateFileViewerSelecting([file]) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.formStyle(.grouped)
|
||||||
|
.fileImporter(isPresented: $picking, allowedContentTypes: [.item, .folder]) { result in
|
||||||
|
do { file = try result.get() }
|
||||||
|
catch { status = error.localizedDescription }
|
||||||
|
}
|
||||||
|
.confirmationDialog("Run Docker command?", isPresented: $confirm, titleVisibility: .visible) {
|
||||||
|
Button("Run Command") { if let pending { run(pending) } }
|
||||||
|
} message: {
|
||||||
|
Text(line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func run(_ args: [String]) {
|
||||||
|
guard process == nil else { return }
|
||||||
|
guard let executable = DockerCommand.executable else {
|
||||||
|
status = "Docker CLI was not found in the standard install locations."
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let child = Process()
|
||||||
|
let pipe = Pipe()
|
||||||
|
child.executableURL = executable
|
||||||
|
child.arguments = args
|
||||||
|
child.standardInput = FileHandle.nullDevice
|
||||||
|
child.standardOutput = pipe
|
||||||
|
child.standardError = pipe
|
||||||
|
do {
|
||||||
|
try child.run()
|
||||||
|
process = child
|
||||||
|
output = ""
|
||||||
|
status = "Running…"
|
||||||
|
} catch {
|
||||||
|
status = error.localizedDescription
|
||||||
|
return
|
||||||
|
}
|
||||||
|
Task {
|
||||||
|
let result = await Task.detached {
|
||||||
|
let reader = pipe.fileHandleForReading
|
||||||
|
var captured = Data()
|
||||||
|
var truncated = false
|
||||||
|
while let bytes = try? reader.read(upToCount: 8192), !bytes.isEmpty {
|
||||||
|
let remaining = max(0, 131_072 - captured.count)
|
||||||
|
captured.append(bytes.prefix(remaining))
|
||||||
|
truncated = truncated || bytes.count > remaining
|
||||||
|
}
|
||||||
|
child.waitUntilExit()
|
||||||
|
return (String(decoding: captured, as: UTF8.self), child.terminationStatus, truncated)
|
||||||
|
}.value
|
||||||
|
output = result.0 + (result.2 ? "\n[Output truncated]" : "")
|
||||||
|
status = "Exited with status \(result.1)."
|
||||||
|
process = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -60,6 +60,14 @@ struct InferenceRequest: Sendable {
|
|||||||
let model: String
|
let model: String
|
||||||
let messages: [Message]
|
let messages: [Message]
|
||||||
let thinking: Thinking
|
let thinking: Thinking
|
||||||
|
let parameters: GenerationParameters
|
||||||
|
|
||||||
|
init(model: String, messages: [Message], thinking: Thinking, parameters: GenerationParameters = .init()) {
|
||||||
|
self.model = model
|
||||||
|
self.messages = messages
|
||||||
|
self.thinking = thinking
|
||||||
|
self.parameters = parameters
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protocol InferenceProvider: Sendable {
|
protocol InferenceProvider: Sendable {
|
||||||
@@ -198,3 +206,123 @@ struct PromptDraft {
|
|||||||
}.joined(separator: "\n\n")
|
}.joined(separator: "\n\n")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Empty fields inherit provider defaults.
|
||||||
|
struct GenerationSettings: Codable {
|
||||||
|
var temperature = ""
|
||||||
|
var maxTokens = ""
|
||||||
|
var topP = ""
|
||||||
|
var topK = ""
|
||||||
|
var minP = ""
|
||||||
|
var context = ""
|
||||||
|
var seed = ""
|
||||||
|
var repeatPenalty = ""
|
||||||
|
var repeatLastN = ""
|
||||||
|
var frequencyPenalty = ""
|
||||||
|
var presencePenalty = ""
|
||||||
|
var keepAlive = ""
|
||||||
|
var stop = ""
|
||||||
|
var json = false
|
||||||
|
var mlxCache = ""
|
||||||
|
var mlxPrefill = ""
|
||||||
|
|
||||||
|
static let key = "generationSettings"
|
||||||
|
|
||||||
|
static func read(_ data: Data) -> Self {
|
||||||
|
(try? JSONDecoder().decode(Self.self, from: data)) ?? Self()
|
||||||
|
}
|
||||||
|
|
||||||
|
func parameters(mlxOnly: Bool) throws -> GenerationParameters {
|
||||||
|
func number(_ value: String, _ title: String, _ range: ClosedRange<Double>) throws -> Double? {
|
||||||
|
let text = value.trimmingCharacters(in: .whitespaces)
|
||||||
|
guard !text.isEmpty else { return nil }
|
||||||
|
guard let result = Double(text), range.contains(result) else {
|
||||||
|
throw StudioError("\(title) must be between \(range.lowerBound) and \(range.upperBound).")
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
func integer(_ value: String, _ title: String, _ range: ClosedRange<Int>) throws -> Int? {
|
||||||
|
let text = value.trimmingCharacters(in: .whitespaces)
|
||||||
|
guard !text.isEmpty else { return nil }
|
||||||
|
guard let result = Int(text), range.contains(result) else {
|
||||||
|
throw StudioError("\(title) must be between \(range.lowerBound) and \(range.upperBound).")
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
var result = GenerationParameters()
|
||||||
|
result.temperature = try number(temperature, "Temperature", 0...2)
|
||||||
|
result.maxTokens = try integer(maxTokens, "Maximum output tokens", 1...1_048_576)
|
||||||
|
result.topP = try number(topP, "Top P", 0...1)
|
||||||
|
result.repeatPenalty = try number(repeatPenalty, "Repeat penalty", 0.01...10)
|
||||||
|
result.repeatLastN = try integer(repeatLastN, "Repeat window", 0...1_048_576)
|
||||||
|
result.mlxCache = try integer(mlxCache, "MLX rolling cache", 8...1_048_576)
|
||||||
|
result.mlxPrefill = try integer(mlxPrefill, "MLX prefill", 1...32768)
|
||||||
|
result.stop = stop.components(separatedBy: "\n").filter { !$0.isEmpty }
|
||||||
|
guard result.stop.count <= 32, result.stop.allSatisfy({ $0.utf8.count <= 512 }) else {
|
||||||
|
throw StudioError("Use up to 32 stop sequences, each up to 512 bytes.")
|
||||||
|
}
|
||||||
|
if !mlxOnly {
|
||||||
|
result.topK = try integer(topK, "Top K", 0...1_048_576)
|
||||||
|
result.minP = try number(minP, "Min P", 0...1)
|
||||||
|
result.context = try integer(context, "Context length", 1...1_048_576)
|
||||||
|
result.seed = try integer(seed, "Seed", 0...Int(Int32.max))
|
||||||
|
result.frequencyPenalty = try number(frequencyPenalty, "Frequency penalty", -2...2)
|
||||||
|
result.presencePenalty = try number(presencePenalty, "Presence penalty", -2...2)
|
||||||
|
let duration = keepAlive.trimmingCharacters(in: .whitespaces)
|
||||||
|
result.keepAlive = duration.isEmpty ? nil : duration
|
||||||
|
result.json = json
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct GenerationParameters: Sendable {
|
||||||
|
var temperature: Double?
|
||||||
|
var maxTokens: Int?
|
||||||
|
var topP: Double?
|
||||||
|
var topK: Int?
|
||||||
|
var minP: Double?
|
||||||
|
var context: Int?
|
||||||
|
var seed: Int?
|
||||||
|
var repeatPenalty: Double?
|
||||||
|
var repeatLastN: Int?
|
||||||
|
var frequencyPenalty: Double?
|
||||||
|
var presencePenalty: Double?
|
||||||
|
var keepAlive: String?
|
||||||
|
var stop: [String] = []
|
||||||
|
var json = false
|
||||||
|
var mlxCache: Int?
|
||||||
|
var mlxPrefill: Int?
|
||||||
|
}
|
||||||
|
|
||||||
|
struct StopMatcher {
|
||||||
|
let sequences: [String]
|
||||||
|
private(set) var stopped = false
|
||||||
|
private var pending = ""
|
||||||
|
|
||||||
|
init(sequences: [String]) { self.sequences = sequences }
|
||||||
|
|
||||||
|
mutating func append(_ chunk: String) -> String {
|
||||||
|
guard !stopped else { return "" }
|
||||||
|
guard !sequences.isEmpty else { return chunk }
|
||||||
|
pending += chunk
|
||||||
|
if let first = sequences.compactMap({ pending.range(of: $0, options: .literal)?.lowerBound }).min() {
|
||||||
|
let output = String(pending[..<first])
|
||||||
|
pending = ""
|
||||||
|
stopped = true
|
||||||
|
return output
|
||||||
|
}
|
||||||
|
let maximum = min(pending.count, sequences.map(\.count).max() ?? 0)
|
||||||
|
let held = (0...maximum).reversed().first { length in
|
||||||
|
sequences.contains { $0.hasPrefix(pending.suffix(length)) }
|
||||||
|
} ?? 0
|
||||||
|
let output = String(pending.dropLast(held))
|
||||||
|
pending = String(pending.suffix(held))
|
||||||
|
return output
|
||||||
|
}
|
||||||
|
|
||||||
|
mutating func finish() -> String {
|
||||||
|
defer { pending = "" }
|
||||||
|
return pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -46,18 +46,31 @@ actor MLXProvider: InferenceProvider {
|
|||||||
}
|
}
|
||||||
var thinkingOutput = MLXThinking()
|
var thinkingOutput = MLXThinking()
|
||||||
let input = try await model.prepare(input: UserInput(chat: history, additionalContext: context))
|
let input = try await model.prepare(input: UserInput(chat: history, additionalContext: context))
|
||||||
let output = try await model.generate(input: input, parameters: GenerateParameters(maxTokens: 1024))
|
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)
|
||||||
|
let output = try await model.generate(input: input, parameters: parameters)
|
||||||
|
var stopMatcher = StopMatcher(sequences: config.stop)
|
||||||
continuation.yield(.backend("MLX · \(URL(fileURLWithPath: directory).lastPathComponent)"))
|
continuation.yield(.backend("MLX · \(URL(fileURLWithPath: directory).lastPathComponent)"))
|
||||||
var finished = false
|
var finished = false
|
||||||
for await event in output {
|
generation: for await event in output {
|
||||||
try Task.checkCancellation()
|
try Task.checkCancellation()
|
||||||
switch event {
|
switch event {
|
||||||
case .chunk(let text):
|
case .chunk(let chunk):
|
||||||
|
let text = stopMatcher.append(chunk)
|
||||||
if supportsThinking {
|
if supportsThinking {
|
||||||
for delta in thinkingOutput.append(text) { continuation.yield(delta) }
|
for delta in thinkingOutput.append(text) { continuation.yield(delta) }
|
||||||
} else {
|
} else if !text.isEmpty {
|
||||||
continuation.yield(.answer(text))
|
continuation.yield(.answer(text))
|
||||||
}
|
}
|
||||||
|
if stopMatcher.stopped {
|
||||||
|
finished = true
|
||||||
|
break generation
|
||||||
|
}
|
||||||
case .info(let info):
|
case .info(let info):
|
||||||
finished = true
|
finished = true
|
||||||
continuation.yield(.metrics(ProviderMetrics(tokens: info.generationTokenCount, seconds: info.generateTime)))
|
continuation.yield(.metrics(ProviderMetrics(tokens: info.generationTokenCount, seconds: info.generateTime)))
|
||||||
@@ -68,7 +81,12 @@ actor MLXProvider: InferenceProvider {
|
|||||||
}
|
}
|
||||||
try Task.checkCancellation()
|
try Task.checkCancellation()
|
||||||
guard finished else { throw StudioError("MLX generation ended without completion information.") }
|
guard finished else { throw StudioError("MLX generation ended without completion information.") }
|
||||||
for delta in thinkingOutput.finish() { continuation.yield(delta) }
|
let remainder = stopMatcher.finish()
|
||||||
|
if supportsThinking {
|
||||||
|
for delta in thinkingOutput.append(remainder) + thinkingOutput.finish() { continuation.yield(delta) }
|
||||||
|
} else if !remainder.isEmpty {
|
||||||
|
continuation.yield(.answer(remainder))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+51
-3
@@ -40,6 +40,56 @@ struct Ollama: InferenceProvider {
|
|||||||
let messages: [WireMessage]
|
let messages: [WireMessage]
|
||||||
let think: Thinking?
|
let think: Thinking?
|
||||||
let stream = true
|
let stream = true
|
||||||
|
let options: Options?
|
||||||
|
let keep_alive: String?
|
||||||
|
let format: String?
|
||||||
|
|
||||||
|
init(_ request: InferenceRequest) {
|
||||||
|
model = request.model
|
||||||
|
messages = request.messages.map { WireMessage(role: $0.role, content: $0.content) }
|
||||||
|
think = request.thinking == .automatic ? nil : request.thinking
|
||||||
|
let parameters = request.parameters
|
||||||
|
let overrides = Options(parameters)
|
||||||
|
options = overrides.isEmpty ? nil : overrides
|
||||||
|
keep_alive = parameters.keepAlive
|
||||||
|
format = parameters.json ? "json" : nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Options: Encodable {
|
||||||
|
let temperature: Double?
|
||||||
|
let num_predict: Int?
|
||||||
|
let top_p: Double?
|
||||||
|
let top_k: Int?
|
||||||
|
let min_p: Double?
|
||||||
|
let num_ctx: Int?
|
||||||
|
let seed: Int?
|
||||||
|
let repeat_penalty: Double?
|
||||||
|
let repeat_last_n: Int?
|
||||||
|
let frequency_penalty: Double?
|
||||||
|
let presence_penalty: Double?
|
||||||
|
let stop: [String]?
|
||||||
|
|
||||||
|
init(_ p: GenerationParameters) {
|
||||||
|
temperature = p.temperature
|
||||||
|
num_predict = p.maxTokens
|
||||||
|
top_p = p.topP
|
||||||
|
top_k = p.topK
|
||||||
|
min_p = p.minP
|
||||||
|
num_ctx = p.context
|
||||||
|
seed = p.seed
|
||||||
|
repeat_penalty = p.repeatPenalty
|
||||||
|
repeat_last_n = p.repeatLastN
|
||||||
|
frequency_penalty = p.frequencyPenalty
|
||||||
|
presence_penalty = p.presencePenalty
|
||||||
|
stop = p.stop.isEmpty ? nil : p.stop
|
||||||
|
}
|
||||||
|
|
||||||
|
var isEmpty: Bool {
|
||||||
|
temperature == nil && num_predict == nil && top_p == nil && top_k == nil && min_p == nil &&
|
||||||
|
num_ctx == nil && seed == nil && repeat_penalty == nil && repeat_last_n == nil &&
|
||||||
|
frequency_penalty == nil && presence_penalty == nil && stop == nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ModelBody: Encodable {
|
struct ModelBody: Encodable {
|
||||||
@@ -130,9 +180,7 @@ struct Ollama: InferenceProvider {
|
|||||||
|
|
||||||
func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
|
func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
|
||||||
streaming { continuation in
|
streaming { continuation in
|
||||||
let body = ChatBody(model: request.model,
|
let body = ChatBody(request)
|
||||||
messages: request.messages.map { WireMessage(role: $0.role, content: $0.content) },
|
|
||||||
think: request.thinking == .automatic ? nil : request.thinking)
|
|
||||||
let (bytes, response) = try await Self.session.bytes(for: self.request("chat", body: body))
|
let (bytes, response) = try await Self.session.bytes(for: self.request("chat", body: body))
|
||||||
try Self.validate(response)
|
try Self.validate(response)
|
||||||
continuation.yield(.backend("Ollama · \(request.model)"))
|
continuation.yield(.backend("Ollama · \(request.model)"))
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ final class StudioModel: ObservableObject {
|
|||||||
func stop() { generation?.cancel() }
|
func stop() { generation?.cancel() }
|
||||||
|
|
||||||
func send(endpoint: String, model: String, mlxPath: String, thinking: Thinking, failover: Bool,
|
func send(endpoint: String, model: String, mlxPath: String, thinking: Thinking, failover: Bool,
|
||||||
mlxOnly: Bool, recall: Bool, useDocuments: Bool, instructions: String) {
|
mlxOnly: Bool, recall: Bool, useDocuments: Bool, instructions: String, settings: GenerationSettings) {
|
||||||
let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
|
let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
let tag = model.trimmingCharacters(in: .whitespacesAndNewlines)
|
let tag = model.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
guard !running, !text.isEmpty else { return }
|
guard !running, !text.isEmpty else { return }
|
||||||
@@ -83,6 +83,7 @@ final class StudioModel: ObservableObject {
|
|||||||
}
|
}
|
||||||
do {
|
do {
|
||||||
let ollama = mlxOnly ? nil : try ollamaClient(endpoint: endpoint)
|
let ollama = mlxOnly ? nil : try ollamaClient(endpoint: endpoint)
|
||||||
|
let parameters = try settings.parameters(mlxOnly: mlxOnly)
|
||||||
let store = try database()
|
let store = try database()
|
||||||
let chat = try selected ?? create(String(text.prefix(48)))
|
let chat = try selected ?? create(String(text.prefix(48)))
|
||||||
let user = Message(role: .user, content: text)
|
let user = Message(role: .user, content: text)
|
||||||
@@ -128,12 +129,12 @@ final class StudioModel: ObservableObject {
|
|||||||
status = ""
|
status = ""
|
||||||
running = true
|
running = true
|
||||||
partial = Message(role: .assistant, content: "")
|
partial = Message(role: .assistant, content: "")
|
||||||
let localRequest = InferenceRequest(model: mlxPath, messages: context, thinking: thinking)
|
let localRequest = InferenceRequest(model: mlxPath, messages: context, thinking: thinking, parameters: parameters)
|
||||||
let local: Router.Producer = { [mlx] in mlx.generate(localRequest) }
|
let local: Router.Producer = { [mlx] in mlx.generate(localRequest) }
|
||||||
let start = ProcessInfo.processInfo.systemUptime
|
let start = ProcessInfo.processInfo.systemUptime
|
||||||
let stream: AsyncThrowingStream<Delta, Error>
|
let stream: AsyncThrowingStream<Delta, Error>
|
||||||
if let ollama {
|
if let ollama {
|
||||||
let request = InferenceRequest(model: tag, messages: context, thinking: thinking)
|
let request = InferenceRequest(model: tag, messages: context, thinking: thinking, parameters: parameters)
|
||||||
stream = Router.stream(primary: { ollama.generate(request) },
|
stream = Router.stream(primary: { ollama.generate(request) },
|
||||||
fallback: failover && !mlxPath.isEmpty ? local : nil)
|
fallback: failover && !mlxPath.isEmpty ? local : nil)
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+44
-2
@@ -125,7 +125,8 @@ final class LiveInferenceTests: XCTestCase {
|
|||||||
XCTAssertTrue(models.contains { $0.name == tag })
|
XCTAssertTrue(models.contains { $0.name == tag })
|
||||||
_ = try await ollama.details(for: tag)
|
_ = try await ollama.details(for: tag)
|
||||||
let stream = ollama.generate(InferenceRequest(
|
let stream = ollama.generate(InferenceRequest(
|
||||||
model: tag, messages: [Message(role: .user, content: "Reply with one word: hello.")], thinking: .off
|
model: tag, messages: [Message(role: .user, content: "Reply with one word: hello.")],
|
||||||
|
thinking: .off, parameters: GenerationParameters(temperature: 0, maxTokens: 64)
|
||||||
))
|
))
|
||||||
var answer = ""
|
var answer = ""
|
||||||
for try await event in stream {
|
for try await event in stream {
|
||||||
@@ -141,7 +142,7 @@ final class LiveInferenceTests: XCTestCase {
|
|||||||
let mlx = MLXProvider()
|
let mlx = MLXProvider()
|
||||||
let request = InferenceRequest(
|
let request = InferenceRequest(
|
||||||
model: directory, messages: [Message(role: .user, content: "Reply with one word: hello.")],
|
model: directory, messages: [Message(role: .user, content: "Reply with one word: hello.")],
|
||||||
thinking: .automatic
|
thinking: .automatic, parameters: GenerationParameters(temperature: 0, maxTokens: 64)
|
||||||
)
|
)
|
||||||
let output = try await collect(Router.stream(primary: { failing() }, fallback: { mlx.generate(request) }))
|
let output = try await collect(Router.stream(primary: { failing() }, fallback: { mlx.generate(request) }))
|
||||||
XCTAssertTrue(output.contains {
|
XCTAssertTrue(output.contains {
|
||||||
@@ -322,3 +323,44 @@ final class WorkspaceExperienceTests: XCTestCase {
|
|||||||
XCTAssertTrue(try store.searchConversations("original").isEmpty)
|
XCTAssertTrue(try store.searchConversations("original").isEmpty)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final class GenerationConfigurationTests: XCTestCase {
|
||||||
|
func testOllamaOverridesAndSilentSystemRole() throws {
|
||||||
|
var settings = GenerationSettings()
|
||||||
|
settings.temperature = "0"
|
||||||
|
settings.maxTokens = "128"
|
||||||
|
settings.context = "4096"
|
||||||
|
settings.stop = "END\nDONE"
|
||||||
|
let options = try settings.parameters(mlxOnly: false)
|
||||||
|
let request = InferenceRequest(model: "fixture", messages: [
|
||||||
|
Message(role: .system, content: "Quiet instruction"),
|
||||||
|
Message(role: .user, content: "First visible message")
|
||||||
|
], thinking: .off, parameters: options)
|
||||||
|
let json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(Ollama.ChatBody(request))) as? [String: Any])
|
||||||
|
let wire = try XCTUnwrap(json["options"] as? [String: Any])
|
||||||
|
let messages = try XCTUnwrap(json["messages"] as? [[String: String]])
|
||||||
|
XCTAssertEqual(messages.map { $0["role"] }, ["system", "user"])
|
||||||
|
XCTAssertEqual(wire["temperature"] as? Double, 0)
|
||||||
|
XCTAssertEqual(wire["num_predict"] as? Int, 128)
|
||||||
|
XCTAssertEqual(wire["num_ctx"] as? Int, 4096)
|
||||||
|
XCTAssertEqual(wire["stop"] as? [String], ["END", "DONE"])
|
||||||
|
XCTAssertNil(wire["top_k"])
|
||||||
|
settings.temperature = "NaN"
|
||||||
|
XCTAssertThrowsError(try settings.parameters(mlxOnly: false))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testStopMatcherHandlesStreamingBoundaries() {
|
||||||
|
var matcher = StopMatcher(sequences: ["[stop]", "END"])
|
||||||
|
XCTAssertEqual(matcher.append("Hello [st"), "Hello ")
|
||||||
|
XCTAssertEqual(matcher.append("op]ignore"), "")
|
||||||
|
XCTAssertTrue(matcher.stopped)
|
||||||
|
XCTAssertEqual(matcher.finish(), "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testDockerArgumentsPreserveQuotedValues() throws {
|
||||||
|
XCTAssertEqual(try DockerCommand.arguments(#"docker logs --since "1 hour" 'my container'"#),
|
||||||
|
["logs", "--since", "1 hour", "my container"])
|
||||||
|
XCTAssertEqual(try DockerCommand.arguments("ps ; echo"), ["ps", ";", "echo"])
|
||||||
|
XCTAssertThrowsError(try DockerCommand.arguments("docker logs 'unclosed"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user