1717package com.google.ai.sample.feature.multimodal
1818
1919import android.graphics.Bitmap
20+ import android.util.Log
2021import androidx.lifecycle.ViewModel
2122import androidx.lifecycle.viewModelScope
2223import com.google.ai.client.generativeai.GenerativeModel
2324import com.google.ai.client.generativeai.type.content
25+ import com.google.ai.sample.ScreenOperatorAccessibilityService
26+ import com.google.ai.sample.util.CommandParser
2427import kotlinx.coroutines.Dispatchers
2528import kotlinx.coroutines.flow.MutableStateFlow
2629import kotlinx.coroutines.flow.StateFlow
@@ -30,6 +33,7 @@ import kotlinx.coroutines.launch
3033class PhotoReasoningViewModel (
3134 private val generativeModel : GenerativeModel
3235) : ViewModel() {
36+ private val TAG = " PhotoReasoningViewModel"
3337
3438 private val _uiState : MutableStateFlow <PhotoReasoningUiState > =
3539 MutableStateFlow (PhotoReasoningUiState .Initial )
@@ -56,11 +60,43 @@ class PhotoReasoningViewModel(
5660
5761 generativeModel.generateContentStream(inputContent)
5862 .collect { response ->
59- outputContent + = response.text
63+ val newText = response.text ? : " "
64+ outputContent + = newText
6065 _uiState .value = PhotoReasoningUiState .Success (outputContent)
66+
67+ // Parse and execute commands from the response
68+ processCommands(newText)
6169 }
6270 } catch (e: Exception ) {
63- _uiState .value = PhotoReasoningUiState .Error (e.localizedMessage ? : " " )
71+ Log .e(TAG , " Error generating content: ${e.message} " , e)
72+ _uiState .value = PhotoReasoningUiState .Error (e.localizedMessage ? : " Unknown error" )
73+ }
74+ }
75+ }
76+
77+ /* *
78+ * Process commands found in the AI response
79+ */
80+ private fun processCommands (text : String ) {
81+ viewModelScope.launch(Dispatchers .Main ) {
82+ try {
83+ // Parse commands from the text
84+ val commands = CommandParser .parseCommands(text)
85+
86+ if (commands.isNotEmpty()) {
87+ Log .d(TAG , " Found ${commands.size} commands in response" )
88+
89+ // Execute each command
90+ commands.forEach { command ->
91+ Log .d(TAG , " Executing command: $command " )
92+ ScreenOperatorAccessibilityService .executeCommand(command)
93+
94+ // Add a small delay between commands to avoid overwhelming the system
95+ kotlinx.coroutines.delay(500 )
96+ }
97+ }
98+ } catch (e: Exception ) {
99+ Log .e(TAG , " Error processing commands: ${e.message} " , e)
64100 }
65101 }
66102 }
0 commit comments