אפשר להשתמש בה רק כשמשתמשים ב-Vertex AI Gemini API כספק ה-API. |
כשמתקשרים אל Vertex AI Gemini API מהאפליקציה באמצעות SDK של Firebase AI Logic, אפשר להנחות מודל Gemini ליצור טקסט על סמך קלט רב-אופני, כמו תמונות, קובצי PDF, סרטונים ואודיו.
כדי לכלול קבצים בבקשה, אפשר להשתמש בתג Cloud Storage for Firebase עבור החלקים שאינם טקסט בקלט (כמו קובצי מדיה). הנה כמה דברים שחשוב לדעת על התכונה הזו:
אפשר להשתמש ב-Cloud Storage for Firebase עם כל בקשה מרובת-אופנים (למשל, גם יצירת טקסט וגם צ'אט) אם משתמשים ב-Vertex AI Gemini API. בדוגמאות שבמדריך הזה מוצג קלט בסיסי של טקסט ותמונה.
בנתוני הקלט של הבקשה מציינים את סוג ה-MIME של הקובץ ואת כתובת ה-URL שלו Cloud Storage for Firebase (שמתחילה תמיד ב-
gs://
). הערכים האלה הם מטא-נתונים שמוקצים באופן אוטומטי לכל קובץ שמועלה לדלי Cloud Storage.צריך להשתמש בסוג קובץ וכתובת URL נתמכים.
במדריך הזה מוסבר איך להגדיר את Cloud Storage for Firebase, להעלות קובץ לדלי Cloud Storage for Firebase מהאפליקציה, ואז לכלול את סוג ה-MIME של הקובץ ואת כתובת ה-URL של Cloud Storage for Firebase בבקשה הרב-מודאלית אל Gemini API.
רוצה לראות את דוגמאות הקוד? או שכבר הגדרת את Cloud Storage for Firebase ואתה מוכן להתחיל להשתמש בו עם בקשות מולטימודאליות?
למה כדאי להשתמש ב-Cloud Storage for Firebase באפליקציה?
Cloud Storage for Firebase משתמש באותה תשתית מהירה, מאובטחת וניתנת להרחבה כמו Google Cloud Storage כדי לאחסן נתונים בינאריים גדולים (BLOB) וקבצים, וערכות ה-SDK ללקוח שלו מיועדות במיוחד לאפליקציות לנייד ולאינטרנט.
ב-SDK של Firebase AI Logic, גודל הבקשה המקסימלי הוא 20MB. אם הבקשה גדולה מדי, מתקבלת שגיאת HTTP 413. אם גודל הקובץ יגרום לגודל הבקשה הכולל לחרוג מ-20 MB, צריך להשתמש בכתובת URL של Cloud Storage for Firebase כדי לכלול את הקובץ בבקשה הרב-מודאלית. עם זאת, אם הקובץ קטן, אפשר לעיתים קרובות להעביר אותו ישירות כנתונים מוטמעים (שימו לב: קובץ שמועבר כנתונים מוטמעים מקודד ל-base64 במהלך ההעברה, מה שמגדיל את גודל הבקשה).
אלה כמה יתרונות נוספים של שימוש ב-Cloud Storage for Firebase:
משתמשי קצה יכולים להעלות תמונות ישירות מהאפליקציה שלכם ל-Cloud Storage for Firebase bucket, ואז אתם יכולים לכלול את התמונות האלה בהנחיות מרובות-אופנים פשוט על ידי ציון סוג ה-MIME של הקובץ וכתובת ה-URL של Cloud Storage for Firebase (שהיא מזהה של הקובץ).
אם אתם צריכים לספק תמונות למשתמשי הקצה, תוכלו לחסוך להם זמן ורוחב פס, במיוחד אם איכות הרשת שלהם נמוכה או לא יציבה.
- אם העלאה או הורדה של קובץ מופסקות, ערכות ה-SDK של Cloud Storage for Firebase מפעילות מחדש את הפעולה באופן אוטומטי מהמקום שבו היא הופסקה.
- אפשר להשתמש באותו קובץ שהועלה כמה פעמים בלי שמשתמש הקצה יצטרך להעלות את אותו קובץ בכל פעם שהוא נדרש באפליקציה (למשל בבקשה חדשה מרובת-אופנים).
אתם יכולים להגביל את הגישה של משתמשי קצה לקבצים שמאוחסנים ב-Cloud Storage for Firebase באמצעות Firebase Security Rules, שמאפשרים רק למשתמש מורשה להעלות, להוריד או למחוק קבצים.
אפשר לגשת לקבצים ב-bucket מ-Firebase או מ-Google Cloud, וכך ליהנות מגמישות בעיבוד בצד השרת, כמו סינון תמונות או המרת וידאו באמצעות ממשקי Google Cloud Storage API.
באילו סוגים של קבצים וכתובות URL יש תמיכה?
אלה הדרישות לקבצים ולכתובות URL כשרוצים להשתמש בכתובות URL של Cloud Storage for Firebase SDK Firebase AI Logic:
הקובץ צריך לעמוד בדרישות של קובצי קלט לבקשות מולטימודאליות. הדרישות האלה כוללות סוג MIME וגודל קובץ.
הקובץ צריך להיות מאוחסן בקטגוריה Cloud Storage for Firebase (כלומר, הקטגוריה נגישה לשירותי Firebase, כמו Firebase Security Rules). אם אתם יכולים לראות את הקטגוריה במסוף Firebase, זו קטגוריה Cloud Storage for Firebase.
קטגוריית Cloud Storage for Firebase צריכה להיות באותו פרויקט Firebase שבו רשמתם את האפליקציה.
כתובת ה-URL של Cloud Storage for Firebase חייבת להתחיל ב-
gs://
, שזו הדרך שבה בנויות כל כתובות ה-URL של Google Cloud Storage.כתובת ה-URL של הקובץ לא יכולה להיות כתובת URL של דפדפן (לדוגמה, כתובת ה-URL של תמונה שמצאתם באינטרנט).
בנוסף, Firebase Security Rules של הקטגוריה צריך לאפשר גישה מתאימה לקובץ. לדוגמה:
אם יש לכם כללים ציבוריים, כל משתמש או לקוח יכולים לגשת לקובץ.
אם יש לכם כללים חזקים (מומלץ מאוד), מערכת Firebase תבדוק שלמשתמש או ללקוח המחוברים יש גישה מספקת לקובץ לפני שהיא מאפשרת לבצע את השיחה עם כתובת ה-URL שסופקה.
שימוש בכתובות URL של Cloud Storage for Firebase עם Firebase AI Logic
אפשר להשתמש בה רק כשמשתמשים ב-Vertex AI Gemini API כספק ה-API. |
שלב 1: הגדרת Cloud Storage for Firebase
הוראות מפורטות להגדרת Cloud Storage for Firebase זמינות במדריך לתחילת העבודה: iOS+ | Android | אינטרנט | Flutter | Unity
אלה המשימות העיקריות שצריך לבצע:
יוצרים או מייבאים Cloud Storage for Firebase bucket בפרויקט Firebase.
החלת Firebase Security Rules על הקטגוריה הזו. Rules לעזור לכם לאבטח את הקבצים על ידי הגבלת הגישה למשתמשי קצה מורשים.
מוסיפים לאפליקציה את ספריית הלקוח של Cloud Storage for Firebase.
שימו לב שאפשר לדלג על המשימה הזו, אבל במקרה כזה תמיד צריך לכלול במפורש את סוג ה-MIME ואת ערכי כתובות ה-URL בבקשות.
שלב 2: העלאת קובץ למאגר
במסמכי התיעוד של Cloud Storage אפשר לקרוא על כל הדרכים השונות להעלאת קבצים לקטגוריה. לדוגמה, אפשר להעלות קבצים מקומיים מהמכשיר של משתמש הקצה, כמו תמונות וסרטונים מהמצלמה. מידע נוסף: iOS+ | Android | אינטרנט | Flutter | Unity
כשמעלים קובץ לקטגוריה, Cloud Storage מחיל אוטומטית את שני חלקי המידע הבאים על הקובץ. תצטרכו לכלול את הערכים האלה בבקשה (כמו שמוצג בשלב הבא במדריך הזה).
סוג MIME: זהו סוג המדיה של הקובץ (לדוגמה,
image/png
). המערכת תנסה לזהות באופן אוטומטי את סוג ה-MIME במהלך ההעלאה ותחיל את המטא-נתונים האלה על האובייקט בדלי. עם זאת, אפשר לציין את סוג ה-MIME במהלך ההעלאה.Cloud Storage for Firebase כתובת URL: מזהה ייחודי של הקובץ. כתובת ה-URL חייבת להתחיל ב-
gs://
.
שלב 3: כוללים את סוג ה-MIME וכתובת ה-URL של הקובץ בבקשה מולטימודלית
אחרי שמאחסנים קובץ בדלי, אפשר לכלול בבקשה את סוג ה-MIME וכתובת ה-URL שלו. שימו לב: הדוגמאות האלה מציגות בקשה שלא מועברת בסטרימינג, אבל אפשר להשתמש בכתובות URL גם עם סטרימינג וצ'אט.generateContent
כדי לכלול את הקובץ בבקשה, אפשר להשתמש באחת מהאפשרויות הבאות:
אפשרות 1: הוספת סוג ה-MIME וכתובת ה-URL באמצעות הפניה לאחסון
אפשרות 2: הוספה מפורשת של סוג ה-MIME וכתובת ה-URL
אפשרות 1: הוספת סוג ה-MIME וכתובת ה-URL באמצעות הפניה ל-Storage
לפני שמנסים את הדוגמה הזו, חשוב לוודא שסיימתם את המדריך לתחילת העבודה עם ערכות ה-SDK של Firebase AI Logic. |
משתמשים באפשרות הזו אם העליתם את הקובץ לקטגוריה ואתם רוצים לכלול אותו מיד (באמצעות הפניה ל-Storage) בבקשה. הקריאה מחייבת גם את סוג ה-MIME וגם את כתובת ה-URL של Cloud Storage for Firebase.
Swift
// Upload an image file using Cloud Storage for Firebase.
let storageRef = Storage.storage().reference(withPath: "images/image.jpg")
guard let imageURL = Bundle.main.url(forResource: "image", withExtension: "jpg") else {
fatalError("File 'image.jpg' not found in main bundle.")
}
let metadata = try await storageRef.putFileAsync(from: imageURL)
// Get the MIME type and Cloud Storage for Firebase URL.
guard let mimeType = metadata.contentType else {
fatalError("The MIME type of the uploaded image is nil.")
}
// Construct a URL in the required format.
let storageURL = "gs://\(storageRef.bucket)/\(storageRef.fullPath)"
let prompt = "What's in this picture?"
// Construct the imagePart with the MIME type and the URL.
let imagePart = FileDataPart(uri: storageURL, mimeType: mimeType)
// To generate text output, call generateContent with the prompt and the imagePart.
let result = try await model.generateContent(prompt, imagePart)
if let text = result.text {
print(text)
}
Kotlin
ב-Kotlin, המתודות ב-SDK הזה הן פונקציות השהיה וצריך להפעיל אותן מהיקף של Coroutine.// Upload an image file using Cloud Storage for Firebase.
val storageRef = Firebase.storage.reference.child("images/image.jpg")
val fileUri = Uri.fromFile(File("image.jpg"))
try {
val taskSnapshot = storageRef.putFile(fileUri).await()
// Get the MIME type and Cloud Storage for Firebase file path.
val mimeType = taskSnapshot.metadata?.contentType
val bucket = taskSnapshot.metadata?.bucket
val filePath = taskSnapshot.metadata?.path
if (mimeType != null && bucket != null) {
// Construct a URL in the required format.
val storageUrl = "gs://$bucket/$filePath"
// Construct a prompt that includes text, the MIME type, and the URL.
val prompt = content {
fileData(mimeType = mimeType, uri = storageUrl)
text("What's in this picture?")
}
// To generate text output, call generateContent with the prompt.
val response = generativeModel.generateContent(prompt)
println(response.text)
}
} catch (e: StorageException) {
// An error occurred while uploading the file.
} catch (e: GoogleGenerativeAIException) {
// An error occurred while generating text.
}
Java
ב-Java, השיטות ב-SDK הזה מחזירותListenableFuture
.
// Upload an image file using Cloud Storage for Firebase.
StorageReference storage = FirebaseStorage.getInstance().getReference("images/image.jpg");
Uri fileUri = Uri.fromFile(new File("images/image.jpg"));
storage.putFile(fileUri).addOnSuccessListener(taskSnapshot -> {
// Get the MIME type and Cloud Storage for Firebase file path.
String mimeType = taskSnapshot.getMetadata().getContentType();
String bucket = taskSnapshot.getMetadata().getBucket();
String filePath = taskSnapshot.getMetadata().getPath();
if (mimeType != null && bucket != null) {
// Construct a URL in the required format.
String storageUrl = "gs://" + bucket + "/" + filePath;
// Create a prompt that includes text, the MIME type, and the URL.
Content prompt = new Content.Builder()
.addFileData(storageUrl, mimeType)
.addText("What's in this picture?")
.build();
// To generate text output, call generateContent with the prompt.
GenerativeModelFutures modelFutures = GenerativeModelFutures.from(model);
ListenableFuture<GenerateContentResponse> response = modelFutures.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(@NonNull Throwable t) {
t.printStackTrace();
}
}, executor);
}
}).addOnFailureListener(e -> {
// An error occurred while uploading the file.
e.printStackTrace();
});
Web
// Upload an image file using Cloud Storage for Firebase.
const storageRef = ref(storage, "image.jpg");
const uploadResult = await uploadBytes(storageRef, file);
// Get the MIME type and Cloud Storage for Firebase URL.
// toString() is the simplest way to construct the Cloud Storage for Firebase URL
// in the required format.
const mimeType = uploadResult.metadata.contentType;
const storageUrl = uploadResult.ref.toString();
// Construct the imagePart with the MIME type and the URL.
const imagePart = { fileData: { mimeType, fileUri: storageUrl }};
// To generate text output, call generateContent with the prompt and imagePart.
const result = await model.generateContent([prompt, imagePart]);
console.log(result.response.text());
Dart
// Upload an image file using Cloud Storage for Firebase.
final storageRef = FirebaseStorage.instance.ref();
final imageRef = storageRef.child("images/image.jpg");
await imageRef.putData(data);
// Get the MIME type and Cloud Storage for Firebase file path.
final metadata = await imageRef.getMetadata();
final mimeType = metadata.contentType;
final bucket = imageRef.bucket;
final fullPath = imageRef.fullPath;
final prompt = TextPart("What's in the picture?");
// Construct a URL in the required format.
final storageUrl = 'gs://$bucket/$fullPath';
// Construct the filePart with the MIME type and the URL.
final filePart = FileData(mimeType, storageUrl);
// To generate text output, call generateContent with the text and the filePart.
final response = await model.generateContent([
Content.multi([prompt, filePart])
]);
print(response.text);
Unity
var storageRef = FirebaseStorage.DefaultInstance.GetReference("images/image.jpg");
var metadata = await storageRef.PutFileAsync(filePathToJpg);
// Get the MIME type and Cloud Storage for Firebase URL.
var mimeType = metadata.ContentType;
// Construct a URL in the required format.
var storageURL = new Uri($"gs://{storageRef.Bucket}/{storageRef.Path}");
var prompt = ModelContent.Text("What's in this picture?");
// Construct a FileData that explicitly includes the MIME type and
// Cloud Storage for Firebase URL values.
var fileData = ModelContent.FileData(mimeType, storageURL);
// To generate text output, call GenerateContentAsync with the prompt and fileData.
var response = await model.GenerateContentAsync(new [] { prompt, fileData });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
אפשרות 2: לכלול את סוג ה-MIME ואת כתובת ה-URL באופן מפורש
לפני שמנסים את הדוגמה הזו, חשוב לוודא שסיימתם את המדריך לתחילת העבודה עם ערכות ה-SDK של Firebase AI Logic. |
משתמשים באפשרות הזו אם יודעים את הערכים של סוג ה-MIME ושל כתובת ה-URL של Cloud Storage for Firebase ורוצים לכלול אותם באופן מפורש בבקשה המולטימודלית. הקריאה מחייבת גם את סוג ה-MIME וגם את כתובת ה-URL.
Swift
let prompt = "What's in this picture?"
// Construct an imagePart that explicitly includes the MIME type and
// Cloud Storage for Firebase URL values.
let imagePart = FileDataPart(uri: "gs://bucket-name/path/image.jpg", mimeType: "image/jpeg")
// To generate text output, call generateContent with the prompt and imagePart.
let result = try await model.generateContent(prompt, imagePart)
if let text = result.text {
print(text)
}
Kotlin
ב-Kotlin, המתודות ב-SDK הזה הן פונקציות השהיה וצריך להפעיל אותן מהיקף של Coroutine.// Construct a prompt that explicitly includes the MIME type and Cloud Storage for Firebase URL values.
val prompt = content {
fileData(mimeType = "image/jpeg", uri = "gs://bucket-name/path/image.jpg")
text("What's in this picture?")
}
// To generate text output, call generateContent with the prompt.
val response = generativeModel.generateContent(prompt)
println(response.text)
Java
ב-Java, השיטות ב-SDK הזה מחזירותListenableFuture
.
// Construct a prompt that explicitly includes the MIME type and Cloud Storage for Firebase URL values.
Content prompt = new Content.Builder()
.addFilePart("gs://bucket-name/path/image.jpg", "image/jpeg")
.addText("What's in this picture?")
.build();
// To generate text output, call generateContent with the prompt
GenerativeModelFutures modelFutures = GenerativeModelFutures.from(model);
ListenableFuture<GenerateContentResponse> response = modelFutures.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(@NonNull Throwable t) {
t.printStackTrace();
}
}, executor);
Web
const prompt = "What's in this picture?";
// Construct an imagePart that explicitly includes the MIME type and Cloud Storage for Firebase URL values.
const imagePart = { fileData: { mimeType: "image/jpeg", fileUri: "gs://bucket-name/path/image.jpg" }};
// To generate text output, call generateContent with the prompt and imagePart.
const result = await model.generateContent([prompt, imagePart]);
console.log(result.response.text());
Dart
final prompt = TextPart("What's in the picture?");
// Construct a filePart that explicitly includes the MIME type and Cloud Storage for Firebase URL values.
final filePart = FileData('image/jpeg', 'gs://bucket-name/path/image.jpg'),
// To generate text output, call generateContent with the prompt and filePart.
final response = await model.generateContent([
Content.multi([prompt, filePart])
]);
print(response.text);
Unity
var prompt = ModelContent.Text("What's in this picture?");
// Construct a FileData that explicitly includes the MIME type and
// Cloud Storage for Firebase URL values.
var fileData = ModelContent.FileData(
mimeType: "image/jpeg",
uri: new Uri("gs://bucket-name/path/image.jpg")
);
// To generate text output, call GenerateContentAsync with the prompt and fileData.
var response = await model.GenerateContentAsync(new [] { prompt, fileData });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");