אפשר לבקש ממודל Gemini לנתח קובצי תמונה שאתם מספקים בתוך שורה (בקידוד base64) או דרך כתובת URL. כשמשתמשים ב-Firebase AI Logic, אפשר לשלוח את הבקשה הזו ישירות מהאפליקציה.
בעזרת היכולת הזו תוכלו לבצע פעולות כמו:
- ליצור כיתובים או לענות על שאלות לגבי תמונות
- כותבים סיפור קצר או שיר על תמונה
- זיהוי אובייקטים בתמונה והחזרת קואורדינטות של תיבת מלבנית להיקף שלהם
- לתייג או לסווג קבוצת תמונות לפי סנטימנט, סגנון או מאפיין אחר
מעבר לדוגמאות הקוד מעבר לקוד של תגובות בסטרימינג
במדריכים נוספים מפורטות אפשרויות נוספות לעבודה עם תמונות יצירת פלט מובנה צ'אט בכמה סבבים ניתוח תמונות במכשיר יצירת תמונות |
לפני שמתחילים
לוחצים על ספק Gemini API כדי להציג בדף הזה תוכן וקוד ספציפיים לספק. |
אם עדיין לא עשיתם זאת, כדאי לעיין במדריך למתחילים, שבו מוסבר איך מגדירים את פרויקט Firebase, מחברים את האפליקציה ל-Firebase, מוסיפים את ה-SDK, מאתחלים את שירות הקצה העורפי של ספק Gemini API שבחרתם ויוצרים מכונה של GenerativeModel
.
כדי לבדוק את ההנחיות ולבצע בהן שינויים, ואפילו לקבל קטע קוד שנוצר, מומלץ להשתמש ב-Google AI Studio.
יצירת טקסט מקובצי תמונה (מקודדים ב-base64)
לפני שמנסים את הדוגמה הזו, צריך להשלים את הקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה צריך גם ללחוץ על הלחצן של ספק ה-Gemini API שבחרתם כדי להציג תוכן ספציפי לספק בדף הזה. |
אתם יכולים לבקש ממודל Gemini ליצור טקסט על ידי הצגת הנחיות עם טקסט ותמונות – ולספק את mimeType
של כל קובץ קלט ואת הקובץ עצמו. בהמשך הדף מפורטות הדרישות וההמלצות לקובצי קלט.
Swift
אפשר להפעיל את הפונקציה generateContent()
כדי ליצור טקסט מקלט מולטי-מודאלי של טקסט ותמונות.
קלט של קובץ יחיד
import FirebaseAI
// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(modelName: "gemini-2.0-flash")
guard let image = UIImage(systemName: "bicycle") else { fatalError() }
// Provide a text prompt to include with the image
let prompt = "What's in this picture?"
// To generate text output, call generateContent and pass in the prompt
let response = try await model.generateContent(image, prompt)
print(response.text ?? "No text in response.")
קלט של מספר קבצים
import FirebaseAI
// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(modelName: "gemini-2.0-flash")
guard let image1 = UIImage(systemName: "car") else { fatalError() }
guard let image2 = UIImage(systemName: "car.2") else { fatalError() }
// Provide a text prompt to include with the images
let prompt = "What's different between these pictures?"
// To generate text output, call generateContent and pass in the prompt
let response = try await model.generateContent(image1, image2, prompt)
print(response.text ?? "No text in response.")
Kotlin
אפשר להפעיל את הפונקציה generateContent()
כדי ליצור טקסט מקלט מולטי-מודאלי של טקסט ותמונות.
קלט של קובץ יחיד
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel("gemini-2.0-flash")
// Loads an image from the app/res/drawable/ directory
val bitmap: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky)
// Provide a prompt that includes the image specified above and text
val prompt = content {
image(bitmap)
text("What developer tool is this mascot from?")
}
// To generate text output, call generateContent with the prompt
val response = generativeModel.generateContent(prompt)
print(response.text)
קלט של מספר קבצים
ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה (suspend) וצריך לקרוא להן מהיקף של פונקציית אירוע (coroutine).
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel("gemini-2.0-flash")
// Loads an image from the app/res/drawable/ directory
val bitmap1: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky)
val bitmap2: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky_eats_pizza)
// Provide a prompt that includes the images specified above and text
val prompt = content {
image(bitmap1)
image(bitmap2)
text("What is different between these pictures?")
}
// To generate text output, call generateContent with the prompt
val response = generativeModel.generateContent(prompt)
print(response.text)
Java
אפשר להפעיל את הפונקציה generateContent()
כדי ליצור טקסט מקלט מולטי-מודאלי של טקסט ותמונות.
ListenableFuture
.
קלט של קובץ יחיד
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-2.0-flash");
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sparky);
// Provide a prompt that includes the image specified above and text
Content content = new Content.Builder()
.addImage(bitmap)
.addText("What developer tool is this mascot from?")
.build();
// To generate text output, call generateContent with the prompt
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
קלט של מספר קבצים
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-2.0-flash");
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.sparky);
Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(), R.drawable.sparky_eats_pizza);
// Provide a prompt that includes the images specified above and text
Content prompt = new Content.Builder()
.addImage(bitmap1)
.addImage(bitmap2)
.addText("What's different between these pictures?")
.build();
// To generate text output, call generateContent with the prompt
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
אפשר להפעיל את הפונקציה generateContent()
כדי ליצור טקסט מקלט מולטי-מודאלי של טקסט ותמונות.
קלט של קובץ יחיד
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";
// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, { model: "gemini-2.0-flash" });
// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
const base64EncodedDataPromise = new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(',')[1]);
reader.readAsDataURL(file);
});
return {
inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
};
}
async function run() {
// Provide a text prompt to include with the image
const prompt = "What do you see?";
const fileInputEl = document.querySelector("input[type=file]");
const imagePart = await fileToGenerativePart(fileInputEl.files[0]);
// To generate text output, call generateContent with the text and image
const result = await model.generateContent([prompt, imagePart]);
const response = result.response;
const text = response.text();
console.log(text);
}
run();
קלט של מספר קבצים
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";
// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, { model: "gemini-2.0-flash" });
// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
const base64EncodedDataPromise = new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(',')[1]);
reader.readAsDataURL(file);
});
return {
inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
};
}
async function run() {
// Provide a text prompt to include with the images
const prompt = "What's different between these pictures?";
// Prepare images for input
const fileInputEl = document.querySelector("input[type=file]");
const imageParts = await Promise.all(
[...fileInputEl.files].map(fileToGenerativePart)
);
// To generate text output, call generateContent with the text and images
const result = await model.generateContent([prompt, ...imageParts]);
const response = result.response;
const text = response.text();
console.log(text);
}
run();
Dart
אפשר להפעיל את הפונקציה generateContent()
כדי ליצור טקסט מקלט מולטי-מודאלי של טקסט ותמונות.
קלט של קובץ יחיד
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
FirebaseAI.googleAI().generativeModel(model: 'gemini-2.0-flash');
// Provide a text prompt to include with the image
final prompt = TextPart("What's in the picture?");
// Prepare images for input
final image = await File('image0.jpg').readAsBytes();
final imagePart = InlineDataPart('image/jpeg', image);
// To generate text output, call generateContent with the text and image
final response = await model.generateContent([
Content.multi([prompt,imagePart])
]);
print(response.text);
קלט של מספר קבצים
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
FirebaseAI.googleAI().generativeModel(model: 'gemini-2.0-flash');
final (firstImage, secondImage) = await (
File('image0.jpg').readAsBytes(),
File('image1.jpg').readAsBytes()
).wait;
// Provide a text prompt to include with the images
final prompt = TextPart("What's different between these pictures?");
// Prepare images for input
final imageParts = [
InlineDataPart('image/jpeg', firstImage),
InlineDataPart('image/jpeg', secondImage),
];
// To generate text output, call generateContent with the text and images
final response = await model.generateContent([
Content.multi([prompt, ...imageParts])
]);
print(response.text);
Unity
אפשר להפעיל את הפונקציה GenerateContentAsync()
כדי ליצור טקסט מקלט מולטי-מודאלי של טקסט ותמונות.
קלט של קובץ יחיד
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");
// Convert a Texture2D into InlineDataParts
var grayImage = ModelContent.InlineData("image/png",
UnityEngine.ImageConversion.EncodeToPNG(UnityEngine.Texture2D.grayTexture));
// Provide a text prompt to include with the image
var prompt = ModelContent.Text("What's in this picture?");
// To generate text output, call GenerateContentAsync and pass in the prompt
var response = await model.GenerateContentAsync(new [] { grayImage, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
קלט של מספר קבצים
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");
// Convert Texture2Ds into InlineDataParts
var blackImage = ModelContent.InlineData("image/png",
UnityEngine.ImageConversion.EncodeToPNG(UnityEngine.Texture2D.blackTexture));
var whiteImage = ModelContent.InlineData("image/png",
UnityEngine.ImageConversion.EncodeToPNG(UnityEngine.Texture2D.whiteTexture));
// Provide a text prompt to include with the images
var prompt = ModelContent.Text("What's different between these pictures?");
// To generate text output, call GenerateContentAsync and pass in the prompt
var response = await model.GenerateContentAsync(new [] { blackImage, whiteImage, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
איך בוחרים מודל שמתאים לתרחיש לדוגמה ולסוג האפליקציה שלכם
שידור התשובה
לפני שמנסים את הדוגמה הזו, צריך להשלים את הקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה צריך גם ללחוץ על הלחצן של ספק ה-Gemini API שבחרתם כדי להציג תוכן ספציפי לספק בדף הזה. |
כדי לקבל אינטראקציות מהירות יותר, אפשר לא להמתין לתוצאה המלאה של יצירת המודל, אלא להשתמש בסטרימינג כדי לטפל בתוצאות חלקיות.
כדי להעביר את התשובה בסטרימינג, קוראים ל-generateContentStream
.
דרישות והמלצות לגבי קובצי תמונה להזנה
חשוב לזכור שקובץ שסופק כנתונים בתוך שורה מקודד ל-base64 במהלך ההעברה, וכתוצאה מכך גדל גודל הבקשה. אם בקשה גדולה מדי, תקבלו את השגיאה HTTP 413.
במאמר 'קבצי קלט נתמכים ודרישות ל-Vertex AI Gemini API' מפורט מידע על הנושאים הבאים:
- אפשרויות שונות לשליחת קובץ בבקשה (בתוך הטקסט או באמצעות כתובת ה-URL של הקובץ)
- דרישות ושיטות מומלצות לקובצי תמונות
סוגי MIME נתמכים של תמונות
Gemini מודלים רב-מודאליים תומכים בסוגי ה-MIME הבאים של תמונות:
סוג ה-MIME של התמונה | Gemini 2.0 Flash | Gemini 2.0 Flash‑Lite |
---|---|---|
PNG – image/png |
||
JPEG – image/jpeg |
||
WebP – image/webp |
מגבלות לכל בקשה
אין הגבלה ספציפית על מספר הפיקסלים בתמונה. עם זאת, תמונות גדולות יותר מוקטנות וממולאות כדי להתאים לרזולוציה מקסימלית של 3072 על 3072, תוך שמירה על יחס הגובה-רוחב המקורי שלהן.
זהו המספר המקסימלי של קובצי תמונה שמותר לשלוח בבקשה להצגת הנחיה:
- Gemini 2.0 Flash ו-Gemini 2.0 Flash‑Lite: 3,000 תמונות
מה עוד אפשר לעשות?
- כך סופרים אסימונים לפני ששולחים הנחיות ארוכות למודל.
- מגדירים את Cloud Storage for Firebase כדי שתוכלו לכלול קבצים גדולים בבקשות עם מודלים מרובים של קלט, ולקבל פתרון מנוהל יותר לשליחת קבצים בהנחיות. הקבצים יכולים לכלול תמונות, קובצי PDF, סרטונים וקטעי אודיו.
-
כדאי להתחיל לחשוב על ההכנות לסביבת הייצור (ראו רשימת המשימות לסביבת הייצור), כולל:
- הגדרת Firebase App Check כדי להגן על Gemini API מפני ניצול לרעה על ידי לקוחות לא מורשים.
- שילוב Firebase Remote Config כדי לעדכן ערכים באפליקציה (כמו שם הדגם) בלי לפרסם גרסה חדשה של האפליקציה.
לנסות יכולות אחרות
- ליצור שיחות עם זיכרון (צ'אט).
- ליצור טקסט מהנחיות בטקסט בלבד.
- יצירת פלט מובנה (כמו JSON) גם מהנחיות טקסט וגם מהנחיות מולטימודליות.
- יצירת תמונות מהנחיות טקסט.
- משתמשים בקריאה לפונקציה כדי לחבר מודלים גנרטיביים למערכות ולמידע חיצוניים.
איך שולטים ביצירת תוכן
- הסבר על תכנון הנחיות, כולל שיטות מומלצות, אסטרטגיות והנחיות לדוגמה.
- להגדיר את הפרמטרים של המודל, כמו טמפרטורה ואסימונים מקסימליים של פלט (עבור Gemini) או יחס גובה-רוחב ויצירת אנשים (עבור Imagen).
- שימוש בהגדרות הבטיחות כדי לשנות את הסבירות לקבלת תשובות שעשויות להיחשב כמזיקות.
מידע נוסף על המודלים הנתמכים
כאן תוכלו לקרוא מידע נוסף על המודלים הזמינים לתרחישי שימוש שונים, על המכסות ועל התמחור שלהם.שליחת משוב על חוויית השימוש ב-Firebase AI Logic