Skip to main content
Archived

This project has been archived by its maintainers, and is no longer receiving any updates.

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

Metadata

Release files for sjgeminifvai 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sjgeminifvai 1.0.0
File Size Uploaded Provenance Actions
sjgeminifvai-1.0.0.tar.gz 6.3 kB Without provenance Details for sjgeminifvai-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sjgeminifvai 1.0.0
File Interpreter ABI Platform Actions
sjgeminifvai-1.0.0-py3-none-any.whl Python 3 none any Details for sjgeminifvai-1.0.0-py3-none-any.whl

Total release size: 14.2 kB

Release files / sjgeminifvai-1.0.0.tar.gz

Download URL sjgeminifvai-1.0.0.tar.gz
Size 6.3 kB
Tags Source
SHA-256 checksum
How to use checksums
9162ab07b9434a74e9e7d1d506548d75b84ce876aacef2f78a7aeec67e50d2fb
BLAKE2b-256 checksum
How to use checksums
7bd5beafb024b05f1cc6d3ca28fc966c5992dba0276d4685b902adc0ab6c7f18
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.0 CPython/3.13.8 Linux/6.14.0-36-generic

Release files / sjgeminifvai-1.0.0-py3-none-any.whl

Download URL sjgeminifvai-1.0.0-py3-none-any.whl
Size 7.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5da850a51a6483c74dac2ef8ac52e031f65fd5d910b9c1fe1dfd1af0437da861
BLAKE2b-256 checksum
How to use checksums
926a8191dd7d4c1b714db0fbef7d9e76e267392b2146c1031ee82fdcae59a274
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.0 CPython/3.13.8 Linux/6.14.0-36-generic

Security for sjgeminifvai 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page