Çok modlu isteklere büyük dosyaları dahil edin ve dosyaları Firebase için Cloud Storage'ı kullanarak yönetin

Yalnızca Vertex AI Gemini API API sağlayıcısı olarak kullanılırken kullanılabilir.

Firebase AI Logic SDK'sını kullanarak uygulamanızdan Vertex AI Gemini API işlevini çağırırken Gemini modelinden resim, PDF, video ve ses gibi çok formatlı bir girişe dayalı metin oluşturmasını isteyebilirsiniz.

Girişin metin olmayan kısımları (ör. medya dosyaları) için isteğe bağlı olarak Cloud Storage for Firebase simgesini kullanarak isteğe dosya ekleyebilirsiniz. Bu özellik hakkında bilmeniz gerekenler:

  • Vertex AI Gemini API kullanıyorsanız Cloud Storage for Firebase simgesini çok formatlı tüm isteklerde (ör. hem metin oluşturma hem de sohbet) kullanabilirsiniz. Bu kılavuzdaki örneklerde temel bir metin ve resim girişi gösterilmektedir.

  • İstek girişinde dosyanın MIME türünü ve Cloud Storage for Firebase URL'sini (her zaman gs:// ile başlar) belirtirsiniz. Bu değerler, Cloud Storage paketine yüklenen tüm dosyalara otomatik olarak atanan meta verilerdir.

  • Desteklenen bir dosya türü ve URL kullanmanız gerekir.


Bu çözüm kılavuzunda, Cloud Storage for Firebase nasıl ayarlanacağı, uygulamanızdan Cloud Storage for Firebase paketine nasıl dosya yükleneceği ve ardından Gemini API'a gönderilen çok formatlı isteğinize dosyanın MIME türü ile Cloud Storage for Firebase URL'sinin nasıl ekleneceği açıklanmaktadır.

Kod örneklerini görmek ister misiniz? Cloud Storage for Firebase'ı kurdunuz mu ve çok formatlı isteklerinizle kullanmaya hazır mısınız?

Kod örneklerine git

Uygulamanızda neden Cloud Storage for Firebase kullanmalısınız?

Cloud Storage for Firebase, blob'ları ve dosyaları depolamak için Google Cloud Storage ile aynı hızlı, güvenli ve ölçeklenebilir altyapıyı kullanır. İstemci SDK'ları ise özellikle mobil ve web uygulamaları için geliştirilmiştir.

Firebase AI Logic SDK'ları için maksimum istek boyutu 20 MB'tır. İstek çok büyükse HTTP 413 hatası alırsınız. Bir dosyanın boyutu, toplam istek boyutunun 20 MB'ı aşmasına neden olacaksa dosyayı çok formatlı isteğinize eklemek için Cloud Storage for Firebase URL'si kullanın. Ancak küçük bir dosyayı genellikle doğrudan satır içi veri olarak iletebilirsiniz (Bununla birlikte, satır içi veri olarak sağlanan bir dosyanın aktarım sırasında base64 ile kodlandığını ve bu durumun isteğin boyutunu artırdığını unutmayın).

Cloud Storage for Firebase kullanmanın diğer bazı avantajları:

  • Son kullanıcıların, resimleri doğrudan uygulamanızdan bir Cloud Storage for Firebase paketine yüklemesini sağlayabilirsiniz. Ardından, dosyanın MIME türünü ve Cloud Storage for Firebase URL'sini (dosyanın tanımlayıcısı) belirterek bu resimleri çok formatlı istemlerinize ekleyebilirsiniz.

  • Son kullanıcılarınızın resim sağlaması gerektiğinde, özellikle ağ kalitesi düşük veya kararsızsa zamandan ve bant genişliğinden tasarruf etmelerini sağlayabilirsiniz.

    • Bir dosya yükleme veya indirme işlemi kesintiye uğrarsa Cloud Storage for Firebase SDK'ları işlemi kaldığı yerden otomatik olarak yeniden başlatır.
    • Yüklenen aynı dosya, son kullanıcının uygulamanızda her gerektiğinde (ör. yeni bir çok formatlı istekte) aynı dosyayı yüklemesi gerekmeden birden çok kez kullanılabilir.
  • Cloud Storage for Firebase'da depolanan dosyalara son kullanıcı erişimini kısıtlamak için Firebase Security Rules'ı kullanabilirsiniz. Bu ayarlar, yalnızca yetkili bir kullanıcının dosya yüklemesine, indirmesine veya silmesine izin verir.

  • Paketinizdeki dosyalara Firebase'den veya Google Cloud üzerinden erişebilirsiniz. Bu sayede, Google Cloud Storage API'lerini kullanarak resim filtreleme veya video kod dönüştürme gibi sunucu tarafı işlemleri yapabilirsiniz.

Hangi dosya türleri ve URL'ler desteklenir?

