Gemini Developer API

Android geliştiricilerin, Gemini Pro ve Flash modellerine erişmek için Firebase AI Logic'i kullanarak Gemini Developer API'yi kullanmasını öneririz. Kredi kartı kullanmadan başlamanıza olanak tanır ve geniş kapsamlı bir ücretsiz katman sunar. Entegrasyonunuzu küçük bir kullanıcı tabanıyla doğruladıktan sonra ücretli katmana geçerek ölçeklendirebilirsiniz.

Firebase Android SDK'sı içeren bir Android uygulamasının resmi. Bir ok, SDK'dan Cloud ortamındaki Firebase'e işaret ediyor. Firebase'den gelen başka bir ok, Gemini Developer API'yi gösterir. Gemini Developer API de Cloud'daki Gemini Pro ve Flash'a bağlıdır.
Şekil 1. Gemini Developer API'ye erişmek için Firebase AI Logic entegrasyon mimarisi.

Başlarken

Gemini API ile doğrudan uygulamanızdan etkileşime geçmeden önce, istemlerle ilgili bilgi edinme ve Firebase ile uygulamanızı SDK'yı kullanacak şekilde ayarlama da dahil olmak üzere birkaç işlem yapmanız gerekir.

İstemlerle deneme yapma

İstemlerle denemeler yapmak, Android uygulamanız için en iyi ifadeyi, içeriği ve biçimi bulmanıza yardımcı olabilir. Google AI Studio, uygulamanızın kullanım alanları için istemleri prototip haline getirmek ve tasarlamak üzere kullanabileceğiniz bir IDE'dir.

Kullanım alanınız için doğru istemi oluşturmak, bilimden çok sanattır. Bu nedenle deneme yapmak çok önemlidir. İstemler hakkında daha fazla bilgiyi Firebase dokümanlarında bulabilirsiniz.

İsteminiz hazır olduğunda, kodunuza ekleyebileceğiniz kod snippet'leri almak için "<>" düğmesini tıklayın.

Firebase projesi oluşturma ve uygulamanızı Firebase'e bağlama

Uygulamanızdan API'yi çağırmaya hazır olduğunuzda Firebase'i ve SDK'yı uygulamanızda ayarlamak için Firebase AI Logic başlangıç kılavuzunun "1. Adım" bölümündeki talimatları uygulayın.

Gradle bağımlılığını ekleme

Uygulama modülünüze aşağıdaki Gradle bağımlılığını ekleyin:

Kotlin

dependencies {
  // ... other androidx dependencies

  // Import the BoM for the Firebase platform
  implementation(platform("com.google.firebase:firebase-bom:33.13.0"))

  // Add the dependency for the Firebase AI Logic library When using the BoM,
  // you don't specify versions in Firebase library dependencies
  implementation("com.google.firebase:firebase-ai")
}

Java

dependencies {
  // Import the BoM for the Firebase platform
  implementation(platform("com.google.firebase:firebase-bom:33.13.0"))

  // Add the dependency for the Firebase AI Logic library When using the BoM,
  // you don't specify versions in Firebase library dependencies
  implementation("com.google.firebase:firebase-ai")

  // Required for one-shot operations (to use `ListenableFuture` from Guava
  // Android)
  implementation("com.google.guava:guava:31.0.1-android")

  // Required for streaming operations (to use `Publisher` from Reactive
  // Streams)
  implementation("org.reactivestreams:reactive-streams:1.0.4")
}

Üretken modeli başlatma

Bir GenerativeModel örneği oluşturarak ve model adını belirterek başlayın:

Kotlin

val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-2.0-flash")

Java

GenerativeModel firebaseAI = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-2.0-flash");

GenerativeModelFutures model = GenerativeModelFutures.from(firebaseAI);

Gemini Developer API ile kullanılabilen mevcut modeller hakkında daha fazla bilgi edinin. Ayrıca model parametrelerini yapılandırma hakkında daha fazla bilgi edinebilirsiniz.

Uygulamanızdan Gemini Developer API ile etkileşim kurma

Firebase'i ve uygulamanızı SDK'yı kullanacak şekilde ayarladığınıza göre, uygulamanızdan Gemini Developer API ile etkileşime geçmeye hazırsınız.

Metin oluşturma

Metin yanıt oluşturmak için isteminizle birlikte generateContent()'ü arayın.

Kotlin

scope.launch {
  val response = model.generateContent("Write a story about a magic backpack.")
}

Java

Content prompt = new Content.Builder()
    .addText("Write a story about a magic backpack.")
    .build();

ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        [...]
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Resimlerden ve diğer medyalardan metin oluşturma

