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 @@ -59,6 +59,8 @@ class GeminiProviderImpl
private val httpClient: HttpClient,
private val toolConverter: GeminiToolConverter,
) : LlmProvider {
override val defaultModelName: String = DEFAULT_MODEL_NAME

override suspend fun getAvailableModels(apiKey: String?): List<LlmModel> {
if (apiKey.isNullOrBlank()) {
return emptyList()
Expand Down Expand Up @@ -104,7 +106,10 @@ class GeminiProviderImpl
supportedMethods == null ||
VALUE_GENERATE_CONTENT in supportedMethods

if (modelId.startsWith(GEMINI_MODEL_PREFIX) && supportsGenerateContent) {
if (modelId.startsWith(GEMINI_MODEL_PREFIX) &&
supportsGenerateContent &&
!isSpecializedModel(modelId)
) {
LlmModel(LlmProviderName.GEMINI, modelId)
} else {
null
Expand All @@ -117,6 +122,13 @@ class GeminiProviderImpl
}
}

/**
* Whether [modelId] belongs to one of [SPECIALIZED_MODEL_NAME_PARTS]: models that support
* `generateContent` but aren't meant for chat with function calling.
*/
private fun isSpecializedModel(modelId: String): Boolean =
SPECIALIZED_MODEL_NAME_PARTS.any { part -> "-$modelId-".contains("-$part-") }

override suspend fun generateResponse(
previousInteractionId: String?,
input: LlmInput,
Expand Down Expand Up @@ -384,6 +396,22 @@ class GeminiProviderImpl
private const val MODEL_NAME_PREFIX = "models/"
private const val GEMINI_MODEL_PREFIX = "gemini-"

/**
* Name parts of Gemini model families that support `generateContent` but aren't meant for
* chat with function calling: speech generation, image generation, transcription, Omni
* media generation, robotics, computer use, and Live and native audio. A model is hidden
* when one of them appears as whole `-`-separated parts of its name, so that new general
* models keep appearing without code changes.
*/
private val SPECIALIZED_MODEL_NAME_PARTS =
listOf("tts", "image", "nano-banana", "transcribe", "omni", "robotics", "computer-use", "live", "audio")

/**
* The model for new threads while the API lists it. The `-latest` alias follows the current
* Flash model, where a pinned version can be retired or run out of capacity.
*/
private const val DEFAULT_MODEL_NAME = "gemini-flash-latest"

private const val KEY_MODEL = "model"
private const val KEY_SERVICE_TIER = "service_tier"
private const val KEY_INPUT = "input"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,16 @@ import com.example.appfunctions.agent.data.ServiceTier
/** Interface for LLM providers to generate responses. */
interface LlmProvider {
/**
* Retrieves the list of available models from this LLM provider.
* The name of the model new threads use while [getAvailableModels] lists it, or null for no
* preference. See [resolveDefaultModel].
*/
val defaultModelName: String?
get() = null

/**
* Retrieves the list of available models from this LLM provider: the models that can run the
* agent's chat with function calling, in display order. The order doesn't determine the default
* model, which [resolveDefaultModel] picks.
*
* @param apiKey The API key for the LLM provider, or null/blank if not configured.
* @return The list of available [LlmModel]s supported by this provider.
Expand Down Expand Up @@ -51,6 +60,14 @@ interface LlmProvider {
): LlmResponse
}

/**
* Returns the model for new threads among [availableModels], the models this provider's
* [LlmProvider.getAvailableModels] returned: the model named [LlmProvider.defaultModelName]
* if it is listed, otherwise the first available model, or null if there are none.
*/
fun LlmProvider.resolveDefaultModel(availableModels: List<LlmModel>): LlmModel? =
availableModels.find { it.modelName == defaultModelName } ?: availableModels.firstOrNull()

/** Represents the input to the LLM, which can be a user message or a response from a tool. */
sealed class LlmInput {
/** Represents a new message from the user. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -421,18 +421,14 @@ fun AgentDemoLoadedScreen(
}
},
)
val defaultModel =
uiState.currentThread
?.llmModel
?.takeUnless { uiState.isCurrentThreadLive }
?: uiState.availableModels.firstOrNull()
val newThreadModel = uiState.newThreadModel
IconButton(
onClick = {
if (defaultModel != null) {
onEvent(AgentUiEvent.OnCreateThread(defaultModel))
if (newThreadModel != null) {
onEvent(AgentUiEvent.OnCreateThread(newThreadModel))
}
},
enabled = defaultModel != null,
enabled = newThreadModel != null,
modifier = Modifier.padding(horizontal = 8.dp),
) {
Icon(imageVector = Icons.Default.Add, contentDescription = "Create Thread")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ 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
import com.example.appfunctions.agent.domain.resolveDefaultModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
Expand Down Expand Up @@ -79,7 +80,7 @@ class AgentDemoViewModel
val uiState: StateFlow<AgentUiState> = _uiState.asStateFlow()

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

private var observationJob: Job? = null
Expand All @@ -88,17 +89,25 @@ class AgentDemoViewModel
init {
viewModelScope.launch {
settingsRepository.geminiApiKey.collectLatest { geminiApiKey ->
val models =
LlmProviderName.entries.flatMap { providerName ->
val choicesByProvider =
LlmProviderName.entries.map { providerName ->
val apiKey =
when (providerName) {
LlmProviderName.GEMINI -> geminiApiKey
}
llmProviderFactory.getProvider(providerName).getAvailableModels(apiKey)
val provider = llmProviderFactory.getProvider(providerName)
val models = provider.getAvailableModels(apiKey)
ModelChoices(models, provider.resolveDefaultModel(models))
}
availableModels.value = models
if (models.isNotEmpty() && manageThreadsUseCase.getThreads().first().isEmpty()) {
createAndSelectThread(models.first())
val choices =
ModelChoices(
availableModels = choicesByProvider.flatMap { it.availableModels },
defaultModel = choicesByProvider.firstNotNullOfOrNull { it.defaultModel },
)
modelChoices.value = choices
val defaultModel = choices.defaultModel
if (defaultModel != null && manageThreadsUseCase.getThreads().first().isEmpty()) {
createAndSelectThread(defaultModel)
}
}
}
Expand Down Expand Up @@ -139,13 +148,13 @@ class AgentDemoViewModel
},
savedStateHandle.getStateFlow<String?>(MainActivity.ARG_THREAD_ID, null),
installedApps,
availableModels,
modelChoices,
liveSetupPrompt,
) {
snapshot,
targetThreadId,
apps,
models,
choices,
setupPrompt,
->
ThreadConfig(
Expand All @@ -155,7 +164,7 @@ class AgentDemoViewModel
activeLiveSession = snapshot.activeLiveSession,
targetThreadId = targetThreadId,
installedApps = apps,
availableModels = models,
modelChoices = choices,
liveSetupPrompt = setupPrompt,
)
}
Expand Down Expand Up @@ -206,7 +215,8 @@ class AgentDemoViewModel
activePendingActionIds =
currentLoadedState?.activePendingActionIds ?: emptySet(),
installedApps = config.installedApps,
availableModels = config.availableModels,
availableModels = config.modelChoices.availableModels,
defaultModel = config.modelChoices.defaultModel,
)

if (currentThread == null) {
Expand Down Expand Up @@ -418,6 +428,12 @@ private data class ThreadConfig(
val activeLiveSession: ActiveLiveSession?,
val targetThreadId: String?,
val installedApps: List<AppInfo>,
val availableModels: List<LlmModel>,
val modelChoices: ModelChoices,
val liveSetupPrompt: LiveSetupPrompt?,
)

/** The models the picker offers, and the default model among them for new threads. */
private data class ModelChoices(
val availableModels: List<LlmModel> = emptyList(),
val defaultModel: LlmModel? = null,
)
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,22 @@ sealed class AgentUiState {
val activePendingActionIds: Set<String> = emptySet(),
val installedApps: List<AppInfo> = emptyList(),
val availableModels: List<LlmModel> = emptyList(),
) : AgentUiState()
/** The model for new threads among [availableModels], as its provider resolves it. */
val defaultModel: LlmModel? = null,
) : AgentUiState() {
/**
* The model for a new thread: the current thread's model while [availableModels] offers it,
* otherwise [defaultModel]. While no models are loaded, new threads keep the current
* thread's model. A Live thread's model is never copied.
*/
val newThreadModel: LlmModel?
get() =
currentThread
?.llmModel
?.takeUnless { isCurrentThreadLive }
?.takeIf { availableModels.isEmpty() || it in availableModels }
?: defaultModel
}
}

/** Setup prompt or launch request emitted when starting a Live voice session. */
Expand Down
Loading
Loading