Gemini API を使用してテキストを生成する

Gemini モデルに、テキストのみのプロンプトまたはマルチモーダル プロンプトからテキストを生成するよう指示できます。Vertex AI in Firebase を使用する場合は、アプリから直接このリクエストを行うことができます。

マルチモーダル プロンプトには、複数の種類の入力(テキスト、画像、PDF、テキスト ファイル、音声、動画など)を含めることができます。

このガイドでは、テキストのみのプロンプトと、ファイルを含む基本的なマルチモーダル プロンプトからテキストを生成する方法について説明します。

テキストのみの入力のコードサンプルに移動 マルチモーダル入力のコードサンプルに移動


テキストを操作するためのその他のオプションについては、他のガイドをご覧ください
構造化出力を生成する マルチターン チャット 双方向ストリーミング テキストから画像を生成する

始める前に

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

プロンプトのテストと反復処理、生成されたコード スニペットの取得には、Vertex AI Studio を使用することをおすすめします。

テキストの送受信

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

テキストのみの入力でプロンプトを与えることで、Gemini モデルにテキストの生成を依頼できます。

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

// Provide a prompt that contains text
let prompt = "Write a story about a magic backpack."

// To generate text output, call generateContent with the text input
let response = try await model.generateContent(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")

// Provide a prompt that contains text
val prompt = "Write a story about a magic backpack."

// To generate text output, call generateContent with the text input
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);

// Provide a prompt that contains text
Content prompt = new Content.Builder()
    .addText("Write a story about a magic backpack.")
    .build();

// To generate text output, call generateContent with the text input
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" });

// Wrap in an async function so you can use await
async function run() {
  // Provide a prompt that contains text
  const prompt = "Write a story about a magic backpack."

  // To generate text output, call generateContent with the text input
  const result = await model.generateContent(prompt);

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

// Provide a prompt that contains text
final prompt = [Content.text('Write a story about a magic backpack.')];

// To generate text output, call generateContent with the text input
final response = await model.generateContent(prompt);
print(response.text);

テキストとファイルを送信(マルチモーダル)してテキストを受信する

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

テキストとファイルでプロンプトを与えることで、Gemini モデルにテキストの生成を依頼できます。各入力ファイルの mimeType とファイル自体を指定します。入力ファイルの要件と推奨事項については、このページの下部をご覧ください。

次の例は、インライン データ(Base64 エンコード ファイル)として提供された単一の動画ファイルを分析して、ファイル入力からテキストを生成する方法の基本を示しています。

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

// 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() を呼び出して、テキスト ファイルと動画ファイルのマルチモーダル入力からテキストを生成できます。

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() を呼び出して、テキスト ファイルと動画ファイルのマルチモーダル入力からテキストを生成できます。

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() を呼び出して、テキスト ファイルと動画ファイルのマルチモーダル入力からテキストを生成できます。

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() を呼び出して、テキスト ファイルと動画ファイルのマルチモーダル入力からテキストを生成できます。

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 を呼び出します。



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

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

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



Google アシスタントの機能

その他の機能を試す

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

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

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

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


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