Text mit der Gemini API in Vertex AI generieren

In diesem Dokument erfahren Sie, wie Sie die Clientbibliotheken von Google Cloud für Swift verwenden, um Text- und multimodale Anfragen an die Gemini API in Vertex AI zu senden und die Antworten zu lesen.

Hinweis

Zum Ausführen der Schritte in diesem Dokument benötigen Sie ein Google Cloud -Projekt mit aktivierter Abrechnung und aktivierter Vertex AI API. Für die Verwendung von Vertex AI-Modellen fallen Gebühren an. Weitere Informationen finden Sie unter Vertex AI-Preise.

  1. Richten Sie Ihr Projekt ein und aktivieren Sie die Vertex AI API. Folgen Sie dazu der Anleitung zur Einrichtung von Vertex AI.
  2. Richten Sie die Swift-Clientbibliotheken ein, indem Sie der Kurzanleitung: Erste Schritte mit Swift folgen.
  3. Prüfen Sie, ob Ihr Hauptkonto die IAM-Rolle (Identity and Access Management) „Vertex AI-Nutzer“ (roles/aiplatform.user) oder die Berechtigung aiplatform.endpoints.predict hat.

Vertex AI-Clientbibliothek hinzufügen

So fügen Sie Ihrem Projekt das Paket swift-google-cloud-aiplatform-v1 und das zugehörige Modul GoogleCloudAIPlatformV1 hinzu:

  1. Fügen Sie das Paket swift-google-cloud-aiplatform-v1 zu Ihren Package.swift-Abhängigkeiten hinzu:

    swift package add-dependency \
        https://github.com/googleapis/swift-google-cloud-aiplatform-v1.git --from 0.6.0
    
  2. Fügen Sie das GoogleCloudAIPlatformV1-Modul als Abhängigkeit Ihres Ziels hinzu:

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

    Ersetzen Sie TARGET_NAME durch den Namen Ihres Ziels.

Text-Prompt senden

So senden Sie einen Text-Prompt an die Gemini API in Vertex AI und lesen die generierte Textantwort:

  1. Fügen Sie die Importe hinzu, die für die Verwendung der Clientbibliothek erforderlich sind:

    import Foundation
    import GoogleCloudAIPlatformV1

  2. Definieren Sie eine Funktion, die die Projekt-ID als Parameter akzeptiert:

    func sample(projectId: String) async throws {

  3. Initialisieren Sie eine PredictionServiceClient-Instanz mit den Standardeinstellungen:

    let client = try PredictionServiceClient()

  4. Erstellen Sie den Namen der Modellressource:

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

  5. Erstellen Sie ein GenerateContentRequest-Objekt und rufen Sie generateContent(request:) auf:

    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. Prüfen Sie promptFeedback auf Sicherheitsblöcke und extrahieren Sie den generierten Text aus der ersten Kandidatenantwort:

    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 und Bild senden

Verwenden Sie dieselben Foundation- und GoogleCloudAIPlatformV1-Importe und die sample(projectId:)-Funktionssignatur wie im vorherigen Abschnitt. So senden Sie eine multimodale Anfrage mit einem Cloud Storage-Bild-URI und einem Text-Prompt:

  1. Initialisieren Sie eine PredictionServiceClient-Instanz:

    let client = try PredictionServiceClient()

  2. Erstellen Sie den Namen der Modellressource:

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

  3. Erstellen Sie das Bildobjekt Part mit dem Cloud Storage-URI und dem MIME-Typ:

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

  4. Erstellen Sie das Prompt-Textobjekt Part:

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

  5. Senden Sie das multimodale GenerateContentRequest-Objekt mit 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. Prüfen Sie promptFeedback auf Sicherheitsblöcke und extrahieren Sie den generierten Text aus der ersten Kandidatenantwort:

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

Vollständiger Code

Die folgenden Beispiele zeigen den vollständigen Code für beide Anfragen. Rufen Sie try await sample(projectId: "PROJECT_ID") über den asynchronen Einstiegspunkt @main Ihrer Anwendung auf und ersetzen Sie PROJECT_ID durch Ihre Projekt-ID in Google Cloud . Führen Sie dann swift run aus, um eine Ausgabe wie die folgende zu erhalten:

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 und Bild

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

Nächste Schritte