Puedes pedirle a un modelo Gemini que genere texto a partir de una instrucción solo de texto o una instrucción multimodal. Cuando usas Firebase AI Logic, puedes hacer esta solicitud directamente desde tu app.
Las instrucciones multimodales pueden incluir varios tipos de entrada (como texto junto con imágenes, PDFs, archivos de texto sin formato, audio y video).
En esta guía, se muestra cómo generar texto a partir de un mensaje solo de texto y de un mensaje multimodal básico que incluye un archivo.
Ir a muestras de código para entrada solo de texto Ir a muestras de código para entrada multimodal
Consulta otras guías para obtener más opciones para trabajar con texto Generar resultados estructurados Chat de varios turnos Transmisión bidireccional Generar texto en el dispositivo Generar imágenes a partir de texto |
Antes de comenzar
Haz clic en tu proveedor de Gemini API para ver el contenido y el código específicos del proveedor en esta página. |
Si aún no lo has hecho, completa la guía de introducción, en la que se describe cómo configurar tu proyecto de Firebase, conectar tu app a Firebase, agregar el SDK, inicializar el servicio de backend para el proveedor de Gemini API que elijas y crear una instancia de GenerativeModel
.
Para probar y, luego, iterar tus instrucciones, e incluso obtener un fragmento de código generado, te recomendamos usar Google AI Studio.
Generar texto a partir de entrada de solo texto
Antes de probar esta muestra, completa la sección
Antes de comenzar de esta guía
para configurar tu proyecto y tu app. En esa sección, también harás clic en un botón para el proveedor de Gemini API que elijas, de modo que veas contenido específico del proveedor en esta página. |
Puedes pedirle a un modelo Gemini que genere texto con una instrucción que incluya solo texto como entrada.
Puedes llamar a generateContent()
para generar texto a partir de una entrada de solo texto.
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.5-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.")
Puedes llamar a generateContent()
para generar texto a partir de una entrada de solo texto.
// 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.5-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)
Puedes llamar a generateContent()
para generar texto a partir de una entrada de solo texto.
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.5-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);
Puedes llamar a generateContent()
para generar texto a partir de una entrada de solo texto.
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.5-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();
Puedes llamar a generateContent()
para generar texto a partir de una entrada de solo texto.
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.5-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);
Puedes llamar a GenerateContentAsync()
para generar texto a partir de una entrada de solo texto.
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.5-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.");
Aprende a elegir un modelo adecuados para tu caso de uso y tu app.
Genera texto a partir de entradas de texto y archivos (multimodales)
Antes de probar esta muestra, completa la sección
Antes de comenzar de esta guía
para configurar tu proyecto y tu app. En esa sección, también harás clic en un botón para el proveedor de Gemini API que elijas, de modo que veas contenido específico del proveedor en esta página. |
Puedes pedirle a un modelo Gemini que genere texto proporcionándole texto y un archivo, es decir, el mimeType
de cada archivo de entrada y el archivo en sí. Más adelante en esta página, encontrarás los requisitos y las recomendaciones para los archivos de entrada.
En el siguiente ejemplo, se muestran los conceptos básicos para generar texto a partir de un archivo de entrada analizando un solo archivo de video proporcionado como datos intercalados (archivo codificado en base64).
Ten en cuenta que este ejemplo muestra cómo proporcionar el archivo de forma intercalada, pero los SDKs también admiten proporcionar una URL de YouTube.¿Necesitas un archivo de video de muestra?
Puedes usar este archivo disponible públicamente con un tipo de MIME de
video/mp4
(ver o descargar archivo).https://storage.googleapis.com/cloud-samples-data/video/animals.mp4
Puedes llamar a generateContent()
para generar texto a partir de la entrada multimodal de archivos de texto y video.
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.5-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.")
Puedes llamar a generateContent()
para generar texto a partir de la entrada multimodal de archivos de texto y video.
// 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.5-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 ?: "")
}
}
Puedes llamar a generateContent()
para generar texto a partir de la entrada multimodal de archivos de texto y video.
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.5-flash");
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
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();
}
Puedes llamar a generateContent()
para generar texto a partir de la entrada multimodal de archivos de texto y video.
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.5-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();
Puedes llamar a generateContent()
para generar texto a partir de la entrada multimodal de archivos de texto y video.
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.5-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);
Puedes llamar a GenerateContentAsync()
para generar texto a partir de la entrada multimodal de archivos de texto y video.
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.5-flash");
// Provide the video as `data` with the appropriate MIME type.
var video = ModelContent.InlineData("video/mp4",
System.IO.File.ReadAllBytes(System.IO.Path.Combine(
UnityEngine.Application.streamingAssetsPath, "yourVideo.mp4")));
// Provide a text prompt to include with the video
var prompt = ModelContent.Text("What is in the video?");
// To generate text output, call GenerateContentAsync with the text and video
var response = await model.GenerateContentAsync(new [] { video, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
Aprende a elegir un modelo adecuados para tu caso de uso y tu app.
Transmite la respuesta
Antes de probar esta muestra, completa la sección
Antes de comenzar de esta guía
para configurar tu proyecto y tu app. En esa sección, también harás clic en un botón para el proveedor de Gemini API que elijas, de modo que veas contenido específico del proveedor en esta página. |
Puedes lograr interacciones más rápidas sin esperar el resultado completo de la generación del modelo y, en cambio, usar la transmisión para controlar los resultados parciales.
Para transmitir la respuesta, llama a generateContentStream
.
Ver ejemplo: Transmite texto generado a partir de una entrada de solo texto
Puedes llamar a generateContentStream()
para transmitir texto generado a partir de una entrada de solo texto.
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.5-flash")
// Provide a prompt that contains text
let prompt = "Write a story about a magic backpack."
// To stream generated text output, call generateContentStream with the text input
let contentStream = try model.generateContentStream(prompt)
for try await chunk in contentStream {
if let text = chunk.text {
print(text)
}
}
Puedes llamar a generateContentStream()
para transmitir texto generado a partir de una entrada de solo texto.
// 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.5-flash")
// Provide a prompt that includes only text
val prompt = "Write a story about a magic backpack."
// To stream generated text output, call generateContentStream and pass in the prompt
var response = ""
generativeModel.generateContentStream(prompt).collect { chunk ->
print(chunk.text)
response += chunk.text
}
Puedes llamar a generateContentStream()
para transmitir texto generado a partir de una entrada de solo texto.
Publisher
de la biblioteca de Reactive Streams.
// 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.5-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 stream generated text output, call generateContentStream with the text input
Publisher<GenerateContentResponse> streamingResponse =
model.generateContentStream(prompt);
// Subscribe to partial results from the response
final String[] fullResponse = {""};
streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
@Override
public void onNext(GenerateContentResponse generateContentResponse) {
String chunk = generateContentResponse.getText();
fullResponse[0] += chunk;
}
@Override
public void onComplete() {
System.out.println(fullResponse[0]);
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onSubscribe(Subscription s) { }
});
Puedes llamar a generateContentStream()
para transmitir texto generado a partir de una entrada de solo texto.
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.5-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 stream generated text output, call generateContentStream with the text input
const result = await model.generateContentStream(prompt);
for await (const chunk of result.stream) {
const chunkText = chunk.text();
console.log(chunkText);
}
console.log('aggregated response: ', await result.response);
}
run();
Puedes llamar a generateContentStream()
para transmitir texto generado a partir de una entrada de solo texto.
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.5-flash');
// Provide a prompt that contains text
final prompt = [Content.text('Write a story about a magic backpack.')];
// To stream generated text output, call generateContentStream with the text input
final response = model.generateContentStream(prompt);
await for (final chunk in response) {
print(chunk.text);
}
Puedes llamar a GenerateContentStreamAsync()
para transmitir texto generado a partir de una entrada de solo texto.
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.5-flash");
// Provide a prompt that contains text
var prompt = "Write a story about a magic backpack.";
// To stream generated text output, call GenerateContentStreamAsync with the text input
var responseStream = model.GenerateContentStreamAsync(prompt);
await foreach (var response in responseStream) {
if (!string.IsNullOrWhiteSpace(response.Text)) {
UnityEngine.Debug.Log(response.Text);
}
}
Aprende a elegir un modelo adecuados para tu caso de uso y tu app.
Ver ejemplo: Transmite texto generado a partir de una entrada multimodal
Puedes llamar a generateContentStream()
para transmitir texto generado a partir de la entrada multimodal de texto y un solo video.
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.5-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 stream generated text output, call generateContentStream with the text and video
let contentStream = try model.generateContentStream(video, prompt)
for try await chunk in contentStream {
if let text = chunk.text {
print(text)
}
}
Puedes llamar a generateContentStream()
para transmitir texto generado a partir de la entrada multimodal de texto y un solo video.
// 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.5-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 stream generated text output, call generateContentStream with the prompt
var fullResponse = ""
generativeModel.generateContentStream(prompt).collect { chunk ->
Log.d(TAG, chunk.text ?: "")
fullResponse += chunk.text
}
}
}
Puedes llamar a generateContentStream()
para transmitir texto generado a partir de la entrada multimodal de texto y un solo video.
Publisher
de la biblioteca de Reactive Streams.
// 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.5-flash");
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
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 stream generated text output, call generateContentStream with the prompt
Publisher<GenerateContentResponse> streamingResponse =
model.generateContentStream(prompt);
final String[] fullResponse = {""};
streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
@Override
public void onNext(GenerateContentResponse generateContentResponse) {
String chunk = generateContentResponse.getText();
fullResponse[0] += chunk;
}
@Override
public void onComplete() {
System.out.println(fullResponse[0]);
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onSubscribe(Subscription s) {
}
});
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Puedes llamar a generateContentStream()
para transmitir texto generado a partir de la entrada multimodal de texto y un solo video.
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.5-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 stream generated text output, call generateContentStream with the text and video
const result = await model.generateContentStream([prompt, videoPart]);
for await (const chunk of result.stream) {
const chunkText = chunk.text();
console.log(chunkText);
}
}
run();
Puedes llamar a generateContentStream()
para transmitir texto generado a partir de la entrada multimodal de texto y un solo video.
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.5-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 stream generated text output, call generateContentStream with the text and image
final response = await model.generateContentStream([
Content.multi([prompt,videoPart])
]);
await for (final chunk in response) {
print(chunk.text);
}
Puedes llamar a GenerateContentStreamAsync()
para transmitir texto generado a partir de la entrada multimodal de texto y un solo video.
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.5-flash");
// Provide the video as `data` with the appropriate MIME type.
var video = ModelContent.InlineData("video/mp4",
System.IO.File.ReadAllBytes(System.IO.Path.Combine(
UnityEngine.Application.streamingAssetsPath, "yourVideo.mp4")));
// Provide a text prompt to include with the video
var prompt = ModelContent.Text("What is in the video?");
// To stream generated text output, call GenerateContentStreamAsync with the text and video
var responseStream = model.GenerateContentStreamAsync(new [] { video, prompt });
await foreach (var response in responseStream) {
if (!string.IsNullOrWhiteSpace(response.Text)) {
UnityEngine.Debug.Log(response.Text);
}
}
Aprende a elegir un modelo adecuados para tu caso de uso y tu app.
Requisitos y recomendaciones para los archivos de imágenes de entrada
Ten en cuenta que un archivo proporcionado como datos intercalados se codifica en base64 durante la transmisión, lo que aumenta el tamaño de la solicitud. Recibirás un error HTTP 413 si una solicitud es demasiado grande.
Consulta Archivos de entrada y requisitos compatibles para Vertex AI Gemini API para obtener información detallada sobre lo siguiente:
- Diferentes opciones para proporcionar un archivo en una solicitud (ya sea intercalado o con la URL o el URI del archivo)
- Tipos de archivos admitidos
- Tipos de MIME admitidos y cómo especificarlos
- Requisitos y prácticas recomendadas para archivos y solicitudes multimodales
¿Qué más puedes hacer?
- Aprende a contar tokens antes de enviar instrucciones largas al modelo.
- Configura Cloud Storage for Firebase para poder incluir archivos grandes en tus solicitudes multimodales y tener una solución más administrada para proporcionar archivos en las instrucciones. Los archivos pueden incluir imágenes, PDFs, videos y audio.
-
Comienza a pensar en la preparación para la producción (consulta la lista de tareas de producción), que incluye lo siguiente:
- Configura Firebase App Check para proteger Gemini API contra el abuso de clientes no autorizados.
- Integra Firebase Remote Config para actualizar valores en tu app (como el nombre del modelo) sin lanzar una nueva versión de la app.
Prueba otras capacidades
- Crea conversaciones de varios turnos (chat).
- Generar texto a partir de instrucciones solo de texto
- Genera resultados estructurados (como JSON) a partir de instrucciones tanto de texto como multimodales.
- Generar imágenes a partir de instrucciones de texto (Gemini o Imagen)
- Usa herramientas (como llamadas a funciones y fundamentación con la Búsqueda de Google) para conectar un modelo Gemini a otras partes de tu app y a sistemas e información externos.
Más información para controlar la generación de contenido
- Comprende el diseño de instrucciones, incluidas las prácticas recomendadas, las estrategias y los ejemplos de instrucciones.
- Configura los parámetros del modelo, como la temperatura y la cantidad máxima de tokens de salida (para Gemini) o la relación de aspecto y la generación de personas (para Imagen).
- Usar la configuración de seguridad para ajustar la probabilidad de obtener respuestas que se puedan considerar dañinas
Más información sobre los modelos compatibles
Obtén información sobre los modelos disponibles para diversos casos de uso, sus cuotas y sus precios.Envía comentarios sobre tu experiencia con Firebase AI Logic