Files
Sprachmittler/Packages/SprachmittlerKit/Sources/SprachmittlerOllama/OllamaCatalogClient.swift
T
schihei 26b493e7e5 feat(m1): Ollama client, catalog, streaming chat and CLI (T1.1-T1.6)
Add endpoint policy and redirect-safe ephemeral HTTP client, error mapping, catalog cache and version checks, streaming chat with phase timeouts/cancellation, provisional Hy-MT3 prompt/language/request factory, warm-up policy, and sprachmittler-cli models/show/translate. Recapture the 7B fixtures; defer the 1.8B VERIFY items; document ADR-016. Also fix the signature checker's pipefail SIGPIPE issue.
2026-11-26 13:04:22 +01:00

118 lines
4.0 KiB
Swift

import Foundation
/// The concrete catalog client. Model details are cached by digest for the app lifetime;
/// `refresh()` invalidates the cache after a model pull or removal.
public actor OllamaCatalogClient: OllamaCatalog {
private let http: any OllamaHTTPTransport
private let minimumVersion: OllamaVersion
private var detailsByDigest: [String: ModelDetails] = [:]
private var digestByName: [String: String] = [:]
/// Creates a catalog client over an HTTP transport.
public init(http: any OllamaHTTPTransport, minimumVersion: OllamaVersion = .minimumSupported) {
self.http = http
self.minimumVersion = minimumVersion
}
public func serverVersion() async throws -> String {
let response = try await http.send(.init(path: "/api/version"), model: nil)
return try decode(VersionResponse.self, from: response).version
}
public func installedModels() async throws -> [InstalledModel] {
let response = try await http.send(.init(path: "/api/tags"), model: nil)
let models = try decode(TagsResponse.self, from: response).models
digestByName = models.reduce(into: [:]) { result, model in
result[model.normalizedName] = model.digest
}
return models
}
public func show(model: String) async throws -> ModelDetails {
let normalized = InstalledModel.normalizedName(model)
if digestByName[normalized] == nil {
_ = try await installedModels()
}
if let digest = digestByName[normalized], let cached = detailsByDigest[digest] {
return cached
}
let body = try JSONEncoder().encode(ShowRequest(model: model))
let request = OllamaHTTPRequest(method: .post, path: "/api/show", body: body)
let response = try await http.send(request, model: model)
let details = try decode(ModelDetails.self, from: response)
if let digest = digestByName[normalized] {
detailsByDigest[digest] = details
}
return details
}
public func loadedModels() async throws -> [LoadedModel] {
let response = try await http.send(.init(path: "/api/ps"), model: nil)
return try decode(PsResponse.self, from: response).models
}
/// Clears the per-digest details cache and the name→digest map.
public func refresh() async {
detailsByDigest.removeAll()
digestByName.removeAll()
}
/// Throws `OllamaError.unsupportedVersion` when the server is older than the minimum.
public func checkMinimumVersion() async throws {
let found = try await serverVersion()
guard let parsed = OllamaVersion(found), parsed >= minimumVersion else {
throw OllamaError.unsupportedVersion(
found: found,
required: minimumVersion.description
)
}
}
private func decode<Value: Decodable>(
_ type: Value.Type,
from response: OllamaHTTPResponse
) throws -> Value {
do {
return try JSONDecoder().decode(type, from: response.body)
} catch {
throw OllamaError.decoding("Invalid \(type) response")
}
}
}
private struct VersionResponse: Decodable {
let version: String
}
private struct TagsResponse: Decodable {
let models: [InstalledModel]
private enum CodingKeys: String, CodingKey {
case models
}
init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
models = try container.decodeIfPresent([InstalledModel].self, forKey: .models) ?? []
}
}
private struct PsResponse: Decodable {
let models: [LoadedModel]
private enum CodingKeys: String, CodingKey {
case models
}
init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
models = try container.decodeIfPresent([LoadedModel].self, forKey: .models) ?? []
}
}
private struct ShowRequest: Encodable {
let model: String
}