·3 min read

Exploring Google AI SDK for Swift: Gemini AI Model for Text Only Input

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

Great to see ⁦@googledevs⁩ supporting #Swift for their new AI SDK. It’s a great language for AI research and development. https://t.co/JxBuYrAf5b

— Tim Sneath (@timsneath) December 14, 2023

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")](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:
 
```Swift
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.

 

Post Topics

Explore more in these categories:

Related Articles

Exploring Stream's Video SDK: Creating a WWDC Watch Party App

Build a WWDC 2024 Watch Party App using Stream's Video SDK. Implement video playback, calling features, and synchronize playback for seamless group viewing. Dive into Stream's powerful tools to create interactive experiences for Apple developers and elevate your WWDC experience.

Exploring Claude: 3.7 Sonnet iOS Development

Explore the capabilities of Claude 3.7 Sonnet in iOS development, featuring improved code refactoring, SwiftUI integration, and efficient file handling. Learn how this AI model streamlines development workflows and handles complex coding tasks with remarkable accuracy and speed.