在 Vertex AI 中使用 Gemini API 生成文本

本文档介绍了如何使用 Google Cloud Swift 客户端库向 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 User 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)
    }
  }
}

后续步骤