Friday, May 24, 2024
HomeiOS DevelopmentGoogle I/O 2024: Construct a Cat Chatbot utilizing Gemini on Android

Google I/O 2024: Construct a Cat Chatbot utilizing Gemini on Android


Gemini is a household of synthetic intelligence (AI) fashions launched by Google, with every mannequin specializing in particular use circumstances. At I/O 2024, Google introduced the Gemini 1.5 Professional and Gemini 1.5 Flash fashions. These fashions can be found by way of the Google AI Consumer SDK.

On this tutorial, you’ll create an AI chatbot named CatBot utilizing the Gemini 1.5 Professional mannequin. On this chatbot, you’ll work together with a enjoyable cat named Milo.

In the course of the course of, you’ll study to:

  • Setup the Google AI API Key.
  • Configure and combine the Gemini mannequin.
  • Create a chat UI.
  • Add security checks.

And with that, it’s time to get began.

Getting Began

Obtain the supplies for this tutorial by clicking the Obtain Supplies button on the prime or backside of the tutorial. Then, open the starter mission in Android Studio Jellyfish or later.

CatBot starter project files inside Android Studio

You’ll work on CatBot, an AI-based chatbot that allows you to chat with a cat named Milo.

The mission comprises the next recordsdata:

  • MainActivity: Accommodates the primary Exercise and hosts the Composables.
  • ChatMessage: A knowledge class representing every message.
  • ChatScreen: A Composable describing the chat display.
  • ChatViewModel: A ViewModel representing the state of the chat display. It’ll include the logic of dealing with outgoing and incoming messages.

Construct and run the app. You’ll see the next display:

Cat chatbot starter project screen

The display has an enter area for the chat message and a ship button. Proper now, sending a message doesn’t do something. You’ll change this all through the tutorial.

Producing the API key

First, you’ll want an API key to work together with the Gemini APIs. Head over to https://aistudio.google.com/app which can open the Google AI Studio. On the proper facet of the studio, you’ll see the Mannequin dropdown:

Google AI Studio Model Dropdown

Choose the Gemini 1.5 Flash mannequin.

Though the Gemini 1.5 Professional mannequin is extra highly effective, the Gemini 1.5 Flash is considerably quicker, making it extra appropriate for this chatbot utility.

Subsequent, click on Get API key on the left navigation panel:

Google AI Studio Get API Key button

You’ll get the next display in the event you haven’t created an API key earlier:

Google AI Studio Create API Key button

Click on Create API key. You’ll get the Create API Key dialog as proven under:

Google AI Studio Create API Key for new project dialog

Choose Create API key in new mission. As soon as the API key has been generated, you’ll see a dialog along with your new API key. Copy the API Key and head again to Android Studio.

Open native.properties and add the next code:


apiKey=your API key right here

Within the code above, change your API key right here with the API key you copied earlier.

Be aware: This methodology of specifying the API key contained in the Android mission is simply appropriate for prototypes. For manufacturing apps, the API key needs to be current on the backend, and entry to the mannequin ought to solely be executed by way of an API.

Now that the API secret’s prepared, you can begin modeling the chat message.

Modeling the Chat Message

On this chatbot, there will be three sorts of messages:

  1. Consumer messages
  2. Replies from the mannequin
  3. Error messages

To mannequin the sorts of messages, create a brand new class named ChatParticipant and add the next code:


enum class ChatParticipant {
  USER,
  AI,
  ERROR
}

Within the code above, you created an enum class with three attainable values, every representing a sort of message.

Subsequent, it is advisable to affiliate every chat message with a selected participant. Open ChatMessage and add the next attribute to the info class:


val participant: ChatParticipant

The ChatMessage class will now be as follows:


knowledge class ChatMessage(
  val id: String = UUID.randomUUID().toString(),
  val message: String,
  val participant: ChatParticipant
)

Configuring the Gemini Mannequin

You’ll want the Google AI Consumer SDK to entry the Gemini mannequin on Android. Open the app-module construct.gradle and add the next dependency:


implementation("com.google.ai.shopper.generativeai:generativeai:0.6.0")

Do a Gradle sync and anticipate the dependency to complete downloading.

Subsequent, create a brand new file named Mannequin.kt and add the next code:


inside val mannequin = GenerativeModel(
  // 1
  modelName = "gemini-1.5-flash-latest",
  // 2
  apiKey = BuildConfig.apiKey,
  // 3
  generationConfig = generationConfig {
    temperature = 0.7f
  },
  // 4
  systemInstruction = content material {
    textual content("You're a enjoyable cat named Milo. " +
        "Give mischievous solutions in most 3 strains. " +
        "Attempt to hold the dialog going")
  }
)

The code above creates a brand new occasion of GenerativeModel with the next arguments:

  • modelName: Because you’re utilizing Gemini 1.5 Flash, the modelName is gemini-1.5-flash-latest. Within the case of Gemini 1.5 Professional, the mannequin identify could be gemini-1.5-pro-latest.
  • apiKey: This worth is extracted from the native.properties worth you set earlier within the tutorial.
  • generationConfig: The mannequin configuration. Right here, you set the temperature worth to 0.7. The temperature will be something between 0 and 1. A decrease temperature will result in a extra predictable response, whereas the next temperature will result in a extra inventive response.
  • systemInstruction: That is the bottom immediate to your mannequin, which can decide the persona of your mannequin. For this app, you’re asking the mannequin to behave like a enjoyable cat named Milo and offering further particulars.

Be aware: Don’t import the BuildConfig class from the Google AI Consumer SDK. If you construct the mission, the wanted BuildConfig shall be generated.

Including Preliminary Historical past

When engaged on a dialog app utilizing the Gemini API, you possibly can add message historical past together with the system immediate. This allows you to present the mannequin with the context of a earlier dialog so the person can proceed a dialog throughout app periods.

Open ChatViewModel and alter the constructor to:


class ChatViewModel(
  generativeModel: GenerativeModel = mannequin
)

ChatViewModel now takes an occasion of GenerativeModel as a constructor argument, and the default worth is about to the occasion you created within the earlier part.

Subsequent, you’ll want to supply the chat historical past. Add the next code contained in the ChatViewModel class:


// 1
non-public val chat = generativeModel.startChat(
  // 2
  historical past = listOf(
    //3
    content material("person") {
      textual content("Hi there n")
    },
    content material("mannequin") {
      textual content("Meow!  What's up, human?  Did you deliver me any tuna?  😉 n")
    }
  )
)

Within the code above, you:

  1. Begin a brand new chat with the startChat methodology.
  2. Specify the historical past argument as an inventory of messages.
  3. Specify that the person despatched the primary message and the mannequin despatched the second.

Now that the mannequin has the context of the message historical past, the UI ought to show the messages once you open the app.

Change the initialization of _uiState:


non-public val _uiState: MutableStateFlow<Checklist<ChatMessage>> =
  MutableStateFlow(
    chat.historical past.map { content material ->
      ChatMessage(
        message = content material.components.first().asTextOrNull() ?: "",
          participant = if (content material.position == "person")
            ChatParticipant.USER
          else
            ChatParticipant.AI,
      )
    }
  )

Within the code above, you iterate over the chat historical past and map every message to an occasion of ChatMessage. You then set the default worth of the state to include the message historical past.

Now, each time you run the app, a dialog historical past shall be accessible, making it straightforward to proceed the dialog.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments