Você pode pedir que um modelo Gemini analise os arquivos de imagem fornecidos inline (codificados em base64) ou por URL. Ao usar Firebase AI Logic, é possível fazer essa solicitação diretamente no app.
Com esse recurso, é possível:
- Criar legendas ou responder a perguntas sobre imagens
- Escreva uma história curta ou um poema sobre uma imagem
- Detectar objetos em uma imagem e retornar as coordenadas da caixa delimitadora
- Rotular ou categorizar um conjunto de imagens por sentimento, estilo ou outra característica
Ir para exemplos de código Ir para o código das respostas transmitidas por streaming
Consulte outros guias para conferir outras opções de trabalho com imagens Gerar saída estruturada Chat com vários turnos Analisar imagens no dispositivo Gerar imagens |
Antes de começar
Clique no seu provedor de Gemini API para conferir o conteúdo e o código específicos do provedor nesta página. |
Se ainda não tiver feito isso, conclua o
guia de início, que descreve como
configurar seu projeto do Firebase, conectar seu app ao Firebase, adicionar o SDK,
inicializar o serviço de back-end para o provedor de Gemini API escolhido e
criar uma instância de GenerativeModel
.
Para testar e iterar comandos e até receber um snippet de código gerado, recomendamos usar Google AI Studio.
Gerar texto com base em arquivos de imagem (codificados em base64)
Antes de testar este exemplo, conclua a
seção Antes de começar deste guia
para configurar seu projeto e app. Nessa seção, você também clicará em um botão do provedor Gemini API escolhido para acessar o conteúdo específico do provedor nessa página. |
É possível pedir a um modelo Gemini para
gerar texto solicitando texto e imagens, fornecendo o mimeType
de cada
arquivo de entrada e o arquivo em si. Confira
requisitos e recomendações para arquivos de entrada
mais adiante nesta página.
Swift
Você pode chamar
generateContent()
para gerar texto a partir de uma entrada multimodal de texto e imagens.
Entrada de um único arquivo
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")
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.")
Entrada de vários arquivos
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")
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
Você pode chamar
generateContent()
para gerar texto a partir de uma entrada multimodal de texto e imagens.
Entrada de um único arquivo
// 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")
// 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)
Entrada de vários arquivos
No Kotlin, os métodos neste SDK são funções de suspensão e precisam ser chamados de um escopo de corrotina.
// 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")
// 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
Você pode chamar
generateContent()
para gerar texto a partir de uma entrada multimodal de texto e imagens.
ListenableFuture
.
Entrada de um único arquivo
// 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);
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);
Entrada de vários arquivos
// 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);
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
Você pode chamar
generateContent()
para gerar texto a partir de uma entrada multimodal de texto e imagens.
Entrada de um único arquivo
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 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();
Entrada de vários arquivos
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 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
Você pode chamar
generateContent()
para gerar texto a partir de uma entrada multimodal de texto e imagens.
Entrada de um único arquivo
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 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);
Entrada de vários arquivos
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');
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);
Unity
É possível chamar
generateContent()
para gerar texto a partir de uma entrada multimodal de texto e imagens.
Entrada de um único arquivo
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");
// Convert a Texture2D into InlineDataParts
var grayImage = ModelContent.InlineData("image/png",
UnityEngine.ImageConversion.EncodeToPNG(UnityEngine.Texture2D.grayTexture));
// Provide a text prompt to include with the image
var prompt = ModelContent.Text("What's in this picture?");
// To generate text output, call GenerateContentAsync and pass in the prompt
var response = await model.GenerateContentAsync(new [] { grayImage, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
Entrada de vários arquivos
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");
// Convert Texture2Ds into InlineDataParts
var blackImage = ModelContent.InlineData("image/png",
UnityEngine.ImageConversion.EncodeToPNG(UnityEngine.Texture2D.blackTexture));
var whiteImage = ModelContent.InlineData("image/png",
UnityEngine.ImageConversion.EncodeToPNG(UnityEngine.Texture2D.whiteTexture));
// Provide a text prompt to include with the images
var prompt = ModelContent.Text("What's different between these pictures?");
// To generate text output, call GenerateContentAsync and pass in the prompt
var response = await model.GenerateContentAsync(new [] { blackImage, whiteImage, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
Saiba como escolher um modelo adequado para seu caso de uso e app.
Transmitir a resposta
Antes de testar este exemplo, conclua a
seção Antes de começar deste guia
para configurar seu projeto e app. Nessa seção, você também clicará em um botão do provedor Gemini API escolhido para acessar o conteúdo específico do provedor nessa página. |
É possível alcançar interações mais rápidas sem esperar pelo resultado completo da
geração do modelo e, em vez disso, usar o streaming para processar resultados parciais.
Para transmitir a resposta, chame generateContentStream
.
Requisitos e recomendações para arquivos de imagem de entrada
Um arquivo fornecido como dados inline é codificado em base64 em trânsito, o que aumenta o tamanho da solicitação. Você vai receber um erro HTTP 413 se uma solicitação for muito grande.
Consulte "Arquivos de entrada e requisitos compatíveis com o Vertex AI Gemini API" para saber mais sobre o seguinte:
- Opções diferentes para fornecer um arquivo em uma solicitação (inline ou usando o URL do arquivo)
- Requisitos e práticas recomendadas para arquivos de imagem
Tipos MIME de imagem aceitos
Os modelos multimodais Gemini são compatíveis com os seguintes tipos MIME de imagem:
Tipo de Mime da imagem | Gemini 2.0 Flash | Gemini 2.0 Flash‑Lite |
---|---|---|
PNG - image/png |
||
JPEG - image/jpeg |
||
WebP: image/webp |
Limites por solicitação
Não há um limite específico para o número de pixels em uma imagem. No entanto, imagens maiores são reduzidas e preenchidas para caber em uma resolução máxima de 3072 x 3072, preservando a proporção original.
Este é o número máximo de arquivos de imagem permitidos em uma solicitação de comando:
- Gemini 2.0 Flash e Gemini 2.0 Flash‑Lite: 3.000 imagens
O que mais você pode fazer?
- Saiba como contar tokens antes de enviar comandos longos para o modelo.
- Configure Cloud Storage for Firebase para incluir arquivos grandes nas solicitações multimodais e ter uma solução mais gerenciada para fornecer arquivos em comandos. Os arquivos podem incluir imagens, PDFs, vídeos e áudio.
-
Comece a pensar na preparação para a produção (consulte a
lista de verificação de produção),
incluindo:
- Configurar Firebase App Check para proteger o Gemini API contra abusos de clientes não autorizados.
- Integração de Firebase Remote Config para atualizar valores no app (como o nome do modelo) sem lançar uma nova versão do app.
Testar outros recursos
- Crie conversas com vários turnos (chat).
- Gerar texto com base em comandos somente de texto.
- Gere saída estruturada (como JSON) com comandos de texto e multimodais.
- Gerar imagens com base em comandos de texto.
- Use a chamada de função para conectar modelos generativos a sistemas e informações externas.
Saiba como controlar a geração de conteúdo
- Entenda o design de comandos, incluindo práticas recomendadas, estratégias e exemplos de comandos.
- Configure parâmetros do modelo, como temperatura e máximo de tokens de saída (para Gemini) ou proporção e geração de pessoas (para Imagen).
- Use as configurações de segurança para ajustar a probabilidade de receber respostas que podem ser consideradas nocivas.
Saiba mais sobre os modelos compatíveis
Saiba mais sobre os modelos disponíveis para vários casos de uso e as cotas e o preço.Enviar feedback sobre sua experiência com o Firebase AI Logic