# Firebase AI Logic on Android (Kotlin)
First, ensure you have initialized the Firebase App (see `firebase-basics`
skill). Then, initialize the AI Logic service as below
### 0. Enable Firebase AI Logic via CLI
Before adding dependencies in your app, make sure you enable the AI Logic
service in your Firebase Project using the Firebase CLI:
```bash
npx -y firebase-tools@latest init
# When prompted, select 'AI logic' to enable the Gemini API in your project.
```
______________________________________________________________________
### 1. Add Dependencies
In your module-level `build.gradle.kts` (usually `app/build.gradle.kts`), add
the dependency for Firebase AI:
```kotlin
dependencies {
// [AGENT] Fetch the latest available BoM version from https://firebase.google.com/support/release-notes/android before adding this
implementation(platform("com.google.firebase:firebase-bom:<latest_bom_version>"))
// Add the dependency for the Firebase AI library
implementation("com.google.firebase:firebase-ai")
}
```
______________________________________________________________________
### 2. Initialize and Generate Content
In your Activity or Fragment, initialize the `FirebaseAI` service and generate
content using a Gemini model:
```kotlin
import com.google.firebase.Firebase
import com.google.firebase.ai.ai
import com.google.firebase.ai.type.GenerativeBackend
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initialize with replay protection using limited-use App Check tokens:
val ai = Firebase.ai(
backend = GenerativeBackend.googleAI(),
useLimitedUseAppCheckTokens = true
)
// [AGENT] Replace "<latest_supported_model>" with the latest model from https://firebase.google.com/docs/ai-logic/models.md.txt (do NOT use Gemini 1.x or 2.x models)
val model = ai.generativeModel("<latest_supported_model>")
// Generate content
lifecycleScope.launch {
try {
val response = model.generateContent("Write a story about a magic backpack.")
Log.d(TAG, "Response: ${response.text}")
} catch (e: Exception) {
Log.e(TAG, "Error generating content", e)
}
}
}
}
```
#### App Check Replay Protection on Android
Generative and preview models enforce replay protection using short-lived
(5-minute) limited-use App Check tokens to prevent replay attacks. If you call a
model enforcing replay protection without limited-use tokens, the request is
rejected with:
```text
HTTP 403: "To access this model, you must enforce Firebase App Check"
```
To resolve this on Android, pass `useLimitedUseAppCheckTokens = true` when
calling `Firebase.ai`:
```kotlin
val ai = Firebase.ai(
backend = GenerativeBackend.googleAI(),
useLimitedUseAppCheckTokens = true
)
```
This ensures the SDK requests fresh limited-use tokens (via Play Integrity or
the debug provider) for each request instead of reusing cached tokens.
#### Jetpack Compose (Modern)
Initialize inside a `ComponentActivity` and use `setContent`:
```kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.lifecycle.lifecycleScope
import com.google.firebase.Firebase
import com.google.firebase.ai.ai
import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val ai = Firebase.ai
// [AGENT] Replace with the latest model from https://firebase.google.com/docs/ai-logic/models.md.txt
val model = ai.generativeModel("<latest_supported_model>")
lifecycleScope.launch {
val response = model.generateContent("Hello Gemini!")
setContent {
MaterialTheme {
Text("AI Response: ${response.text}")
}
}
}
}
}
```
______________________________________________________________________
### 3. Multimodal Input (Text and Images)
Pass bitmap data along with text prompts:
```kotlin
val image1: Bitmap = ... // Load your bitmap
val image2: Bitmap = ...
val response = model.generateContent(
content {
image(image1)
image(image2)
text("Analyze these images for me. Compare these two items.")
}
)
Log.d(TAG, response.text)
```
______________________________________________________________________
### 4. Chat Session (Multi-turn)
Maintain chat history automatically:
```kotlin
val chat = model.startChat(
history = listOf(
content("user") { text("Hello, I am a software engineer.") },
content("model") { text("Hello! How can I help you today?") }
)
)
lifecycleScope.launch {
val response = chat.sendMessage("What should I learn next?")
Log.d(TAG, response.text)
}
```
______________________________________________________________________
### 5. Streaming Responses
For faster display, stream the response:
```kotlin
lifecycleScope.launch {
model.generateContentStream("Tell me a long story.")
.collect { chunk ->
print(chunk.text) // Update UI incrementally
}
}
```
______________________________________________________________________
### 6. App Check Debug Provider
For App Check debug tokens during local development and CI/CD, install
`DebugAppCheckProviderFactory.getInstance()` as the App Check provider factory
in debug builds:
```kotlin
if (BuildConfig.DEBUG) {
Firebase.appCheck.installAppCheckProviderFactory(
DebugAppCheckProviderFactory.getInstance()
)
}
```
#### Debug Token Persistence
Emulator resets or clearing app storage erase `SharedPreferences`, causing
`DebugAppCheckProviderFactory` to print a new debug token in Logcat. To persist
a stable debug token across emulator resets and fresh installs without
hardcoding secrets:
> [!WARNING] **CRITICAL: Never Hardcode or Commit Debug Tokens** Never hardcode
> debug token strings in `build.gradle.kts` or Kotlin source files. Store the
> token in gitignored `local.properties` and inject it dynamically.
1. In gitignored `local.properties`:
```properties
APP_CHECK_DEBUG_TOKEN=<YOUR_DEBUG_TOKEN>
```
1. In `app/build.gradle.kts`:
```kotlin
val localProperties = java.util.Properties().apply {
val localPropertiesFile = rootProject.file("local.properties")
if (localPropertiesFile.exists()) {
load(localPropertiesFile.inputStream())
}
}
val appCheckDebugToken = localProperties.getProperty("APP_CHECK_DEBUG_TOKEN")
?: System.getenv("APP_CHECK_DEBUG_TOKEN") ?: ""
android {
defaultConfig {
// For normal emulator runs (injects into AndroidManifest)
manifestPlaceholders["firebaseAppCheckDebugSecret"] = appCheckDebugToken
// For instrumentation tests
if (appCheckDebugToken.isNotEmpty()) {
testInstrumentationRunnerArguments["firebaseAppCheckDebugSecret"] = appCheckDebugToken
}
}
}
```