Firebase SDK の Vertex AI を使用して Gemini API を使ってみる

このガイドでは、選択したプラットフォームの Vertex AI in Firebase SDK を使用して、アプリから直接 Vertex AI Gemini API を呼び出す方法について説明します。

このガイドは、Vertex AI in Firebase SDK を使用して Imagen モデルにアクセスする際にも使用できます。

前提条件

Swift

このガイドは、Xcode を使用して Apple プラットフォーム(iOS など)向けのアプリを開発することに精通していることを前提としています。

  • 開発環境と Apple プラットフォーム アプリが次の要件を満たしていることを確認します。

    • Xcode 16.2 以降
    • アプリが iOS 15 以降または macOS 12 以降をターゲットにしている
  • (省略可)サンプルアプリを確認する。

    クイックスタート アプリをダウンロードする

    SDK を簡単に試したり、さまざまなユースケースの完全な実装を確認したり、独自の Apple プラットフォーム アプリがない場合はサンプルアプリを使用したりできます。サンプルアプリを使用するには、サンプルアプリを Firebase プロジェクトに接続する必要があります。

Kotlin

このガイドは、Android Studio を使用した Android 向けアプリの開発に精通していることを前提としています。

  • 開発環境と Android アプリが次の要件を満たしていることを確認します。

    • Android Studio(最新バージョン)
    • アプリが API レベル 21 以降をターゲットにしていること
  • (省略可)サンプルアプリを確認する。

    サンプルアプリをダウンロードする

    SDK を簡単に試したり、さまざまなユースケースの完全な実装を確認したり、独自の Android アプリがない場合はサンプルアプリを使用したりできます。サンプルアプリを使用するには、サンプルアプリを Firebase プロジェクトに接続する必要があります。

Java

このガイドは、Android Studio を使用した Android 向けアプリの開発に精通していることを前提としています。

  • 開発環境と Android アプリが次の要件を満たしていることを確認します。

    • Android Studio(最新バージョン)
    • アプリが API レベル 21 以降をターゲットにしていること
  • (省略可)サンプルアプリを確認する。

    サンプルアプリをダウンロードする

    SDK を簡単に試したり、さまざまなユースケースの完全な実装を確認したり、独自の Android アプリがない場合はサンプルアプリを使用したりできます。サンプルアプリを使用するには、サンプルアプリを Firebase プロジェクトに接続する必要があります。

Web

このガイドは、JavaScript を使用したウェブアプリ開発に精通していることを前提としています。このガイドはフレームワークに依存していません。

  • 開発環境とウェブアプリが次の要件を満たしていることを確認します。

    • (省略可)Node.js
    • 最新のウェブブラウザ
  • (省略可)サンプルアプリを確認する。

    サンプルアプリをダウンロードする

    SDK を簡単に試したり、さまざまなユースケースの実装を確認したり、独自のウェブアプリがない場合はサンプルアプリを使用したりできます。サンプルアプリを使用するには、Firebase プロジェクトに接続する必要があります。

Dart

このガイドは、Flutter を使用したアプリ開発に精通していることを前提としています。

  • 開発環境と Flutter アプリが次の要件を満たしていることを確認します。

    • Dart 3.2.0 以降
  • (省略可)サンプルアプリを確認する。

    サンプルアプリをダウンロードする

    SDK を簡単に試したり、さまざまなユースケースの完全な実装を確認したり、独自の Flutter アプリがない場合はサンプルアプリを使用したりできます。サンプルアプリを使用するには、Firebase プロジェクトに接続する必要があります。

ステップ 1: Firebase プロジェクトを設定し、アプリを Firebase に接続する

Firebase プロジェクトと Firebase に接続されたアプリがすでにある場合

  1. Firebase コンソールで、Vertex AI ページに移動します。

  2. [Vertex AI in Firebase] カードをクリックして、次のタスクを完了するためのワークフローを開始します。

  3. このガイドの次のステップに進んで、SDK をアプリに追加します。

Firebase プロジェクトと Firebase に接続されたアプリがまだない場合


ステップ 2: SDK を追加する

Firebase プロジェクトが設定され、アプリが Firebase に接続されている(前の手順を参照)ので、Vertex AI in Firebase SDK をアプリに追加できます。

Swift

Swift Package Manager を使用して Firebase の依存関係のインストールと管理を行います。

Vertex AI in Firebase ライブラリは、Gemini モデルと Imagen モデルを操作するための API へのアクセスを提供します。このライブラリは、Apple プラットフォーム向け Firebase SDK(firebase-ios-sdk)の一部として含まれています。

  1. Xcode でアプリのプロジェクトを開いたまま、[File] > [Add Packages] の順に移動します。

  2. プロンプトが表示されたら、Firebase Apple プラットフォーム SDK リポジトリを追加します。

    https://github.com/firebase/firebase-ios-sdk
    
  3. 最新の SDK バージョンを選択します。

  4. FirebaseVertexAI ライブラリを選択します。

