Giter Club home page Giter Club logo

generative-ai-android's Introduction

Google AI SDK for Android

The Google AI client SDK for Android enables developers to use Google's state-of-the-art generative AI models (like Gemini) to build AI-powered features and applications. This SDK supports use cases like:

  • Generate text from text-only input
  • Generate text from text-and-images input (multimodal)
  • Build multi-turn conversations (chat)

For example, with just a few lines of code, you can access Gemini's multimodal capabilities to generate text from text-and-image input:

val generativeModel = GenerativeModel(
    modelName = "gemini-1.0-pro-vision-latest",
    apiKey = BuildConfig.apiKey
)

val cookieImage: Bitmap = // ...
val inputContent = content() {
  image(cookieImage)
  text("Does this look store-bought or homemade?")
}

val response = generativeModel.generateContent(inputContent)
print(response.text)

Note

If you want to access Gemini on-device (Gemini Nano), check out the Google AI Edge SDK for Android, which is enabled via Android AICore.

Try out the sample Android app

This repository contains a sample app demonstrating how the SDK can access and utilize the Gemini model for various use cases.

To try out the sample app you can directly import the project from Android Studio via File > New > Import Sample and searching for Generative AI Sample or follow these steps below:

  1. Check out this repository.
    git clone https://github.com/google/generative-ai-android

  2. Obtain an API key to use with the Google AI SDKs.

  3. Open and build the sample app in the generativeai-android-sample folder of this repo.

  4. Paste your API key into the apiKey property in the local.properties file.

  5. Run the app.

Installation and usage

Add the dependency implementation("com.google.ai.client.generativeai:generativeai:<version>") to your Android project.

For detailed instructions, you can find a quickstart for the Google AI client SDK for Android in the Google documentation.

This quickstart describes how to add your API key and the SDK's dependency to your app, initialize the model, and then call the API to access the model. It also describes some additional use cases and features, like streaming, counting tokens, and controlling responses.

Documentation

Find complete documentation for the Google AI SDKs and the Gemini model in the Google documentation:
https://ai.google.dev/docs

Contributing

See Contributing for more information on contributing to the Google AI client SDK for Android.

License

The contents of this repository are licensed under the Apache License, version 2.0.

generative-ai-android's People

Contributors

5peak2me avatar davidmotson avatar daymxn avatar emilypgoogle avatar google-admin avatar m-asadullah avatar pedrosax avatar rlazo avatar ryanwilson avatar thatfiredev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

generative-ai-android's Issues

Request payload size exceeds the limit: 4194304 bytes.

image

