Google AI SDK for Swift
The Google AI Swift SDK offers a straightforward solution for Swift developers who want to use the Gemini API. The Gemini API provides access to Gemini models, created by Google DeepMind, designed to be multimodal, enabling seamless analysis across text, images, and code.
Getting Started with the Gemini API
To begin using the Gemini API, follow these steps:
- Visit Google AI Studio and log in with your Google account.
- Create an API key, keeping in mind that the free tier may not be available in Europe.
- Clone the repository with the following command:
git clone https://github.com/google/generative-ai-swift
- Open and build the sample app located in the
Examples
folder of the cloned repository. - Run the app once to generate an empty
GenerativeAI-Info.plist
file. - Enter your API key in the
API_KEY
field within theGenerativeAI-Info.plist
file. - Run the app to start working with the SDK.
For more detailed instructions, refer to the Swift SDK tutorial available on ai.google.dev.
Usage Example
-
Incorporate the
generative-ai-swift
into your Xcode project using the Swift Package Manager. -
Import the module:
import GoogleGenerativeAI
-
Initialize the model:
let model = GenerativeModel(name: "gemini-1.5-flash-latest", apiKey: "YOUR_API_KEY")
-
Run a prompt:
let cookieImage = UIImage(...) let prompt = "Do these look store-bought or homemade?" let response = try await model.generateContent(prompt, cookieImage)
Refer to the quickstart for additional examples and features like streaming, token counting, and response control.
Logging
To enable extra logging details in the Xcode console, including cURL commands and raw stream responses, add -GoogleGenerativeAIDebugLogEnabled
as an argument in the Xcode scheme's launch configuration.
Command Line Tool
A command line tool is available to test Gemini model requests via Xcode or the command line:
- Open
Examples/GenerativeAICLI/Package.swift
. - Run it in Xcode and inspect the console for options.
- Adjust the scheme's launch arguments with the preferred options.
Documentation
Comprehensive documentation can be found in the Gemini API Cookbook or on ai.google.dev.
Contributing
For those interested in contributing to the Google AI SDK for Swift, view the Contributing Guide for detailed instructions.
Transition from PaLM SDK
The PaLM API has been decommissioned, so users need to transition to using the Gemini API. Update your application's generative-ai-swift
dependency to version 0.4.0
or higher. Further information about migrating from PaLM to Gemini is available in the migration guide.
Licensing
The project content is licensed under the Apache License, version 2.0.