Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ class GeminiLiveProviderImpl
private val toolConverter: GeminiLiveToolConverter,
private val webSocketConnector: suspend (wsUrl: String) -> WebSocketSession,
) : LiveLlmProvider {
override val liveModel: LlmModel = LlmModel(LlmProviderName.GEMINI, LIVE_MODEL_ID)

@Inject
constructor(
httpClient: HttpClient,
Expand Down Expand Up @@ -653,7 +655,8 @@ class GeminiLiveProviderImpl

companion object {
private const val TAG = "GeminiLiveProvider"
const val LIVE_MODEL_NAME = "models/gemini-3.8-live"
const val LIVE_MODEL_ID = "gemini-3.8-live"
const val LIVE_MODEL_NAME = "models/$LIVE_MODEL_ID"
const val DEFAULT_INPUT_SAMPLE_RATE_HZ = 16_000
const val DEFAULT_OUTPUT_SAMPLE_RATE_HZ = 24_000
private const val GEMINI_LIVE_WS_URL =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,16 @@
package com.example.appfunctions.agent.domain

import androidx.appfunctions.metadata.AppFunctionMetadata
import com.example.appfunctions.agent.data.LlmModel
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext

/** Interface for LLM providers supporting bidirectional realtime audio and tool sessions. */
interface LiveLlmProvider {
/** The [LlmModel] identifier recorded on chat threads created for this live provider. */
val liveModel: LlmModel

/**
* Connects to the live LLM backend, completes session initialization with [tools] and optional
* provider-specific [voiceName], and returns the active [LiveLlmSession]. The caller is
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@ import com.example.appfunctions.agent.data.SettingsRepository
import com.example.appfunctions.agent.data.db.entities.MessageProcessingStatus
import com.example.appfunctions.agent.data.db.entities.MessageRole
import com.example.appfunctions.agent.data.db.entities.ThreadEntity
import com.example.appfunctions.agent.domain.ActiveLiveSession
import com.example.appfunctions.agent.domain.AgentOrchestrator
import com.example.appfunctions.agent.domain.AgentStatus
import com.example.appfunctions.agent.domain.LiveAgentOrchestrator
import com.example.appfunctions.agent.domain.LlmProviderFactory
import com.example.appfunctions.agent.domain.appfunction.AppInfo
import com.example.appfunctions.agent.domain.appfunction.GetAppFunctionsParams
Expand All @@ -35,6 +37,8 @@ import com.example.appfunctions.agent.domain.appfunction.GetInstalledAppsUseCase
import com.example.appfunctions.agent.domain.chat.GetChatHistoryUseCase
import com.example.appfunctions.agent.domain.chat.ManageThreadsUseCase
import com.example.appfunctions.agent.domain.chat.SendMessageUseCase
import com.example.appfunctions.agent.domain.live.CheckAudioPermissionUseCase
import com.example.appfunctions.agent.domain.live.CheckVoiceServiceActiveUseCase
import com.example.appfunctions.agent.domain.pendingintent.ConsumePendingIntentUseCase
import com.example.appfunctions.agent.domain.pendingintent.LaunchPendingIntentUseCase
import com.example.appfunctions.agent.domain.pendingintent.ObserveActivePendingIntentsUseCase
Expand All @@ -60,6 +64,9 @@ class AgentDemoViewModel
private val manageThreadsUseCase: ManageThreadsUseCase,
private val sendMessageUseCase: SendMessageUseCase,
private val agentOrchestrator: AgentOrchestrator,
private val liveAgentOrchestrator: LiveAgentOrchestrator,
private val checkAudioPermissionUseCase: CheckAudioPermissionUseCase,
private val checkVoiceServiceActiveUseCase: CheckVoiceServiceActiveUseCase,
private val settingsRepository: SettingsRepository,
private val llmProviderFactory: LlmProviderFactory,
private val observeActivePendingIntentsUseCase: ObserveActivePendingIntentsUseCase,
Expand All @@ -73,8 +80,10 @@ class AgentDemoViewModel

private val installedApps = MutableStateFlow<List<AppInfo>>(emptyList())
private val availableModels = MutableStateFlow<List<LlmModel>>(emptyList())
private val liveSetupPrompt = MutableStateFlow<LiveSetupPrompt?>(null)

private var observationJob: Job? = null
private var createLiveThreadJob: Job? = null

init {
viewModelScope.launch {
Expand Down Expand Up @@ -124,50 +133,86 @@ class AgentDemoViewModel
manageThreadsUseCase.getThreads(),
settingsRepository.selectedProvider,
agentOrchestrator.status,
) { threads, provider, status ->
Triple(threads, provider, status)
liveAgentOrchestrator.activeSession,
) { threads, provider, status, activeLiveSession ->
AgentStatusSnapshot(threads, provider, status, activeLiveSession)
},
savedStateHandle.getStateFlow<String?>(MainActivity.ARG_THREAD_ID, null),
installedApps,
availableModels,
liveSetupPrompt,
) {
(threads, provider, status),
snapshot,
targetThreadId,
apps,
models,
setupPrompt,
->
ThreadConfig(threads, provider, status, targetThreadId, apps, models)
ThreadConfig(
threads = snapshot.threads,
provider = snapshot.provider,
status = snapshot.status,
activeLiveSession = snapshot.activeLiveSession,
targetThreadId = targetThreadId,
installedApps = apps,
availableModels = models,
liveSetupPrompt = setupPrompt,
)
}
.collectLatest { (threads, _, status, targetThreadId, apps, models) ->
.collectLatest { config ->
val currentThread =
threads.find { it.threadId == targetThreadId } ?: threads.firstOrNull()
config.threads.find { it.threadId == config.targetThreadId }
?: config.threads.firstOrNull()

val previousThreadId =
(_uiState.value as? AgentUiState.Loaded)?.currentThread?.threadId

val activeLiveSession = config.activeLiveSession
val liveStatusForCurrentThread =
if (
currentThread != null &&
activeLiveSession?.threadId == currentThread.threadId
) {
activeLiveSession.status
} else {
null
}
val isAnotherThreadLiveBusy =
activeLiveSession != null &&
activeLiveSession.threadId != currentThread?.threadId

val currentLoadedState = _uiState.value as? AgentUiState.Loaded
val isCurrentThreadLive =
currentThread != null &&
currentThread.llmModel ==
llmProviderFactory
.getLiveProvider(currentThread.llmModel.providerName)
.liveModel
_uiState.value =
AgentUiState.Loaded(
currentThread = currentThread,
isCurrentThreadLive = isCurrentThreadLive,
messages =
if (currentThread != null) {
if (currentThread != null && currentThread.threadId == previousThreadId) {
currentLoadedState?.messages ?: emptyList()
} else {
emptyList()
},
status = status,
threads = threads,
status = config.status,
liveStatus = liveStatusForCurrentThread,
isAnotherThreadLiveBusy = isAnotherThreadLiveBusy,
liveSetupPrompt = config.liveSetupPrompt,
threads = config.threads,
activePendingActionIds =
currentLoadedState?.activePendingActionIds ?: emptySet(),
installedApps = apps,
availableModels = models,
installedApps = config.installedApps,
availableModels = config.availableModels,
)

if (currentThread == null) {
observationJob?.cancel()
observationJob = null
} else if (observationJob == null || previousThreadId != currentThread.threadId) {
// Start observing messages for the current thread if not already doing so
observationJob?.cancel()
observationJob =
viewModelScope.launch {
Expand Down Expand Up @@ -196,7 +241,10 @@ class AgentDemoViewModel
val currentState = _uiState.value
when (event) {
is AgentUiEvent.OnSendMessage -> {
val currentThread = (currentState as? AgentUiState.Loaded)?.currentThread
val currentThread =
(currentState as? AgentUiState.Loaded)
?.takeUnless { it.isCurrentThreadLive }
?.currentThread
if (currentThread != null) {
viewModelScope.launch {
sendMessageUseCase(
Expand All @@ -213,7 +261,7 @@ class AgentDemoViewModel
if (currentState is AgentUiState.Loaded) {
viewModelScope.launch {
val currentThread = currentState.currentThread
if (currentThread != null) {
if (currentThread != null && !currentState.isCurrentThreadLive) {
manageThreadsUseCase.updateThreadModel(
currentThread.threadId,
event.model,
Expand All @@ -236,20 +284,140 @@ class AgentDemoViewModel
launchPendingIntentUseCase(pendingIntent)
}
}
is AgentUiEvent.OnStartLiveSession -> {
tryStartLiveSession(event.targetPackageName)
}
is AgentUiEvent.OnLiveSessionLaunchResult -> {
val pendingThreadId =
savedStateHandle.get<String?>(KEY_PENDING_LAUNCH_THREAD_ID)
val previousThreadId =
savedStateHandle.get<String?>(KEY_PREVIOUS_THREAD_ID)
clearPendingLaunchThread()
if (event.isLaunched) {
liveSetupPrompt.value = null
} else {
savedStateHandle[MainActivity.ARG_THREAD_ID] = previousThreadId
if (pendingThreadId != null) {
viewModelScope.launch {
manageThreadsUseCase.deleteThread(pendingThreadId)
}
}
liveSetupPrompt.value = LiveSetupPrompt.AssistLaunchFailed
}
}
is AgentUiEvent.OnAudioPermissionResult -> {
val pendingTarget =
savedStateHandle.get<String?>(KEY_PENDING_LIVE_TARGET_PACKAGE)
if (event.isGranted) {
liveSetupPrompt.value = null
tryStartLiveSession(pendingTarget)
} else {
clearPendingLiveTarget()
liveSetupPrompt.value = LiveSetupPrompt.AudioPermissionDenied
}
}
AgentUiEvent.OnAssistantSettingsReturned -> {
val pendingTarget =
savedStateHandle.get<String?>(KEY_PENDING_LIVE_TARGET_PACKAGE)
clearPendingLiveTarget()
if (checkVoiceServiceActiveUseCase()) {
launchNewLiveSession(pendingTarget)
} else {
liveSetupPrompt.value = LiveSetupPrompt.AssistantNotSelected
}
Comment thread
juliantoledo marked this conversation as resolved.
Resolved
}
AgentUiEvent.OnAssistantSettingsUnavailable -> {
clearPendingLiveTarget()
liveSetupPrompt.value = LiveSetupPrompt.AssistantSettingsUnavailable
}
AgentUiEvent.OnDismissLiveSetupPrompt -> {
clearPendingLiveTarget()
liveSetupPrompt.value = null
}
}
}

private fun tryStartLiveSession(targetPackageName: String?) {
if (
liveAgentOrchestrator.activeSession.value != null ||
agentOrchestrator.status.value != AgentStatus.Idle
) {
return
}
if (!checkAudioPermissionUseCase()) {
savedStateHandle[KEY_PENDING_LIVE_TARGET_PACKAGE] = targetPackageName
liveSetupPrompt.value = LiveSetupPrompt.RequestAudioPermission(targetPackageName)
return
}
if (!checkVoiceServiceActiveUseCase()) {
savedStateHandle[KEY_PENDING_LIVE_TARGET_PACKAGE] = targetPackageName
liveSetupPrompt.value = LiveSetupPrompt.SelectDigitalAssistant(targetPackageName)
return
}
clearPendingLiveTarget()
launchNewLiveSession(targetPackageName)
}

private fun launchNewLiveSession(targetPackageName: String?) {
if (
createLiveThreadJob?.isActive == true ||
savedStateHandle.get<String?>(KEY_PENDING_LAUNCH_THREAD_ID) != null
) {
return
}
createLiveThreadJob =
viewModelScope.launch {
val previousThreadId =
(_uiState.value as? AgentUiState.Loaded)?.currentThread?.threadId
val selectedProvider = settingsRepository.selectedProvider.first()
val liveModel = llmProviderFactory.getLiveProvider(selectedProvider).liveModel
val liveThreadId = manageThreadsUseCase.createThread(liveModel)
savedStateHandle[KEY_PENDING_LAUNCH_THREAD_ID] = liveThreadId
savedStateHandle[KEY_PREVIOUS_THREAD_ID] = previousThreadId
savedStateHandle[MainActivity.ARG_THREAD_ID] = liveThreadId
liveSetupPrompt.value =
LiveSetupPrompt.LaunchAssistSession(
threadId = liveThreadId,
targetPackageName = targetPackageName,
)
}
}

private fun clearPendingLiveTarget() {
savedStateHandle.remove<String?>(KEY_PENDING_LIVE_TARGET_PACKAGE)
}

private fun clearPendingLaunchThread() {
savedStateHandle.remove<String?>(KEY_PENDING_LAUNCH_THREAD_ID)
savedStateHandle.remove<String?>(KEY_PREVIOUS_THREAD_ID)
}

private suspend fun createAndSelectThread(llmModel: LlmModel) {
val threadId = manageThreadsUseCase.createThread(llmModel)
savedStateHandle[MainActivity.ARG_THREAD_ID] = threadId
}

private companion object {
const val KEY_PENDING_LIVE_TARGET_PACKAGE = "pending_live_target_package"
const val KEY_PENDING_LAUNCH_THREAD_ID = "pending_launch_live_thread_id"
const val KEY_PREVIOUS_THREAD_ID = "previous_thread_id_before_live"
}
}

private data class AgentStatusSnapshot(
val threads: List<ThreadEntity>,
val provider: LlmProviderName,
val status: AgentStatus,
val activeLiveSession: ActiveLiveSession?,
)

private data class ThreadConfig(
val threads: List<ThreadEntity>,
val provider: LlmProviderName,
val status: AgentStatus,
val activeLiveSession: ActiveLiveSession?,
val targetThreadId: String?,
val installedApps: List<AppInfo>,
val availableModels: List<LlmModel>,
val liveSetupPrompt: LiveSetupPrompt?,
)
Loading
Loading