Files
ai_studio/Sources/Ollama.swift
T

348 lines
14 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 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
}
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) }
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 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)
}
}
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 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 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).")
}
}
}