iOS & macOS Quickstart
This guide shows how to add the Swift AI SDK to an iOS or macOS app, call models, and stream results into your UI.
1) Install via Swift Package Manager
Section titled “1) Install via Swift Package Manager”In Xcode: File → Add Package Dependencies…
- Package URL: https://github.com/teunlao/swift-ai-sdk
- Add products:
SwiftAISDK,OpenAIProvider(and other providers as needed)
2) Configure API Keys
Section titled “2) Configure API Keys”Set environment variables in your scheme or via a secure configuration:
OPENAI_API_KEY=sk-...The default provider shortcuts (e.g., openai) read standard env vars automatically.
3) Minimal call (blocking)
Section titled “3) Minimal call (blocking)”import SwiftAISDKimport OpenAIProvider
let result = try await generateText( model: openai("gpt-4o"), prompt: "Hello from Swift!")print(result.text)4) Streaming in SwiftUI
Section titled “4) Streaming in SwiftUI”import SwiftUIimport SwiftAISDKimport OpenAIProvider
@MainActorfinal class ChatViewModel: ObservableObject { @Published var output: String = "" @Published var isLoading = false
func send(_ prompt: String) { isLoading = true output = "" Task { do { let stream = try streamText( model: openai("gpt-4o"), prompt: prompt ) for try await delta in stream.textStream { output += delta } } catch { output = "Error: \(error)" } isLoading = false } }}
struct ChatView: View { @StateObject var vm = ChatViewModel() @State var input = "Write a haiku about vectors"
var body: some View { VStack(alignment: .leading) { TextEditor(text: $input).frame(height: 120) Button(vm.isLoading ? "Streaming…" : "Send") { vm.send(input) } ScrollView { Text(vm.output).monospaced() } } .padding() }}5) Tools (optional)
Section titled “5) Tools (optional)”struct EchoPayload: Codable, Sendable { let message: String}
let echo = tool( description: "Echo back the input data", inputSchema: EchoPayload.self) { payload, _ in EchoPayload(message: payload.message.uppercased())}
let result = try await generateText( model: openai("gpt-4o"), tools: ["echo": echo.eraseToTool()], prompt: "Call echo with {\"message\":\"Hello!\"}")Keep long‑running work off the main actor; UI updates should be marshalled on the main thread.