ChatGPT Shiny R app

This is a simple integration of ChatGPT into shiny R. At first I wanted to do this in Python but it was easier to do a web app in R Shiny. I used code from this site to get started:

https://www.listendata.com/2023/05/chatgpt-in-r.html#steps_to_run_chatgpt_in_r

The app is hosted at: https://twong.shinyapps.io/chat_bot/

The R code for this shiny app is below.

library(shiny)
library(httr)

ui <- fluidPage(
  titlePanel("ChatGPT Shiny App"),
  textInput("user_input", "Enter your message:"),
  actionButton("submit_btn", "Submit"),
  p(""),
  textOutput("chat_output"),
  p(""),
  p("Code for this page is at https://codelooper.com/post/2023-12-22-chatgpt-code-in-python-in-r-markdown"),

  tags$head(tags$style("#chat_output{color: #C24A53;
                                 font-size: 25px;
                                 #font-style: italic;
                                 font-family: Georgia;
                                 padding-left: 25px;
                                 }"
  )
  )

)

server <- function(input, output, session) {
  conversation_history <- reactiveVal(list())

  observeEvent(input$submit_btn, {
    user_message <- isolate(input$user_input)
    conversation <- isolate(conversation_history())
    conversation <- c(conversation, list(list(role = "system", content = "You:")))
    conversation <- c(conversation, list(list(role = "user", content = user_message)))

    # Make a request to the OpenAI API
    response <- httr::POST(
      url = "https://api.openai.com/v1/chat/completions",
      add_headers(
        "Content-Type" = "application/json",
        "Authorization" = paste("Bearer", "API_KEY", sep = " ")
      ),
      body = list(
        model = "gpt-3.5-turbo",
        messages = conversation
      ),
      encode = "json"
    )

    # Extract the bot's message from the API response
    bot_message <- httr::content(response, "text")
    bot_message <- content(response)$choices[[1]]$message$content



    print(conversation)
    conversation <- c(conversation, list(list(role = "assistant", content = bot_message)))

    conversation_history(conversation)
    output$chat_output <- renderText({
      # Display only the assistant's reply
      assistant_reply <- tail(conversation, 1)[[1]]$content
      assistant_reply
      })

    })

}

shinyApp(ui, server)

Note: Replace API_KEY with your own API key.


See also