chat_append_message | R Documentation |
For advanced users who want to control the message chunking behavior. Most
users should use chat_append()
instead.
chat_append_message(
id,
msg,
chunk = TRUE,
operation = c("append", "replace"),
session = getDefaultReactiveDomain()
)
id |
The ID of the chat element |
msg |
The message to append. Should be a named list with |
chunk |
Whether |
operation |
The operation to perform on the message. If |
session |
The Shiny session object |
Returns nothing (invisible(NULL)
).
library(shiny)
library(coro)
library(bslib)
library(shinychat)
# Dumbest chatbot in the world: ignores user input and chooses
# a random, vague response.
fake_chatbot <- async_generator(function(id, input) {
responses <- c(
"What does that suggest to you?",
"I see.",
"I'm not sure I understand you fully.",
"What do you think?",
"Can you elaborate on that?",
"Interesting question! Let's examine thi... **See more**"
)
# Use low-level chat_append_message() to temporarily set a progress message
chat_append_message(id, list(role = "assistant", content = "_Thinking..._ "))
await(async_sleep(1))
# Clear the progress message
chat_append_message(id, list(role = "assistant", content = ""), operation = "replace")
for (chunk in strsplit(sample(responses, 1), "")[[1]]) {
yield(chunk)
await(async_sleep(0.02))
}
})
ui <- page_fillable(
chat_ui("chat", fill = TRUE)
)
server <- function(input, output, session) {
observeEvent(input$chat_user_input, {
response <- fake_chatbot("chat", input$chat_user_input)
chat_append("chat", response)
})
}
shinyApp(ui, server)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.