private fun imageConvertText(uri: Uri) {
        loadingDialog.show()
        try {
            Log.d("result", "bitmap start")
            val bitmap =
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    val source = ImageDecoder.createSource(this.contentResolver, uri)
                    ImageDecoder.decodeBitmap(source)
                } else {
                    MediaStore.Images.Media.getBitmap(this.contentResolver, uri)
                }
            val baos = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
            val size = baos.toByteArray()
            Log.d("result", size.size.toString())
            Log.d("result", "bitmap completed")
            val inputContent = content {
                image(bitmap)
                text("Read text from image")
            }
            Log.d("result", "api start")

            try {
                var mainResult = ""
                CoroutineScope(Dispatchers.IO).launch {
                    generativeModel.generateContentStream(inputContent)
                        .collect { response ->
                            val result = response.text.toString().trim()
                            Log.d("result", "api end")
                            runOnUiThread {
                                loadingDialog.dismiss()
                                if (result.isNotEmpty()) {
                                    mainResult += result
                                    Log.d("result", "set Text")

                                    menuBinding.outputImg.setImageBitmap(null)
                                    menuBinding.outputImg.setImageBitmap(bitmap)
                                    menuBinding.outputImg.visible()
                                    menuBinding.edNumber.setText(mainResult)
                                } else {
                                    Log.d("result", "No text found in the photo")
                                    menuBinding.outputImg.gone()
                                    menuBinding.outputImg.setImageBitmap(null)
                                    showToast("No text found in the photo")
                                }
                            }
                        }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                loadingDialog.dismiss()
                showToast(e.message.toString())
            }

        } catch (e: Exception) {
            e.printStackTrace()
            loadingDialog.dismiss()
            showToast(e.message.toString())
        }

Using the sdk on my flutter app through MethodChannel

Hi,
I am trying to use the SDK to communicate with my flutter app using methodchannel but i am getting this error

First this error

ERROR:C:\Users\xxxx\.gradle\caches\transforms-3\5d19816a0b04a46bdd05877142eefa50\transformed\jetified-generativeai-0.1.2-runtime.jar: D8: com.android.tools.r8.internal.Hc: Sealed classes are not supported as program classes

then this again

Execution failed for task ':app:mergeExtDexDebug'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform generativeai-0.1.2.aar (com.google.ai.client.generativeai:generativeai:0.1.2) to match attributes {artifactType=android-dex, asm-transformed-variant=NONE, dexing-enable-desugaring=true, dexing-enable-jacoco-instrumentation=false, dexing-is-debuggable=true, dexing-min-sdk=26, org.gradle.category=library, org.gradle.dependency.bundling=external, org.gradle.libraryelements=aar, org.gradle.status=release, org.gradle.usage=java-runtime}.
      > Execution failed for DexingNoClasspathTransform: C:\Users\Arafat Benson\.gradle\caches\transforms-3\5d19816a0b04a46bdd05877142eefa50\transformed\jetified-generativeai-0.1.2-runtime.jar.
         > Error while dexing.

could you help me with the cause of this? thanks

Failed to send message

After a request fails once, subsequent requests will fail every time.

java.util.concurrent.CancellationException: Parent job is Canceled error reported

The log is as follows:

2024-02-26 21:43:10.633 32688-2795  System.err                  W  com.google.ai.client.generativeai.type.UnknownException: Something unexpected happened.
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at com.google.ai.client.generativeai.type.GoogleGenerativeAIException$Companion.from(Exceptions.kt:45)
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at com.google.ai.client.generativeai.GenerativeModel.generateContent(GenerativeModel.kt:88)
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at com.google.ai.client.generativeai.GenerativeModel$generateContent$1.invokeSuspend(Unknown Source:15)
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at android.os.Handler.handleCallback(Handler.java:888)
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at android.os.Handler.dispatchMessage(Handler.java:100)
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at android.os.Looper.loop(Looper.java:213)
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at android.app.ActivityThread.main(ActivityThread.java:8178)
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at java.lang.reflect.Method.invoke(Native Method)
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
2024-02-26 21:43:10.634 32688-2795  System.err                  W  Caused by: java.util.concurrent.CancellationException: Parent job is Cancelled
2024-02-26 21:43:10.634 32688-2795  System.err                  W  	at io.ktor.client.engine.UtilsKt$attachToUserJob$cleanupHandler$1.invoke(Utils.kt:97)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.engine.UtilsKt$attachToUserJob$cleanupHandler$1.invoke(Utils.kt:95)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at kotlinx.coroutines.JobSupport.invokeOnCompletion(JobSupport.kt:1529)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at kotlinx.coroutines.Job$DefaultImpls.invokeOnCompletion$default(Job.kt:357)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.engine.HttpClientEngineKt.createCallContext(HttpClientEngine.kt:166)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.engine.HttpClientEngine$DefaultImpls.executeWithinCallContext(HttpClientEngine.kt:91)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.engine.HttpClientEngine$DefaultImpls.access$executeWithinCallContext(HttpClientEngine.kt:24)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.engine.HttpClientEngine$install$1.invokeSuspend(HttpClientEngine.kt:70)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.engine.HttpClientEngine$install$1.invoke(Unknown Source:15)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.engine.HttpClientEngine$install$1.invoke(Unknown Source:4)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:120)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:78)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.execute$ktor_utils(SuspendFunctionGun.kt:98)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpSend$DefaultSender.execute(HttpSend.kt:138)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpTimeout$Plugin$install$1.invokeSuspend(HttpTimeout.kt:174)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpTimeout$Plugin$install$1.invoke(Unknown Source:15)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpTimeout$Plugin$install$1.invoke(Unknown Source:6)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpSend$InterceptedSender.execute(HttpSend.kt:116)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpRedirect$Plugin$install$1.invokeSuspend(HttpRedirect.kt:64)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpRedirect$Plugin$install$1.invoke(Unknown Source:15)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpRedirect$Plugin$install$1.invoke(Unknown Source:6)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpSend$InterceptedSender.execute(HttpSend.kt:116)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpCallValidator$Companion$install$3.invokeSuspend(HttpCallValidator.kt:151)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpCallValidator$Companion$install$3.invoke(Unknown Source:13)
2024-02-26 21:43:10.635 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpCallValidator$Companion$install$3.invoke(Unknown Source:6)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpSend$InterceptedSender.execute(HttpSend.kt:116)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpSend$Plugin$install$1.invokeSuspend(HttpSend.kt:104)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpSend$Plugin$install$1.invoke(Unknown Source:15)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpSend$Plugin$install$1.invoke(Unknown Source:4)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:120)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:78)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.proceedWith(SuspendFunctionGun.kt:88)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.DefaultTransformKt$defaultTransformers$1.invokeSuspend(DefaultTransform.kt:57)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.DefaultTransformKt$defaultTransformers$1.invoke(Unknown Source:11)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.DefaultTransformKt$defaultTransformers$1.invoke(Unknown Source:4)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:120)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:78)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.proceedWith(SuspendFunctionGun.kt:88)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.contentnegotiation.ContentNegotiation$Plugin$install$1.invokeSuspend(ContentNegotiation.kt:252)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.contentnegotiation.ContentNegotiation$Plugin$install$1.invoke(Unknown Source:11)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.contentnegotiation.ContentNegotiation$Plugin$install$1.invoke(Unknown Source:4)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:120)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:78)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.proceedWith(SuspendFunctionGun.kt:88)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpCallValidator$Companion$install$1.invokeSuspend(HttpCallValidator.kt:130)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpCallValidator$Companion$install$1.invoke(Unknown Source:13)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpCallValidator$Companion$install$1.invoke(Unknown Source:4)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:120)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:78)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpRequestLifecycle$Plugin$install$1.invokeSuspend(HttpRequestLifecycle.kt:38)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpRequestLifecycle$Plugin$install$1.invoke(Unknown Source:11)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.client.plugins.HttpRequestLifecycle$Plugin$install$1.invoke(Unknown Source:4)
2024-02-26 21:43:10.636 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:120)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:78)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at io.ktor.util.pipeline.SuspendFunctionGun.execute$ktor_utils(SuspendFunctionGun.kt:98)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:77)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at io.ktor.client.HttpClient.execute$ktor_client_core(HttpClient.kt:191)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at io.ktor.client.statement.HttpStatement.executeUnsafe(HttpStatement.kt:108)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at io.ktor.client.statement.HttpStatement.execute(HttpStatement.kt:47)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at io.ktor.client.statement.HttpStatement.execute(HttpStatement.kt:62)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at com.google.ai.client.generativeai.internal.api.APIController.generateContent(APIController.kt:185)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at com.google.ai.client.generativeai.GenerativeModel.generateContent(GenerativeModel.kt:86)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at com.google.ai.client.generativeai.Chat.sendMessage(Chat.kt:60)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at com.google.ai.client.generativeai.java.ChatFutures$FuturesImpl$sendMessage$1.invokeSuspend(ChatFutures.kt:54)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at com.google.ai.client.generativeai.java.ChatFutures$FuturesImpl$sendMessage$1.invoke(Unknown Source:8)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at com.google.ai.client.generativeai.java.ChatFutures$FuturesImpl$sendMessage$1.invoke(Unknown Source:4)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at kotlinx.coroutines.intrinsics.UndispatchedKt.startCoroutineUndispatched(Undispatched.kt:44)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:112)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:126)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at kotlinx.coroutines.BuildersKt__Builders_commonKt.async(Builders.common.kt:91)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at kotlinx.coroutines.BuildersKt.async(Unknown Source:1)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at androidx.concurrent.futures.SuspendToFutureAdapter.launchFuture(SuspendToFutureAdapter.kt:86)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at androidx.concurrent.futures.SuspendToFutureAdapter.launchFuture$default(SuspendToFutureAdapter.kt:81)
2024-02-26 21:43:10.637 32688-2795  System.err                  W  	at com.google.ai.client.generativeai.java.ChatFutures$FuturesImpl.sendMessage(ChatFutures.kt:54)

