Generate text using the Gemini API in Vertex AI

This document shows you how to use the Google Cloud client libraries for Swift to send text and multimodal requests to the Gemini API in Vertex AI and read the responses.

Before you begin

To complete the steps in this document, you need a Google Cloud project with billing enabled and the Vertex AI API enabled. Using Vertex AI models incurs charges; see Vertex AI pricing for details.

  1. Set up your project and enable the Vertex AI API by following the Vertex AI setup guide.
  2. Set up the Swift client libraries by following Quickstart: Get started with Swift.
  3. Verify that your principal has the Vertex AI User Identity and Access Management (IAM) role (roles/aiplatform.user) or aiplatform.endpoints.predict permission.

Add the Vertex AI client library

To add the swift-google-cloud-aiplatform-v1 package and its GoogleCloudAIPlatformV1 module to your project, follow these steps:

  1. Add the swift-google-cloud-aiplatform-v1 package to your Package.swift dependencies:

    swift package add-dependency \
        https://github.com/googleapis/swift-google-cloud-aiplatform-v1.git --from 0.6.0
    
  2. Add the GoogleCloudAIPlatformV1 module as a dependency of your target:

    swift package add-target-dependency \
        GoogleCloudAIPlatformV1 TARGET_NAME \
        --package swift-google-cloud-aiplatform-v1
    

    Replace TARGET_NAME with the name of your target.

Send a text prompt

To send a text prompt to the Gemini API in Vertex AI and read the generated text response, follow these steps:

  1. Add the imports needed to use the client library:

    import Foundation
    import GoogleCloudAIPlatformV1

  2. Define a function that accepts the project ID as a parameter:

    func sample(projectId: String) async throws {

  3. Initialize a PredictionServiceClient instance using the default settings:

    let client = try PredictionServiceClient()

  4. Construct the model resource name:

    let model = "projects/\(projectId)/locations/global/publishers/google/models/gemini-3.8-flash"

  5. Build a GenerateContentRequest object and call generateContent(request:):

    let request = GenerateContentRequest().with {
      $0.model = model
      $0.contents = [
        Content().with { content in
          content.role = "user"
          content.parts = [
            Part().with { part in
              part.data = .text(
                "What's a good name for a flower shop that specializes in selling bouquets of dried flowers?"
              )
            }
          ]
        }
      ]
    }
    let response = try await client.generateContent(request: request)

  6. Check promptFeedback for safety blocks and extract the generated text from the first candidate response:

    if let feedback = response.promptFeedback, feedback.blockReason != .unspecified {
      print("Prompt was blocked: \(feedback.blockReason)")
      if !feedback.blockReasonMessage.isEmpty {
        print("Reason: \(feedback.blockReasonMessage)")
      }
      return
    }
    
    guard let candidate = response.candidates.first,
      let content = candidate.content
    else {
      print("No candidate content returned.")
      return
    }
    
    for part in content.parts {
      if case .text(let text)? = part.data {
        print(text)
      }
    }

Send a prompt and an image

Use the same Foundation and GoogleCloudAIPlatformV1 imports and sample(projectId:) function signature as the previous section. Follow these steps to send a multimodal request with a Cloud Storage image URI and a text prompt:

  1. Initialize a PredictionServiceClient instance:

    let client = try PredictionServiceClient()

  2. Construct the model resource name:

    let model = "projects/\(projectId)/locations/global/publishers/google/models/gemini-3.8-flash"

  3. Build the image Part object with the Cloud Storage URI and MIME type:

    let imagePart = Part().with {
      $0.data = .fileData(
        FileData().with { fileData in
          fileData.mimeType = "image/jpeg"
          fileData.fileUri = "gs://generativeai-downloads/images/scones.jpg"
        }
      )
    }

  4. Build the prompt text Part object:

    let textPart = Part().with {
      $0.data = .text("Describe this picture.")
    }

  5. Send the multimodal GenerateContentRequest object using generateContent(request:):

    let request = GenerateContentRequest().with {
      $0.model = model
      $0.contents = [
        Content().with { content in
          content.role = "user"
          content.parts = [imagePart, textPart]
        }
      ]
    }
    let response = try await client.generateContent(request: request)

  6. Check promptFeedback for safety blocks and extract the generated text from the first candidate response:

    if let feedback = response.promptFeedback, feedback.blockReason != .unspecified {
      print("Prompt was blocked: \(feedback.blockReason)")
      if !feedback.blockReasonMessage.isEmpty {
        print("Reason: \(feedback.blockReasonMessage)")
      }
      return
    }
    
    guard let candidate = response.candidates.first,
      let content = candidate.content
    else {
      print("No candidate content returned.")
      return
    }
    
    for part in content.parts {
      if case .text(let text)? = part.data {
        print(text)
      }
    }

Complete code

The following examples show the complete code for both requests. Call try await sample(projectId: "PROJECT_ID") from your app's @main async entry point, replacing PROJECT_ID with your Google Cloud project ID. Then run swift run to print output similar to the following:

The image shows scones with blueberries and flowers next to cups of coffee.

Text prompt

import Foundation
import GoogleCloudAIPlatformV1

func sample(projectId: String) async throws {
  let client = try PredictionServiceClient()

  let model = "projects/\(projectId)/locations/global/publishers/google/models/gemini-3.8-flash"

  let request = GenerateContentRequest().with {
    $0.model = model
    $0.contents = [
      Content().with { content in
        content.role = "user"
        content.parts = [
          Part().with { part in
            part.data = .text(
              "What's a good name for a flower shop that specializes in selling bouquets of dried flowers?"
            )
          }
        ]
      }
    ]
  }
  let response = try await client.generateContent(request: request)
  if let feedback = response.promptFeedback, feedback.blockReason != .unspecified {
    print("Prompt was blocked: \(feedback.blockReason)")
    if !feedback.blockReasonMessage.isEmpty {
      print("Reason: \(feedback.blockReasonMessage)")
    }
    return
  }

  guard let candidate = response.candidates.first,
    let content = candidate.content
  else {
    print("No candidate content returned.")
    return
  }

  for part in content.parts {
    if case .text(let text)? = part.data {
      print(text)
    }
  }
}

Prompt and image

import Foundation
import GoogleCloudAIPlatformV1

func sample(projectId: String) async throws {
  let client = try PredictionServiceClient()

  let model = "projects/\(projectId)/locations/global/publishers/google/models/gemini-3.8-flash"

  let imagePart = Part().with {
    $0.data = .fileData(
      FileData().with { fileData in
        fileData.mimeType = "image/jpeg"
        fileData.fileUri = "gs://generativeai-downloads/images/scones.jpg"
      }
    )
  }

  let textPart = Part().with {
    $0.data = .text("Describe this picture.")
  }

  let request = GenerateContentRequest().with {
    $0.model = model
    $0.contents = [
      Content().with { content in
        content.role = "user"
        content.parts = [imagePart, textPart]
      }
    ]
  }
  let response = try await client.generateContent(request: request)
  if let feedback = response.promptFeedback, feedback.blockReason != .unspecified {
    print("Prompt was blocked: \(feedback.blockReason)")
    if !feedback.blockReasonMessage.isEmpty {
      print("Reason: \(feedback.blockReasonMessage)")
    }
    return
  }

  guard let candidate = response.candidates.first,
    let content = candidate.content
  else {
    print("No candidate content returned.")
    return
  }

  for part in content.parts {
    if case .text(let text)? = part.data {
      print(text)
    }
  }
}

What's next