Mit der Gemini API Text aus multimodalen Prompts generieren

Wenn Sie die Gemini API über ein Vertex AI in Firebase SDK von Ihrer App aus aufrufen, können Sie das Gemini-Modell auffordern, Text basierend auf einer multimodalen Eingabe zu generieren. Multimodale Prompts können mehrere Modalitäten (oder Eingabetypen) umfassen, z. B. Text zusammen mit Bildern, PDFs, Textdateien, Video und Audio.

In jeder multimodalen Anfrage müssen Sie immer Folgendes angeben:

Zum Testen und Iterieren multimodaler Prompts empfehlen wir die Verwendung von Vertex AI Studio.

Hinweis

Lesen Sie den Startleitfaden, in dem beschrieben wird, wie Sie ein Firebase-Projekt einrichten, Ihre App mit Firebase verbinden, das SDK hinzufügen, den Vertex AI-Dienst initialisieren und eine GenerativeModel-Instanz erstellen.

Text aus Text und einem einzelnen Bild generieren Text aus Text und mehreren Bildern generieren Text aus Text und einem Video generieren

Beispielmediendateien

Wenn Sie noch keine Mediadateien haben, können Sie die folgenden öffentlich zugänglichen Dateien verwenden. Da diese Dateien in Bucket gespeichert sind, die nicht zu Ihrem Firebase-Projekt gehören, müssen Sie das Format https://storage.googleapis.com/BUCKET_NAME/PATH/TO/FILE für die URL verwenden.

Text aus Text und einem einzelnen Bild generieren

Lesen Sie den Abschnitt Vorbereitung in dieser Anleitung, bevor Sie dieses Beispiel ausprobieren.

Sie können Gemini API mit multimodalen Prompts aufrufen, die sowohl Text als auch eine einzelne Datei enthalten (z. B. ein Bild, wie in diesem Beispiel).

Lesen Sie sich die Anforderungen und Empfehlungen für Eingabedateien durch.

Swift

Sie können generateContent() aufrufen, um Text aus einer multimodalen Prompt-Anfrage zu generieren, die Text und ein einzelnes Bild enthält:

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

Sie können generateContent() aufrufen, um Text aus einer multimodalen Prompt-Anfrage zu generieren, die Text und ein einzelnes Bild enthält:

In Kotlin sind die Methoden in diesem SDK Suspend-Funktionen und müssen aus einem Coroutine-Kontext aufgerufen werden.
// 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

Sie können generateContent() aufrufen, um Text aus einer multimodalen Prompt-Anfrage zu generieren, die Text und ein einzelnes Bild enthält:

Bei Java geben die Methoden in diesem SDK eine ListenableFuture zurück.
// 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

Sie können generateContent() aufrufen, um Text aus einer multimodalen Prompt-Anfrage zu generieren, die Text und ein einzelnes Bild enthält:

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

Sie können generateContent() aufrufen, um Text aus einer multimodalen Prompt-Anfrage zu generieren, die Text und ein einzelnes Bild enthält:

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

Hier erfahren Sie, wie Sie ein Modell und optional einen Standort auswählen, die für Ihren Anwendungsfall und Ihre App geeignet sind.

Text aus Text und mehreren Bildern generieren

Lesen Sie den Abschnitt Vorbereitung in dieser Anleitung, bevor Sie dieses Beispiel ausprobieren.

Sie können Gemini API mit multimodalen Prompts aufrufen, die sowohl Text als auch mehrere Dateien (z. B. Bilder, wie in diesem Beispiel) enthalten.

Lesen Sie sich die Anforderungen und Empfehlungen für Eingabedateien durch.

Swift

Sie können generateContent() aufrufen, um Text aus einer multimodalen Prompt-Anfrage zu generieren, die Text und mehrere Bilder enthält:

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

Sie können generateContent() aufrufen, um Text aus einer multimodalen Prompt-Anfrage zu generieren, die Text und mehrere Bilder enthält:

