This directory contains example code demonstrating how to use SwiftAIAgentCore in your iOS/macOS applications.
-
API Keys: You'll need API keys from OpenAI and/or Anthropic:
- OpenAI: https://platform.openai.com/api-keys
- Anthropic: https://console.anthropic.com/
-
Set Environment Variables:
export OPENAI_API_KEY="your-openai-key" export ANTHROPIC_API_KEY="your-anthropic-key"
The BasicExample.swift demonstrates:
- Creating an AI agent
- Sending simple messages
- Streaming responses in real-time
- Multi-turn conversations
To run:
swift run BasicExampleThe AdvancedExample.swift shows:
- Custom configuration with retry policies
- Token estimation and validation
- Comprehensive error handling
- Using multiple AI providers
- Conversation management with truncation
Add SwiftAIAgentCore to your Xcode project via Swift Package Manager:
https://github.com/VDurocher/Swift-AI-Agent-Core
import SwiftAIAgentCore
// Create an agent
let agent = try AIAgentImplementation.gpt4(apiKey: apiKey)
// Send a message
let response = try await agent.send(message: "Hello!")
// Stream a response
for try await chunk in agent.stream(message: "Tell me a story") {
print(chunk, terminator: "")
}import SwiftUI
import SwiftAIAgentCore
struct ChatView: View {
@State private var messages: [AIMessage] = []
@State private var input = ""
@State private var isLoading = false
let agent: AIAgent
var body: some View {
VStack {
ScrollView {
ForEach(messages) { message in
MessageRow(message: message)
}
}
HStack {
TextField("Message", text: $input)
Button("Send") {
Task { await sendMessage() }
}
.disabled(isLoading)
}
}
}
func sendMessage() async {
guard !input.isEmpty else { return }
let userMessage = AIMessage.user(input)
messages.append(userMessage)
input = ""
isLoading = true
do {
let response = try await agent.send(messages: messages)
messages.append(response)
} catch {
print("Error: \(error)")
}
isLoading = false
}
}-
API Key Security: Never hardcode API keys. Use environment variables or secure storage.
-
Error Handling: Always wrap AI calls in do-catch blocks and handle specific error types.
-
Token Management: Use
TokenEstimatorto validate message size before sending. -
Retry Logic: Configure appropriate retry policies based on your use case.
-
Streaming: Use streaming for long responses to improve perceived performance.
-
Conversation Context: Truncate old messages when approaching token limits.
- Verify your API key is correct and active
- Check that you're using the right key for the right provider
- Implement exponential backoff (already built into the library)
- Consider using aggressive retry policy
- Monitor your API usage
- Use
TokenEstimator.validate()before sending - Truncate conversations with
TokenEstimator.truncate() - Reduce
maxResponseTokensin configuration