ערכות ה-SDK Firebase AI Logic מאפשרות לכם גישה למודלים Imagen (דרך Imagen API) כדי ליצור תמונות מהנחיית טקסט. בעזרת היכולת הזו, אתם יכולים:
- יצירת תמונות מהנחיות שנכתבו בשפה טבעית
- יצירת תמונות במגוון רחב של פורמטים וסגנונות
- עיבוד טקסט בתמונות
הערה: Firebase AI Logic עדיין לא תומך בכל התכונות שזמינות במודלים של Imagen. מידע נוסף זמין בהמשך הדף בקטע יכולות ותכונות נתמכות.
בחירה בין מודלים של Gemini ושל Imagen
ערכות ה-SDK של Firebase AI Logic תומכות ביצירת תמונות באמצעות מודל Gemini או מודל Imagen. ברוב תרחישי השימוש, כדאי להתחיל עם Gemini ואז לבחור ב-Imagen למשימות מיוחדות שבהן איכות התמונה היא קריטית.
חשוב לשים לב: ערכות Firebase AI Logic SDK עדיין לא תומכות בקלט של תמונות (למשל, לצורך עריכה) עם מודלים של Imagen. לכן, אם אתם רוצים לעבוד עם תמונות קלט, אתם יכולים להשתמש במודל Gemini במקום זאת.
בוחרים באפשרות Gemini אם רוצים:
- כדי להשתמש בידע על העולם ובהיגיון כדי ליצור תמונות רלוונטיות להקשר.
- כדי לשלב טקסט ותמונות בצורה חלקה.
- להטמיע רכיבים חזותיים מדויקים ברצפים ארוכים של טקסט.
- כדי לערוך תמונות בשיחה תוך שמירה על ההקשר.
בוחרים באפשרות Imagen אם רוצים:
- כדי לתת עדיפות לאיכות התמונה, לריאליזם, לפרטים אומנותיים או לסגנונות ספציפיים (למשל, אימפרסיוניזם או אנימה).
- כדי לציין במפורש את יחס הגובה-רוחב או את הפורמט של התמונות שנוצרו.
לפני שמתחילים
לוחצים על הספק Gemini API כדי לראות בדף הזה תוכן וקוד שספציפיים לספק. |
אם עדיין לא עשיתם את זה, כדאי לעיין במדריך לתחילת העבודה. במדריך הזה מוסבר איך להגדיר את פרויקט Firebase, לקשר את האפליקציה ל-Firebase, להוסיף את ה-SDK, לאתחל את שירות ה-Backend עבור ספק ה-API שבחרתם וליצור מופע של ImagenModel
.
מודלים שתומכים ביכולת הזו
Gemini Developer API תומך רק ביצירת תמונות באמצעות המודל היציב העדכני ביותר Imagen 3, ולא במודלים אחרים של Imagen. המגבלות האלה של מודל Imagen חלות ללא קשר לאופן שבו ניגשים אל Gemini Developer API.
imagen-3.0-generate-002
יצירת תמונות מקלט טקסט בלבד
אתם יכולים לבקש ממודל Imagen ליצור תמונות באמצעות הנחיות טקסט. אתם יכולים ליצור תמונה אחת או כמה תמונות.
יצירת תמונה אחת מקלט של טקסט בלבד
לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים שבקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה צריך גם ללחוץ על לחצן של ספק Gemini API שבחרתם כדי שיוצג בדף הזה תוכן שספציפי לספק. |
אתם יכולים לבקש ממודל Imagen ליצור תמונה אחת באמצעות הנחיית טקסט.
חשוב ליצור מופע של ImagenModel
ולהתקשר אל generateImages
.
Swift
import FirebaseAI
// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create an `ImagenModel` instance with a model that supports your use case
let model = ai.imagenModel(modelName: "imagen-3.0-generate-002")
// Provide an image generation prompt
let prompt = "An astronaut riding a horse"
// To generate an image, call `generateImages` with the text prompt
let response = try await model.generateImages(prompt: prompt)
// Handle the generated image
guard let image = response.images.first else {
fatalError("No image in the response.")
}
let uiImage = UIImage(data: image.data)
Kotlin
// Using this SDK to access Imagen models is a Preview release and requires opt-in
@OptIn(PublicPreviewAPI::class)
suspend fun generateImage() {
// Initialize the Gemini Developer API backend service
// Create an `ImagenModel` instance with an Imagen model that supports your use case
val imagenModel = Firebase.ai(backend = GenerativeBackend.googleAI()).imagenModel("imagen-3.0-generate-002")
// Provide an image generation prompt
val prompt = "An astronaut riding a horse"
// To generate an image, call `generateImages` with the text prompt
val imageResponse = imagenModel.generateImages(prompt)
// Handle the generated image
val image = imageResponse.images.first()
val bitmapImage = image.asBitmap()
}
Java
// Initialize the Gemini Developer API backend service
// Create an `ImagenModel` instance with an Imagen model that supports your use case
ImagenModel imagenModel = FirebaseAI.getInstance(GenerativeBackend.googleAI()).imagenModel(
/* modelName */ "imagen-3.0-generate-002");
ImagenModelFutures model = ImagenModelFutures.from(imagenModel);
// Provide an image generation prompt
String prompt = "An astronaut riding a horse";
// To generate an image, call `generateImages` with the text prompt
Futures.addCallback(model.generateImages(prompt), new FutureCallback<ImagenGenerationResponse<ImagenInlineImage>>() {
@Override
public void onSuccess(ImagenGenerationResponse<ImagenInlineImage> result) {
if (result.getImages().isEmpty()) {
Log.d("TAG", "No images generated");
}
Bitmap bitmap = result.getImages().get(0).asBitmap();
// Use the bitmap to display the image in your UI
}
@Override
public void onFailure(Throwable t) {
// ...
}
}, Executors.newSingleThreadExecutor());
Web
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 an `ImagenModel` instance with an Imagen 3 model that supports your use case
const imagenModel = getImagenModel(ai, { model: "imagen-3.0-generate-002" });
// Provide an image generation prompt
const prompt = "An astronaut riding a horse.";
// To generate an image, call `generateImages` with the text prompt
const response = await imagenModel.generateImages(prompt)
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out
if (response.filteredReason) {
console.log(response.filteredReason);
}
if (response.images.length == 0) {
throw new Error("No images in the response.")
}
const image = response.images[0];
Dart
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 an `ImagenModel` instance with an Imagen model that supports your use case
final model =
FirebaseAI.googleAI().imagenModel(model: 'imagen-3.0-generate-002');
// Provide an image generation prompt
const prompt = 'An astronaut riding a horse.';
// To generate an image, call `generateImages` with the text prompt
final response = await model.generateImages(prompt);
if (response.images.isNotEmpty) {
final image = response.images[0];
// Process the image
} else {
// Handle the case where no images were generated
print('Error: No images were generated.');
}
Unity
עדיין אין תמיכה בשימוש ב-Imagen ב-Unity, אבל כדאי לבדוק שוב בקרוב.
איך בוחרים מודל שמתאימים לתרחיש השימוש ולאפליקציה שלכם.
יצירת כמה תמונות מקלט טקסט בלבד
לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים שבקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה. בקטע הזה צריך גם ללחוץ על לחצן של ספק Gemini API שבחרתם כדי שיוצג בדף הזה תוכן שספציפי לספק. |
כברירת מחדל, מודלים של Imagen יוצרים רק תמונה אחת לכל בקשה.
עם זאת, אפשר לבקש ממודל Imagen ליצור כמה תמונות בכל בקשה על ידי ציון ImagenGenerationConfig
כשיוצרים את מופע ImagenModel
.
חשוב ליצור מופע של ImagenModel
ולהתקשר אל generateImages
.
Swift
import FirebaseAI
// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create an `ImagenModel` instance with a model that supports your use case
let model = ai.imagenModel(
modelName: "imagen-3.0-generate-002",
// Configure the model to generate multiple images for each request
// See: https://firebase.google.com/docs/ai-logic/model-parameters
generationConfig: ImagenGenerationConfig(numberOfImages: 4)
)
// Provide an image generation prompt
let prompt = "An astronaut riding a horse"
// To generate images, call `generateImages` with the text prompt
let response = try await model.generateImages(prompt: prompt)
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out
if let filteredReason = response.filteredReason {
print(filteredReason)
}
// Handle the generated images
let uiImages = response.images.compactMap { UIImage(data: $0.data) }
Kotlin
// Using this SDK to access Imagen models is a Preview release and requires opt-in
@OptIn(PublicPreviewAPI::class)
suspend fun generateImage() {
// Initialize the Gemini Developer API backend service
// Create an `ImagenModel` instance with an Imagen model that supports your use case
val imagenModel = Firebase.ai(backend = GenerativeBackend.googleAI()).imagenModel(
modelName = "imagen-3.0-generate-002",
// Configure the model to generate multiple images for each request
// See: https://firebase.google.com/docs/ai-logic/model-parameters
generationConfig = ImagenGenerationConfig(numberOfImages = 4)
)
// Provide an image generation prompt
val prompt = "An astronaut riding a horse"
// To generate images, call `generateImages` with the text prompt
val imageResponse = imagenModel.generateImages(prompt)
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out
if (imageResponse.filteredReason != null) {
Log.d(TAG, "FilteredReason: ${imageResponse.filteredReason}")
}
for (image in imageResponse.images) {
val bitmap = image.asBitmap()
// Use the bitmap to display the image in your UI
}
}
Java
// Configure the model to generate multiple images for each request
// See: https://firebase.google.com/docs/ai-logic/model-parameters
ImagenGenerationConfig imagenGenerationConfig = new ImagenGenerationConfig.Builder()
.setNumberOfImages(4)
.build();
// Initialize the Gemini Developer API backend service
// Create an `ImagenModel` instance with an Imagen model that supports your use case
ImagenModel imagenModel = FirebaseAI.getInstance(GenerativeBackend.googleAI()).imagenModel(
/* modelName */ "imagen-3.0-generate-002",
/* imageGenerationConfig */ imagenGenerationConfig);
ImagenModelFutures model = ImagenModelFutures.from(imagenModel);
// Provide an image generation prompt
String prompt = "An astronaut riding a horse";
// To generate images, call `generateImages` with the text prompt
Futures.addCallback(model.generateImages(prompt), new FutureCallback<ImagenGenerationResponse<ImagenInlineImage>>() {
@Override
public void onSuccess(ImagenGenerationResponse<ImagenInlineImage> result) {
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out
if (result.getFilteredReason() != null){
Log.d("TAG", "FilteredReason: " + result.getFilteredReason());
}
// Handle the generated images
List<ImagenInlineImage> images = result.getImages();
for (ImagenInlineImage image : images) {
Bitmap bitmap = image.asBitmap();
// Use the bitmap to display the image in your UI
}
}
@Override
public void onFailure(Throwable t) {
// ...
}
}, Executors.newSingleThreadExecutor());
Web
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 an `ImagenModel` instance with an Imagen 3 model that supports your use case
const imagenModel = getImagenModel(
ai,
{
model: "imagen-3.0-generate-002",
// Configure the model to generate multiple images for each request
// See: https://firebase.google.com/docs/ai-logic/model-parameters
generationConfig: {
numberOfImages: 4
}
}
);
// Provide an image generation prompt
const prompt = "An astronaut riding a horse.";
// To generate images, call `generateImages` with the text prompt
const response = await imagenModel.generateImages(prompt)
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out
if (response.filteredReason) {
console.log(response.filteredReason);
}
if (response.images.length == 0) {
throw new Error("No images in the response.")
}
const images = response.images[0];
Dart
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 an `ImagenModel` instance with an Imagen model that supports your use case
final model =
FirebaseAI.googleAI().imagenModel(
model: 'imagen-3.0-generate-002',
// Configure the model to generate multiple images for each request
// See: https://firebase.google.com/docs/ai-logic/model-parameters
generationConfig: ImagenGenerationConfig(numberOfImages: 4),
);
// Provide an image generation prompt
const prompt = 'An astronaut riding a horse.';
// To generate images, call `generateImages` with the text prompt
final response = await model.generateImages(prompt);
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out
if (response.filteredReason != null) {
print(response.filteredReason);
}
if (response.images.isNotEmpty) {
final images = response.images;
for(var image in images) {
// Process the image
}
} else {
// Handle the case where no images were generated
print('Error: No images were generated.');
}
Unity
עדיין אין תמיכה בשימוש ב-Imagen ב-Unity, אבל כדאי לבדוק שוב בקרוב.
איך בוחרים מודל שמתאימים לתרחיש השימוש ולאפליקציה שלכם.
תכונות נתמכות ודרישות
מודלים של Imagen מציעים הרבה תכונות שקשורות ליצירת תמונות. בקטע הזה מתואר מה נתמך כשמשתמשים במודלים עם Firebase AI Logic.
יכולות ותכונות נתמכות
. Firebase AI Logic תומך בתכונות האלה של מודלים של Imagen.
יצירת אנשים ופנים (בהנחה שלפרויקט Firebase יש אישור מ-Google Cloud)
יצירת טקסט בתוך תמונות שנוצרו
הוספת סימן מים לתמונות שנוצרו
הגדרת פרמטרים ליצירת תמונות, כמו מספר התמונות שנוצרו, יחס הגובה-רוחב וסימן מים
הגדרה של הגדרות בטיחות
Firebase AI Logic לא תומך בתכונות המתקדמות האלה של מודלים של Imagen.
שימו לב שרוב התכונות האלה דורשות להיות ברשימה מאושרת של משתמשים, גם כשמשתמשים במודלים של Imagen בצד השרת.
תכונות לעריכה או למניפולציה של תמונות, כולל הגדלת תמונות
הכללת תמונות בבקשה למודל (למשל, ללמידה עם מעט דוגמאות)
אימות סימני מים דיגיטליים באמצעות ערכות ה-SDK
כדי לוודא שתמונה מסוימת מכילה סימן מים, אפשר להעלות את התמונה ל-Vertex AI Studio באמצעות הכרטיסייה Media.יצירת תמונות דינמיות מטקסט (יצירת MP4)
יצירת תמונות באמצעות סגנון מוגדר מראש
הפעלת
includeSafetyAttributes
, כלומר אי אפשר להחזיר אתsafetyAttributes.categories
ואתsafetyAttributes.scores
השבתה של שיפור ההנחיות (הפרמטר
enhancePrompt
), כלומר כלי לשכתוב הנחיות שמבוסס על LLM תמיד יוסיף באופן אוטומטי פרטים נוספים להנחיה שסופקה כדי ליצור תמונות באיכות גבוהה יותר שמשקפות טוב יותר את ההנחיה שסופקהכתיבת תמונה שנוצרה ישירות לתוך Google Cloud Storage כחלק מהתשובה של המודל (הפרמטר
storageUri
). במקום זאת, התמונות תמיד מוחזרות בתשובה כבייטים של תמונה שמקודדים ב-Base64.
אם רוצים להעלות תמונה שנוצרה ל-Cloud Storage, אפשר להשתמש ב-Cloud Storage for Firebase.
מפרטים ומגבלות
נכס (לכל בקשה) | ערך |
---|---|
מספר מקסימלי של טוקנים לקלט | 480 טוקנים |
מספר התמונות המקסימלי בפלט | 4 תמונות |
רזולוציות נתמכות של תמונות פלט (בפיקסלים) |
|
מה עוד אפשר לעשות?
-
מתחילים לחשוב על הכנה לייצור (ראו את רשימת המשימות לביצוע לפני העברה לייצור), כולל:
- הגדרת Firebase App Check כדי להגן על Gemini API מפני ניצול לרעה על ידי לקוחות לא מורשים.
- שילוב של Firebase Remote Config כדי לעדכן ערכים באפליקציה (כמו שם המודל) בלי לפרסם גרסה חדשה של האפליקציה.
איך שולטים ביצירת תוכן
- הסבר על תכנון הנחיות, כולל שיטות מומלצות, אסטרטגיות ודוגמאות להנחיות.
- הגדרת פרמטרים של מודל Imagen כמו יצירת אנשים, יחס גובה-רוחב והוספת סימן מים.
- שימוש בהגדרות בטיחות כדי לשנות את הסבירות לקבלת תשובות שעלולות להיחשב מזיקות.
מידע נוסף על המודלים הנתמכים
מידע על המודלים שזמינים לתרחישי שימוש שונים ועל המיכסות והתמחור שלהםרוצה לתת משוב על חוויית השימוש ב-Firebase AI Logic?