I'm trying to run the ask_chatgpt function through multiple lines in R. A basic example:
Loading the basic information, excluding the API:
### load current ChatGPT package: https://github.com/jcrodriguez1989/chatgpt
install.packages("chatgpt")
library(chatgpt)
### load GPT API
Sys.setenv(OPENAI_API_KEY = "XXX")
Separate questions:
### first question
cat(ask_chatgpt("Is Arkansas in the United States?"))
Yes, Arkansas is a state in the United States. It is located in the southern region of the country.
### second question
cat(ask_chatgpt("Is Arkansas in India?"))
No, Arkansas is not in India. Arkansas is a state in the United States, while India is a country located in South Asia. They are two separate and distinct geographical locations.
But if, separately, I attempt to run the questions through dplyr::mutate
, I get the following error message:
### write into dataframe
test <- data.frame(x = c("Is Arkansas in the United States?", "Is Arkansas in India?"))
### ask_chatgpt
test <- test %>%
mutate(y = cat(ask_chatgpt(x)))
Error in `mutate()`: ! Problem while computing `y = ask_chatgpt(x)`. Caused by error in `gpt_get_completions()`: ! list(message = "Invalid type for 'messages[13].content[0]': expected an object, but got a string instead.", type = "invalid_request_error", param = "messages[13].content[0]", code = "invalid_type") Backtrace: 1. test %>% mutate(y = ask_chatgpt(x)) 7. chatgpt::ask_chatgpt(x) 19. chatgpt:::gpt_get_completions(question, messages = chat_session_messages) 20. base::stop(content(post_res))
How can I fix this? I'm not sure I see an obvious solution in the documentation. Thanks!
The outputs of the cat() are not objects that R can further process. If you want to ask multiple questions and save the answers, try sapply.
test <- data.frame(
x = c("Is Arkansas in the United States?", "Is Arkansas in India?")
)
test$y <- sapply(test$x, ask_chatgpt)