میتوانید از مدل Gemini بخواهید فایلهای تصویری را که ارائه میدهید به صورت درون خطی (با کدگذاری پایه 64) یا از طریق URL تجزیه و تحلیل کند. وقتی از Firebase AI Logic استفاده میکنید، میتوانید این درخواست را مستقیماً از برنامه خود ارسال کنید.
با این قابلیت می توانید کارهایی مانند:
- زیرنویس ایجاد کنید یا به سوالات مربوط به تصاویر پاسخ دهید
- یک داستان کوتاه یا یک شعر در مورد یک تصویر بنویسید
- اشیاء را در یک تصویر شناسایی کنید و مختصات جعبه مرزی را برای آنها برگردانید
- مجموعه ای از تصاویر را بر اساس احساسات، سبک یا ویژگی های دیگر برچسب یا دسته بندی کنید
پرش به نمونه کد پرش به کد برای پاسخ های جریانی
راهنماهای دیگر را برای گزینه های اضافی برای کار با تصاویر ببینید ایجاد خروجی ساختاریافته چت چند نوبتی تجزیه و تحلیل تصاویر روی دستگاه تولید تصاویر |
قبل از شروع
برای مشاهده محتوا و کد ارائه دهنده خاص در این صفحه، روی ارائه دهنده API Gemini خود کلیک کنید. |
اگر قبلاً این کار را نکردهاید، راهنمای شروع را کامل کنید، که نحوه راهاندازی پروژه Firebase را توضیح میدهد، برنامه خود را به Firebase متصل کنید، SDK را اضافه کنید، سرویس Backend را برای ارائهدهنده API Gemini انتخابی خود مقداردهی کنید و یک نمونه GenerativeModel
ایجاد کنید.
میتوانید از این فایل در دسترس عموم با نوع MIME
image/jpeg
( مشاهده یا دانلود فایل ) استفاده کنید.https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg
تولید متن از فایل های تصویری (با کدگذاری پایه 64)
قبل از امتحان این نمونه، بخش قبل از شروع این راهنما را تکمیل کنید تا پروژه و برنامه خود را راه اندازی کنید. در آن بخش، همچنین روی دکمه ای برای ارائه دهنده API Gemini انتخابی خود کلیک می کنید تا محتوای خاص ارائه دهنده را در این صفحه ببینید . |
میتوانید از یک مدل Gemini بخواهید که متنی را با درخواست متن و تصویر تولید کند—با ارائه mimeType
هر فایل ورودی و خود فایل. الزامات و توصیههای مربوط به فایلهای ورودی را بعداً در این صفحه پیدا کنید.
سویفت
برای تولید متن از ورودی چند وجهی متن و تصاویر، میتوانید 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 توابع تعلیق هستند و باید از یک محدوده 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);
وحدت
شما می توانید 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.");
بیاموزید که چگونه یک مدل مناسب برای مورد استفاده و برنامه خود انتخاب کنید.
جریان پاسخ
قبل از امتحان این نمونه، بخش قبل از شروع این راهنما را تکمیل کنید تا پروژه و برنامه خود را راه اندازی کنید. در آن بخش، همچنین روی دکمه ای برای ارائه دهنده API Gemini انتخابی خود کلیک می کنید تا محتوای خاص ارائه دهنده را در این صفحه ببینید . |
میتوانید با منتظر ماندن برای کل نتیجه تولید مدل، به تعاملات سریعتری برسید و در عوض از استریم برای مدیریت نتایج جزئی استفاده کنید. برای پخش جریانی پاسخ، generateContentStream
را فراخوانی کنید.
سویفت
میتوانید generateContentStream()
را فراخوانی کنید تا متن تولید شده را از ورودی چند وجهی متن و تصاویر پخش کنید.
ورودی تک فایل
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 stream generated text output, call generateContentStream and pass in the prompt
let contentStream = try model.generateContentStream(image, prompt)
for try await chunk in contentStream {
if let text = chunk.text {
print(text)
}
}
ورودی چند فایل
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 stream generated text output, call generateContentStream and pass in the prompt
let contentStream = try model.generateContentStream(image1, image2, prompt)
for try await chunk in contentStream {
if let text = chunk.text {
print(text)
}
}
Kotlin
میتوانید generateContentStream()
را فراخوانی کنید تا متن تولید شده را از ورودی چند وجهی متن و تصاویر پخش کنید.
ورودی تک فایل
// 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 stream generated text output, call generateContentStream with the prompt
var fullResponse = ""
generativeModel.generateContentStream(prompt).collect { chunk ->
print(chunk.text)
fullResponse += chunk.text
}
ورودی چند فایل
// 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's different between these pictures?")
}
// To stream generated text output, call generateContentStream with the prompt
var fullResponse = ""
generativeModel.generateContentStream(prompt).collect { chunk ->
print(chunk.text)
fullResponse += chunk.text
}
Java
میتوانید generateContentStream()
را فراخوانی کنید تا متن تولید شده را از ورودی چند وجهی متن و تصاویر پخش کنید.
Publisher
را از کتابخانه Reactive Streams برمیگرداند. ورودی تک فایل
// 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 prompt = new Content.Builder()
.addImage(bitmap)
.addText("What developer tool is this mascot from?")
.build();
// To stream generated text output, call generateContentStream with the prompt
Publisher<GenerateContentResponse> streamingResponse = model.generateContentStream(prompt);
final String[] fullResponse = {""};
streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
@Override
public void onNext(GenerateContentResponse generateContentResponse) {
String chunk = generateContentResponse.getText();
fullResponse[0] += chunk;
}
@Override
public void onComplete() {
System.out.println(fullResponse[0]);
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onSubscribe(Subscription s) {
}
});
ورودی چند فایل
// 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 stream generated text output, call generateContentStream with the prompt
Publisher<GenerateContentResponse> streamingResponse = model.generateContentStream(prompt);
final String[] fullResponse = {""};
streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
@Override
public void onNext(GenerateContentResponse generateContentResponse) {
String chunk = generateContentResponse.getText();
fullResponse[0] += chunk;
}
@Override
public void onComplete() {
System.out.println(fullResponse[0]);
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onSubscribe(Subscription s) {
}
});
Web
میتوانید generateContentStream()
را فراخوانی کنید تا متن تولید شده را از ورودی چند وجهی متن و تصاویر پخش کنید.
ورودی تک فایل
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?";
// Prepare image for input
const fileInputEl = document.querySelector("input[type=file]");
const imagePart = await fileToGenerativePart(fileInputEl.files[0]);
// To stream generated text output, call generateContentStream with the text and image
const result = await model.generateContentStream([prompt, imagePart]);
for await (const chunk of result.stream) {
const chunkText = chunk.text();
console.log(chunkText);
}
}
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?";
const fileInputEl = document.querySelector("input[type=file]");
const imageParts = await Promise.all(
[...fileInputEl.files].map(fileToGenerativePart)
);
// To stream generated text output, call generateContentStream with the text and images
const result = await model.generateContentStream([prompt, ...imageParts]);
for await (const chunk of result.stream) {
const chunkText = chunk.text();
console.log(chunkText);
}
}
run();
Dart
میتوانید generateContentStream()
را فراخوانی کنید تا متن تولید شده را از ورودی چند وجهی متن و تصاویر پخش کنید.
ورودی تک فایل
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 stream generated text output, call generateContentStream with the text and image
final response = await model.generateContentStream([
Content.multi([prompt,imagePart])
]);
await for (final chunk in response) {
print(chunk.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 stream generated text output, call generateContentStream with the text and images
final response = await model.generateContentStream([
Content.multi([prompt, ...imageParts])
]);
await for (final chunk in response) {
print(chunk.text);
}
وحدت
میتوانید GenerateContentStreamAsync()
را فراخوانی کنید تا متن تولید شده را از ورودی چندوجهی متن و تصاویر پخش کنید.
ورودی تک فایل
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 gray = 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 stream generated text output, call GenerateContentStreamAsync and pass in the prompt
var responseStream = model.GenerateContentStreamAsync(new [] { gray, prompt });
await foreach (var response in responseStream) {
if (!string.IsNullOrWhiteSpace(response.Text)) {
UnityEngine.Debug.Log(response.Text);
}
}
ورودی چند فایل
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 black = ModelContent.InlineData("image/png",
UnityEngine.ImageConversion.EncodeToPNG(UnityEngine.Texture2D.blackTexture));
var white = 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 stream generated text output, call GenerateContentStreamAsync and pass in the prompt
var responseStream = model.GenerateContentStreamAsync(new [] { black, white, prompt });
await foreach (var response in responseStream) {
if (!string.IsNullOrWhiteSpace(response.Text)) {
UnityEngine.Debug.Log(response.Text);
}
}
الزامات و توصیهها برای فایلهای تصویری ورودی
توجه داشته باشید که فایلی که به عنوان داده های درون خطی ارائه می شود در حین انتقال روی base64 کدگذاری می شود که حجم درخواست را افزایش می دهد. اگر درخواست خیلی بزرگ باشد، خطای HTTP 413 دریافت می کنید.
برای کسب اطلاعات دقیق در مورد موارد زیر به "فایل های ورودی پشتیبانی شده و الزامات برای Vertex AI Gemini API " مراجعه کنید:
- گزینه های مختلف برای ارائه یک فایل در یک درخواست (به صورت درون خطی یا با استفاده از URL فایل)
- الزامات و بهترین روش ها برای فایل های تصویری
انواع MIME تصویر پشتیبانی شده
مدلهای چند وجهی Gemini از انواع MIME تصویر زیر پشتیبانی میکنند:
نوع MIME تصویر | فلش جمینی 2.0 | 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 : 3000 تصویر
چه کار دیگری می توانید انجام دهید؟
- قبل از ارسال پیام های طولانی به مدل، نحوه شمارش نشانه ها را بیاموزید.
- Cloud Storage for Firebase راهاندازی کنید تا بتوانید فایلهای حجیم را در درخواستهای چندوجهی خود بگنجانید و راهحل مدیریتشدهتری برای ارائه فایلها در درخواستها داشته باشید. فایلها میتوانند شامل تصاویر، PDF، ویدیو و صدا باشند.
- در مورد آماده شدن برای تولید فکر کنید (به چک لیست تولید مراجعه کنید)، از جمله:
- راهاندازی Firebase App Check برای محافظت از Gemini API در برابر سوء استفاده توسط مشتریان غیرمجاز.
- یکپارچه سازی Firebase Remote Config برای به روز رسانی مقادیر در برنامه شما (مانند نام مدل) بدون انتشار نسخه جدید برنامه.
قابلیت های دیگر را امتحان کنید
- مکالمات چند نوبتی (چت) بسازید.
- متن را از اعلانهای فقط متنی ایجاد کنید.
- خروجی ساختاریافته (مانند JSON) را هم از دستورات متنی و هم از چند وجهی ایجاد کنید.
- تولید تصاویر از پیام های متنی
- از فراخوانی تابع برای اتصال مدل های مولد به سیستم ها و اطلاعات خارجی استفاده کنید.
یاد بگیرید چگونه تولید محتوا را کنترل کنید
- طراحی سریع، از جمله بهترین شیوهها، استراتژیها و درخواستهای نمونه را درک کنید .
- پارامترهای مدل مانند دما و نشانههای حداکثر خروجی (برای Gemini ) یا نسبت ابعاد و تولید شخص (برای Imagen ) را پیکربندی کنید.
- از تنظیمات ایمنی برای تنظیم احتمال دریافت پاسخ هایی که ممکن است مضر تلقی شوند استفاده کنید .
درباره مدل های پشتیبانی شده بیشتر بدانید
در مورد مدل های موجود برای موارد استفاده مختلف و سهمیه ها و قیمت آنها اطلاعات کسب کنید.درباره تجربه خود با Firebase AI Logic بازخورد بدهید