使用R调用自定义ChatGPT助手时遭遇Error 404错误求助
解决OpenAI自定义助手R调用404问题
你遇到的404错误是因为用错了API接口:create_chat_completion只能调用OpenAI的基础预训练模型(比如gpt-3.5-turbo),不能直接传入自定义助手的ID(asst_xxx格式)。自定义助手需要通过OpenAI的助手API流程来调用,而不是直接当作模型使用。
不需要修改助手配置,只需要调整R代码,改用助手API的调用逻辑,具体步骤如下:
- 创建一个对话线程
- 向线程中添加用户的句子消息
- 触发助手运行处理消息
- 等待运行完成后提取结果
修改后的完整R代码:
library(openai) library(purrr) # 用于轮询等待运行状态 Sys.setenv(OPENAI_API_KEY = 'XXXXXXXXXXXXXXXXXX') score_sentence_CSM <- function(mySentence) { # 1. 创建对话线程 thread <- create_thread() thread_id <- thread$id # 2. 向线程添加用户消息 create_message( thread_id = thread_id, role = "user", content = paste("How to classify the following sentence according to your instructions (your answer is only a number): ", mySentence) ) # 3. 运行助手 run <- create_run( thread_id = thread_id, assistant_id = "asst_3JVWE1StXCNELM4PBbJrDe8O" # 替换为你的自定义助手ID ) run_id <- run$id # 4. 轮询等待运行完成 repeat { run_status <- retrieve_run(thread_id = thread_id, run_id = run_id) if (run_status$status %in% c("completed", "failed", "cancelled")) break Sys.sleep(1) # 每秒查询一次状态 } # 5. 获取助手的回复消息 messages <- list_messages(thread_id = thread_id) # 提取最新的助手回复 assistant_reply <- messages$data[[1]]$content[[1]]$text$value return(assistant_reply) } # 测试调用 score_sentence_CSM("The future is bright")
关键说明:
- 自定义助手的ID要放在
assistant_id参数中,而非model参数 - 助手API基于线程(Thread)模式,必须遵循「创建线程→添加消息→运行助手→获取结果」的完整流程
- 必须添加轮询逻辑,因为助手处理消息需要一定时间,无法立即返回结果
内容的提问来源于stack exchange,提问作者Xavier Bronlet
相关产品推荐
相关产品推荐

