我在R中尝试通过多行运行ask_chatgpt函数。这是一个基本的示例:
加载基本信息,不包括API:
### 加载当前的ChatGPT包:https://github.com/jcrodriguez1989/chatgptinstall.packages("chatgpt")library(chatgpt)### 加载GPT APISys.setenv(OPENAI_API_KEY = "XXX")
单独的问题:
### 第一个问题cat(ask_chatgpt("Is Arkansas in the United States?"))
是的,阿肯色州是美国的一个州。它位于该国的南部地区。
### 第二个问题cat(ask_chatgpt("Is Arkansas in India?"))
不,阿肯色州不在印度。阿肯色州是美国的一个州,而印度是位于南亚的一个国家。它们是两个独立且不同的地理位置。
但是,如果我尝试通过dplyr::mutate
单独运行这些问题,我会得到以下错误消息:
### 写入数据框test <- data.frame(x = c("Is Arkansas in the United States?", "Is Arkansas in India?"))### ask_chatgpttest <- test %>% mutate(y = cat(ask_chatgpt(x)))
在`mutate()`中出错:! 在计算`y = ask_chatgpt(x)`时出现问题。由`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”) 回溯: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))
我该如何解决这个问题?我在文档中没有看到明显的解决方案。谢谢!
回答:
cat()的输出不是R可以进一步处理的对象。如果你想问多个问题并保存答案,可以尝试使用sapply。
test <- data.frame( x = c("Is Arkansas in the United States?", "Is Arkansas in India?"))test$y <- sapply(test$x, ask_chatgpt)