एजेंटिक वर्कफ़्लो के दौरान, AgentRunner क्लास और AgentSession इंटरफ़ेस, रिएक्टिव इवेंट स्ट्रीम उत्सर्जित करते हैं. ये स्ट्रीम, मॉडल की तर्क प्रक्रिया, टूल के इस्तेमाल, और टेक्स्ट वाले जवाबों को दिखाती हैं. इस पेज पर, Kotlin Coroutines और Jetpack Compose का इस्तेमाल करके, इवेंट इकट्ठा करने और उन्हें अपने यूज़र इंटरफ़ेस (यूआई) से कनेक्ट करने का तरीका बताया गया है.
AgentEvent के इंटरफ़ेस को समझना
AgentSession.runAsync() और AgentRunner.runSingleTurnAsync() तरीके, Flow<AgentEvent> स्ट्रीम दिखाते हैं. रीज़निंग लूप के पूरा होने का इंतज़ार करने के बजाय,
एजेंट के काम करने के दौरान आपके ऐप्लिकेशन को रीयल-टाइम अपडेट मिलते हैं:
इवेंट का टाइप |
ब्यौरा |
यूज़र इंटरफ़ेस (यूआई) की सामान्य कार्रवाई |
|
Gemini Nano से जनरेट किए गए, बढ़ने वाले टेक्स्ट चंक ( |
जब |
|
यह इवेंट तब ट्रिगर होता है, जब Gemini Nano किसी टूल को चुनता है और उसे इस्तेमाल करने के लिए तैयार होता है. यह |
प्रोग्रेस इंडिकेटर दिखाएं. उदाहरण के लिए, "ऑर्डर का स्टेटस देखा जा रहा है...". |
|
यह तब ट्रिगर होता है, जब ऐप्लिकेशन टूल फ़ंक्शन को एक्ज़ीक्यूट करना पूरा कर लेता है. यह |
टूल के स्टेटस को 'पूरा हो गया' पर सेट करें. |
ViewModel क्लास में इवेंट इकट्ठा करना
प्रॉम्प्ट डिस्पैच को मैनेज करने और Compose स्क्रीन पर यूज़र इंटरफ़ेस (यूआई) की स्थिति दिखाने के लिए, Android ViewModel क्लास का इस्तेमाल करें:
package com.example.ai.agent.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.mlkit.genai.agent.AgentEvent
import com.google.mlkit.genai.agent.AgentRunner
import com.google.mlkit.genai.agent.AgentSession
import com.google.mlkit.genai.common.GenAiException
import com.google.mlkit.genai.prompt.Content
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
data class AgentUiState(
val messages: List<String> = emptyList(),
val currentResponse: String = "",
val activeToolStatus: String? = null,
val isLoading: Boolean = false,
val errorMessage: String? = null
)
class ChatViewModel(
private val runner: AgentRunner,
private val sessionId: String = "default_chat_session"
) : ViewModel() {
private val session: AgentSession = runner.getOrCreateSession(sessionId)
private val _uiState = MutableStateFlow(AgentUiState())
val uiState: StateFlow<AgentUiState> = _uiState.asStateFlow()
fun sendMessage(userText: String) {
_uiState.update {
it.copy(
messages = it.messages + userText,
currentResponse = "",
activeToolStatus = null,
isLoading = true,
errorMessage = null
)
}
viewModelScope.launch {
val content = Content.builder().text(userText).build()
session.runAsync(content)
.catch { e ->
val message = when {
e is GenAiException && e.errorCode == GenAiException.ErrorCode.MAX_TURNS_EXCEEDED ->
"Agent exceeded the maximum reasoning turns allowed."
e is GenAiException && e.errorCode == GenAiException.ErrorCode.NOT_AVAILABLE ->
"On-device AI is currently unavailable."
e is GenAiException && e.errorCode == GenAiException.ErrorCode.BUSY ->
"On-device AI is busy. Please try again."
else -> e.localizedMessage ?: "Agent error"
}
_uiState.update {
it.copy(
isLoading = false,
activeToolStatus = null,
errorMessage = message
)
}
}
.collect { event ->
when (event) {
is AgentEvent.TextMessage -> {
_uiState.update {
it.copy(
currentResponse = if (event.isPartial) {
it.currentResponse + event.text
} else {
event.text.ifEmpty { it.currentResponse }
},
activeToolStatus = null
)
}
}
is AgentEvent.FunctionCall -> {
_uiState.update {
it.copy(
activeToolStatus =
"Executing ${event.name}..."
)
}
}
is AgentEvent.FunctionResponse -> {
_uiState.update {
it.copy(
activeToolStatus =
"Received data from ${event.name}"
)
}
}
else -> {}
}
}
// Finalize message once stream completes
_uiState.update {
it.copy(
messages = it.messages + it.currentResponse,
currentResponse = "",
activeToolStatus = null,
isLoading = false
)
}
}
}
override fun onCleared() {
super.onCleared()
// Release session memory and cancel active coroutines
session.close()
}
}
टेक्स्ट टोकन सीधे तौर पर निकालना
ऐसे बातचीत वाले इंटरफ़ेस के लिए जिनमें टूल के इस्तेमाल की जानकारी को यूज़र इंटरफ़ेस (यूआई) में अलग से दिखाने की ज़रूरत नहीं होती, Flow<AgentEvent> इंटरफ़ेस पर textTokens() एक्सटेंशन फ़ंक्शन का इस्तेमाल करें:
import com.google.mlkit.genai.agent.textTokens
import com.google.mlkit.genai.prompt.Content
val content = Content.builder().text(userText).build()
session.runAsync(content)
.textTokens()
.collect { token ->
appendTokenToChatBubble(token)
}
Jetpack Compose में रेंडर करना
स्ट्रीम किए गए टेक्स्ट और लाइव टूल ऐक्टिविटी को रेंडर करने के लिए, AgentUiState स्टेट को ऐप्लिकेशन बनाने की सुविधा में इस्तेमाल करें:
package com.example.ai.agent.ui
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun AgentChatScreen(
viewModel: ChatViewModel,
modifier: Modifier = Modifier
) {
val state by viewModel.uiState.collectAsState()
var inputText by remember { mutableStateOf("") }
Column(modifier = modifier.fillMaxSize().padding(16.dp)) {
LazyColumn(
modifier = Modifier.weight(1f).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(state.messages) { message ->
Card(modifier = Modifier.fillMaxWidth()) {
Text(text = message, modifier = Modifier.padding(12.dp))
}
}
if (state.activeToolStatus != null) {
item {
Text(
text = state.activeToolStatus ?: "",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.secondary
)
}
}
if (state.currentResponse.isNotEmpty()) {
item {
Card(
colors = CardDefaults.cardColors(
containerColor =
MaterialTheme.colorScheme.surfaceVariant
),
modifier = Modifier.fillMaxWidth()
) {
Text(
text = state.currentResponse,
modifier = Modifier.padding(12.dp)
)
}
}
}
}
Row(
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
TextField(
value = inputText,
onValueChange = { inputText = it },
modifier = Modifier.weight(1f),
placeholder = { Text("Ask about an order...") }
)
Button(
onClick = {
if (inputText.isNotBlank()) {
viewModel.sendMessage(inputText)
inputText = ""
}
},
enabled = !state.isLoading
) {
Text("Send")
}
}
}
}
अगले चरण
- टूल तय करें में जाकर, टूल तय करने का तरीका जानें.
- सेशन और लाइफ़साइकल मैनेज करना में जाकर, सेशन की मेमोरी मैनेज करना और रोटेशन को हैंडल करना.