R/ask_chatgpt.R

Defines functions ask_chatgpt

Documented in ask_chatgpt

#' Ask ChatGPT
#'
#' Note: See also `reset_chat_session`.
#'
#' @param question The question to ask ChatGPT.
#'
#' @examples
#' \dontrun{
#' cat(ask_chatgpt("What do you think about R language?"))
#' }
#'
#' @return A character value with the response generated by ChatGPT.
#'
#' @export
#'
ask_chatgpt <- function(question) {
  # Get the existing chat session messages, and add the new message.
  chat_session_messages <- append(get("chat_session_messages", envir = .state), list(
    list(role = "user", content = question)
  ))
  # Send the query to ChatGPT.
  chat_gpt_reply <- parse_response(gpt_get_completions(question, messages = chat_session_messages))
  chat_session_messages <- append(chat_session_messages, list(
    list(role = "assistant", content = chat_gpt_reply)
  ))
  # Update the chat session messages with the new question and the reply.
  assign("chat_session_messages", chat_session_messages, .state)
  chat_gpt_reply
}

Try the chatgpt package in your browser

Any scripts or data that you put into this service are public.

chatgpt documentation built on May 31, 2023, 6:54 p.m.