Gemini Developer API

Gemini Pro モデルと Flash モデルにアクセスするには、Android デベロッパーは Firebase AI Logic を使用して Gemini Developer API を使用することをおすすめします。クレジット カードなしで利用を開始でき、無料枠が充実しています。小規模なユーザーベースで統合を検証したら、有料の階層に切り替えてスケーリングできます。

Firebase Android SDK を含む Android アプリのイラスト。矢印は、SDK から Cloud 環境内の Firebase を指しています。Firebase から、別の矢印が Gemini Developer API を指しています。これは、Cloud 内の Gemini Pro と Flash に接続されています。
図 1. Gemini Developer API にアクセスするための Firebase AI Logic 統合アーキテクチャ。

スタートガイド

アプリから Gemini API を直接操作する前に、プロンプトの使用方法を学び、Firebase とアプリを設定して SDK を使用できるようにする必要があります。

プロンプトで試す

プロンプトをテストすると、Android アプリに最適なフレーズ、コンテンツ、形式を見つけることができます。Google AI Studio は、アプリのユースケースに合わせてプロンプトのプロトタイプを作成して設計できる IDE です。

ユースケースに適したプロンプトを作成することは、科学というよりは芸術に近く、そのためテストが重要になります。プロンプトについて詳しくは、Firebase のドキュメントをご覧ください。

プロンプトに問題がなければ、[<>] ボタンをクリックして、コードに追加できるコード スニペットを取得します。

Firebase プロジェクトを設定し、アプリを Firebase に接続する

アプリから API を呼び出す準備ができたら、Firebase AI Logic スタートガイドの「ステップ 1」の手順に沿って、アプリで Firebase と SDK を設定します。

Gradle 依存関係を追加する

アプリ モジュールに次の Gradle 依存関係を追加します。

Kotlin

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 Firebase AI Logic library When using the BoM,
  // you don't specify versions in Firebase library dependencies
  implementation("com.google.firebase:firebase-ai")
}

Java

dependencies {
  // Import the BoM for the Firebase platform
  implementation(platform("com.google.firebase:firebase-bom:33.13.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")
}

生成モデルを初期化する

まず、GenerativeModel をインスタンス化し、モデル名を指定します。

Kotlin

val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-2.0-flash")

Java

GenerativeModel firebaseAI = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-2.0-flash");

GenerativeModelFutures model = GenerativeModelFutures.from(firebaseAI);

Gemini Developer API で使用できるモデルの詳細を確認する。モデル パラメータの構成の詳細も併せてご覧ください。

アプリから Gemini Developer API を操作する

SDK を使用するように Firebase とアプリを設定したので、アプリから Gemini Developer API を操作する準備が整いました。

テキストを生成

テキスト レスポンスを生成するには、プロンプトを使用して generateContent() を呼び出します。

Kotlin

scope.launch {
  val response = model.generateContent("Write a story about a magic backpack.")
}

Java

Content prompt = new Content.Builder()
    .addText("Write a story about a magic backpack.")
    .build();

ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        [...]
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

画像やその他のメディアからテキストを生成する

テキストと画像などのメディアを含むプロンプトからテキストを生成することもできます。generateContent() を呼び出すときに、メディアをインライン データとして渡すことができます。

たとえば、ビットマップを使用するには、image コンテンツ タイプを使用します。

Kotlin

scope.launch {
  val response = model.generateContent(
    content {
      image(bitmap)
      text("what is the object in the picture?")
    }
  )
}

Java

Content content = new Content.Builder()
        .addImage(bitmap)
        .addText("what is the object in the picture?")
        .build();

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        [...]
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

音声ファイルを渡すには、inlineData コンテンツ タイプを使用します。

Kotlin

val contentResolver = applicationContext.contentResolver
val inputStream = contentResolver.openInputStream(audioUri).use { stream ->
    stream?.let {
        val bytes = stream.readBytes()

        val prompt = content {
            inlineData(bytes, "audio/mpeg")  // Specify the appropriate audio MIME type
            text("Transcribe this audio recording.")
        }

        val response = model.generateContent(prompt)
    }
}

Java

ContentResolver resolver = getApplicationContext().getContentResolver();

try (InputStream stream = resolver.openInputStream(audioUri)) {
    File audioFile = new File(new URI(audioUri.toString()));
    int audioSize = (int) audioFile.length();
    byte audioBytes = new byte[audioSize];
    if (stream != null) {
        stream.read(audioBytes, 0, audioBytes.length);
        stream.close();

        // Provide a prompt that includes audio specified earlier and text
        Content prompt = new Content.Builder()
              .addInlineData(audioBytes, "audio/mpeg")  // Specify the appropriate audio MIME type
              .addText("Transcribe what's said in this audio recording.")
              .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 text = result.getText();
                Log.d(TAG, (text == null) ? "" : text);
            }
            @Override
            public void onFailure(Throwable t) {
                Log.e(TAG, "Failed to generate a response", t);
            }
        }, executor);
    } else {
        Log.e(TAG, "Error getting input stream for file.");
        // Handle the error appropriately
    }
} catch (IOException e) {
    Log.e(TAG, "Failed to read the audio file", e);
} catch (URISyntaxException e) {
    Log.e(TAG, "Invalid audio file", e);
}

動画ファイルを提供するには、引き続き inlineData コンテンツ タイプを使用します。

Kotlin

val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
  stream?.let {
    val bytes = stream.readBytes()

    val prompt = content {
        inlineData(bytes, "video/mp4")  // Specify the appropriate video MIME type
        text("Describe the content of this video")
    }

    val response = model.generateContent(prompt)
  }
}

Java

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 video specified earlier and text
        Content prompt = new Content.Builder()
                .addInlineData(videoBytes, "video/mp4")
                .addText("Describe the content of this 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();
}

同様に、PDF(application/pdf)ドキュメントとプレーンテキスト(text/plain)ドキュメントを渡し、それぞれの MIME タイプをパラメータとして渡すこともできます。

マルチターン チャット

マルチターンの会話をサポートすることもできます。startChat() 関数でチャットを初期化します。必要に応じて、モデルにメッセージ履歴を指定できます。次に、sendMessage() 関数を呼び出してチャット メッセージを送信します。

Kotlin

val chat = model.startChat(
    history = listOf(
        content(role = "user") { text("Hello, I have 2 dogs in my house.") },
        content(role = "model") { text("Great to meet you. What would you like to know?")   }
    )
)

scope.launch {
   val response = chat.sendMessage("How many paws are in my house?")
}

Java

Content.Builder userContentBuilder = new Content.Builder();
userContentBuilder.setRole("user");
userContentBuilder.addText("Hello, I have 2 dogs in my house.");
Content userContent = userContentBuilder.build();

Content.Builder modelContentBuilder = new Content.Builder();
modelContentBuilder.setRole("model");
modelContentBuilder.addText("Great to meet you. What would you like to know?");
Content modelContent = userContentBuilder.build();

List<Content> history = Arrays.asList(userContent, modelContent);

// Initialize the chat
ChatFutures chat = model.startChat(history);

// Create a new user message
Content.Builder messageBuilder = new Content.Builder();
messageBuilder.setRole("user");
messageBuilder.addText("How many paws are in my house?");

Content message = messageBuilder.build();

// Send the message
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(message);
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);

詳細については、Firebase のドキュメントをご覧ください。

次のステップ