יצירת טקסט באמצעות Gemini API ב-Vertex AI

במסמך הזה מוסבר איך להשתמש בספריות הלקוח של Google Cloud ל-Swift כדי לשלוח בקשות טקסט ובקשות מולטימודאליות ל-Gemini API ב-Vertex AI ולקרוא את התשובות.

לפני שמתחילים

כדי לבצע את השלבים שבמסמך הזה, צריך Google Cloud פרויקט שמופעלים בו החיוב ו-Vertex AI API. השימוש במודלים של Vertex AI כרוך בחיובים. פרטים נוספים זמינים במאמר התמחור של Vertex AI.

  1. מגדירים את הפרויקט ומפעילים את Vertex AI API לפי המדריך להגדרת Vertex AI.
  2. מגדירים את ספריות הלקוח של Swift לפי ההוראות במאמר מדריך למתחילים: תחילת העבודה עם Swift.
  3. מוודאים שלחשבון המשתמש יש את התפקיד "משתמש ב-Vertex AI" (roles/aiplatform.user) או את ההרשאה aiplatform.endpoints.predict בניהול הזהויות והרשאות הגישה (IAM).

הוספה של ספריית הלקוח של 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 בשם היעד.

שליחת פרומפט טקסטואלי

כדי לשלוח פרומפט טקסטואלי ל-Gemini API ב-Vertex AI ולקרוא את טקסט דינמי מבוסס-AI שנוצר, בצעו את השלבים הבאים:

  1. מוסיפים את הייבוא שנדרש כדי להשתמש בספריית הלקוח:

    import Foundation
    import GoogleCloudAIPlatformV1

  2. מגדירים פונקציה שמקבלת את מזהה הפרויקט כפרמטר:

    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 ומחלצים את טקסט דינמי מבוסס-AI מהתשובה הראשונה:

    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:) כמו בקטע הקודם. כדי לשלוח בקשה מולטי-מודאלית עם URI של תמונה ב-Cloud Storage והנחיית טקסט:

  1. מפעילים מכונה של PredictionServiceClient:

    let client = try PredictionServiceClient()

  2. יוצרים את שם המשאב של המודל:

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

  3. יוצרים את האובייקט Part של התמונה באמצעות ה-URI של Cloud Storage וסוג ה-MIME:

    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. שולחים את האובייקט המולטי-מודאלי GenerateContentRequest באמצעות 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. בודקים אם יש חסימות בטיחות ב-promptFeedback ומחלצים את טקסט דינמי מבוסס-AI מהתשובה הראשונה:

    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 . לאחר מכן מריצים את הפקודה 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)
    }
  }
}

המאמרים הבאים