-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdvancedExample.swift
More file actions
168 lines (133 loc) · 5.53 KB
/
Copy pathAdvancedExample.swift
File metadata and controls
168 lines (133 loc) · 5.53 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
import Foundation
import SwiftAIAgentCore
/// Advanced example demonstrating production-grade features
///
/// This example shows:
/// - Custom configuration with retry policies
/// - Token estimation and validation
/// - Error handling and recovery
/// - Multiple AI providers (OpenAI and Anthropic)
/// - Conversation management
struct AdvancedExample {
// MARK: - Custom Configuration
static func customConfigurationExample() async throws {
print("⚙️ Example: Custom Configuration\n")
let config = AIConfiguration(
model: .gpt4Turbo,
apiKey: "your-api-key",
temperature: 0.5, // More deterministic
maxResponseTokens: 500,
timeout: 60,
retryPolicy: .aggressive // More aggressive retry
)
let agent = try AIAgentImplementation(configuration: config)
print("✅ Agent configured with custom settings")
print(" Model: \(config.model.name)")
print(" Temperature: \(config.temperature)")
print(" Max tokens: \(config.maxResponseTokens)\n")
}
// MARK: - Token Management
static func tokenManagementExample() async throws {
print("🎫 Example: Token Management\n")
let messages = [
AIMessage.system("You are a helpful assistant."),
AIMessage.user("Explain quantum computing.")
]
// Estimate tokens before sending
let estimatedTokens = TokenEstimator.estimate(messages: messages)
print("Estimated tokens: \(estimatedTokens)")
// Check if it fits within limits
let fitsInGPT35 = TokenEstimator.fitsWithin(messages: messages, limit: 4000)
print("Fits in GPT-3.5 context: \(fitsInGPT35)")
// Validate against model
do {
try TokenEstimator.validate(
messages: messages,
model: .gpt4,
maxResponseTokens: 1000
)
print("✅ Messages validated successfully\n")
} catch {
print("❌ Token validation failed: \(error)\n")
}
}
// MARK: - Error Handling
static func errorHandlingExample() async throws {
print("🛡️ Example: Error Handling\n")
let agent = try AIAgentImplementation.gpt4(apiKey: "invalid-key")
do {
_ = try await agent.send(message: "Hello")
} catch let error as AIError {
switch error {
case .invalidAPIKey:
print("❌ API key is invalid")
case .rateLimit(let retryAfter):
if let retry = retryAfter {
print("⏳ Rate limited. Retry after \(retry) seconds")
}
case .networkError(let underlying):
print("🌐 Network error: \(underlying)")
case .tokenLimitExceeded(let current, let max):
print("📊 Token limit exceeded: \(current)/\(max)")
default:
print("❌ Error: \(error.errorDescription ?? "Unknown")")
}
// Check if error is recoverable
if error.isRecoverable {
print("♻️ This error can be retried\n")
} else {
print("🚫 This error cannot be retried\n")
}
}
}
// MARK: - Multiple Providers
static func multipleProvidersExample() async throws {
print("🔄 Example: Multiple AI Providers\n")
// OpenAI Agent
let gptAgent = try AIAgentImplementation.gpt4(
apiKey: ProcessInfo.processInfo.environment["OPENAI_API_KEY"] ?? ""
)
// Anthropic Agent
let claudeAgent = try AIAgentImplementation.claude3Sonnet(
apiKey: ProcessInfo.processInfo.environment["ANTHROPIC_API_KEY"] ?? ""
)
let prompt = "What is Swift in one sentence?"
// Query both
async let gptResponse = gptAgent.send(message: prompt)
async let claudeResponse = claudeAgent.send(message: prompt)
print("GPT-4: \(try await gptResponse)")
print("Claude: \(try await claudeResponse)\n")
}
// MARK: - Conversation Management
static func conversationManagementExample() async throws {
print("💬 Example: Conversation Management\n")
let agent = try AIAgentImplementation.gpt4(apiKey: "your-api-key")
var conversation: [AIMessage] = [
.system("You are a Swift expert. Keep responses concise.")
]
// Helper to add messages and get responses
func chat(_ userMessage: String) async throws -> String {
conversation.append(.user(userMessage))
// Check token count before sending
let tokens = TokenEstimator.estimate(messages: conversation)
print("Current tokens: \(tokens)")
// Truncate if needed
if tokens > 3000 {
conversation = TokenEstimator.truncate(
messages: conversation,
limit: 2000,
keepSystemMessages: true
)
print("⚠️ Truncated conversation to fit limits")
}
let response = try await agent.send(messages: conversation)
conversation.append(response)
return response.content
}
// Simulated multi-turn conversation
_ = try await chat("What is a protocol?")
_ = try await chat("Give me an example.")
_ = try await chat("How is it different from inheritance?")
print("Final conversation has \(conversation.count) messages\n")
}
}