Files
ai_studio/Sources/Ollama.swift
T
Mark Gregory 2238df4631 Build AI Studio for macOS
Add branded startup, Ollama and MLX inference, persistent chat and document retrieval, confirmed MCP tools, and reproducible build and test scripts.
2026-11-16 13:14:00 +00:00

173 lines
7.1 KiB
Swift

import Foundation
struct Ollama: InferenceProvider {
struct Model: Decodable, Identifiable, Sendable {
let name: String
let size: Int64?
var id: String { name }
}
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 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
}
struct ChatBody: Encodable {
let model: String
let messages: [WireMessage]
let think: Thinking?
let stream = true
}
struct ModelBody: Encodable {
let model: String
}
struct ModelDetails: Decodable {
let capabilities: [String]?
}
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)
}
}
private 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 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(model: request.model,
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))
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 { 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).")
}
}
}