-
Notifications
You must be signed in to change notification settings - Fork 7.4k
Add sample app for bidirectional streaming #2716
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
abcb97c
add stuff
VinayGuthal 2beb94e
add live model
VinayGuthal bbe9d50
merge with master
VinayGuthal 69177a6
avoid merge conflicts
VinayGuthal 10d9d05
add function calling
VinayGuthal d265dcd
revert
VinayGuthal 9810299
update
VinayGuthal 4730522
update
VinayGuthal 93f60a9
update
VinayGuthal d9e7380
update
VinayGuthal be51e11
Address comments
VinayGuthal bf9baa5
update sample
VinayGuthal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
103 changes: 103 additions & 0 deletions
103
...base-ai/app/src/main/java/com/google/firebase/quickstart/ai/feature/live/BidiViewModel.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
package com.google.firebase.quickstart.ai.feature.media.imagen | ||
|
||
import android.Manifest | ||
import android.graphics.Bitmap | ||
import androidx.annotation.RequiresPermission | ||
import androidx.lifecycle.SavedStateHandle | ||
import androidx.lifecycle.ViewModel | ||
import androidx.lifecycle.viewModelScope | ||
import androidx.navigation.toRoute | ||
import com.google.firebase.Firebase | ||
import com.google.firebase.ai.FirebaseAI | ||
import com.google.firebase.ai.ImagenModel | ||
import com.google.firebase.ai.LiveGenerativeModel | ||
import com.google.firebase.ai.ai | ||
import com.google.firebase.ai.type.FunctionCallPart | ||
import com.google.firebase.ai.type.FunctionResponsePart | ||
import com.google.firebase.ai.type.GenerativeBackend | ||
import com.google.firebase.ai.type.ImagenAspectRatio | ||
import com.google.firebase.ai.type.ImagenImageFormat | ||
import com.google.firebase.ai.type.ImagenPersonFilterLevel | ||
import com.google.firebase.ai.type.ImagenSafetyFilterLevel | ||
import com.google.firebase.ai.type.ImagenSafetySettings | ||
import com.google.firebase.ai.type.InlineDataPart | ||
import com.google.firebase.ai.type.LiveServerContent | ||
import com.google.firebase.ai.type.LiveServerMessage | ||
import com.google.firebase.ai.type.LiveSession | ||
import com.google.firebase.ai.type.PublicPreviewAPI | ||
import com.google.firebase.ai.type.ResponseModality | ||
import com.google.firebase.ai.type.SpeechConfig | ||
import com.google.firebase.ai.type.TextPart | ||
import com.google.firebase.ai.type.Tool | ||
import com.google.firebase.ai.type.Voice | ||
import com.google.firebase.ai.type.asTextOrNull | ||
import com.google.firebase.ai.type.imagenGenerationConfig | ||
import com.google.firebase.ai.type.liveGenerationConfig | ||
import com.google.firebase.app | ||
import com.google.firebase.quickstart.ai.FIREBASE_AI_SAMPLES | ||
import com.google.firebase.quickstart.ai.feature.live.StreamRealtimeRoute | ||
import com.google.firebase.quickstart.ai.feature.text.functioncalling.WeatherRepository | ||
import com.google.firebase.quickstart.ai.feature.text.functioncalling.WeatherRepository.Companion.fetchWeather | ||
import kotlinx.coroutines.CoroutineScope | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.flow.MutableStateFlow | ||
import kotlinx.coroutines.flow.StateFlow | ||
import kotlinx.coroutines.launch | ||
import kotlinx.coroutines.runBlocking | ||
import kotlinx.serialization.json.JsonObject | ||
import kotlinx.serialization.json.jsonPrimitive | ||
|
||
@OptIn(PublicPreviewAPI::class) | ||
class BidiViewModel( | ||
savedStateHandle: SavedStateHandle | ||
) : ViewModel() { | ||
private val sampleId = savedStateHandle.toRoute<StreamRealtimeRoute>().sampleId | ||
private val sample = FIREBASE_AI_SAMPLES.first { it.id == sampleId } | ||
|
||
// Firebase AI Logic | ||
private var liveSession: LiveSession | ||
|
||
init { | ||
val liveGenerationConfig = liveGenerationConfig { | ||
speechConfig = SpeechConfig(voice = Voice("CHARON")) | ||
// Change this to ContentModality.TEXT if you want text output. | ||
responseModality = ResponseModality.AUDIO | ||
} | ||
@OptIn(PublicPreviewAPI::class) | ||
val liveModel = FirebaseAI.getInstance(Firebase.app, sample.backend).liveModel( | ||
"gemini-live-2.5-flash", | ||
generationConfig = liveGenerationConfig, | ||
tools = sample.tools | ||
) | ||
runBlocking { | ||
liveSession = liveModel.connect() | ||
} | ||
} | ||
|
||
fun handler(fetchWeatherCall: FunctionCallPart) : FunctionResponsePart { | ||
val response:JsonObject | ||
fetchWeatherCall.let { | ||
val city = it.args["city"]?.jsonPrimitive?.content | ||
val state = it.args["state"]?.jsonPrimitive?.content | ||
val date = it.args["date"]?.jsonPrimitive?.content | ||
runBlocking { | ||
response = if(!city.isNullOrEmpty() and !state.isNullOrEmpty() and date.isNullOrEmpty()) { | ||
fetchWeather(city!!, state!!, date!!) | ||
} else { | ||
JsonObject(emptyMap()) | ||
} | ||
} | ||
} | ||
return FunctionResponsePart("fetchWeather", response, fetchWeatherCall.id) | ||
} | ||
@RequiresPermission(Manifest.permission.RECORD_AUDIO) | ||
suspend fun startConversation() { | ||
liveSession.startAudioConversation(::handler) | ||
} | ||
|
||
fun endConversation() { | ||
liveSession.stopAudioConversation() | ||
} | ||
|
||
|
||
} |
136 changes: 131 additions & 5 deletions
136
.../app/src/main/java/com/google/firebase/quickstart/ai/feature/live/StreamRealtimeScreen.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,146 @@ | ||
package com.google.firebase.quickstart.ai.feature.live | ||
|
||
import androidx.compose.foundation.layout.Box | ||
import android.Manifest | ||
import androidx.annotation.RequiresPermission | ||
import androidx.compose.animation.animateContentSize | ||
import androidx.compose.foundation.layout.Arrangement | ||
import androidx.compose.foundation.layout.Column | ||
import androidx.compose.foundation.layout.Spacer | ||
import androidx.compose.foundation.layout.fillMaxSize | ||
import androidx.compose.foundation.layout.height | ||
import androidx.compose.foundation.layout.padding | ||
import androidx.compose.foundation.layout.size | ||
import androidx.compose.foundation.shape.CircleShape | ||
import androidx.compose.material.icons.Icons | ||
import androidx.compose.material.icons.filled.CallEnd | ||
import androidx.compose.material.icons.filled.Mic | ||
import androidx.compose.material3.Icon | ||
import androidx.compose.material3.IconButton | ||
import androidx.compose.material3.IconButtonDefaults | ||
import androidx.compose.material3.MaterialTheme | ||
import androidx.compose.material3.Surface | ||
import androidx.compose.material3.Text | ||
import androidx.compose.runtime.Composable | ||
import androidx.compose.ui.Alignment | ||
import androidx.compose.ui.Modifier | ||
import androidx.compose.ui.draw.clip | ||
import androidx.compose.ui.graphics.Color | ||
import androidx.compose.ui.text.font.FontWeight | ||
import androidx.compose.ui.unit.dp | ||
import androidx.compose.ui.unit.sp | ||
import androidx.compose.runtime.remember | ||
import androidx.compose.runtime.mutableStateOf | ||
|
||
import androidx.lifecycle.viewmodel.compose.viewModel | ||
import com.google.firebase.quickstart.ai.feature.media.imagen.BidiViewModel | ||
import com.google.firebase.quickstart.ai.feature.media.imagen.ImagenViewModel | ||
import kotlinx.coroutines.CoroutineScope | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.launch | ||
import kotlinx.serialization.Serializable | ||
|
||
@Serializable | ||
class StreamRealtimeRoute(val sampleId: String) | ||
|
||
@RequiresPermission(Manifest.permission.RECORD_AUDIO) | ||
@Composable | ||
fun StreamRealtimeScreen() { | ||
Box( | ||
modifier = Modifier.fillMaxSize() | ||
fun StreamRealtimeScreen(bidiView: BidiViewModel = viewModel<BidiViewModel>()) { | ||
val isConversationActive = remember { mutableStateOf(false) } | ||
val backgroundColor = | ||
MaterialTheme.colorScheme.background | ||
Surface( | ||
modifier = Modifier.fillMaxSize(), | ||
color = backgroundColor | ||
) { | ||
Text("Coming soon") | ||
Column( | ||
modifier = Modifier | ||
.fillMaxSize() | ||
.padding(16.dp), | ||
horizontalAlignment = Alignment.CenterHorizontally, | ||
verticalArrangement = Arrangement.Center | ||
) { | ||
// The content will animate its size when it changes | ||
Column( | ||
horizontalAlignment = Alignment.CenterHorizontally, | ||
modifier = Modifier.animateContentSize() | ||
) { | ||
if (isConversationActive.value) { | ||
// Active state UI | ||
Text( | ||
text = "Conversation Active", | ||
fontSize = 22.sp, | ||
fontWeight = FontWeight.Bold, | ||
color = MaterialTheme.colorScheme.onSurface | ||
) | ||
Spacer(modifier = Modifier.height(8.dp)) | ||
Text( | ||
text = "Tap the end button to stop", | ||
fontSize = 18.sp, | ||
color = MaterialTheme.colorScheme.onSurfaceVariant | ||
) | ||
} else { | ||
// Idle state UI | ||
Text( | ||
text = "Start Conversation", | ||
fontSize = 22.sp, | ||
fontWeight = FontWeight.Bold, | ||
color = MaterialTheme.colorScheme.onSurface | ||
) | ||
Spacer(modifier = Modifier.height(8.dp)) | ||
Text( | ||
text = "Tap the microphone to begin", | ||
fontSize = 18.sp, | ||
color = MaterialTheme.colorScheme.onSurfaceVariant | ||
) | ||
} | ||
} | ||
|
||
Spacer(modifier = Modifier.height(80.dp)) | ||
|
||
// The main button with pulsing animation | ||
if (isConversationActive.value) { | ||
// Button to end the conversation | ||
IconButton( | ||
onClick = { | ||
bidiView.endConversation() | ||
isConversationActive.value = false }, | ||
modifier = Modifier | ||
.size(90.dp) | ||
.clip(CircleShape), | ||
colors = IconButtonDefaults.iconButtonColors( | ||
containerColor = Color(0xFFE63946), // A nice red color | ||
contentColor = Color.White | ||
) | ||
) { | ||
Icon( | ||
imageVector = Icons.Default.CallEnd, | ||
contentDescription = "End Conversation", | ||
modifier = Modifier.size(48.dp) | ||
) | ||
} | ||
} else { | ||
// Button to start the conversation | ||
IconButton( | ||
onClick = { | ||
CoroutineScope(Dispatchers.IO).launch { | ||
bidiView.startConversation() | ||
} | ||
isConversationActive.value = true }, | ||
modifier = Modifier | ||
.size(90.dp) | ||
.clip(CircleShape), | ||
colors = IconButtonDefaults.iconButtonColors( | ||
containerColor = MaterialTheme.colorScheme.primary, | ||
contentColor = Color.White | ||
) | ||
) { | ||
Icon( | ||
imageVector = Icons.Default.Mic, | ||
contentDescription = "Start Conversation", | ||
modifier = Modifier.size(48.dp) | ||
) | ||
} | ||
} | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.