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 realizar esta solicitud directamente desde tu app.
Las instrucciones multimodales pueden incluir varios tipos de entradas (como texto junto con imágenes, archivos PDF, archivos de texto sin formato, audio y video).
En esta guía, se muestra cómo generar texto a partir de un prompt de solo texto y de un prompt multimodal básico que incluye un archivo.
Ir a las muestras de código para la entrada de solo texto Ir a las muestras de código para la entrada multimodal
Consulta otras guías para obtener opciones adicionales para trabajar con texto Genera un resultado estructurado Chat de varios turnos Transmisión bidireccional Genera texto en el dispositivo Genera 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 e iterar tus instrucciones y hasta conseguir un fragmento de código generado, te recomendamos usar Google AI Studio.
Genera texto a partir de una 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 app. En esa sección, también harás clic en un botón del proveedor de Gemini API que elijas para ver contenido específico del proveedor en esta página. |
Puedes pedirle a un modelo de Gemini que genere texto con una entrada de solo texto.
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.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.")
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.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)
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.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);
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.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();
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.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);
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.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.");
Genera texto a partir de una entrada de texto y archivo (multimodal)
Antes de probar esta muestra, completa la sección Antes de comenzar de esta guía para configurar tu proyecto y app. En esa sección, también harás clic en un botón del proveedor de Gemini API que elijas para ver contenido específico del proveedor en esta página. |
Puedes pedirle a un modelo Gemini que genere texto con una instrucción de texto y un archivo, y proporcionar 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 una entrada de archivo analizando un solo archivo de video proporcionado como datos intercalados (archivo codificado en base64).
Ten en cuenta que, en este ejemplo, se muestra cómo proporcionar el archivo intercalado, pero los SDKs también admiten proporcionar una URL de YouTube.¿Necesitas un archivo de video de muestra?
Puedes usar este archivo de acceso público 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 una 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.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.")
Puedes llamar a generateContent()
para generar texto a partir de una 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.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 ?: "")
}
}
Puedes llamar a generateContent()
para generar texto a partir de una 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.0-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 una 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.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();
Puedes llamar a generateContent()
para generar texto a partir de una 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.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);
Puedes llamar a GenerateContentAsync()
para generar texto a partir de una 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.0-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 apropiado 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 app. En esa sección, también harás clic en un botón del proveedor de Gemini API que elijas para ver contenido específico del proveedor en esta página. |
Puedes lograr interacciones más rápidas si no esperas a que se genere todo el resultado del modelo y, en su lugar, usas la transmisión para controlar los resultados parciales.
Para transmitir la respuesta, llama a generateContentStream
.
Ejemplo de vista: 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.0-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.0-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 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.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 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.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 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.0-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.0-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);
}
}
Ver ejemplo: Transmite texto generado a partir de una entrada multimodal
Puedes llamar a generateContentStream()
para transmitir texto generado a partir de una 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.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 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 una 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.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 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 una entrada multimodal de texto y un solo video.
Publisher
de la biblioteca 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.0-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 una 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.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 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 una 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.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 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 una 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.0-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);
}
}
Requisitos y recomendaciones para los archivos de imagen de entrada
Ten en cuenta que un archivo proporcionado como datos intercalados se codifica en base64 en tránsito, 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 admitidos 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?
- Obtén más información para contar tokens antes de enviar instrucciones largas al modelo.
- Configura Cloud Storage for Firebase para que puedas incluir archivos grandes en tus solicitudes multimodales y tener una solución más administrada para proporcionar archivos en instrucciones. Los archivos pueden incluir imágenes, archivos PDF, videos y audio.
-
Comienza a pensar en prepararte para la producción (consulta la
lista de tareas de producción),
lo que incluye lo siguiente:
- Configurar Firebase App Check para proteger el Gemini API del abuso de clientes no autorizados
- Integrar Firebase Remote Config para actualizar los valores de tu app (como el nombre del modelo) sin lanzar una versión nueva de la app
Prueba otras funciones
- Crea conversaciones de varios turnos (chat).
- Generar texto a partir de instrucciones de solo texto
- Genera resultados estructurados (como JSON) a partir de instrucciones multimodales y de texto.
- Genera imágenes a partir de instrucciones de texto (Gemini o Imagen).
- Usa las llamadas a función para conectar los modelos generativos a sistemas y datos externos.
Aprende a 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).
- Usa la configuración de seguridad para ajustar la probabilidad de recibir respuestas que se puedan considerar dañinas.
Más información sobre los modelos compatibles
Obtén información sobre los modelos disponibles para varios casos de uso y sus cuotas y precios.Envía comentarios sobre tu experiencia con Firebase AI Logic