Metin ve resim veya diğer medya öğelerini içeren bir istemden de metin oluşturabilirsiniz. generateContent() işlevini çağırırken medyayı satır içi veri olarak iletebilirsiniz.

Örneğin, bir bitmap kullanmak için image içerik türünü kullanın:

Kotlin

scope.launch {
  val response = model.generateContent(
    content {
      image(bitmap)
      text("what is the object in the picture?")
    }
  )
}

Java

Content content = new Content.Builder()
        .addImage(bitmap)
        .addText("what is the object in the picture?")
        .build();

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        [...]
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Ses dosyası göndermek için inlineData içerik türünü kullanın:

Kotlin

val contentResolver = applicationContext.contentResolver
val inputStream = contentResolver.openInputStream(audioUri).use { stream ->
    stream?.let {
        val bytes = stream.readBytes()

        val prompt = content {
            inlineData(bytes, "audio/mpeg")  // Specify the appropriate audio MIME type
            text("Transcribe this audio recording.")
        }

        val response = model.generateContent(prompt)
    }
}

Java

ContentResolver resolver = getApplicationContext().getContentResolver();

try (InputStream stream = resolver.openInputStream(audioUri)) {
    File audioFile = new File(new URI(audioUri.toString()));
    int audioSize = (int) audioFile.length();
    byte audioBytes = new byte[audioSize];
    if (stream != null) {
        stream.read(audioBytes, 0, audioBytes.length);
        stream.close();

        // Provide a prompt that includes audio specified earlier and text
        Content prompt = new Content.Builder()
              .addInlineData(audioBytes, "audio/mpeg")  // Specify the appropriate audio MIME type
              .addText("Transcribe what's said in this audio recording.")
              .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 text = result.getText();
                Log.d(TAG, (text == null) ? "" : text);
            }
            @Override
            public void onFailure(Throwable t) {
                Log.e(TAG, "Failed to generate a response", t);
            }
        }, executor);
    } else {
        Log.e(TAG, "Error getting input stream for file.");
        // Handle the error appropriately
    }
} catch (IOException e) {
    Log.e(TAG, "Failed to read the audio file", e);
} catch (URISyntaxException e) {
    Log.e(TAG, "Invalid audio file", e);
}

Video dosyası sağlamak için inlineData içerik türünü kullanmaya devam edin:

Kotlin

val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
  stream?.let {
    val bytes = stream.readBytes()

    val prompt = content {
        inlineData(bytes, "video/mp4")  // Specify the appropriate video MIME type
        text("Describe the content of this video")
    }

    val response = model.generateContent(prompt)
  }
}

Java

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 video specified earlier and text
        Content prompt = new Content.Builder()
                .addInlineData(videoBytes, "video/mp4")
                .addText("Describe the content of this 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();
}

Benzer şekilde, PDF (application/pdf) ve düz metin (text/plain) dokümanlarını, ilgili MIME türlerini parametre olarak göndererek de iletebilirsiniz.

Çoklu turlu sohbet

Birden fazla katılımcının yer aldığı sohbetleri de destekleyebilirsiniz. startChat() işleviyle sohbet başlatın. İsteğe bağlı olarak modele bir mesaj geçmişi sağlayabilirsiniz. Ardından sohbet mesajı göndermek için sendMessage() işlevini çağırın.

Kotlin

val chat = model.startChat(
    history = listOf(
        content(role = "user") { text("Hello, I have 2 dogs in my house.") },
        content(role = "model") { text("Great to meet you. What would you like to know?")   }
    )
)

scope.launch {
   val response = chat.sendMessage("How many paws are in my house?")
}

Java

Content.Builder userContentBuilder = new Content.Builder();
userContentBuilder.setRole("user");
userContentBuilder.addText("Hello, I have 2 dogs in my house.");
Content userContent = userContentBuilder.build();

Content.Builder modelContentBuilder = new Content.Builder();
modelContentBuilder.setRole("model");
modelContentBuilder.addText("Great to meet you. What would you like to know?");
Content modelContent = userContentBuilder.build();

List<Content> history = Arrays.asList(userContent, modelContent);

// Initialize the chat
ChatFutures chat = model.startChat(history);

// Create a new user message
Content.Builder messageBuilder = new Content.Builder();
messageBuilder.setRole("user");
messageBuilder.addText("How many paws are in my house?");

Content message = messageBuilder.build();

// Send the message
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(message);
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);

Daha fazla ayrıntı için Firebase belgelerini inceleyin.

Sonraki adımlar