Generare testo utilizzando l'API Gemini

Puoi chiedere a un modello Gemini di generare testo da un prompt di solo testo o da un prompt multimodale. Quando utilizzi Vertex AI in Firebase, puoi effettuare questa richiesta direttamente dalla tua app.

I prompt multimodali possono includere più tipi di input, come testo e immagini, PDF, file di testo, audio e video.

Questa guida mostra come generare testo da un prompt di solo testo e da un prompt multimodale di base che include un file.

Vai agli esempi di codice per l'input solo testo Vai agli esempi di codice per l'input multimodale


Consulta altre guide per ulteriori opzioni per lavorare con il testo
Genera output strutturato Chat con più turni Streaming bidirezionale Genera immagini da testo

Prima di iniziare

Se non l'hai ancora fatto, consulta la guida introduttiva, che descrive come configurare il progetto Firebase, collegare l'app a Firebase, aggiungere l'SDK, inizializzare il servizio Vertex AI e creare un'istanza GenerativeModel.

Per testare e eseguire l'iterazione sui prompt e persino per ottenere uno snippet di codice generato, ti consigliamo di utilizzare Vertex AI Studio.

Inviare e ricevere messaggi

Prima di provare questo esempio, assicurati di aver completato la sezione Prima di iniziare di questa guida.

Puoi chiedere a un modello Gemini di generare testo tramite prompt con input di solo testo.

Swift

Puoi chiamare generateContent() per generare testo da un input di solo testo.

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

Puoi chiamare generateContent() per generare testo da un input di solo testo.

Per Kotlin, i metodi in questo SDK sono funzioni sospese e devono essere chiamati da un ambito 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

Puoi chiamare generateContent() per generare testo da un input di solo testo.

Per Java, i metodi in questo SDK restituiscono un 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

Puoi chiamare generateContent() per generare testo da un input di solo testo.

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

Puoi chiamare generateContent() per generare testo da un input di solo testo.

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

Inviare testo e un file (multimodale) e ricevere testo

Prima di provare questo sample, assicurati di aver completato la sezione Prima di iniziare di questa guida.

Puoi chiedere a un modello Gemini di generare testo fornendo un prompt con testo e un file, fornendo il mimeType di ogni file di input e il file stesso. Trova requisiti e consigli per i file di input più avanti in questa pagina.

L'esempio seguente mostra le nozioni di base su come generare testo da un input file analizzando un singolo file video fornito come dati incorporati (file codificato in base64).

Swift

Puoi chiamare generateContent() per generare testo dall'input multimodale di file di testo e video.

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

Puoi chiamare generateContent() per generare testo dall'input multimodale di file di testo e video.

Per Kotlin, i metodi in questo SDK sono funzioni sospese e devono essere chiamati da un ambito 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

Puoi chiamare generateContent() per generare testo dall'input multimodale di file di testo e video.

Per Java, i metodi in questo SDK restituiscono un 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

Puoi chiamare generateContent() per generare testo dall'input multimodale di file di testo e video.

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

Puoi chiamare generateContent() per generare testo da input multimodali di file di testo e video.

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

Scopri come scegliere un modello e, facoltativamente, una località appropriata per il tuo caso d'uso e la tua app.

Visualizza la risposta in streaming

Prima di provare questo esempio, assicurati di aver completato la sezione Prima di iniziare di questa guida.

Puoi ottenere interazioni più rapide non aspettando l'intero risultato della generazione del modello, ma utilizzando lo streaming per gestire i risultati parziali. Per riprodurre in streaming la risposta, chiama generateContentStream.



Requisiti e consigli per i file immagine di input

Consulta File di input supportati e requisiti per Vertex AI Gemini API per informazioni dettagliate su quanto segue:

  • Diverse opzioni per fornire un file in una richiesta (in linea o utilizzando l'URL o l'URI del file)
  • Tipi di file supportati
  • Tipi MIME supportati e come specificarli
  • Requisiti e best practice per file e richieste multimodali



Cos'altro puoi fare?

Provare altre funzionalità

Scopri come controllare la generazione di contenuti

Puoi anche sperimentare con i prompt e le configurazioni del modello utilizzando Vertex AI Studio.

Scopri di più sui modelli supportati

Scopri i modelli disponibili per vari casi d'uso e le relative quote e prezzi.


Inviare un feedback sulla tua esperienza con Vertex AI in Firebase