Add generative AI responses the SociaLite sample app

Animated screenshot showing the SociaLite chatbot in
action

The SociaLite sample app demonstrates how to use Android platform APIs to implement features that are commonly deployed in social network and communications apps. We have integrated the Gemini API using the Google AI client SDK to demonstrate how chatbot capabilities can be implemented in your own Android apps.

This sample code uses Gemini Flash which fast and cost-effective. Learn more about the Gemini models. To implement an AI-driven chatbot in the Socialite demo, we used the system instructions functionality of the Gemini API to modify the behavior of the model. In this case, we use the prompt "Please respond to this chat conversation like a friendly cat". This Gemini-infused version of SociaLite also uses the multimodal capabilities of the model to let the chatbot react to images.

Implement the Gemini API

The chatbot implementation is primarily located in the ChatRepository class. The GenerativeModel class lets you interact with the Gemini API, which is instantiated as follows:

val generativeModel = GenerativeModel(
  // Set the model name to the latest Gemini model.
  modelName = "gemini-1.5-pro-latest",
  // Set your Gemini API key in the API_KEY variable in your
  // local.properties file
  apiKey = BuildConfig.API_KEY,
  // Set a system instruction to set the behavior of the model.
  systemInstruction = content {
    text("Please respond to this chat conversation like a friendly cat.")
  },
)

In a coroutine scope, initiate a chat by passing pastMessages to startChat() to ensure that the model has access to conversation history. This gives your chatbot the ability to maintain context and generate coherent responses that build on previous exchanges.

val pastMessages = getMessageHistory(chatId)
val chat = generativeModel.startChat(
  history = pastMessages,
)

Use the sendMessage() method to pass messages to the model.

Test the AI chatbot

You can test it yourself by following these steps:

  1. Check out the code for the SociaLite sample app and open it in Android Studio.
  2. Create a Gemini API key in Google AI studio.
  3. Add your Gemini API key as an API_KEY variable to your local.properties file.
  4. Sync and run your app.
  5. In the SociaLite app, tap Settings and then tap AI Chatbot so that the button label reads "AI Chatbot: enabled".

You are now ready to chat!

Additional resources

Learn more about the Google AI SDK. If your app already integrates Firebase, you can also access the Gemini API from Vertex AI in Firebase.