-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAIBackendManager+Enhanced.swift
More file actions
372 lines (301 loc) · 11.7 KB
/
Copy pathAIBackendManager+Enhanced.swift
File metadata and controls
372 lines (301 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import Foundation
import SwiftUI
import Combine
//
// AIBackendManager+Enhanced.swift
// Enhanced features for AIBackendManager
//
// Adds: Auto-fallback, connection testing, usage tracking, notifications, performance metrics
// Author: Jordan Koch
// Date: 2026-01-26
//
extension AIBackendManager {
// MARK: - Auto-Fallback System
/// Try to generate with fallback to other backends if primary fails
func generateWithFallback(
prompt: String,
systemPrompt: String? = nil,
temperature: Float = 0.7,
maxTokens: Int = 2048
) async throws -> String {
let preferredBackends = getAvailableBackendsInOrder()
var lastError: Error?
for backend in preferredBackends {
let previousBackend = activeBackend
activeBackend = backend
do {
let result = try await generate(
prompt: prompt,
systemPrompt: systemPrompt,
temperature: temperature,
maxTokens: maxTokens
)
// Success! Log and return
if backend != previousBackend {
await MainActor.run {
sendNotification(
title: "Backend Fallback",
message: "Switched to \(backend.rawValue) after \(previousBackend?.rawValue ?? "unknown") failed"
)
}
}
return result
} catch {
lastError = error
continue
}
}
// All backends failed
throw lastError ?? AIBackendError.noBackendAvailable
}
private func getAvailableBackendsInOrder() -> [AIBackend] {
var backends: [AIBackend] = []
// Start with currently selected
if let active = activeBackend, isBackendAvailable(active) {
backends.append(active)
}
// Add other available backends in priority order
let priorityOrder: [AIBackend] = [
.ollama, .openAI, .tinyChat, .tinyLLM, .openWebUI,
.googleCloud, .azureCognitive, .ibmWatson, .mlx, .awsAI
]
for backend in priorityOrder where !backends.contains(backend) && isBackendAvailable(backend) {
backends.append(backend)
}
return backends
}
private func isBackendAvailable(_ backend: AIBackend) -> Bool {
switch backend {
case .ollama: return isOllamaAvailable
case .mlx: return isMLXAvailable
case .tinyLLM: return isTinyLLMAvailable
case .tinyChat: return isTinyChatAvailable
case .openWebUI: return isOpenWebUIAvailable
case .openAI: return isOpenAIAvailable
case .googleCloud: return isGoogleCloudAvailable
case .azureCognitive: return isAzureAvailable
case .awsAI: return isAWSAvailable
case .ibmWatson: return isIBMWatsonAvailable
}
}
// MARK: - Connection Testing
@Published var connectionTestResults: [AIBackend: ConnectionTestResult] = [:]
struct ConnectionTestResult {
let success: Bool
let responseTime: TimeInterval?
let error: String?
let timestamp: Date
}
func testConnection(for backend: AIBackend) async -> ConnectionTestResult {
let startTime = Date()
do {
// Save current backend
let previousBackend = activeBackend
activeBackend = backend
// Try a simple test prompt
_ = try await generate(
prompt: "Say 'hello' in one word",
temperature: 0.1,
maxTokens: 10
)
// Restore previous backend
activeBackend = previousBackend
let responseTime = Date().timeIntervalSince(startTime)
let result = ConnectionTestResult(
success: true,
responseTime: responseTime,
error: nil,
timestamp: Date()
)
await MainActor.run {
connectionTestResults[backend] = result
sendNotification(
title: "Connection Test Passed",
message: "\(backend.rawValue): \(String(format: "%.2f", responseTime))s"
)
}
return result
} catch {
let result = ConnectionTestResult(
success: false,
responseTime: nil,
error: error.localizedDescription,
timestamp: Date()
)
await MainActor.run {
connectionTestResults[backend] = result
sendNotification(
title: "Connection Test Failed",
message: "\(backend.rawValue): \(error.localizedDescription)"
)
}
return result
}
}
// MARK: - Usage Tracking
@Published var usageStats: [AIBackend: UsageStats] = [:]
struct UsageStats: Codable {
var totalTokens: Int = 0
var totalRequests: Int = 0
var totalCost: Double = 0.0 // USD
var averageResponseTime: Double = 0.0 // seconds
var lastUsed: Date?
mutating func recordUsage(tokens: Int, cost: Double, responseTime: TimeInterval) {
totalTokens += tokens
totalRequests += 1
totalCost += cost
// Update running average
let totalTime = averageResponseTime * Double(totalRequests - 1) + responseTime
averageResponseTime = totalTime / Double(totalRequests)
lastUsed = Date()
}
}
func recordUsage(backend: AIBackend, tokens: Int, responseTime: TimeInterval) {
let cost = estimateCost(backend: backend, tokens: tokens)
var stats = usageStats[backend] ?? UsageStats()
stats.recordUsage(tokens: tokens, cost: cost, responseTime: responseTime)
usageStats[backend] = stats
saveUsageStats()
}
private func estimateCost(backend: AIBackend, tokens: Int) -> Double {
// Rough cost estimates per 1M tokens
let costPerMillion: Double = {
switch backend {
case .openAI: return 10.0 // GPT-4o
case .googleCloud: return 7.0
case .azureCognitive: return 10.0
case .awsAI: return 8.0
case .ibmWatson: return 12.0
case .ollama, .mlx, .tinyLLM, .tinyChat, .openWebUI: return 0.0 // Free/local
}
}()
return (Double(tokens) / 1_000_000.0) * costPerMillion
}
private func saveUsageStats() {
// Save to UserDefaults (should migrate to file-based storage for large datasets)
if let data = try? JSONEncoder().encode(usageStats) {
UserDefaults.standard.set(data, forKey: "AIBackend_UsageStats")
}
}
private func loadUsageStats() {
if let data = UserDefaults.standard.data(forKey: "AIBackend_UsageStats"),
let stats = try? JSONDecoder().decode([AIBackend: UsageStats].self, from: data) {
usageStats = stats
}
}
// MARK: - Performance Metrics
@Published var performanceMetrics: [AIBackend: PerformanceMetrics] = [:]
struct PerformanceMetrics {
var averageLatency: TimeInterval = 0.0
var successRate: Double = 0.0
var totalAttempts: Int = 0
var successfulAttempts: Int = 0
var failedAttempts: Int = 0
var lastResponseTime: TimeInterval?
var lastSuccess: Date?
var lastFailure: Date?
mutating func recordSuccess(responseTime: TimeInterval) {
totalAttempts += 1
successfulAttempts += 1
lastResponseTime = responseTime
lastSuccess = Date()
// Update running average
let totalTime = averageLatency * Double(successfulAttempts - 1) + responseTime
averageLatency = totalTime / Double(successfulAttempts)
// Calculate success rate
successRate = Double(successfulAttempts) / Double(totalAttempts)
}
mutating func recordFailure() {
totalAttempts += 1
failedAttempts += 1
lastFailure = Date()
// Recalculate success rate
successRate = Double(successfulAttempts) / Double(totalAttempts)
}
}
func recordPerformance(backend: AIBackend, success: Bool, responseTime: TimeInterval?) {
var metrics = performanceMetrics[backend] ?? PerformanceMetrics()
if success, let responseTime = responseTime {
metrics.recordSuccess(responseTime: responseTime)
} else {
metrics.recordFailure()
}
performanceMetrics[backend] = metrics
}
// MARK: - Notification System
private func sendNotification(title: String, message: String) {
// For macOS, use NSUserNotification or UNUserNotificationCenter
// This is a simplified version
#if os(macOS)
let notification = NSUserNotification()
notification.title = title
notification.informativeText = message
notification.soundName = NSUserNotificationDefaultSoundName
NSUserNotificationCenter.default.deliver(notification)
#endif
print("📢 \(title): \(message)")
}
// MARK: - Background Monitoring
private var monitoringTimer: Timer?
func startBackgroundMonitoring(interval: TimeInterval = 60.0) {
stopBackgroundMonitoring()
monitoringTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
Task { @MainActor [weak self] in
guard let self = self else { return }
let previousAvailability = self.collectAvailabilitySnapshot()
await self.refreshAllBackends()
let currentAvailability = self.collectAvailabilitySnapshot()
// Notify of changes
self.notifyAvailabilityChanges(from: previousAvailability, to: currentAvailability)
}
}
}
func stopBackgroundMonitoring() {
monitoringTimer?.invalidate()
monitoringTimer = nil
}
private func collectAvailabilitySnapshot() -> [AIBackend: Bool] {
var snapshot: [AIBackend: Bool] = [:]
for backend in AIBackend.allCases {
snapshot[backend] = isBackendAvailable(backend)
}
return snapshot
}
private func notifyAvailabilityChanges(from previous: [AIBackend: Bool], to current: [AIBackend: Bool]) {
for backend in AIBackend.allCases {
let wasAvailable = previous[backend] ?? false
let isNowAvailable = current[backend] ?? false
if wasAvailable != isNowAvailable {
let status = isNowAvailable ? "Online" : "Offline"
sendNotification(
title: "Backend Status Changed",
message: "\(backend.rawValue) is now \(status)"
)
}
}
}
}
// MARK: - Keyboard Shortcut Support
#if os(macOS)
import AppKit
extension AIBackendManager {
/// Register global keyboard shortcuts for backend switching
func registerKeyboardShortcuts() {
// ⌘1-⌘9 for quick backend switching
let shortcuts: [(Int, AIBackend)] = [
(1, .ollama),
(2, .openAI),
(3, .mlx),
(4, .tinyLLM),
(5, .googleCloud),
(6, .azureCognitive),
(7, .ibmWatson),
(8, .tinyChat),
(9, .openWebUI)
]
// Note: Actual implementation would use NSEvent.addLocalMonitorForEvents
// This is a placeholder for the concept
print("⌨️ Keyboard shortcuts registered: ⌘1-⌘9 for backend switching")
}
}
#endif