Gemini is a series of artificial intelligence (AI) models developed by Google, each designed for specific use cases. Google introduced the Gemini 1.5 Pro and Gemini 1.5 Flash models at I/O 2024. These models can be accessed through the Google AI Client SDK. This tutorial will guide you through creating an AI chatbot named CatBot using the Gemini 1.5 Pro model. CatBot will interact with a playful cat named Milo. Throughout the tutorial, you will learn how to set up the Google AI API Key, configure and integrate the Gemini model, create a chat UI, and implement safety checks. Let’s get started!
To begin, download the tutorial materials by clicking the Download Materials button at the top or bottom of this page. Then, open the starter project in Android Studio Jellyfish or a later version. The project focuses on CatBot, an AI-powered chatbot that allows users to chat with Milo the cat. The project includes the following files:
– MainActivity: Main Activity containing the Composables
– ChatMessage: Data class representing each message
– ChatScreen: Composable describing the chat screen
– ChatViewModel: ViewModel managing the chat screen state and message handling
Build and run the app to see the initial screen with an input field for chat messages and a send button. Currently, sending a message does not have any functionality, but you will address this as you progress through the tutorial.
First, you need to generate an API key to interact with the Gemini APIs. Visit https://aistudio.google.com/app to access the Google AI Studio. Select the Gemini 1.5 Flash model from the Model dropdown. Click on Get API key in the left navigation panel to create a new API key if you don’t have one already. Copy the generated API key and add it to the local.properties file in Android Studio.
Next, you will model the chat messages in CatBot. Define three types of messages: User messages, Replies from the model, and Error messages by creating a ChatParticipant enum class. Associate each chat message with a participant by adding a participant attribute to the ChatMessage data class.
To configure the Gemini model in Android, you will need to include the Google AI Client SDK dependency in the app-module build.gradle file. Create a new file named Model.kt and initialize the GenerativeModel with the necessary parameters, such as modelName, apiKey, generationConfig, and systemInstruction.
In ChatViewModel, provide the chat history to the GenerativeModel instance to establish context for the conversation. Update the _uiState initialization to map the chat history messages to ChatMessage instances, ensuring that the conversation history is displayed when the app is launched.
By following these steps, you will set up the foundation for CatBot and enable interactions with Milo the cat using the Gemini 1.5 Pro model.
Source link