Cloud Storage for Firebase URL'lerini Firebase AI Logic SDK'larıyla kullanmak istediğinizde dosyalar ve URL'lerle ilgili gereksinimler şunlardır:

  • Dosya, çok formatlı istekler için giriş dosyalarının koşullarını karşılamalıdır. MIME türü ve dosya boyutu gibi koşullar buna dahildir.

  • Dosya, Cloud Storage for Firebase paketinde depolanmalıdır (bu, paketin Firebase Security Rules gibi Firebase hizmetlerine erişilebilir olduğu anlamına gelir). Paketiniz Firebase konsolunda görüntülenebiliyorsa bu bir Cloud Storage for Firebase paketidir.

  • Cloud Storage for Firebase paketi, uygulamanızı kaydettiğiniz Firebase projesinde olmalıdır.

  • Dosyanın Cloud Storage for Firebase URL'si, tüm Google Cloud Storage URL'lerinin oluşturulma şekli olan gs:// ile başlamalıdır.

  • Dosyanın URL'si "tarayıcı" URL'si olamaz (örneğin, internette bulduğunuz bir resmin URL'si).

Ayrıca, paketinizin Firebase Security Rules, dosyaya uygun erişime izin vermelidir. Örneğin:

  • Herkese açık kurallarınız varsa herhangi bir kullanıcı veya istemci dosyaya erişebilir.

  • Güçlü kurallarınız varsa (şiddetle tavsiye edilir) Firebase, oturum açmış kullanıcının veya istemcinin dosyaya yeterli erişimi olup olmadığını kontrol ettikten sonra sağlanan URL ile çağrının devam etmesine izin verir.

Cloud Storage for Firebase URL'lerini Firebase AI Logic ile kullanma

Yalnızca Vertex AI Gemini API API sağlayıcısı olarak kullanılırken kullanılabilir.

1. adım: Cloud Storage for Firebase kurulumunu yapın

Cloud Storage for Firebase'yı ayarlamayla ilgili ayrıntılı talimatları başlangıç kılavuzunda bulabilirsiniz: iOS+ | Android | Web | Flutter | Unity

Yapmanız gereken üst düzey görevler şunlardır:

  1. Firebase projenizde Cloud Storage for Firebase paketi oluşturun veya içe aktarın.

  2. Bu pakete Firebase Security Rules uygulayın. Rules Yetkili son kullanıcılarla erişimi kısıtlayarak dosyalarınızı güvenceye almanıza yardımcı olur.

  3. Uygulamanıza Cloud Storage for Firebase için istemci kitaplığını ekleyin.

    Bu görevi atlayabileceğinizi ancak bu durumda her zaman MIME türü ve URL değerlerini isteklerinize açıkça eklemeniz gerektiğini unutmayın.

2. adım: Bir pakete dosya yükleyin

Cloud Storage dokümanlarında, dosyaları pakete yüklemenin tüm farklı yollarını öğrenebilirsiniz. Örneğin, son kullanıcının cihazındaki yerel dosyaları (ör. kameradan alınan fotoğraf ve videolar) yükleyebilirsiniz. Daha fazla bilgi: iOS+ | Android | Web | Flutter | Unity

Bir pakete dosya yüklediğinizde Cloud Storage, dosyaya otomatik olarak aşağıdaki iki bilgiyi uygular. Bu değerleri isteğe eklemeniz gerekir (bu kılavuzun sonraki adımında gösterildiği gibi).

  • MIME türü: Dosyanın medya türüdür (ör. image/png). Yükleme sırasında MIME türünü otomatik olarak algılamaya çalışırız ve bu meta verileri paketteki nesneye uygularız. Ancak yükleme sırasında MIME türünü isteğe bağlı olarak belirtebilirsiniz.

  • Cloud Storage for Firebase URL'si: Dosyanın benzersiz tanımlayıcısıdır. URL, gs:// ile başlamalıdır.

3. adım: Dosyanın MIME türünü ve URL'sini çok formatlı bir isteğe ekleyin

Bir pakette depolanan dosyanın MIME türünü ve URL'sini isteğe ekleyebilirsiniz. Bu örneklerde akışkan olmayan bir generateContent isteği gösterilmektedir ancak akışkan ve sohbet içeren URL'ler de kullanabilirsiniz.

Dosyayı isteğe eklemek için aşağıdaki seçeneklerden birini kullanabilirsiniz:

1. seçenek: Depolama referansı kullanarak MIME türünü ve URL'yi ekleyin

Bu örneği denemeden önce Firebase AI Logic SDK'lar için başlangıç kılavuzunu tamamladığınızdan emin olun.

Dosyayı kısa süre önce pakete yüklediyseniz ve dosyayı hemen isteğe dahil etmek (Storage referansı aracılığıyla) istiyorsanız bu seçeneği kullanın. Çağrı için hem MIME türü hem de Cloud Storage for Firebase URL'si gerekir.

Swift

// 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'de bu SDK'daki yöntemler askıya alma işlevleridir ve Coroutine kapsamından çağrılmaları gerekir.
// 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 = generativeModel.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 için bu SDK'daki yöntemler bir ListenableFuture döndürür.
// 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);

Unity

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. seçenek: MIME türünü ve URL'yi açıkça ekleyin

Bu örneği denemeden önce Firebase AI Logic SDK'lar için başlangıç kılavuzunu tamamladığınızdan emin olun.

MIME türü ve Cloud Storage for Firebase URL'si değerlerini biliyorsanız ve bunları çok formatlı isteğe açıkça dahil etmek istiyorsanız bu seçeneği kullanın. Çağrı için hem MIME türü hem de URL gerekir.

Swift

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'de bu SDK'daki yöntemler askıya alma işlevleridir ve Coroutine kapsamından çağrılmaları gerekir.
// 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 = generativeModel.generateContent(prompt)
println(response.text)

Java

Java için bu SDK'daki yöntemler bir ListenableFuture döndürür.
// 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);

Unity

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.");