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

完整程式碼

以下範例顯示這兩項要求的完整程式碼。從應用程式的 @main 非同步進入點呼叫 try await sample(projectId: "PROJECT_ID"),並將 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)
    }
  }
}

後續步驟