### Initialize Gemini Model and Start Chat Source: https://github.com/android/ai-samples/blob/main/samples/gemini-chatbot/README.md Initializes the Gemini Flash model using Firebase AI and starts a chat session. This is the core setup for conversational AI. ```kotlin private val generativeModel by lazy { Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel("gemini-2.5-flash") } private val chat = generativeModel.startChat() ``` -------------------------------- ### Initialize ImageDescriber Client Source: https://github.com/android/ai-samples/blob/main/samples/genai-image-description/README.md Initializes the ML Kit GenAI Image Description client with specified options. Ensure the context is available. ```kotlin private var imageDescriber: ImageDescriber = ImageDescription.getClient( ImageDescriberOptions.builder(context).build(), ) ``` -------------------------------- ### Generate Video Summary with Gemini Flash Source: https://github.com/android/ai-samples/blob/main/samples/gemini-video-summarization/README.md Initializes the Gemini Flash model and sends video content along with a text prompt to generate a summary. The response is streamed and appended to a string builder. ```kotlin val generativeModel = Firebase.ai(backend = GenerativeBackend.vertexAI()) .generativeModel("gemini-2.5-flash") val requestContent = content { fileData(videoSource.toString(), "video/mp4") text(promptData) } val outputStringBuilder = StringBuilder() generativeModel.generateContentStream(requestContent).collect { response -> outputStringBuilder.append(response.text) } ``` -------------------------------- ### Initialize Gemini Live Model and Connect Session Source: https://github.com/android/ai-samples/blob/main/samples/gemini-live-todo/README.md Initializes the Gemini Live model with function declarations for task management and establishes a connection to the live session. Handles potential connection errors. ```kotlin val generativeModel = Firebase.ai(backend = GenerativeBackend.vertexAI()).liveModel( "gemini-2.5-flash-native-audio-preview-12-2025", generationConfig = liveGenerationConfig, systemInstruction = systemInstruction, tools = listOf( Tool.functionDeclarations( listOf(getTodoList, addTodo, removeTodo, toggleTodoStatus) ), ), ) try { session = generativeModel.connect() } catch (e: Exception) { Log.e(TAG, "Error connecting to the model", e) liveSessionState.value = LiveSessionState.Error } ``` -------------------------------- ### Instantiate Gemini 3 Pro Image Model Source: https://github.com/android/ai-samples/blob/main/samples/gemini-image-chat/README.md Configure and instantiate the Gemini 3 Pro Image model with specific generation settings, safety thresholds, and a system instruction. Ensure response modalities include both text and image. ```kotlin Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel( "gemini-3-pro-image-preview", generationConfig = generationConfig { temperature = 0.9f topK = 32 topP = 1f maxOutputTokens = 4096 responseModalities = listOf(ResponseModality.TEXT, ResponseModality.IMAGE) }, safetySettings = listOf( SafetySetting(HarmCategory.HARASSMENT, HarmBlockThreshold.MEDIUM_AND_ABOVE), SafetySetting(HarmCategory.HATE_SPEECH, HarmBlockThreshold.MEDIUM_AND_ABOVE), SafetySetting(HarmCategory.SEXUALLY_EXPLICIT, HarmBlockThreshold.MEDIUM_AND_ABOVE), SafetySetting(HarmCategory.DANGEROUS_CONTENT, HarmBlockThreshold.MEDIUM_AND_ABOVE), ), systemInstruction = content { text("""You are a friendly assistant. Keep your responses short.""") }, ) ``` -------------------------------- ### Generate Image Description with Gemini Nano Source: https://github.com/android/ai-samples/blob/main/samples/genai-image-description/README.md Converts a given image URI to a bitmap, builds an ImageDescriptionRequest, and streams back the generated description using the on-device Gemini Nano model. Updates the UI state with partial and final output. ```kotlin private suspend fun generateImageDescription(imageUri: Uri) { _uiState.value = GenAIImageDescriptionUiState.Generating("") val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, imageUri) val request = ImageDescriptionRequest.builder(bitmap).build() imageDescriber.runInference(request) { newText -> _uiState.update { (it as? GenAIImageDescriptionUiState.Generating)?.copy(partialOutput = it.partialOutput + newText) ?: it } }.await() // ... ``` -------------------------------- ### Initialize Generative Model with Gemini Flash Source: https://github.com/android/ai-samples/blob/main/samples/gemini-multimodal/README.md Initializes the generative model using Gemini Flash with specific generation and safety configurations. Ensure the Firebase AI SDK is set up correctly. ```kotlin private val generativeModel by lazy { Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel( "gemini-2.5-flash", generationConfig = generationConfig { temperature = 0.9f topK = 32 topP = 1f maxOutputTokens = 4096 }, safetySettings = listOf( SafetySetting(HarmCategory.HARASSMENT, HarmBlockThreshold.MEDIUM_AND_ABOVE), SafetySetting(HarmCategory.HATE_SPEECH, HarmBlockThreshold.MEDIUM_AND_ABOVE), SafetySetting(HarmCategory.SEXUALLY_EXPLICIT, HarmBlockThreshold.MEDIUM_AND_ABOVE), SafetySetting(HarmCategory.DANGEROUS_CONTENT, HarmBlockThreshold.MEDIUM_AND_ABOVE), ), ) } ``` -------------------------------- ### Generate Summarization using GenAI API Source: https://github.com/android/ai-samples/blob/main/samples/genai-summarization/README.md This snippet shows how to call the generative model to summarize text. It initializes a SummarizationRequest and uses the summarizer's runInference method, handling streaming results and potential exceptions. Consider using await() for synchronous completion or attaching a FutureCallback for asynchronous handling. ```kotlin private suspend fun generateSummarization(summarizer: Summarizer, textToSummarize: String) { _uiState.value = GenAISummarizationUiState.Generating("") val summarizationRequest = SummarizationRequest.builder(textToSummarize).build() try { // Instead of using await() here, alternatively you can attach a FutureCallback summarizer.runInference(summarizationRequest) { newText -> (_uiState.value as? GenAISummarizationUiState.Generating)?.let { _uiState.value = it.copy(generatedOutput = it.generatedOutput + newText) } }.await() } catch (genAiException: GenAiException) { // ... } // ... } ``` -------------------------------- ### Generate Image from Prompt Source: https://github.com/android/ai-samples/blob/main/samples/nanobanana/README.md This Kotlin snippet shows how to call the Gemini generative model to create an image based on a text prompt. It handles the response and extracts the generated bitmap. ```kotlin suspend fun generateImage(prompt: String): Bitmap { val response = generativeModel.generateContent(prompt) return response.candidates.firstOrNull()?.content?.parts?.firstNotNullOfOrNull { it.asImageOrNull() } ?: throw Exception("No image generated") } ``` -------------------------------- ### Run Proofreading Inference - Kotlin Source: https://github.com/android/ai-samples/blob/main/samples/genai-writing-assistance/README.md Initiates proofreading for a given text using the ML Kit Proofreader client. It builds a ProofreadingRequest, runs the inference, and updates the UI with the first result, which has the highest confidence. ```kotlin private suspend fun runProofreadingInference(textToProofread: String) { val proofreadRequest = ProofreadingRequest.builder(textToProofread).build() // More than 1 result may be generated. Results are returned in descending order of // quality of confidence. Here we use the first result which has the highest quality // of confidence. _uiState.value = GenAIWritingAssistanceUiState.Generating val results = proofreader.runInference(proofreadRequest).await() _uiState.value = GenAIWritingAssistanceUiState.Success(results.results[0].text) } ``` -------------------------------- ### Generate Text from Multimodal Prompt Source: https://github.com/android/ai-samples/blob/main/samples/gemini-multimodal/README.md Generates text content by combining a Bitmap image and a text prompt. Returns an empty string if the model response is null. Requires the generativeModel to be initialized. ```kotlin suspend fun generateText(bitmap: Bitmap, prompt: String): String { val multimodalPrompt = content { image(bitmap) text(prompt) } val result = generativeModel.generateContent(multimodalPrompt) return result.text ?: "" } ``` -------------------------------- ### Generate Video Description with Gemini Flash Source: https://github.com/android/ai-samples/blob/main/samples/gemini-video-metadata-creation/README.md Use this function to generate a compelling and concise description for a video. It sends video content and a prompt to the Gemini API, expecting an HTML-formatted response. Ensure the Firebase AI SDK is initialized. ```kotlin suspend fun generateDescription(videoUri: Uri): @Composable () -> Unit { val response = Firebase.ai(backend = GenerativeBackend.vertexAI()) .generativeModel(modelName = "gemini-2.5-flash") .generateContent( content { fileData(videoUri.toString(), "video/mp4") text( """ Provide a compelling and concise description for this video in less than 100 words. Don't assume if you don't know. The description should be engaging and accurately reflect the video's content. You should output your responses in HTML format. Use styling sparingly. You can use the following tags: * Bold: * Italic: * Underline: * Bullet points:
    ,
  • """.trimIndent(), ) }, ) val responseText = response.text return if (responseText != null) { { DescriptionUi(responseText) } } else { { ErrorUi(response.promptFeedback?.blockReasonMessage) } } } ``` -------------------------------- ### Send Multimodal Content to Gemini Chat Source: https://github.com/android/ai-samples/blob/main/samples/gemini-image-chat/README.md Construct a content block that includes both text and an optional image (Bitmap) before sending it to the chat model. This is the core interaction for multimodal input. ```kotlin val content = content { text(message) if (bitmap != null) { image(bitmap) } } val response = chat.sendMessage(content) ``` -------------------------------- ### Instantiate Gemini Hybrid Model in Kotlin Source: https://github.com/android/ai-samples/blob/main/samples/gemini-hybrid/README.md Instantiates the Firebase generative model to leverage hybrid inference, preferring on-device execution. Ensure Firebase is initialized and the necessary dependencies are included. ```kotlin val model = Firebase.ai(backend = GenerativeBackend.googleAI()) .generativeModel( "gemini-2.5-flash-lite", onDeviceConfig = OnDeviceConfig(mode = InferenceMode.PREFER_ON_DEVICE) ) val response = model.generateContent(prompt) ``` -------------------------------- ### Generate Magic Selfie with Gemini API Source: https://github.com/android/ai-samples/blob/main/samples/magic-selfie/README.md This Kotlin snippet calls the generative model to replace an image background. It requires the Firebase AI SDK and a multimodal prompt containing the image and a text description. ```kotlin suspend fun generateMagicSelfie(bitmap: Bitmap, prompt: String): Bitmap { val multimodalPrompt = content { image(bitmap) text("Change the background of this image to $prompt") } val response = generativeModel.generateContent(multimodalPrompt) return response.candidates.firstOrNull()?.content?.parts?.firstNotNullOfOrNull { it.asImageOrNull() } ?: throw Exception("No image generated") } ``` -------------------------------- ### Handle UI State with When Expression in Jetpack Compose Source: https://github.com/android/ai-samples/blob/main/android_architecture.md Use a when expression to handle different UI states (Initial, Generating, Success, Error) when collecting state with `collectAsStateWithLifecycle`. Ensure your ViewModel exposes UI state using flows. ```kotlin val uiState = viewModel.uiState.collectAsStateWithLifecycle() when (uiState) { ScreenState.Initial -> { // Show initial state } ScreenState.Generating -> { // Show generating state } is ScreenState.Success -> { // Show success state } is ScreenState.Error -> { // Show error state } } ``` -------------------------------- ### Define ScreenState Sealed Class for ViewModel Source: https://github.com/android/ai-samples/blob/main/android_architecture.md Use a sealed class to define the UI state for your ViewModel. This approach helps manage different states like initial, loading, success, and error. ```kotlin sealed class ScreenState { data object Initial : ScreenState() data object Generating : ScreenState() // Use for generating content data class Success(val data: String) : ScreenState() // Use to display data data class Error(val message: String) : ScreenState() // Use for error state } ``` -------------------------------- ### Send Message to Gemini Chat Source: https://github.com/android/ai-samples/blob/main/samples/gemini-chatbot/README.md Sends a user's message to the active chat session with the Gemini model and retrieves the response. This function is typically called when a user submits input. ```kotlin fun sendMessage(message: String) { viewModelScope.launch { // ... val response = chat.sendMessage(message) // ... } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.