Skip to content
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

Replace response handling for chat in the sample with streaming api #44

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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 @@ -36,4 +36,17 @@ class ChatUiState(
_messages.add(newMessage)
}
}

fun addOrUpdate(msg: ChatMessage) {
if(!updateMessage(msg.id, msg)) addMessage(msg)
}

fun updateMessage(id: String, newMessage: ChatMessage): Boolean {
val index = _messages.indexOfFirst { it.id == id }
if (index != -1) {
_messages[index] = newMessage
}

return index != -1
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,13 @@ import com.google.ai.client.generativeai.type.content
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectIndexed
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.runningFold
import kotlinx.coroutines.flow.skip
import kotlinx.coroutines.launch
import java.util.UUID

class ChatViewModel(
generativeModel: GenerativeModel
Expand Down Expand Up @@ -61,16 +67,18 @@ class ChatViewModel(

viewModelScope.launch {
try {
val response = chat.sendMessage(userMessage)
twiceyuan marked this conversation as resolved.
Show resolved Hide resolved

_uiState.value.replaceLastPendingMessage()

response.text?.let { modelResponse ->
_uiState.value.addMessage(
val uuid = UUID.randomUUID().toString()
chat.sendMessageStream(userMessage).runningFold("") { message, response ->
message + response.text
}.filter { it.isNotEmpty() }.collectIndexed { index, value ->
if (index == 0) {
_uiState.value.replaceLastPendingMessage()
twiceyuan marked this conversation as resolved.
Show resolved Hide resolved
}
_uiState.value.addOrUpdate(
ChatMessage(
text = modelResponse,
participant = Participant.MODEL,
isPending = false
id = uuid,
text = value,
participant = Participant.MODEL
)
)
}
Expand Down