As a programming enthusiast, I had some problems deploying projects

FAILURE: Build failed with an exception.

  • Where:
    Build file 'C:\Users\14130\AndroidStudioProjects\generative-ai-android\plugins\build.gradle.kts' line: 17

  • What went wrong:
    Plugin [id: 'org.gradle.kotlin.kotlin-dsl', version: '4.1.2'] was not found in any of the following sources:

  • Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
  • Plugin Repositories (could not resolve plugin artifact 'org.gradle.kotlin.kotlin-dsl:org.gradle.kotlin.kotlin-dsl.gradle.plugin:4.1.2')
    Searched in the following repositories:
    Google
    MavenRepo
    Gradle Central Plugin Repository
  • Try:

Run with --info or --debug option to get more log output.
Run with --scan to get full insights.
Get more help at https://help.gradle.org.

  • Exception is:
    org.gradle.api.plugins.UnknownPluginException: Plugin [id: 'org.gradle.kotlin.kotlin-dsl', version: '4.1.2'] was not found in any of the following sources:

    at org.gradle.internal.concurrent.AbstractManagedExecutor$1.run(AbstractManagedExecutor.java:47)

CONFIGURE FAILED in 27s

As a programming enthusiast, I had some problems deploying projects

API available to more countries

While Bard was updated to provide service in many more countries, I wonder when will the API be general available to those countries too?

Do you have an ETA?

Thank you in advance

Something went wrong while trying to deserialize a response from the server

When testing app from Google Play console internal test channel with release build with ;

        minifyEnabled true
        shrinkResources true

