tidyverse / elmer

Call LLM APIs from R
http://elmer.tidyverse.org/
Other
199 stars 28 forks source link

Added a shiny app example in streaming-async.Rmd using `chat_async` #131

Open adisarid opened 1 month ago

adisarid commented 1 month ago

Added shiny app example for chat_async usage

jcheng5 commented 1 month ago

Bit simpler version? input_task_button shows simple progress and also prevents double-clicking. And I got rid of the explicit error handling, I think Shiny's built-in behavior is enough.

library(shiny)
library(bslib)
library(elmer)
library(promises)

ui <- page_sidebar(
  title = "Interactive chat with async",
  sidebar = sidebar(
    title = "Controls",
    useShinyjs(),
    textInput("user_query", "Enter query:"),
    input_task_button("ask_chat", label = "Ask the chat")
  ),
  card(
    card_header("The chat's response"),
    uiOutput("chat_response")
  )
)

server <- function(input, output) {
  output$chat_response <- renderUI({
    # Start the chat fresh each time, as the UI is not a multi-turn conversation
    chat <- chat_openai(
      system_prompt = "You like chatting about star trek, mostly TNG and onwards (not TOS). Answers should be concise and star trek inspired."
    )
    # Asynchronously get the (Markdown) results and render to HTML
    chat$chat_async("Answer this question:", input$user_query) %...>% markdown()
  }) |> bindEvent(input$ask_chat)
}

shinyApp(ui = ui, server = server)
adisarid commented 1 month ago

Great suggestions!, I have updated the PR accordingly. I have also removed the useShinyjs from the ui (it is not needed after your update), thanks.