When calling the Gemini API from your app using a Vertex AI in Firebase SDK, you can prompt the Gemini model to generate text based on a multimodal input. Multimodal prompts can include multiple modalities (or types of input), like text along with images, PDFs, plain-text files, video, and audio.
In each multimodal request, you must always provide the following:
The file's
mimeType
. Learn about each input file's supported MIME types.The file. You can either provide the file as inline data (as shown on this page) or using its URL or URI.
For testing and iterating on multimodal prompts, we recommend using Vertex AI Studio.
Optionally experiment with an alternative "Google AI" version of the Gemini API
Get free-of-charge access (within limits and where available) using Google AI Studio and Google AI client SDKs. These SDKs should be used for prototyping only in mobile and web apps.After you're familiar with how a Gemini API works, migrate to our Vertex AI in Firebase SDKs (this documentation), which have many additional features important for mobile and web apps, like protecting the API from abuse using Firebase App Check and support for large media files in requests.
Optionally call the Vertex AI Gemini API server-side (like with Python, Node.js, or Go)
Use the server-side Vertex AI SDKs, Genkit, or Firebase Extensions for the Gemini API.
Before you begin
If you haven't already, complete the
getting started guide, which describes how to
set up your Firebase project, connect your app to Firebase, add the SDK,
initialize the Vertex AI service, and create a GenerativeModel
instance.
Generate text from text and a single image Generate text from text and multiple images Generate text from text and a video
Sample media files
If you don't already have media files, then you can use the following publicly
available files. Since these files are stored in buckets that aren't in your
Firebase project, you need to use the
https://storage.googleapis.com/BUCKET_NAME/PATH/TO/FILE
format for the URL.
Image:
https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg
with a MIME type ofimage/jpeg
. View or download this image.PDF:
https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf
with a MIME type ofapplication/pdf
. View or download this PDF.Video:
https://storage.googleapis.com/cloud-samples-data/video/animals.mp4
with a MIME type ofvideo/mp4
. View or download this video.Audio:
https://storage.googleapis.com/cloud-samples-data/generative-ai/audio/pixel.mp3
with a MIME type ofaudio/mp3
. Listen to or download this audio.
Generate text from text and a single image
Make sure that you've completed the Before you begin section of this guide before trying this sample.
You can call the Gemini API with multimodal prompts that include both text and a single file (like an image, as shown in this example).
Make sure to review the requirements and recommendations for input files.
Swift
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and a
single image:
import FirebaseVertexAI
// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()
// Create a `GenerativeModel` instance with a model that supports your use case
let model = vertex.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.")
Kotlin
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and a
single image:
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.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)
Java
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and a
single image:
ListenableFuture
.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
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);
Web
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and a
single image:
import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel } from "firebase/vertexai";
// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(vertexAI, { 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's different between these pictures?";
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();
Dart
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and a
single image:
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
final model =
FirebaseVertexAI.instance.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);
Learn how to choose a model and optionally a location appropriate for your use case and app.
Generate text from text and multiple images
Make sure that you've completed the Before you begin section of this guide before trying this sample.
You can call the Gemini API with multimodal prompts that include both text and multiple files (like images, as shown in this example).
Make sure to review the requirements and recommendations for input files.
Swift
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and
multiple images:
import FirebaseVertexAI
// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()
// Create a `GenerativeModel` instance with a model that supports your use case
let model = vertex.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
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and
multiple images:
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.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
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and
multiple images:
ListenableFuture
.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
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
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and
multiple images:
import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel } from "firebase/vertexai";
// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(vertexAI, { 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
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and
multiple images:
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
final model =
FirebaseVertexAI.instance.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);
Learn how to choose a model and optionally a location appropriate for your use case and app.
Generate text from text and a video
Make sure that you've completed the Before you begin section of this guide before trying this sample.
You can call the Gemini API with multimodal prompts that include both text and video file(s) (as shown in this example).
Make sure to review the requirements and recommendations for input files.
Swift
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and a
single video:
import FirebaseVertexAI
// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()
// Create a `GenerativeModel` instance with a model that supports your use case
let model = vertex.generativeModel(modelName: "gemini-2.0-flash")
// Provide the video as `Data` with the appropriate MIME type.
let video = InlineDataPart(data: try Data(contentsOf: videoURL), mimeType: "video/mp4")
// Provide a text prompt to include with the video
let prompt = "What is in the video?"
// To generate text output, call generateContent with the text and video
let response = try await model.generateContent(video, prompt)
print(response.text ?? "No text in response.")
Kotlin
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and a
single video:
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.generativeModel("gemini-2.0-flash")
val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
stream?.let {
val bytes = stream.readBytes()
// Provide a prompt that includes the video specified above and text
val prompt = content {
inlineData(bytes, "video/mp4")
text("What is in the video?")
}
// To generate text output, call generateContent with the prompt
val response = generativeModel.generateContent(prompt)
Log.d(TAG, response.text ?: "")
}
}
Java
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and a
single video:
ListenableFuture
.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(videoUri)) {
File videoFile = new File(new URI(videoUri.toString()));
int videoSize = (int) videoFile.length();
byte[] videoBytes = new byte[videoSize];
if (stream != null) {
stream.read(videoBytes, 0, videoBytes.length);
stream.close();
// Provide a prompt that includes the video specified above and text
Content prompt = new Content.Builder()
.addInlineData(videoBytes, "video/mp4")
.addText("What is in the video?")
.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);
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Web
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and a
single video:
import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel } from "firebase/vertexai";
// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(vertexAI, { 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 video
const prompt = "What do you see?";
const fileInputEl = document.querySelector("input[type=file]");
const videoPart = await fileToGenerativePart(fileInputEl.files[0]);
// To generate text output, call generateContent with the text and video
const result = await model.generateContent([prompt, videoPart]);
const response = result.response;
const text = response.text();
console.log(text);
}
run();
Dart
You can call
generateContent()
to generate text from a multimodal prompt request that includes text and a
single video:
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
final model =
FirebaseVertexAI.instance.generativeModel(model: 'gemini-2.0-flash');
// Provide a text prompt to include with the video
final prompt = TextPart("What's in the video?");
// Prepare video for input
final video = await File('video0.mp4').readAsBytes();
// Provide the video as `Data` with the appropriate mimetype
final videoPart = InlineDataPart('video/mp4', video);
// To generate text output, call generateContent with the text and images
final response = await model.generateContent([
Content.multi([prompt, ...videoPart])
]);
print(response.text);
Learn how to choose a model and optionally a location appropriate for your use case and app.
Stream the response
Make sure that you've completed the Before you begin section of this guide before trying these samples.
You can achieve faster interactions by not waiting for the entire result from
the model generation, and instead use streaming to handle partial results.
To stream the response, call generateContentStream
.
Swift
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and a single image:
import FirebaseVertexAI
// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()
// Create a `GenerativeModel` instance with a model that supports your use case
let model = vertex.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)
}
}
Kotlin
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and a single image:
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.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
}
Java
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and a single image:
Publisher
type from the Reactive Streams library.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
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) {
}
});
Web
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and a single image:
import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel } from "firebase/vertexai";
// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(vertexAI, { 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();
Dart
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and a single image:
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
final model =
FirebaseVertexAI.instance.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);
}
Swift
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and multiple images:
import FirebaseVertexAI
// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()
// Create a `GenerativeModel` instance with a model that supports your use case
let model = vertex.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
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and multiple images:
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.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
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and multiple images:
Publisher
type from the Reactive Streams library.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
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
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and multiple images:
import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel } from "firebase/vertexai";
// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(vertexAI, { 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
This example shows how to use
generateContentStream
to stream generated text from a multimodal prompt request that includes text
and multiple images:
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
final model =
FirebaseVertexAI.instance.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);
}
Swift
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and a single video:
import FirebaseVertexAI
// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()
// Create a `GenerativeModel` instance with a model that supports your use case
let model = vertex.generativeModel(modelName: "gemini-2.0-flash")
// Provide the video as `Data` with the appropriate MIME type
let video = InlineDataPart(data: try Data(contentsOf: videoURL), mimeType: "video/mp4")
// Provide a text prompt to include with the video
let prompt = "What is in the video?"
// To stream generated text output, call generateContentStream with the text and video
let contentStream = try model.generateContentStream(video, prompt)
for try await chunk in contentStream {
if let text = chunk.text {
print(text)
}
}
Kotlin
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and a single video:
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.generativeModel("gemini-2.0-flash")
val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
stream?.let {
val bytes = stream.readBytes()
// Provide a prompt that includes the video specified above and text
val prompt = content {
inlineData(bytes, "video/mp4")
text("What is in the video?")
}
// To stream generated text output, call generateContentStream with the prompt
var fullResponse = ""
generativeModel.generateContentStream(prompt).collect { chunk ->
Log.d(TAG, chunk.text ?: "")
fullResponse += chunk.text
}
}
}
Java
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and a single video:
Publisher
type from the Reactive Streams library.
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(videoUri)) {
File videoFile = new File(new URI(videoUri.toString()));
int videoSize = (int) videoFile.length();
byte[] videoBytes = new byte[videoSize];
if (stream != null) {
stream.read(videoBytes, 0, videoBytes.length);
stream.close();
// Provide a prompt that includes the video specified above and text
Content prompt = new Content.Builder()
.addInlineData(videoBytes, "video/mp4")
.addText("What is in the video?")
.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) {
}
});
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Web
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and a single video:
import { initializeApp } from "firebase/app";
import { getVertexAI, getGenerativeModel } from "firebase/vertexai";
// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(vertexAI, { 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 video
const prompt = "What do you see?";
const fileInputEl = document.querySelector("input[type=file]");
const videoPart = await fileToGenerativePart(fileInputEl.files[0]);
// To stream generated text output, call generateContentStream with the text and video
const result = await model.generateContentStream([prompt, videoPart]);
for await (const chunk of result.stream) {
const chunkText = chunk.text();
console.log(chunkText);
}
}
run();
Dart
You can call
generateContentStream()
to stream generated text from a multimodal prompt request that includes text
and a single video:
import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
final model =
FirebaseVertexAI.instance.generativeModel(model: 'gemini-2.0-flash');
// Provide a text prompt to include with the video
final prompt = TextPart("What's in the video?");
// Prepare video for input
final video = await File('video0.mp4').readAsBytes();
// Provide the video as `Data` with the appropriate mimetype
final videoPart = InlineDataPart('video/mp4', video);
// To stream generated text output, call generateContentStream with the text and image
final response = await model.generateContentStream([
Content.multi([prompt,videoPart])
]);
await for (final chunk in response) {
print(chunk.text);
}
Requirements and recommendations for input files
See Supported input files and requirements for the Vertex AI Gemini API to learn about the following:
- Different options for providing a file in a request
- Supported file types
- Supported MIME types and how to specify them
- Requirements and best practices for files and multimodal requests
What else can you do?
- Learn how to count tokens before sending long prompts to the model.
- Set up Cloud Storage for Firebase so that you can include large files in your multimodal requests and have a more managed solution for providing files in prompts. Files can include images, PDFs, video, and audio.
- Start thinking about preparing for production, including setting up Firebase App Check to protect the Gemini API from abuse by unauthorized clients. Also, make sure to review the production checklist.
Try out other capabilities
- Build multi-turn conversations (chat).
- Generate text from text-only prompts.
- Generate structured output (like JSON) from both text and multimodal prompts.
- Generate images from text prompts.
- Use function calling to connect generative models to external systems and information.
Learn how to control content generation
- Understand prompt design, including best practices, strategies, and example prompts.
- Configure model parameters like temperature and maximum output tokens (for Gemini) or aspect ratio and person generation (for Imagen).
- Use safety settings to adjust the likelihood of getting responses that may be considered harmful.
Learn more about the supported models
Learn about the models available for various use cases and their quotas and pricing.Give feedback about your experience with Vertex AI in Firebase