Skip to main content

Access Gemini Android SDK in Python

This project has been archived.

The maintainers of this project have marked this project as archived. No new releases are expected.

Project description

Gemini (Firebase-Vertex-AI)

Access Gemini Android SDK in Python

[!CAUTION] Firebase-Vertex-AI is now deprecated by the firebase team. Firebase Vertex AI is now Firebase AI. You can find the new Python SimpleJnius implementation here

GitAds Sponsored

Sponsored by GitAds

Usage

Note: NO NEED FOR THREAD OR ASYNC.

For autocompletion in IDE

pip install sjgeminifvai

Set up your firebase project for Android

Read more here

Add SDK to buildozer.spec file

requirements=sjgeminifvai,simplejnius

android.gradle_dependencies=com.google.guava:guava:32.0.1-android,
  org.reactivestreams:reactive-streams:1.0.4,com.google.firebase:firebase-vertexai:16.0.0-beta04

Interact with Vertex Gemini API Without Streaming

Wait for the entire result instead of streaming; the result is only returned after the model completes the entire generation process.

from sjgeminifvai.jclass import (
    FirebaseVertexAI,
    ContentBuilder,
    GenerativeModelFutures
)
from simplejnius.guava.jclass import Futures
from simplejnius.guava.jinterface import FutureCallback
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput


class GeminiApp(App):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.future_callback = None
        self.response = None
        self.prompt = None
        self.textinput = None
        self.label = None

        # Initialize the Vertex AI service and the generative model
        # Specify a model that supports your use case
        # Gemini 1.5 models are versatile and can be used with all API capabilities
        vertex = FirebaseVertexAI.getInstance()
        self.gm = vertex.generativeModel("gemini-1.5-flash")

        # Use the GenerativeModelFutures Java compatibility layer which offers
        # support for ListenableFuture and Publisher APIs
        self.model = GenerativeModelFutures.from_(self.gm)

    def build(self):
        self.label = Label()
        self.textinput = TextInput(
            size_hint_y=.1,
            hint_text="Chat with gemini",
            on_text_validate=self.chat_gemini
        )
        box = BoxLayout(orientation="vertical")
        box.add_widget(self.label)
        box.add_widget(self.textinput)
        return box

    def chat_gemini(self, instance):
        # Provide a prompt that contains text
        self.prompt = (
            ContentBuilder()
            .addText(instance.text)
            .build()
        )

        # To generate text output, call generateContent with the text input
        self.response = self.model.generateContentResponse(self.prompt)

        self.future_callback = FutureCallback(
            callback=dict(
                on_success=self.get_gemin_reply,
                on_failure=print
            )
        )
        Futures.addCallback(self.response, self.future_callback)

    def get_gemini_reply(self, result):
        self.label.text = result.getText()


if __name__ == "__main__":
    GeminiApp().run()

# report any bug or error if the above code does not work as expected

Interact with Vertex Gemini API With Streaming

You can achieve faster interactions by not waiting for the entire result from the model generation, and instead use streaming to handle partial results.

This example shows how to use generateContentStream to stream generated text from a prompt request that includes only text:

from sjgeminifvai.jclass import (
    FirebaseVertexAI,
    ContentBuilder,
    GenerativeModelFutures
)
from simplejnius.reactivestreams.jinterface import Subscriber
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.clock import Clock


class GeminiApp(App):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.subscriber = None
        self.gcr = None
        self.streaming_response = None
        self.prompt = None
        self.textinput = None
        self.label = None

        # Initialize the Vertex AI service and the generative model
        # Specify a model that supports your use case
        # Gemini 1.5 models are versatile and can be used with all API capabilities
        vertex = FirebaseVertexAI.getInstance()
        self.gm = vertex.generativeModel("gemini-1.5-flash")

        # Use the GenerativeModelFutures Java compatibility layer which offers
        # support for ListenableFuture and Publisher APIs
        self.model = GenerativeModelFutures.from_(self.gm)

    def build(self):
        self.label = Label()
        self.textinput = TextInput(
            size_hint_y=.1,
            hint_text="Chat with gemini",
            on_text_validate=self.chat_gemini
        )
        box = BoxLayout(orientation="vertical")
        box.add_widget(self.label)
        box.add_widget(self.textinput)
        return box

    def chat_gemini(self, instance):
        # Provide a prompt that contains text
        self.prompt = (
            ContentBuilder()
            .addText(instance.text)
            .build()
        )

        # To stream generated text output, call generateContentStream with the text input
        self.streaming_response = self.model.generateContentStream(self.prompt)

        self.subscriber = Subscriber(
            callback=dict(
                on_next=self.get_gemini_reply,
                on_complete=lambda result: setattr(self.label, "text", result.getText()),
                on_error=print,
                on_subscribe=print
            )
        )
        self.streaming_response.subscribe(self.subscriber)

    def get_gemini_reply(self, result):
        chunk = result.getText()

        def add_chunk_to_label(_):
            self.label.text += chunk

        Clock.schedule_once(add_chunk_to_label)


if __name__ == "__main__":
    GeminiApp().run()

# report any bug or error if the above code does not work as expected

Examples to interact with images and videos coming soon

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sjgeminifvai-1.0.0.tar.gz (6.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sjgeminifvai-1.0.0-py3-none-any.whl (7.8 kB view details)

Uploaded Python 3

File details

Details for the file sjgeminifvai-1.0.0.tar.gz.

File metadata

  • Download URL: sjgeminifvai-1.0.0.tar.gz
  • Upload date:
  • Size: 6.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.0 CPython/3.13.8 Linux/6.14.0-36-generic

File hashes

Hashes for sjgeminifvai-1.0.0.tar.gz
Algorithm Hash digest
SHA256 9162ab07b9434a74e9e7d1d506548d75b84ce876aacef2f78a7aeec67e50d2fb
MD5 4def3840ef84dcd06e6a20e8e78308d8
BLAKE2b-256 7bd5beafb024b05f1cc6d3ca28fc966c5992dba0276d4685b902adc0ab6c7f18

See more details on using hashes here.

File details

Details for the file sjgeminifvai-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: sjgeminifvai-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 7.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.0 CPython/3.13.8 Linux/6.14.0-36-generic

File hashes

Hashes for sjgeminifvai-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5da850a51a6483c74dac2ef8ac52e031f65fd5d910b9c1fe1dfd1af0437da861
MD5 14252bba42d0d79599775b2a54bc1145
BLAKE2b-256 926a8191dd7d4c1b714db0fbef7d9e76e267392b2146c1031ee82fdcae59a274

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page