R中ask_chatgpt结合dplyr::mutate报错:预期对象却获字符串
在R中批量调用ask_chatgpt函数的报错解决方法
问题场景
单独调用ask_chatgpt函数查询单个问题时运行正常,但通过dplyr::mutate批量处理数据框中的问题列表时,出现以下错误:
Error in
mutate(): ! Problem while computingy = ask_chatgpt(x). Caused by error ingpt_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")
错误原因
ask_chatgpt默认仅支持单个字符串输入,直接在mutate中传递向量x会导致函数接收整个向量而非逐个处理元素,触发API请求格式错误。cat()函数的作用是将内容打印到控制台,其返回值为NULL,无法作为有效结果存入数据框列中。
解决方法
方法1:使用dplyr的rowwise()逐行处理
通过rowwise()让mutate按行逐个调用ask_chatgpt,并去掉多余的cat():
# 创建测试数据框 test <- data.frame(x = c("Is Arkansas in the United States?", "Is Arkansas in India?")) # 逐行调用ask_chatgpt并存储结果 test <- test %>% rowwise() %>% mutate(y = ask_chatgpt(x)) %>% ungroup() # 处理完成后取消按行分组
方法2:使用purrr包批量映射处理
借助purrr::map_chr逐个遍历问题向量,调用ask_chatgpt并返回字符串结果:
library(purrr) # 创建测试数据框 test <- data.frame(x = c("Is Arkansas in the United States?", "Is Arkansas in India?")) # 批量处理问题并添加结果列 test$y <- map_chr(test$x, ask_chatgpt)
验证结果
处理完成后,查看数据框test即可得到每个问题对应的ChatGPT回答:
print(test)
输出示例:
x y 1 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. 2 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.
内容的提问来源于stack exchange,提问作者computer_guy2000
相关产品推荐
相关产品推荐

