يمكنك أن تطلب من نموذج 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 FirebaseAILogic
// 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.5-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 FirebaseAILogic
// 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.5-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.5-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 = model.generateContent(prompt)
print(response.text)
إدخال ملفات متعددة
في Kotlin، تكون الطرق في حزمة تطوير البرامج هذه عبارة عن دوال معلّقة ويجب استدعاؤها من نطاق روتين فرعي.
// 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.5-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 = model.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.5-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.5-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.5-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.5-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.5-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.5-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.5-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.5-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 إذا كان الطلب كبيرًا جدًا.
يُرجى الاطّلاع على صفحة "الملفات والمتطلبات المتوافقة" للحصول على معلومات تفصيلية حول ما يلي:
- خيارات مختلفة لتقديم ملف في طلب (إما مضمّنًا أو باستخدام عنوان URL الخاص بالملف)
- المتطلبات وأفضل الممارسات المتعلّقة بملفات الصور
أنواع MIME المتوافقة مع الصور
تتوافق النماذج المتعدّدة الوسائط مع أنواع MIME التالية للصور: Gemini
- PNG -
image/png - JPEG -
image/jpeg - WebP -
image/webp
الحدود القصوى لكل طلب
ليس هناك حدّ أقصى لعدد وحدات البكسل في الصورة. ومع ذلك، يتم تصغير حجم الصور الأكبر وإضافة مساحة فارغة إليها لتناسب دقة قصوى تبلغ 3072 × 3072 مع الحفاظ على نسبة العرض إلى الارتفاع الأصلية.
الحدّ الأقصى لعدد الملفات لكل طلب: 3,000 ملف صورة
ما هي الإجراءات الأخرى التي يمكنك اتّخاذها؟
- تعرَّف على كيفية احتساب الرموز المميزة قبل إرسال طلبات طويلة إلى النموذج.
- إعداد Cloud Storage for Firebase ليصبح بإمكانك تضمين ملفات كبيرة في طلباتك المتعددة الوسائط والحصول على حلّ أكثر إدارةً لتوفير الملفات في الطلبات يمكن أن تتضمّن الملفات صورًا وملفات PDF وفيديوهات وملفات صوتية.
-
ابدأ التفكير في الاستعداد للإنتاج (راجِع قائمة المهام لعملية الإنتاج)، بما في ذلك:
- إعداد Firebase App Check لحماية Gemini API من إساءة الاستخدام من قِبل العملاء غير المصرَّح لهم
- دمج Firebase Remote Config لتعديل القيم في تطبيقك (مثل اسم النموذج) بدون طرح إصدار جديد من التطبيق.
تجربة إمكانات أخرى
- إنشاء محادثات متعدّدة الجولات (محادثة)
- إنشاء نص من طلبات نصية فقط
- إنشاء نتائج منظَّمة (مثل JSON) من الطلبات النصية والوسائط المتعددة
- إنشاء صور من الطلبات النصية (Gemini أو Imagen)
- استخدام أدوات (مثل استدعاء الدوال والاستناد إلى معلومات من "بحث Google") لربط نموذج Gemini بأجزاء أخرى من تطبيقك والأنظمة والمعلومات الخارجية
كيفية التحكّم في إنشاء المحتوى
- التعرّف على تصميم الطلبات، بما في ذلك أفضل الممارسات والاستراتيجيات وأمثلة على الطلبات
- ضبط مَعلمات النموذج مثل درجة العشوائية والحد الأقصى لعدد الرموز المميزة في الرد (بالنسبة إلى Gemini) أو نسبة العرض إلى الارتفاع وإنشاء صور أشخاص (بالنسبة إلى Imagen)
- استخدام إعدادات الأمان لتعديل احتمالية تلقّي ردود قد تُعتبر ضارة
مزيد من المعلومات عن النماذج المتوافقة
يمكنك الاطّلاع على النماذج المتاحة لمختلف حالات الاستخدام والحصص والأسعار الخاصة بها.تقديم ملاحظات حول تجربتك مع Firebase AI Logic