上記の作業が完了すると、Xcode は依存関係の解決とバックグラウンドでのダウンロードを自動的に開始します。

Kotlin

Vertex AI in Firebase SDK for Android(firebase-vertexai)は、Gemini モデルと Imagen モデルを操作するための API へのアクセスを提供します。

モジュール(アプリレベル)の Gradle ファイル<project>/<app-module>/build.gradle.kts など)に、Android 用 Vertex AI in Firebase ライブラリの依存関係を追加します。ライブラリのバージョニングの制御には、Firebase Android BoM を使用することをおすすめします。

dependencies {
  // ... other androidx dependencies

  // Import the BoM for the Firebase platform
  implementation(platform("com.google.firebase:firebase-bom:33.13.0"))

  // Add the dependency for the Vertex AI in Firebase library
  // When using the BoM, you don't specify versions in Firebase library dependencies
  implementation("com.google.firebase:firebase-vertexai")
}

Firebase Android BoM を使用すると、アプリは常に互換性のあるバージョンの Firebase Android ライブラリを使用します。

Java

Vertex AI in Firebase SDK for Android(firebase-vertexai)は、Gemini モデルと Imagen モデルを操作するための API へのアクセスを提供します。

モジュール(アプリレベル)の Gradle ファイル<project>/<app-module>/build.gradle.kts など)に、Android 用 Vertex AI in Firebase ライブラリの依存関係を追加します。ライブラリのバージョニングの制御には、Firebase Android BoM を使用することをおすすめします。

Java の場合は、2 つのライブラリを追加する必要があります。

dependencies {
  // ... other androidx dependencies

  // Import the BoM for the Firebase platform
  implementation(platform("com.google.firebase:firebase-bom:33.13.0"))

  // Add the dependency for the Vertex AI in Firebase library
  // When using the BoM, you don't specify versions in Firebase library dependencies
  implementation("com.google.firebase:firebase-vertexai")

  // Required for one-shot operations (to use `ListenableFuture` from Guava Android)
  implementation("com.google.guava:guava:31.0.1-android")

  // Required for streaming operations (to use `Publisher` from Reactive Streams)
  implementation("org.reactivestreams:reactive-streams:1.0.4")
}

Firebase Android BoM を使用すると、アプリは常に互換性のあるバージョンの Firebase Android ライブラリを使用します。

Web

Vertex AI in Firebase ライブラリは、Gemini モデルと Imagen モデルを操作するための API へのアクセスを提供します。このライブラリは、Firebase JavaScript SDK for Web の一部として含まれています。

  1. npm を使用して Firebase JS SDK for Web をインストールします。

    npm install firebase
    
  2. アプリで Firebase を初期化します。

    import { initializeApp } from "firebase/app";
    
    // 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);
    

Dart

Flutter 用の Vertex AI in Firebase プラグイン(firebase_vertexai)は、Gemini モデルと Imagen モデルを操作するための API へのアクセスを提供します。

  1. Flutter プロジェクト ディレクトリで、次のコマンドを実行してコア プラグインと Vertex AI in Firebase プラグインをインストールします。

    flutter pub add firebase_core && flutter pub add firebase_vertexai
    
  2. lib/main.dart ファイルで、Firebase Core プラグイン、Vertex AI in Firebase プラグイン、および前に生成した構成ファイルをインポートします。

    import 'package:firebase_core/firebase_core.dart';
    import 'package:firebase_vertexai/firebase_vertexai.dart';
    import 'firebase_options.dart';
    
  3. また、lib/main.dart ファイルで、構成ファイルによってエクスポートされた DefaultFirebaseOptions オブジェクトを使用して Firebase を初期化します。

    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
    
  4. Flutter アプリケーションを再ビルドします。

    flutter run
    

ステップ 3: Vertex AI サービスを初期化して GenerativeModel インスタンスを作成する

API 呼び出しを行い、Gemini モデルにプロンプトを送信するには、Vertex AI サービスを初期化して GenerativeModel インスタンスを作成する必要があります。

Swift

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

Kotlin

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

Java

Java の場合、この SDK のストリーミング メソッドは Reactive Streams ライブラリPublisher 型を返します。
// 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");

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

Web

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

Dart

import 'package:firebase_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
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');

このスタートガイドを完了したら、ユースケースとアプリに適したモデルと(必要に応じて)ロケーションを選択する方法を学びます。

ステップ 4: モデルにプロンプト リクエストを送信する

アプリを Firebase に接続し、SDK を追加して、Vertex AI サービスと生成モデルを初期化したので、Gemini モデルにプロンプト リクエストを送信する準備が整いました。

generateContent() を使用すると、テキストのみのプロンプト リクエストからテキストを生成できます。

Swift

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

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

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

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

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

Google アシスタントの機能

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

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

その他の機能を試す

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

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


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