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

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

このガイドは、Firebase AI Logic 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 プロジェクトに接続する必要があります。

Unity

このガイドは、Unity を使用したゲーム開発に精通していることを前提としています。

  • 開発環境と Unity ゲームが次の要件を満たしていることを確認します。

    • Unity エディタ 2021 LTS 以降
  • (省略可)サンプルアプリを確認する。

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

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

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

  1. Firebase コンソールにログインし、Firebase プロジェクトを選択します。

  2. Firebase コンソールで、[Firebase AI Logic] ページに移動します。

  3. [使ってみる] をクリックして、プロジェクトに必要な API とリソースを設定するガイド付きワークフローを開始します。

  4. Firebase AI Logic SDK で使用する「Gemini API」プロバイダを選択します。必要に応じて、後で他の API プロバイダを設定して使用できます。

    • Gemini Developer API - 課金は任意(無料の Spark 料金プランで利用可能)
      コンソールでは、必要な API が有効になり、プロジェクトに Gemini API キーが作成されます。
      この Gemini API キーをアプリのコードベースに追加しないでください詳細

      料金プランをアップグレードする場合は、後で請求を設定できます。

    • Vertex AI Gemini API - 課金システムが必要(従量課金制の Blaze 料金プランが必要)
      コンソールを使用すると、課金システムを設定したり、プロジェクトで必要な API を有効にしたりできます。

  5. コンソールのワークフローでプロンプトが表示されたら、画面上の指示に沿ってアプリを登録し、Firebase に接続します。

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

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

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

Swift

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

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

Firebase をすでに使用している場合は、Firebase パッケージが v11.13.0 以降であることを確認します。

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

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

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

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

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

Kotlin

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

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

dependencies {
  // ... other androidx dependencies

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

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

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

Java

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

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

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

dependencies {
  // ... other androidx dependencies

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

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

  // 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

Firebase AI Logic ライブラリは、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 の Firebase AI Logic プラグイン(firebase_ai)は、Gemini モデルと Imagen モデルを操作するための API へのアクセスを提供します。

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

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

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

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

    flutter run
    

Unity

  1. Firebase Unity SDK をダウンロードし、適切な場所に展開します。

    Firebase Unity SDK はプラットフォーム固有ではありません。

  2. 開いている Unity プロジェクトで、[Assets] > [Import Package] > [Custom Package] を選択します。

  3. 解凍した SDK から FirebaseAI パッケージを選択します。

  4. [Import Unity Package] ウィンドウで [Import] をクリックします。

  5. Firebase コンソールの設定ワークフローに戻り、[次へ] をクリックします。

ステップ 3: サービスを初期化してモデル インスタンスを作成する

Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。

Gemini Developer APIFirebase AI Logic クライアント SDK を使用する場合は、Gemini API キーをアプリのコードベースに追加しないでください詳細

Gemini モデルにプロンプトを送信する前に、選択した API プロバイダのサービスを選択し、GenerativeModel インスタンスを作成します。

Swift


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(modelName: "gemini-2.0-flash")

Kotlin


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-2.0-flash")

Java


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-2.0-flash");

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

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// 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 Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, { model: "gemini-2.0-flash" });

Dart


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

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-2.0-flash');

Unity


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");

使用している機能によっては、GenerativeModel インスタンスを作成しない場合があることに注意してください。

また、このスタートガイドを完了したら、ユースケースとアプリに適したモデルを選択する方法を学びます。

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

これで、Gemini モデルにプロンプト リクエストを送信する準備が整いました。

generateContent() を使用すると、テキストを含むプロンプトからテキストを生成できます。

Swift


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.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 Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .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 Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-2.0-flash");

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

// 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 { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// 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 Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, { 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_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
      FirebaseAI.googleAI().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);

Unity


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");

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

// To generate text output, call GenerateContentAsync with the text input
var response = await model.GenerateContentAsync(prompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

Google アシスタントの機能

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

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

その他の機能を試す

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

プロンプトとモデル構成をテストしたり、Google AI Studio を使用して生成されたコード スニペットを取得したりすることもできます。


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