555 lines
23 KiB
Swift
555 lines
23 KiB
Swift
import Foundation
|
|
|
|
struct Ollama: InferenceProvider {
|
|
struct Model: Decodable, Identifiable, Sendable {
|
|
let name: String
|
|
let size: Int64?
|
|
let details: Metadata?
|
|
var id: String { name }
|
|
|
|
enum CodingKeys: String, CodingKey { case name, model, size, details }
|
|
|
|
init(from decoder: Decoder) throws {
|
|
let values = try decoder.container(keyedBy: CodingKeys.self)
|
|
name = try values.decodeIfPresent(String.self, forKey: .name) ?? values.decode(String.self, forKey: .model)
|
|
size = try? values.decode(Int64.self, forKey: .size)
|
|
details = try? values.decode(Metadata.self, forKey: .details)
|
|
}
|
|
}
|
|
|
|
struct Frame: Decodable {
|
|
struct Text: Decodable {
|
|
let content: String?
|
|
let thinking: String?
|
|
let tool_calls: [ToolCall]?
|
|
}
|
|
struct ToolCall: Decodable {}
|
|
let message: Text?
|
|
let done: Bool?
|
|
let eval_count: Int?
|
|
let eval_duration: Double?
|
|
let error: String?
|
|
let status: String?
|
|
let total: Int64?
|
|
let completed: Int64?
|
|
|
|
static func decode(_ line: String) throws -> Self {
|
|
let frame = try JSONDecoder().decode(Self.self, from: Data(line.utf8))
|
|
if let error = frame.error { throw StudioError(error) }
|
|
return frame
|
|
}
|
|
}
|
|
|
|
struct WireMessage: Encodable {
|
|
let role: Role
|
|
let content: String
|
|
let images: [Data]?
|
|
}
|
|
|
|
struct ChatBody: Encodable {
|
|
let model: String
|
|
let messages: [WireMessage]
|
|
let think: Thinking?
|
|
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, images: $0.imagePNG.map { [$0] })
|
|
}
|
|
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 {
|
|
let model: String
|
|
}
|
|
|
|
struct Metadata: Decodable, Sendable {
|
|
let format: String?
|
|
let family: String?
|
|
let parameters: String?
|
|
let quantization: String?
|
|
|
|
enum CodingKeys: String, CodingKey {
|
|
case format, family
|
|
case parameters = "parameter_size"
|
|
case quantization = "quantization_level"
|
|
}
|
|
}
|
|
|
|
struct ModelDetails: Decodable {
|
|
let capabilities: [String]?
|
|
let details: Metadata?
|
|
let architecture: String?
|
|
let contextLength: Int?
|
|
|
|
enum CodingKeys: String, CodingKey {
|
|
case capabilities, details
|
|
case modelInfo = "model_info"
|
|
}
|
|
|
|
private struct InfoKey: CodingKey {
|
|
var stringValue: String
|
|
var intValue: Int? { nil }
|
|
init(stringValue: String) { self.stringValue = stringValue }
|
|
init?(intValue: Int) { return nil }
|
|
}
|
|
|
|
init(from decoder: Decoder) throws {
|
|
let values = try decoder.container(keyedBy: CodingKeys.self)
|
|
capabilities = try values.decodeIfPresent([String].self, forKey: .capabilities)
|
|
details = try? values.decode(Metadata.self, forKey: .details)
|
|
let info = try? values.nestedContainer(keyedBy: InfoKey.self, forKey: .modelInfo)
|
|
let architecture = try? info?.decode(String.self, forKey: InfoKey(stringValue: "general.architecture"))
|
|
self.architecture = architecture
|
|
contextLength = architecture.flatMap {
|
|
try? info?.decode(Int.self, forKey: InfoKey(stringValue: $0 + ".context_length"))
|
|
}
|
|
}
|
|
}
|
|
|
|
private final class NoRedirects: NSObject, URLSessionTaskDelegate, Sendable {
|
|
func urlSession(
|
|
_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
|
|
newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void
|
|
) {
|
|
completionHandler(nil)
|
|
}
|
|
}
|
|
|
|
fileprivate static let session: URLSession = {
|
|
let config = URLSessionConfiguration.ephemeral
|
|
config.timeoutIntervalForRequest = 120
|
|
config.timeoutIntervalForResource = 7200
|
|
return URLSession(configuration: config, delegate: NoRedirects(), delegateQueue: nil)
|
|
}()
|
|
|
|
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, !host.isEmpty,
|
|
["http", "https"].contains(components.scheme?.lowercased()),
|
|
components.user == nil, components.password == nil, components.query == nil,
|
|
components.fragment == nil, let url = components.url else {
|
|
throw StudioError("Enter an HTTP or HTTPS Ollama URL without credentials, a query or a fragment.")
|
|
}
|
|
guard !token.contains(where: \.isNewline) else {
|
|
throw StudioError("The Ollama bearer token must be a single line.")
|
|
}
|
|
let local = ["localhost", "127.0.0.1", "[::1]", "::1"].contains(components.host?.lowercased())
|
|
if !token.isEmpty && !local && components.scheme?.lowercased() != "https" {
|
|
throw StudioError("Use HTTPS to send an Ollama bearer token to a remote server.")
|
|
}
|
|
base = url
|
|
self.token = token
|
|
}
|
|
|
|
func models() async throws -> [Model] {
|
|
struct Result: Decodable { let models: [Model] }
|
|
let request = makeRequest("tags")
|
|
let (data, result) = try await Self.session.data(for: request)
|
|
try Self.validate(result)
|
|
return try JSONDecoder().decode(Result.self, from: data).models
|
|
}
|
|
|
|
func details(for model: String) async throws -> ModelDetails {
|
|
let (data, result) = try await Self.session.data(for: request("show", body: ModelBody(model: model)))
|
|
try Self.validate(result)
|
|
return try JSONDecoder().decode(ModelDetails.self, from: data)
|
|
}
|
|
|
|
func copy(_ source: String, to destination: String) async throws {
|
|
struct CopyBody: Encodable { let source: String; let destination: String }
|
|
let request = try request("copy", body: CopyBody(source: source, destination: destination))
|
|
let (_, result) = try await Self.session.data(for: request)
|
|
try Self.validate(result)
|
|
}
|
|
|
|
func delete(_ model: String) async throws {
|
|
let (_, result) = try await Self.session.data(for: request("delete", method: "DELETE", body: ModelBody(model: model)))
|
|
try Self.validate(result)
|
|
}
|
|
|
|
func pull(_ model: String) -> AsyncThrowingStream<String, Error> {
|
|
streaming { continuation in
|
|
let (bytes, response) = try await Self.session.bytes(for: request("pull", body: ModelBody(model: model)))
|
|
try Self.validate(response)
|
|
for try await line in bytes.lines where !line.isEmpty {
|
|
try Task.checkCancellation()
|
|
let frame = try Frame.decode(line)
|
|
if let status = frame.status {
|
|
if let total = frame.total, total > 0, let completed = frame.completed {
|
|
let bounded = min(max(completed, 0), total)
|
|
continuation.yield("\(status) · \(Int(Double(bounded) / Double(total) * 100))%")
|
|
} else {
|
|
continuation.yield(status)
|
|
}
|
|
if status == "success" { return }
|
|
}
|
|
}
|
|
throw StudioError("Ollama ended the download stream before reporting success.")
|
|
}
|
|
}
|
|
|
|
func generate(_ request: InferenceRequest) -> AsyncThrowingStream<Delta, Error> {
|
|
streaming { continuation in
|
|
let body = ChatBody(request)
|
|
let (bytes, response) = try await Self.session.bytes(for: self.request("chat", body: body))
|
|
try Self.validate(response)
|
|
continuation.yield(.backend("Ollama · \(request.model)"))
|
|
for try await line in bytes.lines where !line.isEmpty {
|
|
try Task.checkCancellation()
|
|
let frame = try Frame.decode(line)
|
|
if let calls = frame.message?.tool_calls, !calls.isEmpty {
|
|
continuation.yield(.committed)
|
|
throw StudioError("The model returned a tool call, but no tools are configured.")
|
|
}
|
|
if let text = frame.message?.thinking, !text.isEmpty { continuation.yield(.thinking(text)) }
|
|
if let text = frame.message?.content, !text.isEmpty { continuation.yield(.answer(text)) }
|
|
if frame.done == true {
|
|
if let count = frame.eval_count, let duration = frame.eval_duration {
|
|
continuation.yield(.metrics(ProviderMetrics(tokens: count, seconds: duration / 1_000_000_000)))
|
|
}
|
|
return
|
|
}
|
|
}
|
|
throw StudioError("Ollama disconnected before completing the response.")
|
|
}
|
|
}
|
|
|
|
private func request(_ path: String, method: String = "POST", body: some Encodable) throws -> URLRequest {
|
|
var request = makeRequest(path)
|
|
request.httpMethod = method
|
|
request.httpBody = try JSONEncoder().encode(body)
|
|
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
return request
|
|
}
|
|
|
|
private func makeRequest(_ path: String) -> URLRequest {
|
|
var request = URLRequest(url: base.appending(path: "api/" + path))
|
|
if !token.isEmpty { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }
|
|
return request
|
|
}
|
|
|
|
private static func validate(_ response: URLResponse) throws {
|
|
guard let http = response as? HTTPURLResponse else { throw StudioError("Invalid Ollama response.") }
|
|
guard (200..<300).contains(http.statusCode) else {
|
|
throw StudioError("Ollama returned HTTP \(http.statusCode).")
|
|
}
|
|
}
|
|
}
|
|
|
|
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 WireMessage: Encodable {
|
|
struct Part: Encodable {
|
|
struct ImageURL: Encodable { let url: String }
|
|
let type: String
|
|
var text: String? = nil
|
|
var image_url: ImageURL? = nil
|
|
}
|
|
|
|
let message: Message
|
|
enum CodingKeys: CodingKey { case role, content }
|
|
|
|
func encode(to encoder: Encoder) throws {
|
|
var container = encoder.container(keyedBy: CodingKeys.self)
|
|
try container.encode(message.role, forKey: .role)
|
|
if let url = message.imageDataURL {
|
|
try container.encode([
|
|
Part(type: "text", text: message.content),
|
|
Part(type: "image_url", image_url: .init(url: url))
|
|
], forKey: .content)
|
|
} else {
|
|
try container.encode(message.content, forKey: .content)
|
|
}
|
|
}
|
|
}
|
|
|
|
struct Body: Encodable {
|
|
struct ResponseFormat: Encodable { let type = "json_object" }
|
|
let model: String
|
|
let messages: [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 { WireMessage(message: $0) }
|
|
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?
|
|
}
|
|
struct Usage: Decodable { let completion_tokens: Int? }
|
|
let error: Failure?
|
|
let choices: [Choice]?
|
|
let usage: Usage?
|
|
}
|
|
|
|
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) }
|
|
if let tokens = frame.usage?.completion_tokens, tokens >= 0 {
|
|
continuation.yield(.metrics(ProviderMetrics(tokens: tokens, seconds: 0)))
|
|
}
|
|
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.") }
|
|
}
|
|
}
|
|
|
|
static func pluginIDs(_ text: String) -> [String] {
|
|
var seen = Set<String>()
|
|
return text.split(whereSeparator: { $0 == "," || $0.isWhitespace })
|
|
.map { $0.hasPrefix("mcp/") ? String($0) : "mcp/\($0)" }
|
|
.filter { $0.count > 4 && seen.insert($0).inserted }
|
|
}
|
|
|
|
func generateWithPlugins(_ request: InferenceRequest, plugins: [String]) -> AsyncThrowingStream<Delta, Error> {
|
|
streaming { continuation in
|
|
guard !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
|
throw StudioError("Enter an LM Studio API token in Settings → Models to use installed plugins.")
|
|
}
|
|
var server = base
|
|
if server.lastPathComponent == "v1" {
|
|
server.deleteLastPathComponent()
|
|
}
|
|
var wire = URLRequest(url: server.appending(path: "api/v1/chat"))
|
|
wire.httpMethod = "POST"
|
|
wire.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
|
|
wire.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
wire.setValue("text/event-stream", forHTTPHeaderField: "Accept")
|
|
wire.httpBody = try JSONEncoder().encode(PluginChatBody(request, plugins: plugins))
|
|
let (bytes, response) = try await Ollama.session.bytes(for: wire)
|
|
try validate(response)
|
|
continuation.yield(.backend("LM Studio Plugins · \(request.model)"))
|
|
for try await line in bytes.lines where line.hasPrefix("data:") {
|
|
try Task.checkCancellation()
|
|
let payload = line.dropFirst(5).trimmingCharacters(in: .whitespacesAndNewlines)
|
|
guard !payload.isEmpty else { continue }
|
|
let event = try JSONDecoder().decode(PluginChatEvent.self, from: Data(payload.utf8))
|
|
switch event.type {
|
|
case "message.delta":
|
|
if let content = event.content { continuation.yield(.answer(content)) }
|
|
case "reasoning.delta":
|
|
if let content = event.content { continuation.yield(.thinking(content)) }
|
|
case "tool_call.start":
|
|
continuation.yield(.committed)
|
|
case "error":
|
|
throw StudioError(event.error?.message ?? "LM Studio plugin chat failed.")
|
|
case "chat.end":
|
|
if let stats = event.result?.stats, stats.total_output_tokens >= 0 {
|
|
continuation.yield(.metrics(ProviderMetrics(tokens: stats.total_output_tokens, seconds: 0)))
|
|
}
|
|
return
|
|
default:
|
|
break
|
|
}
|
|
}
|
|
throw StudioError("LM Studio disconnected before completing the plugin response.")
|
|
}
|
|
}
|
|
|
|
struct PluginChatBody: Encodable {
|
|
struct Input: Encodable {
|
|
struct Part: Encodable {
|
|
let type: String
|
|
var content: String? = nil
|
|
var data_url: String? = nil
|
|
}
|
|
|
|
let text: String
|
|
let imageURL: String?
|
|
|
|
func encode(to encoder: Encoder) throws {
|
|
var container = encoder.singleValueContainer()
|
|
if let imageURL {
|
|
try container.encode([Part(type: "text", content: text), Part(type: "image", data_url: imageURL)])
|
|
} else {
|
|
try container.encode(text)
|
|
}
|
|
}
|
|
}
|
|
|
|
let model: String
|
|
let input: Input
|
|
let system_prompt: String?
|
|
let integrations: [String]
|
|
let stream = true
|
|
let store = false
|
|
let temperature: Double?
|
|
let top_p: Double?
|
|
let max_output_tokens: Int?
|
|
let context_length: Int?
|
|
|
|
init(_ request: InferenceRequest, plugins: [String]) {
|
|
model = request.model
|
|
integrations = plugins
|
|
let system = request.messages.filter { $0.role == .system }.map(\.content)
|
|
system_prompt = system.isEmpty ? nil : system.joined(separator: "\n\n")
|
|
// Native chat accepts user input and a system prompt. Preserve prepared history as reference text.
|
|
let conversation = request.messages.filter { $0.role != .system }
|
|
let history = conversation.dropLast()
|
|
var text = conversation.last?.content ?? ""
|
|
if !history.isEmpty {
|
|
let transcript = history.map { "\($0.role.rawValue): \($0.content)" }.joined(separator: "\n\n")
|
|
text = "Previous conversation for reference:\n\(transcript)\n\nLatest message:\n\(text)"
|
|
}
|
|
input = Input(text: text, imageURL: conversation.last?.imageDataURL)
|
|
temperature = request.parameters.temperature
|
|
top_p = request.parameters.topP
|
|
max_output_tokens = request.parameters.maxTokens
|
|
context_length = request.parameters.context
|
|
}
|
|
}
|
|
|
|
private struct PluginChatEvent: Decodable {
|
|
struct Failure: Decodable { let message: String }
|
|
struct Result: Decodable {
|
|
struct Stats: Decodable { let total_output_tokens: Int }
|
|
let stats: Stats?
|
|
}
|
|
let type: String
|
|
let content: String?
|
|
let error: Failure?
|
|
let result: Result?
|
|
}
|
|
|
|
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).")
|
|
}
|
|
}
|
|
}
|