Вы можете попросить модель Gemini генерировать текст из текстового или мультимодального приглашения. Когда вы используете Vertex AI в Firebase , вы можете сделать этот запрос прямо из своего приложения.
Мультимодальные подсказки могут включать в себя несколько типов ввода (например, текст вместе с изображениями, PDF-файлы, текстовые файлы, аудио и видео).
В этом руководстве показано, как генерировать текст из текстового приглашения и из базового мультимодального приглашения, включающего файл.
Перейти к примерам кода для ввода только текста.arrow_downwardПерейти к примерам кода для мультимодального ввода
Дополнительные возможности работы с текстом см. в других руководствах. Генерация структурированного вывода Многоходовой чат Двунаправленная потоковая передача Генерация изображений из текста |
Прежде чем начать
Если вы еще этого не сделали, прочтите руководство по началу работы , в котором описывается, как настроить проект Firebase, подключить приложение к Firebase, добавить SDK, инициализировать службу Vertex AI и создать экземпляр GenerativeModel
.
Для тестирования и повторения ваших подсказок и даже получения сгенерированного фрагмента кода мы рекомендуем использовать Vertex AI Studio .
Отправить текст и получить текст
Прежде чем приступать к работе с этим примером, убедитесь, что вы завершили раздел « Перед началом работы» данного руководства.
Вы можете попросить модель Gemini сгенерировать текст, запросив только текстовый ввод.
Быстрый
Вы можете вызвать функцию generateContent()
для генерации текста из текстового ввода.
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
Вы можете вызвать функцию generateContent()
для генерации текста из текстового ввода.
// 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
Вы можете вызвать функцию generateContent()
для генерации текста из текстового ввода.
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
Вы можете вызвать функцию generateContent()
для генерации текста из текстового ввода.
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
Вы можете вызвать функцию generateContent()
для генерации текста из текстового ввода.
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);
Отправьте текст и файл (мультимодальный) и получите текст
Прежде чем приступать к работе с этим примером, убедитесь, что вы завершили раздел « Перед началом работы» данного руководства.
Вы можете попросить модель Gemini сгенерировать текст, запросив текст и файл, указав mimeType
каждого входного файла и сам файл. Требования и рекомендации для входных файлов вы найдете далее на этой странице.
В следующем примере показаны основы создания текста из входного файла путем анализа одного видеофайла, предоставленного в виде встроенных данных (файл в кодировке Base64).
Вы можете использовать этот общедоступный файл с MIME-типом
video/mp4
( просмотреть или загрузить файл ).https://storage.googleapis.com/cloud-samples-data/video/animals.mp4
Быстрый
Вы можете вызвать функцию generateContent()
для генерации текста из мультимодального ввода текстовых и видеофайлов.
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
Вы можете вызвать функцию generateContent()
для генерации текста из мультимодального ввода текстовых и видеофайлов.
// 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
Вы можете вызвать функцию generateContent()
для генерации текста из мультимодального ввода текстовых и видеофайлов.
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
Вы можете вызвать функцию generateContent()
для генерации текста из мультимодального ввода текстовых и видеофайлов.
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
Вы можете вызвать функцию generateContent()
для генерации текста из мультимодального ввода текстовых и видеофайлов.
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);
Узнайте, как выбрать модель и, при необходимости, местоположение, подходящее для вашего варианта использования и приложения.
Трансляция ответа
Прежде чем приступать к работе с этим примером, убедитесь, что вы завершили раздел « Перед началом работы» данного руководства.
Вы можете добиться более быстрого взаимодействия, не дожидаясь получения всего результата от создания модели, а вместо этого используйте потоковую передачу для обработки частичных результатов. Чтобы передать ответ в потоковом режиме, generateContentStream
.
Быстрый
Вы можете вызвать generateContentStream()
для потоковой передачи сгенерированного текста из текстового ввода.
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 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)
}
}
Kotlin
Вы можете вызвать generateContentStream()
для потоковой передачи сгенерированного текста из текстового ввода.
// 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 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
}
Java
Вы можете вызвать generateContentStream()
для потоковой передачи сгенерированного текста из текстового ввода.
Publisher
из библиотеки Reactive Streams . // 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 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) { }
});
Web
Вы можете вызвать generateContentStream()
для потоковой передачи сгенерированного текста из текстового ввода.
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 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();
Dart
Вы можете вызвать generateContentStream()
для потоковой передачи сгенерированного текста из текстового ввода.
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 stream generated text output, call generateContentStream with the text input
final response = model.generateContentStream(prompt);
await for (final chunk in response) {
print(chunk.text);
}
Быстрый
Вы можете вызвать generateContentStream()
для потоковой передачи сгенерированного текста из мультимодального ввода текста и одного видео.
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 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)
}
}
Kotlin
Вы можете вызвать generateContentStream()
для потоковой передачи сгенерированного текста из мультимодального ввода текста и одного видео.
// 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 stream generated text output, call generateContentStream with the prompt
var fullResponse = ""
generativeModel.generateContentStream(prompt).collect { chunk ->
Log.d(TAG, chunk.text ?: "")
fullResponse += chunk.text
}
}
}
Java
Вы можете вызвать generateContentStream()
для потоковой передачи сгенерированного текста из мультимодального ввода текста и одного видео.
Publisher
из библиотеки Reactive Streams . // 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 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();
}
Web
Вы можете вызвать generateContentStream()
для потоковой передачи сгенерированного текста из мультимодального ввода текста и одного видео.
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 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();
Dart
Вы можете вызвать generateContentStream()
для потоковой передачи сгенерированного текста из мультимодального ввода текста и одного видео.
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 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);
}
Требования и рекомендации к файлам входных изображений
См. раздел Поддерживаемые входные файлы и требования для API Vertex AI Gemini, чтобы получить подробную информацию о следующем:
- Различные варианты предоставления файла в запросе (встроенные или с использованием URL-адреса или URI файла).
- Поддерживаемые типы файлов
- Поддерживаемые типы MIME и способы их указания
- Требования и рекомендации для файлов и мультимодальных запросов
Что еще вы можете сделать?
- Узнайте, как считать токены, прежде чем отправлять модели длинные запросы.
- Настройте Cloud Storage for Firebase чтобы вы могли включать большие файлы в свои мультимодальные запросы и иметь более управляемое решение для предоставления файлов в приглашениях. Файлы могут включать изображения, PDF-файлы, видео и аудио.
- Начните думать о подготовке к работе, включая настройку Firebase App Check для защиты Gemini API от злоупотреблений со стороны неавторизованных клиентов. Также обязательно ознакомьтесь с производственным контрольным списком .
Попробуйте другие возможности
- Стройте многоходовые разговоры (чат) .
- Генерация текста из текстовых подсказок .
- Генерируйте структурированный вывод (например, JSON) как из текстовых, так и из мультимодальных подсказок.
- Генерируйте изображения из текстовых подсказок.
- Используйте вызов функций для подключения генеративных моделей к внешним системам и информации.
Узнайте, как контролировать создание контента
- Понимание структуры подсказок , включая лучшие практики, стратегии и примеры подсказок.
- Настройте параметры модели , такие как температура и токены максимальной выходной мощности (для Gemini ) или соотношение сторон и поколение людей (для Imagen ).
- Используйте настройки безопасности , чтобы настроить вероятность получения ответов, которые могут быть расценены как вредные.
Узнайте больше о поддерживаемых моделях
Узнайте о моделях, доступных для различных вариантов использования , а также об их квотах и ценах .Оставьте отзыв о своем опыте использования Vertex AI в Firebase.