PaLM API: Text Quickstart with Swift

Overview

This quickstart demonstrates how to use the PaLM API, which gives you access to Google's latest large language models, with the Swift SDK. It uses the text service of the PaLM API which is a model variation built for text generation use cases such as summarizing texts, drafting outlines, or writing entire texts.

Prerequisites

The latest version of Xcode running on MacOS.1

Setup

Install the API client

The following instructions will guide you through downloading and installing the PaLM Swift SDK, which also includes the sample app you will be using in this tutorial.

git clone https://github.com/google/generative-ai-swift

Obtain an API key

Follow the instructions on the setup page to create an API key for your app. You will need this API key in the next step.

Try out the sample application (Optional)

Navigate into the Examples folder in your cloned generative-ai-swift directory and open the PaLMText app in Xcode.

cd generative-ai-swift/Examples/PaLMChat
xed .
  1. While in Xcode, press CMD+B to build the app. When building the app for the first time the build script will generate a new file PaLM-Info.plist
  2. In Xcode, open PaLM-Info.plist and paste your API key into the API_KEY setting

    Add API key

  3. Press CMD+R to run the app. The phone simulator will launch and show a simple UI with a text input field, a button, and a text output area. Enter a couple of paragraphs of text into the input field and tap the Summarize button to summarize the text you entered. You can also paste a URL to an article to have the model summarize the article.

Use the SDK in your app

Add the SDK package to your project

To use the PaLM API in your own app, add the GoogleGenerativeAI package to your app:

  1. Create a new Swift app.
  2. Right-click on your project in the project navigator.
  3. Select Add Packages from the context menu.
  4. In the Add Packages dialog, paste the package URL into the search bar: https://github.com/google/generative-ai-swift
  5. Click on Add Package. Xcode will now download and add the GoogleGenerativeAI to your project.

Initialize the API client

Before you can make any API calls, you need to import and initialize the API client.

  1. Import the GoogleGenerativeAI module:

    import GoogleGenerativeAI
    
  2. Initialize the API client:

    let palmClient = GenerativeLanguage(apiKey: "YOUR API KEY")
    

Call the Text service

Now you're ready to call the PaLM API's text service. Call the generateText method with a prompt to get a response from the model. See the Intro to LLMs guide to learn more about prompting.

let prompt = "Write a story about a magic backpack."
let response = try? await palmClient.generateText(with: prompt)
if let candidate = response?.candidates?.first, let text = candidate.output {
  print(text)
}

  1. Xcode and MacOS is a trademark of Apple Inc., registered in the U.S. and other countries and regions.