Support OpenAI-compatible inference endpoints
This commit is contained in:
+84
-12
@@ -49,6 +49,9 @@ struct ChatView: View {
|
||||
@AppStorage("thinking") private var thinking = Thinking.automatic
|
||||
@AppStorage("failover") private var failover = true
|
||||
@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("globalPromptMode") private var promptMode = PromptMode.standard
|
||||
@AppStorage("globalCustomPrompt") private var customPrompt = ""
|
||||
@@ -60,6 +63,10 @@ struct ChatView: View {
|
||||
@State private var renaming = false
|
||||
@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] {
|
||||
search.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
? studio.conversations : studio.searchConversations(search)
|
||||
@@ -153,14 +160,14 @@ struct ChatView: View {
|
||||
private var composer: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
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")
|
||||
.font(.caption)
|
||||
if !mlxOnly {
|
||||
Text(endpoint).font(.caption).foregroundStyle(.secondary).lineLimit(1)
|
||||
Text(activeEndpoint).font(.caption).foregroundStyle(.secondary).lineLimit(1)
|
||||
}
|
||||
Spacer()
|
||||
if !mlxOnly || MLXThinking.supports(mlxPath) {
|
||||
if (!mlxOnly && !compatibleEnabled) || (mlxOnly && MLXThinking.supports(mlxPath)) {
|
||||
let modes: [Thinking] = mlxOnly ? [.automatic, .off, .on] : Thinking.allCases
|
||||
Picker("Thinking", selection: Binding(
|
||||
get: { modes.contains(thinking) ? thinking : .automatic },
|
||||
@@ -174,14 +181,14 @@ struct ChatView: View {
|
||||
}
|
||||
if !studio.documents.isEmpty {
|
||||
Toggle(mlxOnly ? "Include matching document excerpts" :
|
||||
"Send matching document excerpts to Ollama", isOn: $useDocuments)
|
||||
"Send matching document excerpts to \(backendName)", isOn: $useDocuments)
|
||||
.font(.caption)
|
||||
.disabled(studio.running)
|
||||
}
|
||||
if let attachment = studio.toolAttachment {
|
||||
HStack {
|
||||
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()
|
||||
Button("Remove", systemImage: "xmark.circle") { studio.removeToolAttachment() }
|
||||
}
|
||||
@@ -201,8 +208,8 @@ struct ChatView: View {
|
||||
Button("Stop", systemImage: "stop.fill") { studio.stop() }
|
||||
} else {
|
||||
Button("Send", systemImage: "arrow.up") {
|
||||
studio.send(endpoint: endpoint, model: model, mlxPath: mlxPath, thinking: thinking,
|
||||
failover: failover, mlxOnly: mlxOnly, recall: recall, useDocuments: useDocuments,
|
||||
studio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking,
|
||||
failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: useDocuments,
|
||||
instructions: promptMode.instructions(custom: customPrompt),
|
||||
settings: GenerationSettings.read(generationSettings))
|
||||
}
|
||||
@@ -266,6 +273,9 @@ struct BackendSettings: View {
|
||||
@AppStorage("mlxPath") private var mlxPath = ""
|
||||
@AppStorage("failover") private var failover = true
|
||||
@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
|
||||
@State private var tag = ""
|
||||
@State private var pickingFolder = false
|
||||
@@ -276,11 +286,18 @@ struct BackendSettings: View {
|
||||
var body: some View {
|
||||
Form {
|
||||
Section("Inference") {
|
||||
Picker("Backend", selection: $mlxOnly) {
|
||||
Text("Prefer Ollama").tag(false)
|
||||
Text("MLX only").tag(true)
|
||||
Picker("Backend", selection: Binding(
|
||||
get: { mlxOnly ? "mlx" : (compatibleEnabled ? "compatible" : "ollama") },
|
||||
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)
|
||||
Toggle("Recall older matching messages in this conversation", isOn: $recall)
|
||||
}
|
||||
@@ -326,6 +343,7 @@ struct BackendSettings: View {
|
||||
}
|
||||
Text(studio.modelStatus).foregroundStyle(.secondary).textSelection(.enabled)
|
||||
}
|
||||
CompatibleEndpointSettings(studio: studio, endpoint: $compatibleEndpoint, model: $compatibleModel)
|
||||
Section("MLX") {
|
||||
LabeledContent("Model folder", value: mlxPath.isEmpty ? "None selected" : mlxPath)
|
||||
HStack {
|
||||
@@ -680,9 +698,11 @@ struct GenerationSettingsView: View {
|
||||
field("Top K", $draft.topK)
|
||||
field("Min P", $draft.minP)
|
||||
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("Presence penalty", $draft.presencePenalty)
|
||||
field("Keep alive (e.g. 5m or 0)", $draft.keepAlive)
|
||||
Toggle("JSON output", isOn: $draft.json)
|
||||
}
|
||||
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 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,7 +107,8 @@ enum Router {
|
||||
|
||||
static func stream(
|
||||
primary: @escaping Producer,
|
||||
fallback: Producer?
|
||||
fallback: Producer?,
|
||||
primaryName: String = "Ollama"
|
||||
) -> AsyncThrowingStream<Delta, Error> {
|
||||
streaming { continuation in
|
||||
var committed = false
|
||||
@@ -135,7 +136,7 @@ enum Router {
|
||||
} catch let fallbackError {
|
||||
try Task.checkCancellation()
|
||||
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()
|
||||
}
|
||||
|
||||
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? {
|
||||
let text = value.trimmingCharacters(in: .whitespaces)
|
||||
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.")
|
||||
}
|
||||
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.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
|
||||
}
|
||||
|
||||
+121
-1
@@ -109,7 +109,7 @@ struct Ollama: InferenceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private static let session: URLSession = {
|
||||
fileprivate static let session: URLSession = {
|
||||
let config = URLSessionConfiguration.ephemeral
|
||||
config.timeoutIntervalForRequest = 120
|
||||
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).")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ final class StudioModel: ObservableObject {
|
||||
@Published private(set) var libraryStatus = ""
|
||||
@Published private(set) var toolAttachment: (name: String, output: String)?
|
||||
@Published private(set) var ollamaToken = ""
|
||||
@Published private(set) var compatibleToken = ""
|
||||
@Published private(set) var models: [Ollama.Model] = []
|
||||
@Published private(set) var status = ""
|
||||
@Published private(set) var modelStatus = ""
|
||||
@@ -25,6 +26,7 @@ final class StudioModel: ObservableObject {
|
||||
|
||||
private var store: Store?
|
||||
private var tokenEndpoint = ""
|
||||
private var compatibleTokenEndpoint = ""
|
||||
private let mlx = MLXProvider()
|
||||
private var generation: Task<Void, Never>?
|
||||
private var management: Task<Void, Never>?
|
||||
@@ -73,17 +75,28 @@ final class StudioModel: ObservableObject {
|
||||
func stop() { generation?.cancel() }
|
||||
|
||||
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 tag = model.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !running, !text.isEmpty else { return }
|
||||
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
|
||||
}
|
||||
do {
|
||||
let ollama = mlxOnly ? nil : try ollamaClient(endpoint: endpoint)
|
||||
let parameters = try settings.parameters(mlxOnly: mlxOnly)
|
||||
let provider: (any InferenceProvider)?
|
||||
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 chat = try selected ?? create(String(text.prefix(48)))
|
||||
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 start = ProcessInfo.processInfo.systemUptime
|
||||
let stream: AsyncThrowingStream<Delta, Error>
|
||||
if let ollama {
|
||||
if let provider {
|
||||
let request = InferenceRequest(model: tag, messages: context, thinking: thinking, parameters: parameters)
|
||||
stream = Router.stream(primary: { ollama.generate(request) },
|
||||
fallback: failover && !mlxPath.isEmpty ? local : nil)
|
||||
stream = Router.stream(primary: { provider.generate(request) },
|
||||
fallback: failover && !mlxPath.isEmpty ? local : nil,
|
||||
primaryName: name)
|
||||
} else {
|
||||
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 }
|
||||
}
|
||||
|
||||
@@ -156,6 +170,15 @@ final class StudioModel: ObservableObject {
|
||||
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 {
|
||||
try Ollama(endpoint: endpoint, token: endpoint == tokenEndpoint ? ollamaToken : "")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user