Membuat teks dari perintah multimodal menggunakan Gemini API

Saat memanggil Gemini API dari aplikasi menggunakan Vertex AI in Firebase SDK, Anda dapat meminta model Gemini untuk membuat teks berdasarkan input multimodal. Perintah multimodal dapat mencakup beberapa modalitas (atau jenis input), seperti teks beserta gambar, PDF, file teks biasa, video, dan audio.

Dalam setiap permintaan multimodal, Anda harus selalu memberikan hal berikut:

  • mimeType file. Pelajari setiap jenis MIME file input yang didukung.

  • File. Anda dapat memberikan file sebagai data inline (seperti yang ditunjukkan di halaman ini) atau menggunakan URL atau URI-nya.

Untuk menguji dan melakukan iterasi pada perintah multimodal, sebaiknya gunakan Vertex AI Studio.

Sebelum memulai

Jika Anda belum melakukannya, selesaikan panduan memulai, yang menjelaskan cara menyiapkan project Firebase, menghubungkan aplikasi ke Firebase, menambahkan SDK, menginisialisasi layanan Vertex AI, dan membuat instance GenerativeModel.

Membuat teks dari teks dan satu gambar Membuat teks dari teks dan beberapa gambar Membuat teks dari teks dan video

Contoh file media

Jika belum memiliki file media, Anda dapat menggunakan file berikut yang tersedia secara publik. Karena file ini disimpan di bucket yang tidak ada dalam project Firebase Anda, Anda harus menggunakan format https://storage.googleapis.com/BUCKET_NAME/PATH/TO/FILE untuk URL.

  • Gambar: https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg dengan jenis MIME image/jpeg. Lihat atau download gambar ini.

  • PDF: https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf dengan jenis MIME application/pdf. Lihat atau download PDF ini.

  • Video: https://storage.googleapis.com/cloud-samples-data/video/animals.mp4 dengan jenis MIME video/mp4. Tonton atau download video ini.

  • Audio: https://storage.googleapis.com/cloud-samples-data/generative-ai/audio/pixel.mp3 dengan jenis MIME audio/mp3. Dengarkan atau download audio ini.

Membuat teks dari teks dan satu gambar

Pastikan Anda telah menyelesaikan bagian Sebelum memulai dalam panduan ini sebelum mencoba contoh ini.

Anda dapat memanggil Gemini API dengan perintah multimodal yang menyertakan teks dan satu file (seperti gambar, seperti yang ditunjukkan dalam contoh ini).

Pastikan untuk meninjau persyaratan dan rekomendasi untuk file input.

Swift

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan satu gambar:

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

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan satu gambar:

Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil dari Cakupan coroutine.
// 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

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan satu gambar:

Untuk Java, metode dalam SDK ini menampilkan 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

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan satu gambar:

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

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan satu gambar:

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);

Pelajari cara memilih model dan secara opsional lokasi yang sesuai untuk kasus penggunaan dan aplikasi Anda.

Membuat teks dari teks dan beberapa gambar

Pastikan Anda telah menyelesaikan bagian Sebelum memulai dalam panduan ini sebelum mencoba contoh ini.

Anda dapat memanggil Gemini API dengan perintah multimodal yang menyertakan teks dan beberapa file (seperti gambar, seperti yang ditunjukkan dalam contoh ini).

Pastikan untuk meninjau persyaratan dan rekomendasi untuk file input.

Swift

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan beberapa gambar:

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

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan beberapa gambar:

Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil dari Cakupan coroutine.
// 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

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan beberapa gambar:

Untuk Java, metode dalam SDK ini menampilkan 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

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan beberapa gambar:

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

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan beberapa gambar:

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);

Pelajari cara memilih model dan secara opsional lokasi yang sesuai untuk kasus penggunaan dan aplikasi Anda.

Membuat teks dari teks dan video

Pastikan Anda telah menyelesaikan bagian Sebelum memulai dalam panduan ini sebelum mencoba contoh ini.

Anda dapat memanggil Gemini API dengan perintah multimodal yang menyertakan file teks dan video (seperti yang ditunjukkan dalam contoh ini).

Pastikan untuk meninjau persyaratan dan rekomendasi untuk file input.

Swift

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan satu 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

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan satu video:

Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil dari Cakupan coroutine.
// 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

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan satu video:

Untuk Java, metode dalam SDK ini menampilkan 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

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan satu 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

Anda dapat memanggil generateContent() untuk membuat teks dari permintaan perintah multimodal yang menyertakan teks dan satu 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);

Pelajari cara memilih model dan secara opsional lokasi yang sesuai untuk kasus penggunaan dan aplikasi Anda.

Menampilkan respons secara bertahap

Pastikan Anda telah menyelesaikan bagian Sebelum memulai dalam panduan ini sebelum mencoba contoh ini.

Anda dapat mencapai interaksi yang lebih cepat dengan tidak menunggu seluruh hasil dari pembuatan model, dan sebagai gantinya menggunakan streaming untuk menangani hasil sebagian. Untuk melakukan streaming respons, panggil generateContentStream.



Persyaratan dan rekomendasi untuk file input

Lihat File input dan persyaratan yang didukung untuk Gemini API in Vertex AI untuk mempelajari hal berikut:

  • Berbagai opsi untuk memberikan file dalam permintaan
  • Jenis file yang didukung
  • Jenis MIME yang didukung dan cara menentukannya
  • Persyaratan dan praktik terbaik untuk file dan permintaan multimodal



Kamu bisa apa lagi?

  • Pelajari cara menghitung token sebelum mengirim perintah panjang ke model.
  • Siapkan Cloud Storage for Firebase agar Anda dapat menyertakan file besar dalam permintaan multimodal dan memiliki solusi yang lebih terkelola untuk menyediakan file dalam perintah. File dapat mencakup gambar, PDF, video, dan audio.
  • Mulailah memikirkan persiapan produksi, termasuk menyiapkan Firebase App Check untuk melindungi Gemini API dari penyalahgunaan oleh klien yang tidak sah. Selain itu, pastikan untuk meninjau checklist produksi.

Mencoba kemampuan lain

Pelajari cara mengontrol pembuatan konten

Anda juga dapat bereksperimen dengan perintah dan konfigurasi model menggunakan Vertex AI Studio.

Pelajari lebih lanjut model yang didukung

Pelajari model yang tersedia untuk berbagai kasus penggunaan serta kuota dan harga-nya.


Berikan masukan tentang pengalaman Anda dengan Vertex AI in Firebase