Getting Started with FreeToken Swift

FreeToken is a powerful Swift client that enables you to integrate AI capabilities directly into your iOS and macOS applications. It supports both local and cloud-based AI processing, document management, and tool integration.

Installation

Add FreeToken to your project using Swift Package Manager:

dependencies: [
    .package(url: "https://github.com/FreeToken/FreeTokenSwift.git", from: "1.0.0")
]

Quick Start

1. Configure the Client

import FreeToken

// Configure with your API token
let client = FreeToken.shared.configure(
    appToken: "your-api-token-here",
    baseURL: URL(string: "https://api.freetoken.ai/api/v1/"), // Optional
    logLevel: .info
)

2. Register Your Device

Before using AI features, register your device with a scope:

await client.registerDeviceSession(scope: "my-app-v1") {
    print("Device registered successfully!")
    // Device is ready for AI operations
} error: { error in
    print("Failed to register device: \(error.localizedDescription)")
}

3. Download AI Model (Optional for Local AI)

If you want to use local AI processing:

await client.downloadAIModel { state in
    switch state {
    case .downloaded:
        print("AI model ready for local processing")
    case .aiNotSupported:
        print("Device doesn't support local AI - will use cloud")
    case .cloudOnly:
        print("Model is cloud-only")
    }
} error: { error in
    print("Failed to download model: \(error.localizedDescription)")
}

4. Create Your First Message Thread

// Create a message thread for conversation
await client.createMessageThread { messageThread in
    print("Created message thread: \(messageThread.id)")
    
    // Add a user message
    let userMessage = Message(role: .user, content: "Hello! Can you help me understand Swift closures?")
    
    await client.addMessageToThread(id: messageThread.id, message: userMessage) { message in
        print("Message added: \(message.content)")
        
        // Run the thread through AI
        await client.runMessageThread(id: messageThread.id) { response in
            print("AI Response: \(response.content)")
        } error: { error in
            print("AI processing failed: \(error.localizedDescription)")
        }
    } error: { error in
        print("Failed to add message: \(error.localizedDescription)")
    }
} error: { error in
    print("Failed to create thread: \(error.localizedDescription)")
}

5. Quick AI Completion

For simple text completions without conversation history:

await client.generateCompletion(prompt: "Explain what a supernova is in simple terms") { completion in
    print("AI Response: \(completion.response)")
} error: { error in
    print("Completion failed: \(error.localizedDescription)")
}

Key Concepts

Message Threads

  • Purpose: Maintain conversation context across multiple AI interactions
  • Persistence: Stored in FreeToken cloud, accessible across app sessions
  • Context: Automatically manages context window and message history

Local vs Cloud Processing

  • Automatic: FreeToken automatically chooses the best processing location
  • Local: Faster, private, works offline (requires model download)
  • Cloud: Access to larger models, always available

Document Store

  • RAG Support: Store documents for AI to reference during conversations
  • Search: Vector-based semantic search across your documents
  • Privacy: Optional private document stores with encryption

Tools

  • Built-in: Web search, document search, and other pre-configured tools
  • Custom: Define your own tools for the AI to call
  • Control: Fine-grained control over which tools are available per conversation

Error Handling

Always handle errors appropriately in your async operations:

do {
    let message = try await client.localChat(
        messages: [Message(role: .user, content: "Hello AI!")],
        uniqueID: "chat-session-1"
    )
    print("Response: \(message.content)")
} catch {
    if let freeTokenError = error as? FreeToken.FreeTokenError {
        switch freeTokenError {
        case .deviceNotRegistered:
            print("Device needs to be registered first")
        case .aiModelNotDownloaded:
            print("AI model needs to be downloaded")
        default:
            print("FreeToken error: \(freeTokenError.localizedDescription)")
        }
    }
}

Next Steps

Best Practices

  1. Always register your device before making AI calls
  2. Handle errors gracefully - network and AI operations can fail
  3. Use message threads for conversational AI experiences
  4. Download models in background to avoid blocking the UI
  5. Implement proper logging to debug issues in development