Symmetric to the web BYOK backend (@mana/browser-llm) and @mana/byok-providers. A new LLMBackendID.byok lets the user bring their own third-party API key (OpenAI/Anthropic/Gemini/Mistral); the call streams device-direct to the provider via URLSession — the key never reaches mana infrastructure. New Sources/ManaLLM/Byok/: - ByokTypes: ByokProviderID, ByokSelection, ByokMessage, ByokKeyResolver, ByokProvider protocol, ByokError. - ByokProviders: 4 URLSession SSE adapters (OpenAI/Mistral share an OpenAI-compat path; Anthropic + Gemini have their own schemas). - ByokKeyVault: Keychain store — deliberately app-private, NOT the shared group.ev.mana.session; no cross-device sync. makeResolver(…) helper. - ByokBackend: LLMBackend conformance; unavailable without a resolver; prompt/key never logged (PII/secret). LLMRouter: setByokResolver / setAllowByokInPick. BYOK is never picked silently (privacy discipline, mirror of web) — reachable via backend(for: .byok). LLMBackendID.byok.isOnDeviceLLM == false. Breaking for apps: LLMBackendID has a new .byok case — exhaustive switches (e.g. settings UI) must handle it. swift build + swift test green (23 tests, 11 new — network/keychain-free: provider registry, availability gating, router pick discipline). Compliance rule (sensitive content not via BYOK by default) in mana/docs/COMPLIANCE.md §5. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
147 lines
5 KiB
Swift
147 lines
5 KiB
Swift
import Foundation
|
|
import OSLog
|
|
|
|
/// Zentrale Drehscheibe: hält alle LLM-Backends, wählt nach App-
|
|
/// Preference + Availability das passende und liefert eine
|
|
/// einheitliche `generate`/`summarize`-API.
|
|
///
|
|
/// **Routing-Logik in `currentBackend()`:**
|
|
///
|
|
/// 1. App übergibt eine Priority-Liste (`preferredBackends`) — z.B.
|
|
/// `[.appleFM, .gemmaE2B, .noOp]`.
|
|
/// 2. Router fragt jedes Backend nach `availability()` und nimmt
|
|
/// das erste mit `.isSelectable`-Status (verfügbar oder lokal
|
|
/// gecacht).
|
|
/// 3. Bei nichts verfügbar → `NoOpBackend`. UI rendert
|
|
/// `availabilityMap()` separat, damit der User weiß warum.
|
|
///
|
|
/// Apps können das auch komplett umgehen und ein Backend direkt
|
|
/// instanziieren — z.B. `await AppleFMBackend().generate(...)`.
|
|
public actor LLMRouter {
|
|
/// Bequemer App-übergreifender Default mit allen vier Backends.
|
|
/// Apps mit weniger Backends überschreiben das.
|
|
public static let shared = LLMRouter()
|
|
|
|
private let appleFM: AppleFMBackend
|
|
private let noOp: NoOpBackend
|
|
private let gemmaE2B: GemmaBackend
|
|
private let gemmaE4B: GemmaBackend
|
|
|
|
/// BYOK-Backend. Bleibt `unavailable` bis `setByokResolver` einen
|
|
/// Resolver liefert. Replace-on-configure (Actor-isoliert, safe).
|
|
private var byok: ByokBackend = ByokBackend()
|
|
|
|
/// Darf `currentBackend()` BYOK still wählen? Default `false` — BYOK
|
|
/// schickt Inhalte zu Dritt-SaaS und ist eine bewusste Nutzer-Wahl
|
|
/// (analog Web `allowByokInPick`, Compliance-Regel für sensible
|
|
/// Inhalte). Direkt nutzbar bleibt es über `backend(for: .byok)`.
|
|
private var allowByokInPick: Bool = false
|
|
|
|
/// Priority-Reihenfolge der Backends. Apps können das je nach
|
|
/// Use-Case justieren — z.B. moodlit will Gemma E2B bevor es FM
|
|
/// (Creative-Mapping), pageta will FM zuerst (Summary).
|
|
private var preferred: [LLMBackendID]
|
|
|
|
/// `gemmaAllowsCellular` reicht die App-Einstellung an die
|
|
/// Gemma-Backends durch — Default `false` (WiFi-only). Bei
|
|
/// Toggle-Change muss App den Router neu instanziieren.
|
|
public init(
|
|
preferred: [LLMBackendID] = [.appleFM, .gemmaE2B, .gemmaE4B, .noOp],
|
|
gemmaAllowsCellular: Bool = false
|
|
) {
|
|
self.preferred = preferred
|
|
self.appleFM = AppleFMBackend()
|
|
self.noOp = NoOpBackend()
|
|
self.gemmaE2B = GemmaBackend(variant: .e2b, allowsCellular: gemmaAllowsCellular)
|
|
self.gemmaE4B = GemmaBackend(variant: .e4b, allowsCellular: gemmaAllowsCellular)
|
|
}
|
|
|
|
public func setPreferred(_ ids: [LLMBackendID]) {
|
|
preferred = ids
|
|
}
|
|
|
|
/// Verdrahtet den BYOK-Key-Resolver (aus dem App-Vault). Vorher ist
|
|
/// `.byok` `unavailable`. `defaultProvider` ist der Wunsch-Anbieter,
|
|
/// wenn ein Call keinen angibt.
|
|
public func setByokResolver(
|
|
_ resolver: @escaping ByokKeyResolver,
|
|
defaultProvider: ByokProviderID? = nil
|
|
) {
|
|
byok = ByokBackend(resolver: resolver, defaultProvider: defaultProvider)
|
|
}
|
|
|
|
/// Erlaubt dem Router, BYOK still zu wählen (Default `false`).
|
|
public func setAllowByokInPick(_ allow: Bool) {
|
|
allowByokInPick = allow
|
|
}
|
|
|
|
public func backend(for id: LLMBackendID) -> LLMBackend {
|
|
switch id {
|
|
case .noOp: noOp
|
|
case .appleFM: appleFM
|
|
case .gemmaE2B: gemmaE2B
|
|
case .gemmaE4B: gemmaE4B
|
|
case .byok: byok
|
|
}
|
|
}
|
|
|
|
/// Wählt das erste verfügbare Backend aus der Preference-Liste.
|
|
/// Bevorzugt strikt `.available` (Modell bereit). Wenn kein
|
|
/// `.available` gefunden → fällt auf `.requiresDownload`-Fall
|
|
/// zurück, falls in der Liste. Letzte Notbremse: NoOp.
|
|
public func currentBackend() async -> LLMBackend {
|
|
// Erster Pass: `.available` only.
|
|
for id in preferred {
|
|
// Datenschutz-Disziplin: BYOK nie still wählen.
|
|
if id == .byok && !allowByokInPick { continue }
|
|
let candidate = backend(for: id)
|
|
if await candidate.availability() == .available {
|
|
return candidate
|
|
}
|
|
}
|
|
// Zweiter Pass: irgendwas selectable (auch requires-Download).
|
|
for id in preferred {
|
|
if id == .byok && !allowByokInPick { continue }
|
|
let candidate = backend(for: id)
|
|
let avail = await candidate.availability()
|
|
if avail.isSelectable {
|
|
LLMLog.router.notice(
|
|
"Router: kein .available — pick \(id.rawValue, privacy: .public) (\(String(describing: avail), privacy: .public))"
|
|
)
|
|
return candidate
|
|
}
|
|
}
|
|
LLMLog.router.notice("Router: keine verfügbaren Backends — NoOp")
|
|
return noOp
|
|
}
|
|
|
|
// MARK: - Convenience
|
|
|
|
public func generate(
|
|
prompt: String,
|
|
instructions: String? = nil,
|
|
maxTokens: Int = 500
|
|
) async -> String? {
|
|
let backend = await currentBackend()
|
|
return await backend.generate(
|
|
prompt: prompt,
|
|
instructions: instructions,
|
|
maxTokens: maxTokens
|
|
)
|
|
}
|
|
|
|
public func summarize(transcript: String) async -> LLMSummary? {
|
|
let backend = await currentBackend()
|
|
return await backend.summarize(transcript: transcript)
|
|
}
|
|
|
|
/// UI-helper: pro Backend-ID den Availability-Status, etwa für die
|
|
/// Settings-Liste. Parallelisiert über die Backends.
|
|
public func availabilityMap() async -> [LLMBackendID: LLMAvailability] {
|
|
var result: [LLMBackendID: LLMAvailability] = [:]
|
|
for id in LLMBackendID.allCases {
|
|
result[id] = await backend(for: id).availability()
|
|
}
|
|
return result
|
|
}
|
|
}
|