"Something went wrong while trying to deserialize a response from the server" error occurs on Model answer

There is no Logcat info on Android Studio when it occurs.

What i tried is : Added lines below to my proguard-rules.pro

-keep class androidx.compose.ui.*.*{*;} -keep class com.google.ai.*.*{*;}

but not works

Thank you!

kotlin version

implementation "com.google.ai.client.generativeai:generativeai:0.1.1" appears incompatible version of Kotlin issue:Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.9.0, expected version is 1.7.1. But I cannot upgrade kotlin & gradle in my project.

I am getting issue in Release build

Hey, I am using Gemini AI and in the release build, I get generativeai.type.InvalidStateException.
I know this is not the right place to ask the question but I google things and I won't able to find any.

Here is the code

GeminiModule

@Module
@InstallIn(SingletonComponent::class)
object GeminiModule {
    @Provides
    @Singleton
    fun provideGemini(): GenerativeModel {
        val harassmentSafety =
            SafetySetting(HarmCategory.HARASSMENT, BlockThreshold.ONLY_HIGH)

        val hateSpeechSafety =
            SafetySetting(HarmCategory.HATE_SPEECH, BlockThreshold.MEDIUM_AND_ABOVE)
        val config = generationConfig {
            stopSequences = listOf(
                "fuck",
                "sex",
            )
            temperature = 0.9f
            topK = 16
            topP = 0.1f
        }
        return GenerativeModel(
            modelName = "gemini-pro",
            apiKey = BuildConfig.apiKey,
            generationConfig = config,
            safetySettings = listOf(
                harassmentSafety, hateSpeechSafety
            )
        )
    }
}

and it's viewModel

@HiltViewModel
class ChatViewModel @Inject constructor(
    private val generativeModel: GenerativeModel,
    private val case: ChatUseCases,
    private val mapper: ChatMessageToModelMapper
) : ViewModel() {

    private var chat: Chat? = null

    private val _uiState: MutableState<ChatUiState> =
        mutableStateOf(ChatUiState())
    val uiState: State<ChatUiState> = _uiState

    private val _isLoading = mutableStateOf<Boolean>(false)
    val isLoading: State<Boolean> get() = _isLoading
    private var job: Job? = null

    init {
        getChat()
    }

    private fun getChat() = viewModelScope.launch {
        val history = mapper.mapFromEntityList(case.getAllChat.invoke()).toContent()
        chat = generativeModel.startChat(history)
        _uiState.value = ChatUiState(
            chat?.history?.map { content ->
                // Map the initial messages
                ChatMessage(
                    text = content.parts.first().asTextOrNull() ?: "",
                    participant = if (content.role == "user") Participant.USER else Participant.MODEL,
                )
            } ?: emptyList()
        )
    }


    fun cancelJob() {
        try {
            _isLoading.value = false
            job?.cancel()
        } catch (e: Exception) {
            Log.e(TAGS.BIT_ERROR.name, "cancelJob: ${e.localizedMessage}")
        }
    }

    fun sendMessage(userMessage: String) {
        // Add a pending message
        val userInput = ChatMessage(
            text = userMessage, participant = Participant.USER,
        )
        _isLoading.value = true
        _uiState.value.addMessage(
            userInput
        )
        job = viewModelScope.launch {
            try {
                val response = chat!!.sendMessage(userMessage)
                _isLoading.value = false
                response.text?.let { modelResponse ->
                    val modelRes = ChatMessage(
                        text = modelResponse, participant = Participant.MODEL
                    )
                    mapper.mapToEntityList(
                        listOf(
                            _uiState.value.getLastMessage()!!
                                .copy(
                                    linkedId = modelRes.id
                                ),
                            modelRes.copy(
                                linkedId = _uiState.value.getLastMessage()!!.id
                            )
                        )
                    ).forEach {
                        case.insertChat.invoke(it)
                    }
                    _uiState.value.addMessage(
                        modelRes
                    )
                }
            } catch (e: Exception) {
                Log.d("AAA", "sendMessage: $e")
                if (e is PromptBlockedException) {
                    _uiState.value.addMessage(
                        ChatMessage(
                            text = "The input you provided contains offensive language, which goes against our community guidelines " +
                                    "and standards. Please refrain from using inappropriate language and ensure that your input is " +
                                    "respectful and adheres to our guidelines. If you have any questions or concerns, feel free " +
                                    "to contact our support team.",
                            participant = Participant.ERROR
                        )
                    )
                    return@launch
                }
                _uiState.value.addMessage(
                    ChatMessage(
                        text = e.localizedMessage ?: "Unknown error",
                        participant = Participant.ERROR
                    )
                )
            } finally {
                _isLoading.value = false
                job = null
            }
        }
    }

}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.