Gemini API を使用してマルチモーダル プロンプトからテキストを生成する

Vertex AI in Firebase SDK を使用してアプリから Gemini API を呼び出すときに、マルチモーダル入力に基づいてテキストを生成するように Gemini モデルにプロンプトを出すことができます。マルチモーダル プロンプトには、テキスト、画像、PDF、テキスト ファイル、動画、音声など、複数のモダリティ(または入力タイプ)を含めることができます。

各マルチモーダル リクエストで、必ず次の情報を指定する必要があります。

  • ファイルの mimeType。各入力ファイルでサポートされている MIME タイプについて確認する。

  • ファイル。ファイルは、(このページに示すように)インライン データとして指定することも、URL または URI を使用して指定することもできます。

マルチモーダル プロンプトのテストと反復処理には、Vertex AI Studio を使用することをおすすめします。

始める前に

まだ行っていない場合は、スタートガイドを完了してください。Firebase プロジェクトの設定、アプリの Firebase への接続、SDK の追加、Vertex AI サービスの初期化、GenerativeModel インスタンスの作成方法が記載されています。

テキストと 1 つの画像からテキストを生成する テキストと複数の画像からテキストを生成する テキストと動画からテキストを生成する

サンプル メディア ファイル

メディア ファイルがない場合は、次の一般公開ファイルを使用できます。これらのファイルは Firebase プロジェクトにないバケットに保存されているため、URL には https://storage.googleapis.com/BUCKET_NAME/PATH/TO/FILE 形式を使用する必要があります。

テキストと 1 つの画像からテキストを生成する

このサンプルを試す前に、このガイドの始める前にのセクションを完了していることを確認してください。

Gemini API は、テキストと単一のファイル(この例の画像など)の両方を含むマルチモーダル プロンプトで呼び出すことができます。

入力ファイルの要件と推奨事項を確認してください。

Swift

generateContent() を呼び出して、テキストと 1 つの画像を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

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

generateContent() を呼び出して、テキストと 1 つの画像を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

Kotlin の場合、この SDK のメソッドは suspend 関数であり、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

generateContent() を呼び出して、テキストと 1 つの画像を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

Java の場合、この SDK のメソッドは 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

generateContent() を呼び出して、テキストと 1 つの画像を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

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

generateContent() を呼び出して、テキストと 1 つの画像を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

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

ユースケースとアプリに適したモデルと、必要に応じてロケーションを選択する方法を学びます。

テキストと複数の画像からテキストを生成する

このサンプルを試す前に、このガイドの始める前にのセクションを完了していることを確認してください。

Gemini API は、テキストと複数のファイル(この例の画像など)の両方を含むマルチモーダル プロンプトで呼び出すことができます。

入力ファイルの要件と推奨事項を確認してください。

Swift

generateContent() を呼び出して、テキストと複数の画像を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

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

generateContent() を呼び出して、テキストと複数の画像を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

Kotlin の場合、この SDK のメソッドは suspend 関数であり、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

generateContent() を呼び出して、テキストと複数の画像を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

Java の場合、この SDK のメソッドは 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

generateContent() を呼び出して、テキストと複数の画像を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

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

generateContent() を呼び出して、テキストと複数の画像を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

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

ユースケースとアプリに適したモデルと、必要に応じてロケーションを選択する方法を学びます。

テキストと動画からテキストを生成する

このサンプルを試す前に、このガイドの始める前にのセクションを完了していることを確認してください。

テキスト ファイルと動画ファイルの両方を含むマルチモーダル プロンプトを使用して Gemini API を呼び出すことができます(この例を参照)。

入力ファイルの要件と推奨事項を確認してください。

Swift

generateContent() を呼び出して、テキストと 1 つの動画を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

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

generateContent() を呼び出して、テキストと 1 つの動画を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

Kotlin の場合、この SDK のメソッドは suspend 関数であり、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

generateContent() を呼び出して、テキストと 1 つの動画を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

Java の場合、この SDK のメソッドは 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

generateContent() を呼び出して、テキストと 1 つの動画を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

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

generateContent() を呼び出して、テキストと 1 つの動画を含むマルチモーダル プロンプト リクエストからテキストを生成できます。

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

ユースケースとアプリに適したモデルと、必要に応じてロケーションを選択する方法を学びます。

レスポンスをストリーミングする

これらのサンプルを試す前に、このガイドの始める前にのセクションを完了していることを確認してください。

モデル生成の結果全体を待たずに、ストリーミングを使用して部分的な結果を処理することで、インタラクションを高速化できます。レスポンスをストリーミングするには、generateContentStream を呼び出します。



入力ファイルの要件と推奨事項

以下については、Gemini API in Vertex AI のサポートされている入力ファイルと要件をご覧ください。

  • リクエストでファイルを提供するさまざまな方法
  • サポートされているファイル形式
  • サポートされている MIME タイプとその指定方法
  • ファイルとマルチモーダル リクエストの要件とベスト プラクティス



Google アシスタントの機能

その他の機能を試す

コンテンツ生成を制御する方法

Vertex AI Studio を使用して、プロンプトとモデル構成をテストすることもできます。

サポートされているモデルの詳細

さまざまなユースケースで利用可能なモデルと、その割り当て料金について学びます。


Vertex AI in Firebase の使用感に関するフィードバックを送信する