I came across Tim's tweet about Google supporting Swift for their AI SDK.

I was unfamiliar with this SDK, so time for exploration and experimentation!

Adding Google AI SDK for Swift as a Dependency

The first step in getting started with this SDK is to add it as a dependency in Xcode. When managing via Swift Package Manager, add GoogleGenerativeAI as a dependency by adding it to the dependencies value of the Package.swift:

dependencies: [
 .package(url: “https://github.com/google/generative-ai-swift.git")
]

Configuring Google AI SDK with your API Key

Once we have added GoogleGenerativeAI as a dependency, we must configure it with your API Key. You can obtain a new API Key via Google AI Studio:

Simple Text Request

I have been playing around with GPT before for music recommendations so we will do a simple prompt to get songs similar to my all-time favorite song, Snuff by Slipknot.

Add the following code to import the package:

import GoogleGenerativeAI

Then, we use the Gemini Pro model to intialise an instance of a generative model with the API key:

let model = GenerativeModel(name: "gemini-pro", apiKey: "AIxxxxxdPFOd9x4O")
‼️ I am using the hard-coded key here for demonstration purposes. DO NOT use API key directly.

A simple prompt to get the response in JSON format:

let prompt = """
"Get me a song similar to Snuff by Slipknot. Provide the response as an array of JSON as { ["artist": "artistName", "song": "songName"] } only. Remove any backticks.
"""

Then, we use the GenerativeModel.generateContent(_:) method with the prompt and get the text out of the response:

struct GenerativeSongModel: Hashable, Codable {
  var artist: String
  var song: String
}

let response = try await model.generateContent(prompt)

if let text = response.text, let data = text.data(using: .utf8) {
  let models = try JSONDecoder().decode([GenerativeSongModel].self, from: data)
  self.models = models
}

Using it with SwiftUI

Here is a simple view to show the data that we got from the model:

struct ContentView: View {
  @State private var models: [GenerativeSongModel] = []

  var body: some View {
    NavigationStack {
      List {
        if models.isEmpty {
          ProgressView()
        } else {
          ForEach(models, id: \.self) { model in
            VStack(alignment: .leading) {
              Text(model.song).bold()
              Text(model.artist)
            }
          }
        }
      }
      .navigationTitle("Google AI SDK Example")
    }
    .task {
      await getSong()
    }
  }
}

And that's it! We have learned how to use the Google AI SDK for Swift with the new Gemini Pro model. The next few posts will discuss multi-turn conversations, image input and advanced configurations.

String Catalog

String Catalog - App Localization on Autopilot

Push to GitHub, and we'll automatically localize your app for 40+ languages, saving you hours of manual work.

Tagged in:

AI