Build AI Studio 1.1 for macOS #1

Open
admin wants to merge 38 commits from admin/ai-studio-v1.1 AGit into main
9 changed files with 309 additions and 30 deletions
Showing only changes of commit caa0a8733b - Show all commits
+15 -1
View File
@@ -7,7 +7,14 @@
| 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. Generation and local tools | Awaiting Docker daemon check | Silent system instructions, runtime parameter overrides, confirmed Docker commands, Finder file actions | | 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 | | 6. Compatibility extensions | In progress | OpenAI-compatible endpoint, MCP stdio, broader desktop automation and runtime controls |
## Phase 6 checklist
- [x] Verify OpenAI-compatible model discovery and streamed chat.
- [ ] Verify with a running LM Studio server.
- [ ] Add MCP stdio transport.
- [ ] Extend desktop actions and runtime controls.
## Phase 3 checklist ## Phase 3 checklist
@@ -50,3 +57,10 @@ 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 the system-role request, option encoding, cross-chunk stop matching, and Docker
argument handling. Docker CLI discovery succeeded; the local daemon socket argument handling. Docker CLI discovery succeeded; the local daemon socket
was missing during the read-only test. Finder actions were compiled. was missing during the read-only test. Finder actions were compiled.
**16 November 2026.** The compatible endpoint passed authenticated model
listing and SSE streaming tests against a local fixture. The running Ollama
server also completed a direct smoke check of the compatible wire format.
The Debug build succeeded. 26 tests passed and the opt-in catalog download
was skipped. A live LM Studio check remains pending because its local server
was unavailable.
+2 -1
View File
@@ -5,6 +5,7 @@ Native SwiftUI chat for Apple silicon Macs running macOS 14 or later. Open `AISt
## 1. Set up a model ## 1. Set up a model
- **Ollama:** In **Settings → Models**, refresh the installed list and select a tag. The default server is `http://127.0.0.1:11434`. Use the same pane to pull, inspect, and delete models. Enter a remote HTTP or HTTPS base URL to use another server. The optional bearer token stays in memory and requires HTTPS for remote servers. - **Ollama:** In **Settings → Models**, refresh the installed list and select a tag. The default server is `http://127.0.0.1:11434`. Use the same pane to pull, inspect, and delete models. Enter a remote HTTP or HTTPS base URL to use another server. The optional bearer token stays in memory and requires HTTPS for remote servers.
- **OpenAI-compatible:** In **Settings → Models**, choose the compatible backend, enter the API base URL (for example `http://127.0.0.1:1234/v1` for LM Studio), then refresh models and select the exact model ID. Remote URLs require HTTPS. An optional bearer token stays in memory and is cleared when the endpoint changes. The server manages model loading. Chat Completions streams the reply and any separately reported reasoning.
- **MLX:** In **Settings → MLX Catalog**, download and select a pinned SmolLM2 or Qwen3 model. **Settings → Models** also accepts a local model folder with configuration, tokenizer files, and safetensors weights. **Use Model** selects on-device inference. **Prefer Ollama** can fall back to the configured MLX folder when Ollama fails before emitting output. - **MLX:** In **Settings → MLX Catalog**, download and select a pinned SmolLM2 or Qwen3 model. **Settings → Models** also accepts a local model folder with configuration, tokenizer files, and safetensors weights. **Use Model** selects on-device inference. **Prefer Ollama** can fall back to the configured MLX folder when Ollama fails before emitting output.
- **Thinking:** The composer sends Boolean or named effort settings to Ollama. Supported MLX templates expose Default, Off, and On. Reported reasoning appears in an expandable section. If an Ollama request is interrupted after emitting text, reasoning, or a tool call, the router keeps that backend. **Stop** cancels generation and retains any partial output. - **Thinking:** The composer sends Boolean or named effort settings to Ollama. Supported MLX templates expose Default, Off, and On. Reported reasoning appears in an expandable section. If an Ollama request is interrupted after emitting text, reasoning, or a tool call, the router keeps that backend. **Stop** cancels generation and retains any partial output.
@@ -41,7 +42,7 @@ Parameters**. Blank fields inherit backend defaults, including AI Studio’s
1,024-token MLX cap. Shared settings include sampling temperature, top-p, 1,024-token MLX cap. Shared settings include sampling temperature, top-p,
output token limit, repetition controls, and stop sequences. Ollama also accepts output token limit, repetition controls, and stop sequences. Ollama also accepts
context length, top-k, min-p, seed, frequency and presence penalties, keep-alive, 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 and JSON response mode. The compatible backend sends temperature, top-p, max tokens, stops, frequency and presence penalties, and JSON mode. Native MLX exposes rolling KV-cache size and prefill
step size. On failover, MLX uses the supported shared and MLX settings. step size. On failover, MLX uses the supported shared and MLX settings.
**Settings → Local Tools** runs a confirmed command through the installed **Settings → Local Tools** runs a confirmed command through the installed
+2 -1
View File
@@ -4,7 +4,7 @@ cd "$(dirname "$0")/.."
base="${AISTUDIO_BUILD_ROOT:-/private/tmp/AIStudio-build-$(id -u)}" base="${AISTUDIO_BUILD_ROOT:-/private/tmp/AIStudio-build-$(id -u)}"
mkdir -p "$base" mkdir -p "$base"
results="$(mktemp -d "$base/test.XXXXXXXX")" results="$(mktemp -d "$base/test.XXXXXXXX")"
if [[ -z "${TEST_RUNNER_AISTUDIO_TEST_MCP_URLS:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_FIXTURE_URL:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_GATEWAY_URL:-}" ]]; then if [[ -z "${TEST_RUNNER_AISTUDIO_TEST_MCP_URLS:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_FIXTURE_URL:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_GATEWAY_URL:-}" || -z "${TEST_RUNNER_AISTUDIO_TEST_COMPATIBLE_URL:-}" ]]; then
python3 -u Tests/Fixtures/server.py >"$results/fixture.log" 2>&1 & python3 -u Tests/Fixtures/server.py >"$results/fixture.log" 2>&1 &
fixture_pid=$! fixture_pid=$!
trap 'kill "$fixture_pid" 2>/dev/null || true' EXIT trap 'kill "$fixture_pid" 2>/dev/null || true' EXIT
@@ -21,6 +21,7 @@ if [[ -z "${TEST_RUNNER_AISTUDIO_TEST_MCP_URLS:-}" || -z "${TEST_RUNNER_AISTUDIO
exit 1 exit 1
fi fi
fixture="http://127.0.0.1:$port" fixture="http://127.0.0.1:$port"
export TEST_RUNNER_AISTUDIO_TEST_COMPATIBLE_URL="${TEST_RUNNER_AISTUDIO_TEST_COMPATIBLE_URL:-$fixture/compatible/v1}"
export TEST_RUNNER_AISTUDIO_TEST_MCP_URLS="${TEST_RUNNER_AISTUDIO_TEST_MCP_URLS:-$fixture/modern,$fixture/legacy}" export TEST_RUNNER_AISTUDIO_TEST_MCP_URLS="${TEST_RUNNER_AISTUDIO_TEST_MCP_URLS:-$fixture/modern,$fixture/legacy}"
export TEST_RUNNER_AISTUDIO_TEST_OLLAMA_GATEWAY_URL="${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_GATEWAY_URL:-$fixture/gateway}" export TEST_RUNNER_AISTUDIO_TEST_OLLAMA_GATEWAY_URL="${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_GATEWAY_URL:-$fixture/gateway}"
export TEST_RUNNER_AISTUDIO_TEST_OLLAMA_FIXTURE_URL="${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_FIXTURE_URL:-$fixture/ollama}" export TEST_RUNNER_AISTUDIO_TEST_OLLAMA_FIXTURE_URL="${TEST_RUNNER_AISTUDIO_TEST_OLLAMA_FIXTURE_URL:-$fixture/ollama}"
+84 -12
View File
@@ -49,6 +49,9 @@ struct ChatView: View {
@AppStorage("thinking") private var thinking = Thinking.automatic @AppStorage("thinking") private var thinking = Thinking.automatic
@AppStorage("failover") private var failover = true @AppStorage("failover") private var failover = true
@AppStorage("mlxOnly") private var mlxOnly = false @AppStorage("mlxOnly") private var mlxOnly = false
@AppStorage("compatibleEnabled") private var compatibleEnabled = false
@AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1"
@AppStorage("compatibleModel") private var compatibleModel = ""
@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 = ""
@@ -60,6 +63,10 @@ struct ChatView: View {
@State private var renaming = false @State private var renaming = false
@State private var newTitle = "" @State private var newTitle = ""
private var backendName: String { compatibleEnabled ? "Compatible API" : "Ollama" }
private var activeEndpoint: String { compatibleEnabled ? compatibleEndpoint : endpoint }
private var activeModel: String { compatibleEnabled ? compatibleModel : model }
private var visibleChats: [Conversation] { private var visibleChats: [Conversation] {
search.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty search.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? studio.conversations : studio.searchConversations(search) ? studio.conversations : studio.searchConversations(search)
@@ -153,14 +160,14 @@ struct ChatView: View {
private var composer: some View { private var composer: some View {
VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading, spacing: 8) {
HStack { HStack {
Label(mlxOnly ? "MLX on this Mac" : "Ollama · \(model.isEmpty ? "Choose a model" : model)", Label(mlxOnly ? "MLX on this Mac" : "\(backendName) · \(activeModel.isEmpty ? "Choose a model" : activeModel)",
systemImage: mlxOnly ? "cpu" : "server.rack") systemImage: mlxOnly ? "cpu" : "server.rack")
.font(.caption) .font(.caption)
if !mlxOnly { if !mlxOnly {
Text(endpoint).font(.caption).foregroundStyle(.secondary).lineLimit(1) Text(activeEndpoint).font(.caption).foregroundStyle(.secondary).lineLimit(1)
} }
Spacer() Spacer()
if !mlxOnly || MLXThinking.supports(mlxPath) { if (!mlxOnly && !compatibleEnabled) || (mlxOnly && MLXThinking.supports(mlxPath)) {
let modes: [Thinking] = mlxOnly ? [.automatic, .off, .on] : Thinking.allCases let modes: [Thinking] = mlxOnly ? [.automatic, .off, .on] : Thinking.allCases
Picker("Thinking", selection: Binding( Picker("Thinking", selection: Binding(
get: { modes.contains(thinking) ? thinking : .automatic }, get: { modes.contains(thinking) ? thinking : .automatic },
@@ -174,14 +181,14 @@ struct ChatView: View {
} }
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 \(backendName)", isOn: $useDocuments)
.font(.caption) .font(.caption)
.disabled(studio.running) .disabled(studio.running)
} }
if let attachment = studio.toolAttachment { if let attachment = studio.toolAttachment {
HStack { HStack {
Label("Attach \(attachment.name) result to next message", systemImage: "paperclip") Label("Attach \(attachment.name) result to next message", systemImage: "paperclip")
if !mlxOnly { Text("Sent to Ollama").foregroundStyle(.secondary) } if !mlxOnly { Text("Sent to \(backendName)").foregroundStyle(.secondary) }
Spacer() Spacer()
Button("Remove", systemImage: "xmark.circle") { studio.removeToolAttachment() } Button("Remove", systemImage: "xmark.circle") { studio.removeToolAttachment() }
} }
@@ -201,8 +208,8 @@ struct ChatView: View {
Button("Stop", systemImage: "stop.fill") { studio.stop() } Button("Stop", systemImage: "stop.fill") { studio.stop() }
} else { } else {
Button("Send", systemImage: "arrow.up") { Button("Send", systemImage: "arrow.up") {
studio.send(endpoint: endpoint, model: model, mlxPath: mlxPath, thinking: thinking, studio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking,
failover: failover, mlxOnly: mlxOnly, recall: recall, useDocuments: useDocuments, failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: useDocuments,
instructions: promptMode.instructions(custom: customPrompt), instructions: promptMode.instructions(custom: customPrompt),
settings: GenerationSettings.read(generationSettings)) settings: GenerationSettings.read(generationSettings))
} }
@@ -266,6 +273,9 @@ struct BackendSettings: View {
@AppStorage("mlxPath") private var mlxPath = "" @AppStorage("mlxPath") private var mlxPath = ""
@AppStorage("failover") private var failover = true @AppStorage("failover") private var failover = true
@AppStorage("mlxOnly") private var mlxOnly = false @AppStorage("mlxOnly") private var mlxOnly = false
@AppStorage("compatibleEnabled") private var compatibleEnabled = false
@AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1"
@AppStorage("compatibleModel") private var compatibleModel = ""
@AppStorage("recall") private var recall = true @AppStorage("recall") private var recall = true
@State private var tag = "" @State private var tag = ""
@State private var pickingFolder = false @State private var pickingFolder = false
@@ -276,11 +286,18 @@ struct BackendSettings: View {
var body: some View { var body: some View {
Form { Form {
Section("Inference") { Section("Inference") {
Picker("Backend", selection: $mlxOnly) { Picker("Backend", selection: Binding(
Text("Prefer Ollama").tag(false) get: { mlxOnly ? "mlx" : (compatibleEnabled ? "compatible" : "ollama") },
Text("MLX only").tag(true) set: { mode in
mlxOnly = mode == "mlx"
compatibleEnabled = mode == "compatible"
}
)) {
Text("Prefer Ollama").tag("ollama")
Text("OpenAI-compatible").tag("compatible")
Text("MLX only").tag("mlx")
} }
Toggle("Fall back to MLX when Ollama fails before output", isOn: $failover) Toggle("Fall back to MLX before output begins", isOn: $failover)
.disabled(mlxOnly) .disabled(mlxOnly)
Toggle("Recall older matching messages in this conversation", isOn: $recall) Toggle("Recall older matching messages in this conversation", isOn: $recall)
} }
@@ -326,6 +343,7 @@ struct BackendSettings: View {
} }
Text(studio.modelStatus).foregroundStyle(.secondary).textSelection(.enabled) Text(studio.modelStatus).foregroundStyle(.secondary).textSelection(.enabled)
} }
CompatibleEndpointSettings(studio: studio, endpoint: $compatibleEndpoint, model: $compatibleModel)
Section("MLX") { Section("MLX") {
LabeledContent("Model folder", value: mlxPath.isEmpty ? "None selected" : mlxPath) LabeledContent("Model folder", value: mlxPath.isEmpty ? "None selected" : mlxPath)
HStack { HStack {
@@ -680,9 +698,11 @@ struct GenerationSettingsView: View {
field("Top K", $draft.topK) field("Top K", $draft.topK)
field("Min P", $draft.minP) field("Min P", $draft.minP)
field("Seed", $draft.seed) field("Seed", $draft.seed)
field("Keep alive (e.g. 5m or 0)", $draft.keepAlive)
}
Section("Ollama and OpenAI-compatible") {
field("Frequency penalty", $draft.frequencyPenalty) field("Frequency penalty", $draft.frequencyPenalty)
field("Presence penalty", $draft.presencePenalty) field("Presence penalty", $draft.presencePenalty)
field("Keep alive (e.g. 5m or 0)", $draft.keepAlive)
Toggle("JSON output", isOn: $draft.json) Toggle("JSON output", isOn: $draft.json)
} }
Section("MLX") { Section("MLX") {
@@ -872,3 +892,55 @@ struct LocalToolsView: View {
} }
} }
} }
struct CompatibleEndpointSettings: View {
@ObservedObject var studio: StudioModel
@Binding var endpoint: String
@Binding var model: String
@State private var models: [String] = []
@State private var connecting = false
@State private var status = ""
var body: some View {
Section("OpenAI-compatible endpoint") {
TextField("Base URL", text: $endpoint, prompt: Text("http://127.0.0.1:1234/v1"))
.disabled(connecting)
SecureField("Bearer token (session only)", text: Binding(
get: { studio.compatibleToken },
set: { studio.setCompatibleToken($0, endpoint: endpoint) }
))
.disabled(connecting)
TextField("Model ID", text: $model)
HStack {
Button("Refresh Models") { Task { await refresh() } }
.disabled(connecting)
if connecting { ProgressView().controlSize(.small) }
if !models.isEmpty {
Menu("Available Models") {
ForEach(models, id: \.self) { name in Button(name) { model = name } }
}
}
}
if !status.isEmpty { Text(status).foregroundStyle(.secondary).textSelection(.enabled) }
Text("Use the API base path, such as /v1 for LM Studio. Model downloads and loading are managed by the server.")
.foregroundStyle(.secondary)
}
.onChange(of: endpoint) { _, value in
studio.setCompatibleToken("", endpoint: value)
models = []
status = ""
}
}
private func refresh() async {
guard !connecting else { return }
connecting = true
models = []
status = ""
defer { connecting = false }
do {
models = try await studio.compatibleClient(endpoint: endpoint).models()
status = models.isEmpty ? "The server returned no models." : "\(models.count) model(s) available."
} catch { status = error.localizedDescription }
}
}
+9 -6
View File
@@ -107,7 +107,8 @@ enum Router {
static func stream( static func stream(
primary: @escaping Producer, primary: @escaping Producer,
fallback: Producer? fallback: Producer?,
primaryName: String = "Ollama"
) -> AsyncThrowingStream<Delta, Error> { ) -> AsyncThrowingStream<Delta, Error> {
streaming { continuation in streaming { continuation in
var committed = false var committed = false
@@ -135,7 +136,7 @@ enum Router {
} catch let fallbackError { } catch let fallbackError {
try Task.checkCancellation() try Task.checkCancellation()
if fallbackError is CancellationError { throw fallbackError } if fallbackError is CancellationError { throw fallbackError }
throw StudioError("Ollama: \(error.localizedDescription) MLX: \(fallbackError.localizedDescription)") throw StudioError("\(primaryName): \(error.localizedDescription) MLX: \(fallbackError.localizedDescription)")
} }
} }
} }
@@ -232,7 +233,7 @@ struct GenerationSettings: Codable {
(try? JSONDecoder().decode(Self.self, from: data)) ?? Self() (try? JSONDecoder().decode(Self.self, from: data)) ?? Self()
} }
func parameters(mlxOnly: Bool) throws -> GenerationParameters { func parameters(mlxOnly: Bool, compatible: Bool = false) throws -> GenerationParameters {
func number(_ value: String, _ title: String, _ range: ClosedRange<Double>) throws -> Double? { func number(_ value: String, _ title: String, _ range: ClosedRange<Double>) throws -> Double? {
let text = value.trimmingCharacters(in: .whitespaces) let text = value.trimmingCharacters(in: .whitespaces)
guard !text.isEmpty else { return nil } guard !text.isEmpty else { return nil }
@@ -262,15 +263,17 @@ struct GenerationSettings: Codable {
throw StudioError("Use up to 32 stop sequences, each up to 512 bytes.") throw StudioError("Use up to 32 stop sequences, each up to 512 bytes.")
} }
if !mlxOnly { if !mlxOnly {
result.frequencyPenalty = try number(frequencyPenalty, "Frequency penalty", -2...2)
result.presencePenalty = try number(presencePenalty, "Presence penalty", -2...2)
result.json = json
}
if !mlxOnly && !compatible {
result.topK = try integer(topK, "Top K", 0...1_048_576) result.topK = try integer(topK, "Top K", 0...1_048_576)
result.minP = try number(minP, "Min P", 0...1) result.minP = try number(minP, "Min P", 0...1)
result.context = try integer(context, "Context length", 1...1_048_576) result.context = try integer(context, "Context length", 1...1_048_576)
result.seed = try integer(seed, "Seed", 0...Int(Int32.max)) 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) let duration = keepAlive.trimmingCharacters(in: .whitespaces)
result.keepAlive = duration.isEmpty ? nil : duration result.keepAlive = duration.isEmpty ? nil : duration
result.json = json
} }
return result return result
} }
+121 -1
View File
@@ -109,7 +109,7 @@ struct Ollama: InferenceProvider {
} }
} }
private static let session: URLSession = { fileprivate static let session: URLSession = {
let config = URLSessionConfiguration.ephemeral let config = URLSessionConfiguration.ephemeral
config.timeoutIntervalForRequest = 120 config.timeoutIntervalForRequest = 120
config.timeoutIntervalForResource = 7200 config.timeoutIntervalForResource = 7200
@@ -225,3 +225,123 @@ struct Ollama: InferenceProvider {
} }
} }
} }
struct CompatibleEndpoint: InferenceProvider {
private let base: URL
private let token: String
init(endpoint: String, token: String = "") throws {
guard let components = URLComponents(string: endpoint.trimmingCharacters(in: .whitespacesAndNewlines)),
let host = components.host?.lowercased(), !host.isEmpty,
components.user == nil, components.password == nil, components.query == nil,
components.fragment == nil, let url = components.url else {
throw StudioError("Enter a base URL including its API path, such as http://127.0.0.1:1234/v1.")
}
let local = ["localhost", "127.0.0.1", "::1", "[::1]"].contains(host)
guard components.scheme?.lowercased() == "https" || (local && components.scheme?.lowercased() == "http") else {
throw StudioError("Use HTTPS for a remote compatible endpoint.")
}
guard !token.contains(where: \.isNewline) else { throw StudioError("The token must be a single line.") }
base = url
self.token = token
}
struct Body: Encodable {
struct ResponseFormat: Encodable { let type = "json_object" }
let model: String
let messages: [Ollama.WireMessage]
let stream = true
let temperature: Double?
let max_tokens: Int?
let top_p: Double?
let frequency_penalty: Double?
let presence_penalty: Double?
let stop: [String]?
let response_format: ResponseFormat?
init(_ request: InferenceRequest) {
model = request.model
messages = request.messages.map { .init(role: $0.role, content: $0.content) }
let options = request.parameters
temperature = options.temperature
max_tokens = options.maxTokens
top_p = options.topP
frequency_penalty = options.frequencyPenalty
presence_penalty = options.presencePenalty
stop = options.stop.isEmpty ? nil : options.stop
response_format = options.json ? ResponseFormat() : nil
}
}
private struct Frame: Decodable {
struct Failure: Decodable { let message: String }
struct Choice: Decodable {
struct Piece: Decodable {
let content: String?
let reasoning_content: String?
let reasoning: String?
let tool_calls: [Ollama.Frame.ToolCall]?
}
let delta: Piece?
let finish_reason: String?
}
let error: Failure?
let choices: [Choice]?
}
func models() async throws -> [String] {
struct Response: Decodable {
struct Entry: Decodable { let id: String }
let data: [Entry]
}
let (data, response) = try await Ollama.session.data(for: urlRequest("models"))
try validate(response)
return Array(Set(try JSONDecoder().decode(Response.self, from: data).data.map(\.id))).sorted()
}
func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
streaming { continuation in
var wire = urlRequest("chat/completions")
wire.httpMethod = "POST"
wire.httpBody = try JSONEncoder().encode(Body(request))
wire.setValue("application/json", forHTTPHeaderField: "Content-Type")
wire.setValue("text/event-stream", forHTTPHeaderField: "Accept")
let (bytes, response) = try await Ollama.session.bytes(for: wire)
try validate(response)
continuation.yield(.backend("Compatible API · \(request.model)"))
var terminal = false
for try await line in bytes.lines where line.hasPrefix("data:") {
try Task.checkCancellation()
let payload = line.dropFirst(5).trimmingCharacters(in: .whitespacesAndNewlines)
if payload == "[DONE]" { return }
if payload.isEmpty { continue }
let frame = try JSONDecoder().decode(Frame.self, from: Data(payload.utf8))
if let error = frame.error { throw StudioError(error.message) }
guard let choice = frame.choices?.first else { continue }
if choice.finish_reason == "tool_calls" || !(choice.delta?.tool_calls ?? []).isEmpty {
continuation.yield(.committed)
throw StudioError("The endpoint returned a tool call. Run tools from Settings.")
}
if let text = choice.delta?.reasoning_content ?? choice.delta?.reasoning, !text.isEmpty {
continuation.yield(.thinking(text))
}
if let text = choice.delta?.content, !text.isEmpty { continuation.yield(.answer(text)) }
terminal = terminal || choice.finish_reason != nil
}
if !terminal { throw StudioError("The compatible endpoint disconnected before completing the response.") }
}
}
private func urlRequest(_ path: String) -> URLRequest {
var request = URLRequest(url: base.appending(path: path))
if !token.isEmpty { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }
return request
}
private func validate(_ response: URLResponse) throws {
guard let http = response as? HTTPURLResponse else { throw StudioError("Invalid compatible endpoint response.") }
guard (200..<300).contains(http.statusCode) else {
throw StudioError("Compatible endpoint returned HTTP \(http.statusCode).")
}
}
}
+31 -8
View File
@@ -12,6 +12,7 @@ final class StudioModel: ObservableObject {
@Published private(set) var libraryStatus = "" @Published private(set) var libraryStatus = ""
@Published private(set) var toolAttachment: (name: String, output: String)? @Published private(set) var toolAttachment: (name: String, output: String)?
@Published private(set) var ollamaToken = "" @Published private(set) var ollamaToken = ""
@Published private(set) var compatibleToken = ""
@Published private(set) var models: [Ollama.Model] = [] @Published private(set) var models: [Ollama.Model] = []
@Published private(set) var status = "" @Published private(set) var status = ""
@Published private(set) var modelStatus = "" @Published private(set) var modelStatus = ""
@@ -25,6 +26,7 @@ final class StudioModel: ObservableObject {
private var store: Store? private var store: Store?
private var tokenEndpoint = "" private var tokenEndpoint = ""
private var compatibleTokenEndpoint = ""
private let mlx = MLXProvider() private let mlx = MLXProvider()
private var generation: Task<Void, Never>? private var generation: Task<Void, Never>?
private var management: Task<Void, Never>? private var management: Task<Void, Never>?
@@ -73,17 +75,28 @@ 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, settings: GenerationSettings) { mlxOnly: Bool, compatible: 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 }
guard mlxOnly ? !mlxPath.isEmpty : !tag.isEmpty else { guard mlxOnly ? !mlxPath.isEmpty : !tag.isEmpty else {
status = mlxOnly ? "Choose an MLX model folder in Settings." : "Choose an Ollama model in Settings." status = mlxOnly ? "Choose an MLX model folder in Settings." : "Choose a model in Settings."
return return
} }
do { do {
let ollama = mlxOnly ? nil : try ollamaClient(endpoint: endpoint) let provider: (any InferenceProvider)?
let parameters = try settings.parameters(mlxOnly: mlxOnly) let name: String
if mlxOnly {
provider = nil
name = "MLX"
} else if compatible {
provider = try compatibleClient(endpoint: endpoint)
name = "Compatible API"
} else {
provider = try ollamaClient(endpoint: endpoint)
name = "Ollama"
}
let parameters = try settings.parameters(mlxOnly: mlxOnly, compatible: compatible)
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)
@@ -133,14 +146,15 @@ final class StudioModel: ObservableObject {
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 provider {
let request = InferenceRequest(model: tag, messages: context, thinking: thinking, parameters: parameters) let request = InferenceRequest(model: tag, messages: context, thinking: thinking, parameters: parameters)
stream = Router.stream(primary: { ollama.generate(request) }, stream = Router.stream(primary: { provider.generate(request) },
fallback: failover && !mlxPath.isEmpty ? local : nil) fallback: failover && !mlxPath.isEmpty ? local : nil,
primaryName: name)
} else { } else {
stream = local() stream = local()
} }
generation = Task { await consume(stream, in: chat, start: start, requested: mlxOnly ? "MLX" : "Ollama") } generation = Task { await consume(stream, in: chat, start: start, requested: name) }
} catch { status = error.localizedDescription } } catch { status = error.localizedDescription }
} }
@@ -156,6 +170,15 @@ final class StudioModel: ObservableObject {
ollamaToken = token ollamaToken = token
} }
func setCompatibleToken(_ token: String, endpoint: String) {
compatibleTokenEndpoint = endpoint
compatibleToken = token
}
func compatibleClient(endpoint: String) throws -> CompatibleEndpoint {
try CompatibleEndpoint(endpoint: endpoint, token: endpoint == compatibleTokenEndpoint ? compatibleToken : "")
}
private func ollamaClient(endpoint: String) throws -> Ollama { private func ollamaClient(endpoint: String) throws -> Ollama {
try Ollama(endpoint: endpoint, token: endpoint == tokenEndpoint ? ollamaToken : "") try Ollama(endpoint: endpoint, token: endpoint == tokenEndpoint ? ollamaToken : "")
} }
+22
View File
@@ -24,6 +24,22 @@ class Handler(BaseHTTPRequestHandler):
message = self.body() message = self.body()
method = message.get('method') method = message.get('method')
args = message.get('params', {}) args = message.get('params', {})
if self.path == '/compatible/v1/chat/completions':
if self.headers.get('Authorization') != 'Bearer fixture-token':
self.reply(401)
return
assert message['stream'] and message['model'] == 'fixture-model'
assert message['messages'][0] == {'role': 'system', 'content': 'Silent instruction'}
assert message['temperature'] == 0 and message['max_tokens'] == 32
assert 'options' not in message and 'think' not in message
frames = [
{'choices': [{'delta': {'reasoning_content': 'Thinking'}}]},
{'choices': [{'delta': {'content': 'Fixture response'}}]},
{'choices': [{'delta': {}, 'finish_reason': 'stop'}]},
]
payload = ''.join(f'data: {json.dumps(frame)}\n\n' for frame in frames)
self.reply(200, (payload + 'data: [DONE]\n\n').encode(), 'text/event-stream')
return
if self.path == '/gateway/api/chat': if self.path == '/gateway/api/chat':
if self.headers.get('Authorization') != 'Bearer fixture-token': if self.headers.get('Authorization') != 'Bearer fixture-token':
self.reply(401) self.reply(401)
@@ -80,6 +96,12 @@ class Handler(BaseHTTPRequestHandler):
self.reply(200, envelope, headers=headers) self.reply(200, envelope, headers=headers)
def do_GET(self): def do_GET(self):
if self.path == '/compatible/v1/models':
if self.headers.get('Authorization') != 'Bearer fixture-token':
self.reply(401)
return
self.reply(200, {'data': [{'id': 'fixture-model'}, {'id': 'fixture-model'}]})
return
if self.path == '/gateway/api/tags': if self.path == '/gateway/api/tags':
if self.headers.get('Authorization') != 'Bearer fixture-token': if self.headers.get('Authorization') != 'Bearer fixture-token':
self.reply(401) self.reply(401)
+23
View File
@@ -364,3 +364,26 @@ final class GenerationConfigurationTests: XCTestCase {
XCTAssertThrowsError(try DockerCommand.arguments("docker logs 'unclosed")) XCTAssertThrowsError(try DockerCommand.arguments("docker logs 'unclosed"))
} }
} }
final class CompatibleEndpointTests: XCTestCase {
func testRequiresHTTPSForRemoteAndRejectsEmbeddedCredentials() throws {
XCTAssertThrowsError(try CompatibleEndpoint(endpoint: "http://example.com/v1"))
XCTAssertThrowsError(try CompatibleEndpoint(endpoint: "https://user:[email protected]/v1"))
XCTAssertNoThrow(try CompatibleEndpoint(endpoint: "http://127.0.0.1:1234/v1"))
}
func testAuthenticatedDiscoveryAndStreaming() async throws {
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_COMPATIBLE_URL"] else {
throw XCTSkip("Set AISTUDIO_TEST_COMPATIBLE_URL to the compatible endpoint fixture.")
}
let client = try CompatibleEndpoint(endpoint: endpoint, token: "fixture-token")
let models = try await client.models()
XCTAssertEqual(models, ["fixture-model"])
let output = try await collect(client.generate(InferenceRequest(model: "fixture-model", messages: [
Message(role: .system, content: "Silent instruction"),
Message(role: .user, content: "Hello")
], thinking: .automatic, parameters: GenerationParameters(temperature: 0, maxTokens: 32))))
XCTAssertEqual(output, [.backend("Compatible API · fixture-model"),
.thinking("Thinking"), .answer("Fixture response")])
}
}