In Kotlin sind die Methoden in diesem SDK Suspend-Funktionen und müssen aus einem Coroutine-Kontext aufgerufen werden.
// 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

Sie können generateContent() aufrufen, um Text aus einer multimodalen Prompt-Anfrage zu generieren, die Text und mehrere Bilder enthält:

Bei Java geben die Methoden in diesem SDK eine ListenableFuture zurück.
// 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

Sie können generateContent() aufrufen, um Text aus einer multimodalen Prompt-Anfrage zu generieren, die Text und mehrere Bilder enthält:

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

Sie können generateContent() aufrufen, um Text aus einer multimodalen Prompt-Anfrage zu generieren, die Text und mehrere Bilder enthält:

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

Hier erfahren Sie, wie Sie ein Modell und optional einen Standort auswählen, die für Ihren Anwendungsfall und Ihre App geeignet sind.

Text aus Text und einem Video generieren

Lesen Sie den Abschnitt Vorbereitung in dieser Anleitung, bevor Sie dieses Beispiel ausprobieren.

Sie können die Gemini API mit multimodalen Prompts aufrufen, die sowohl Text- als auch Videodateien enthalten (wie in diesem Beispiel gezeigt).

Lesen Sie sich die Anforderungen und Empfehlungen für Eingabedateien durch.

Swift

Sie können generateContent() aufrufen, um Text aus einer multimodalen Promptanfrage zu generieren, die Text und ein einzelnes Video enthält:

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

Sie können generateContent() aufrufen, um Text aus einer multimodalen Promptanfrage zu generieren, die Text und ein einzelnes Video enthält:

In Kotlin sind die Methoden in diesem SDK Suspend-Funktionen und müssen aus einem Coroutine-Kontext aufgerufen werden.
// 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

Sie können generateContent() aufrufen, um Text aus einer multimodalen Promptanfrage zu generieren, die Text und ein einzelnes Video enthält:

Bei Java geben die Methoden in diesem SDK eine ListenableFuture zurück.
// 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

Sie können generateContent() aufrufen, um Text aus einer multimodalen Promptanfrage zu generieren, die Text und ein einzelnes Video enthält:

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

Sie können generateContent() aufrufen, um Text aus einer multimodalen Promptanfrage zu generieren, die Text und ein einzelnes Video enthält:

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

Hier erfahren Sie, wie Sie ein Modell und optional einen Standort auswählen, die für Ihren Anwendungsfall und Ihre App geeignet sind.

Antwort streamen

Lesen Sie den Abschnitt Vorbereitung in dieser Anleitung, bevor Sie diese Samples ausprobieren.

Sie können schnellere Interaktionen erzielen, wenn Sie nicht auf das vollständige Ergebnis der Modellgenerierung warten, sondern stattdessen Streaming zum Verarbeiten von Teilergebnissen verwenden. Wenn Sie die Antwort streamen möchten, rufen Sie generateContentStream auf.



Anforderungen und Empfehlungen für Eingabedateien

Unter Unterstützte Eingabedateien und Anforderungen für die Gemini API in Vertex AI finden Sie Informationen zu folgenden Themen:

  • Verschiedene Optionen zum Einreichen einer Datei in einer Anfrage
  • Unterstützte Dateitypen
  • Unterstützte MIME-Typen und deren Angabe
  • Anforderungen und Best Practices für Dateien und multimodale Anfragen



Was können Sie sonst noch tun?

Weitere Funktionen ausprobieren

Inhaltserstellung steuern

Mit Vertex AI Studio können Sie auch mit Prompts und Modellkonfigurationen experimentieren.

Weitere Informationen zu den unterstützten Modellen

Hier finden Sie Informationen zu den Modellen, die für verschiedene Anwendungsfälle verfügbar sind, sowie zu ihren Kontingenten und Preisen.


Feedback zu Vertex AI in Firebase geben