| Доступно только при использовании API Vertex AI Gemini в качестве поставщика API. |
When calling the Vertex AI Gemini API from your app using a Firebase AI Logic SDK, you can prompt a Gemini model to generate text based on a multimodal input, like images, PDFs, video, and audio.
For the non-text parts of the input (like media files), you can optionally use Cloud Storage for Firebase to include files in the request. At a high-level, here's what you need to know about this feature:
You can use Cloud Storage for Firebase with any multimodal request (like both text generation and chat) if you're using the Vertex AI Gemini API . The examples in this guide show a basic text-and-image input.
You specify the file's MIME type and its Cloud Storage for Firebase URL (which always begin with
gs://) in the request input. These values are metadata automatically assigned to any file uploaded to a Cloud Storage bucket.Необходимо использовать поддерживаемый тип файла и URL-адрес .
This solution guide describes how to set up Cloud Storage for Firebase , upload a file to a Cloud Storage for Firebase bucket from your app, and then include the file's MIME type and Cloud Storage for Firebase URL in your multimodal request to the Gemini API .
Хотите посмотреть примеры кода? Или вы уже настроили Cloud Storage for Firebase и готовы начать использовать его для мультимодальных запросов?
Почему стоит использовать Cloud Storage for Firebase для вашего приложения?
Cloud Storage for Firebase uses the same fast, secure, and scalable infrastructure as Google Cloud Storage to store blobs and files, and its client SDKs are specifically built for mobile and web apps.
Для SDK Firebase AI Logic максимальный размер запроса составляет 20 МБ. Если запрос слишком большой, вы получите ошибку HTTP 413. Если размер файла превысит 20 МБ, используйте URL-адрес Cloud Storage for Firebase чтобы включить файл в многомодальный запрос. Однако, если файл небольшой, его часто можно передать напрямую в виде встроенных данных (обратите внимание, что файл, предоставленный в виде встроенных данных, кодируется в base64 во время передачи, что увеличивает размер запроса).
Вот ещё несколько преимуществ использования Cloud Storage for Firebase :
You can have end users upload images directly from your app into a Cloud Storage for Firebase bucket, and then you can include those images in your multimodal prompts just by specifying the file's MIME type and Cloud Storage for Firebase URL (which is an identifier for the file).
Вы можете сэкономить время и трафик конечных пользователей, если им необходимо предоставить изображения, особенно при плохом или нестабильном качестве сети.
- Если загрузка или скачивание файла прерывается, SDK Cloud Storage for Firebase автоматически возобновляет операцию с того места, где она была прервана.
- Один и тот же загруженный файл можно использовать несколько раз, и конечному пользователю не придется загружать его каждый раз, когда он понадобится в вашем приложении (например, в новом мультимодальном запросе).
Вы можете ограничить доступ конечных пользователей к файлам, хранящимся в Cloud Storage for Firebase с помощью Firebase Security Rules , которые разрешают загрузку, скачивание или удаление файлов только авторизованным пользователям.
You can access the files in your bucket from Firebase or from Google Cloud , giving you the flexibility to do server-side processing such as image filtering or video transcoding using the Google Cloud Storage APIs.
Какие типы файлов и URL-адресов поддерживаются?
Ниже приведены требования к файлам и URL-адресам, необходимые для использования Cloud Storage for Firebase URLs с SDK Firebase AI Logic :
Файл должен соответствовать требованиям к входным файлам для многомодальных запросов . Это включает в себя такие требования, как MIME-тип и размер файла.
The file must be stored in a Cloud Storage for Firebase bucket (which means the bucket is accessible to Firebase services, like Firebase Security Rules ). If you can view your bucket in the Firebase console , then it's a Cloud Storage for Firebase bucket.
Корзина Cloud Storage for Firebase должна находиться в том же проекте Firebase, в котором вы зарегистрировали свое приложение.
URL-адрес Cloud Storage for Firebase в файле должен начинаться с
gs://, именно так формируются все URL-адреса Google Cloud Storage .URL-адрес файла не может быть URL-адресом браузера (например, URL-адресом изображения, найденного в интернете).
Кроме того, Firebase Security Rules для вашего хранилища должны разрешать соответствующий доступ к файлу. Например:
Если у вас есть общедоступные правила , то любой пользователь или клиент может получить доступ к файлу.
If you have robust rules (strongly recommended) , then Firebase will check that the signed in user or client has sufficient access to the file before allowing the call to go through with the provided URL.
Используйте Cloud Storage for Firebase с помощью Firebase AI Logic.
| Доступно только при использовании API Vertex AI Gemini в качестве поставщика API. |
Шаг 1 : Настройка Cloud Storage for Firebase
Подробные инструкции по настройке Cloud Storage for Firebase вы найдете в руководстве по началу работы: iOS+ | Android | Web | Flutter | Unity
Вот основные задачи, которые вам предстоит выполнить:
Создайте или импортируйте Cloud Storage for Firebase в свой проект Firebase.
Примените Firebase Security Rules к этому сегменту. Security Rules помогают защитить ваши файлы, ограничивая доступ только авторизованным конечным пользователям.
Добавьте клиентскую библиотеку Cloud Storage for Firebase в свое приложение.
Обратите внимание, что вы можете пропустить этот шаг, но в этом случае вам всегда необходимо явно указывать MIME-тип и значение URL в ваших запросах .
Шаг 2 : Загрузите файл в хранилище (bucket).
In the Cloud Storage documentation, you can learn all the different ways to upload files to a bucket. For example, you can upload local files from the end-user's device, such as photos and videos from the camera. Learn more: iOS+ | Android | Web | Flutter | Unity
When you upload a file to a bucket, Cloud Storage automatically applies the following two pieces of information to the file. You'll need to include these values in the request (as shown in the next step of this guide).
MIME type : This is the media type of the file (for example,
image/png). We'll automatically try to detect the MIME type during upload and apply that metadata to the object in the bucket. However, you can optionally specify the MIME type during upload.URL-адрес Cloud Storage for Firebase : это уникальный идентификатор файла. URL-адрес должен начинаться с
gs://.
Шаг 3 : Включите MIME-тип файла и URL-адрес в многомодальный запрос.
Once you have a file stored in a bucket, you can include its MIME type and URL in a request. Note that these examples show a non-streaming generateContent request, but you can also use URLs with streaming and chat.
Для включения файла в запрос можно использовать один из следующих вариантов:
Вариант 1: Укажите MIME-тип и URL-адрес, используя ссылку на хранилище.
Вариант 2: Укажите MIME-тип и URL-адрес явно.
Вариант 1: Укажите MIME-тип и URL-адрес, используя ссылку на хранилище.
| Прежде чем попробовать этот пример, убедитесь, что вы ознакомились с руководством по началу работы с SDK Firebase AI Logic . |
Use this option if you've just uploaded the file to the bucket, and you want to immediately include the file (via a Storage reference) in the request. The call requires both the MIME type and the Cloud Storage for Firebase URL.
Быстрый
// Upload an image file using Cloud Storage for Firebase.
let storageRef = Storage.storage().reference(withPath: "images/image.jpg")
guard let imageURL = Bundle.main.url(forResource: "image", withExtension: "jpg") else {
fatalError("File 'image.jpg' not found in main bundle.")
}
let metadata = try await storageRef.putFileAsync(from: imageURL)
// Get the MIME type and Cloud Storage for Firebase URL.
guard let mimeType = metadata.contentType else {
fatalError("The MIME type of the uploaded image is nil.")
}
// Construct a URL in the required format.
let storageURL = "gs://\(storageRef.bucket)/\(storageRef.fullPath)"
let prompt = "What's in this picture?"
// Construct the imagePart with the MIME type and the URL.
let imagePart = FileDataPart(uri: storageURL, mimeType: mimeType)
// To generate text output, call generateContent with the prompt and the imagePart.
let result = try await model.generateContent(prompt, imagePart)
if let text = result.text {
print(text)
}
Kotlin
В Kotlin методы в этом SDK являются функциями приостановки и должны вызываться из области видимости сопрограммы .// Upload an image file using Cloud Storage for Firebase.
val storageRef = Firebase.storage.reference.child("images/image.jpg")
val fileUri = Uri.fromFile(File("image.jpg"))
try {
val taskSnapshot = storageRef.putFile(fileUri).await()
// Get the MIME type and Cloud Storage for Firebase file path.
val mimeType = taskSnapshot.metadata?.contentType
val bucket = taskSnapshot.metadata?.bucket
val filePath = taskSnapshot.metadata?.path
if (mimeType != null && bucket != null) {
// Construct a URL in the required format.
val storageUrl = "gs://$bucket/$filePath"
// Construct a prompt that includes text, the MIME type, and the URL.
val prompt = content {
fileData(mimeType = mimeType, uri = storageUrl)
text("What's in this picture?")
}
// To generate text output, call generateContent with the prompt.
val response = model.generateContent(prompt)
println(response.text)
}
} catch (e: StorageException) {
// An error occurred while uploading the file.
} catch (e: GoogleGenerativeAIException) {
// An error occurred while generating text.
}
Java
В Java методы этого SDK возвращают объектListenableFuture . // Upload an image file using Cloud Storage for Firebase.
StorageReference storage = FirebaseStorage.getInstance().getReference("images/image.jpg");
Uri fileUri = Uri.fromFile(new File("images/image.jpg"));
storage.putFile(fileUri).addOnSuccessListener(taskSnapshot -> {
// Get the MIME type and Cloud Storage for Firebase file path.
String mimeType = taskSnapshot.getMetadata().getContentType();
String bucket = taskSnapshot.getMetadata().getBucket();
String filePath = taskSnapshot.getMetadata().getPath();
if (mimeType != null && bucket != null) {
// Construct a URL in the required format.
String storageUrl = "gs://" + bucket + "/" + filePath;
// Create a prompt that includes text, the MIME type, and the URL.
Content prompt = new Content.Builder()
.addFileData(storageUrl, mimeType)
.addText("What's in this picture?")
.build();
// To generate text output, call generateContent with the prompt.
GenerativeModelFutures modelFutures = GenerativeModelFutures.from(model);
ListenableFuture<GenerateContentResponse> response = modelFutures.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(@NonNull Throwable t) {
t.printStackTrace();
}
}, executor);
}
}).addOnFailureListener(e -> {
// An error occurred while uploading the file.
e.printStackTrace();
});
Web
// Upload an image file using Cloud Storage for Firebase.
const storageRef = ref(storage, "image.jpg");
const uploadResult = await uploadBytes(storageRef, file);
// Get the MIME type and Cloud Storage for Firebase URL.
// toString() is the simplest way to construct the Cloud Storage for Firebase URL
// in the required format.
const mimeType = uploadResult.metadata.contentType;
const storageUrl = uploadResult.ref.toString();
// Construct the imagePart with the MIME type and the URL.
const imagePart = { fileData: { mimeType, fileUri: storageUrl }};
// To generate text output, call generateContent with the prompt and imagePart.
const result = await model.generateContent([prompt, imagePart]);
console.log(result.response.text());
Dart
// Upload an image file using Cloud Storage for Firebase.
final storageRef = FirebaseStorage.instance.ref();
final imageRef = storageRef.child("images/image.jpg");
await imageRef.putData(data);
// Get the MIME type and Cloud Storage for Firebase file path.
final metadata = await imageRef.getMetadata();
final mimeType = metadata.contentType;
final bucket = imageRef.bucket;
final fullPath = imageRef.fullPath;
final prompt = TextPart("What's in the picture?");
// Construct a URL in the required format.
final storageUrl = 'gs://$bucket/$fullPath';
// Construct the filePart with the MIME type and the URL.
final filePart = FileData(mimeType, storageUrl);
// To generate text output, call generateContent with the text and the filePart.
final response = await model.generateContent([
Content.multi([prompt, filePart])
]);
print(response.text);
Единство
var storageRef = FirebaseStorage.DefaultInstance.GetReference("images/image.jpg");
var metadata = await storageRef.PutFileAsync(filePathToJpg);
// Get the MIME type and Cloud Storage for Firebase URL.
var mimeType = metadata.ContentType;
// Construct a URL in the required format.
var storageURL = new Uri($"gs://{storageRef.Bucket}/{storageRef.Path}");
var prompt = ModelContent.Text("What's in this picture?");
// Construct a FileData that explicitly includes the MIME type and
// Cloud Storage for Firebase URL values.
var fileData = ModelContent.FileData(mimeType, storageURL);
// To generate text output, call GenerateContentAsync with the prompt and fileData.
var response = await model.GenerateContentAsync(new [] { prompt, fileData });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
Вариант 2: Укажите MIME-тип и URL-адрес явно.
| Прежде чем попробовать этот пример, убедитесь, что вы ознакомились с руководством по началу работы с SDK Firebase AI Logic . |
Use this option if you know the values for the MIME type and Cloud Storage for Firebase URL, and you want to include them explicitly in the multimodal request. The call requires both the MIME type and the URL.
Быстрый
let prompt = "What's in this picture?"
// Construct an imagePart that explicitly includes the MIME type and
// Cloud Storage for Firebase URL values.
let imagePart = FileDataPart(uri: "gs://bucket-name/path/image.jpg", mimeType: "image/jpeg")
// To generate text output, call generateContent with the prompt and imagePart.
let result = try await model.generateContent(prompt, imagePart)
if let text = result.text {
print(text)
}
Kotlin
В Kotlin методы в этом SDK являются функциями приостановки и должны вызываться из области видимости сопрограммы .// Construct a prompt that explicitly includes the MIME type and Cloud Storage for Firebase URL values.
val prompt = content {
fileData(mimeType = "image/jpeg", uri = "gs://bucket-name/path/image.jpg")
text("What's in this picture?")
}
// To generate text output, call generateContent with the prompt.
val response = model.generateContent(prompt)
println(response.text)
Java
В Java методы этого SDK возвращают объектListenableFuture . // Construct a prompt that explicitly includes the MIME type and Cloud Storage for Firebase URL values.
Content prompt = new Content.Builder()
.addFilePart("gs://bucket-name/path/image.jpg", "image/jpeg")
.addText("What's in this picture?")
.build();
// To generate text output, call generateContent with the prompt
GenerativeModelFutures modelFutures = GenerativeModelFutures.from(model);
ListenableFuture<GenerateContentResponse> response = modelFutures.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
System.out.println(resultText);
}
@Override
public void onFailure(@NonNull Throwable t) {
t.printStackTrace();
}
}, executor);
Web
const prompt = "What's in this picture?";
// Construct an imagePart that explicitly includes the MIME type and Cloud Storage for Firebase URL values.
const imagePart = { fileData: { mimeType: "image/jpeg", fileUri: "gs://bucket-name/path/image.jpg" }};
// To generate text output, call generateContent with the prompt and imagePart.
const result = await model.generateContent([prompt, imagePart]);
console.log(result.response.text());
Dart
final prompt = TextPart("What's in the picture?");
// Construct a filePart that explicitly includes the MIME type and Cloud Storage for Firebase URL values.
final filePart = FileData('image/jpeg', 'gs://bucket-name/path/image.jpg'),
// To generate text output, call generateContent with the prompt and filePart.
final response = await model.generateContent([
Content.multi([prompt, filePart])
]);
print(response.text);
Единство
var prompt = ModelContent.Text("What's in this picture?");
// Construct a FileData that explicitly includes the MIME type and
// Cloud Storage for Firebase URL values.
var fileData = ModelContent.FileData(
mimeType: "image/jpeg",
uri: new Uri("gs://bucket-name/path/image.jpg")
);
// To generate text output, call GenerateContentAsync with the prompt and fileData.
var response = await model.GenerateContentAsync(new [] { prompt, fileData });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");