Vertex AI で Gemini API を使用してテキストを生成する

このドキュメントでは、Swift 用の Google Cloud クライアント ライブラリを使用して、Vertex AI の Gemini API にテキスト リクエストとマルチモーダル リクエストを送信し、レスポンスを読み取る方法について説明します。

始める前に

このドキュメントの手順を完了するには、課金が有効で、Vertex AI API が有効になっている Google Cloud プロジェクトが必要です。Vertex AI モデルを使用すると料金が発生します。詳細については、Vertex AI の料金をご覧ください。

  1. Vertex AI 設定ガイドに沿ってプロジェクトを設定し、Vertex AI API を有効にします。
  2. クイックスタート: Swift を使ってみるに沿って、Swift クライアント ライブラリを設定します。
  3. プリンシパルに Vertex AI ユーザー Identity and Access Management(IAM)ロール(roles/aiplatform.user)または aiplatform.endpoints.predict 権限があることを確認します。

Vertex AI クライアント ライブラリを追加する

swift-google-cloud-aiplatform-v1 パッケージとその GoogleCloudAIPlatformV1 モジュールをプロジェクトに追加する手順は次のとおりです。

  1. swift-google-cloud-aiplatform-v1 パッケージを Package.swift 依存関係に追加します。

    swift package add-dependency \
        https://github.com/googleapis/swift-google-cloud-aiplatform-v1.git --from 0.6.0
    
  2. GoogleCloudAIPlatformV1 モジュールをターゲットの依存関係として追加します。

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

    TARGET_NAME は、ターゲットの名前に置き換えます。

テキスト プロンプトを送信する

Vertex AI の Gemini API にテキスト プロンプトを送信し、生成されたテキスト レスポンスを読み取る手順は次のとおりです。

  1. クライアント ライブラリを使用するために必要なインポートを追加します。

    import Foundation
    import GoogleCloudAIPlatformV1

  2. プロジェクト ID をパラメータとして受け取る関数を定義します。

    func sample(projectId: String) async throws {

  3. デフォルト設定を使用して PredictionServiceClient インスタンスを初期化します。

    let client = try PredictionServiceClient()

  4. モデルリソース名を作成します。

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

  5. GenerateContentRequest オブジェクトを作成し、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. promptFeedback で安全ブロックを確認し、最初の候補レスポンスから生成されたテキストを抽出します。

    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)
      }
    }

プロンプトと画像を送信する

前のセクションと同じ Foundation と GoogleCloudAIPlatformV1 のインポート、sample(projectId:) 関数シグネチャを使用します。Cloud Storage の画像 URI とテキスト プロンプトを含むマルチモーダル リクエストを送信する手順は次のとおりです。

  1. PredictionServiceClient インスタンスを初期化します。

    let client = try PredictionServiceClient()

  2. モデルリソース名を作成します。

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

  3. Cloud Storage URI と MIME タイプを使用して画像 Part オブジェクトをビルドします。

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

  4. プロンプト テキストの Part オブジェクトを作成します。

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

  5. generateContent(request:) を使用してマルチモーダル GenerateContentRequest オブジェクトを送信します。

    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. promptFeedback で安全ブロックを確認し、最初の候補レスポンスから生成されたテキストを抽出します。

    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)
      }
    }

コードを補完する

次の例は、両方のリクエストの完全なコードを示しています。try await sample(projectId: "PROJECT_ID") をアプリの @main 非同期エントリ ポイントから呼び出し、PROJECT_ID を Google Cloud プロジェクト ID に置き換えます。次に、swift run を実行して、次のような出力を表示します。

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

テキスト プロンプト

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)
    }
  }
}

プロンプトと画像

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)
    }
  }
}

次のステップ