You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中调用OpenAI平台创建的专属Assistant用于Shiny应用?

调用OpenAI自定义Assistant的R代码修改方案

调用自定义Assistant不能直接使用chat/completions端点,需要改用OpenAI的Assistant API流程,步骤包括创建对话线程、添加用户消息、触发Assistant运行、获取返回结果。以下是适配你现有代码风格(使用httr2包)的修改方案:

1. 定义必要参数

library(httr2)

# 替换为你的OpenAI API密钥
api_key <- "your_openai_api_key"
# 替换为你创建的自定义Assistant的ID(可在OpenAI平台的Assistant详情页查看)
assistant_id <- "your_custom_assistant_id"
# 用户提问内容
user_content <- "2 + 1, where 2 represents a 5 and 1 represents a -1"

2. 创建对话线程

# 创建线程
thread_response <- request("https://api.openai.com/v1/threads") |>
  req_auth_bearer_token(token = api_key) |>
  req_headers("Content-Type" = "application/json") |>
  req_perform() |>
  resp_body_json()

thread_id <- thread_response$id

3. 向线程添加用户消息

# 将用户消息加入线程
request(paste0("https://api.openai.com/v1/threads/", thread_id, "/messages")) |>
  req_auth_bearer_token(token = api_key) |>
  req_headers("Content-Type" = "application/json") |>
  req_body_json(
    data = list(
      role = "user",
      content = user_content
    )
  ) |>
  req_perform()

4. 触发自定义Assistant运行

# 启动Assistant处理线程中的消息
run_response <- request(paste0("https://api.openai.com/v1/threads/", thread_id, "/runs")) |>
  req_auth_bearer_token(token = api_key) |>
  req_headers("Content-Type" = "application/json") |>
  req_body_json(
    data = list(
      assistant_id = assistant_id
    )
  ) |>
  req_perform() |>
  resp_body_json()

run_id <- run_response$id

5. 等待运行完成并提取回复

Assistant运行需要一定时间,需轮询状态直到任务完成:

# 轮询运行状态,直到任务结束
repeat {
  run_status <- request(paste0("https://api.openai.com/v1/threads/", thread_id, "/runs/", run_id)) |>
    req_auth_bearer_token(token = api_key) |>
    req_perform() |>
    resp_body_json()
  
  if (run_status$status %in% c("completed", "failed", "cancelled")) {
    break
  }
  Sys.sleep(1) # 每秒查询一次状态
}

# 获取线程中的所有消息,提取Assistant的最新回复
messages_response <- request(paste0("https://api.openai.com/v1/threads/", thread_id, "/messages")) |>
  req_auth_bearer_token(token = api_key) |>
  req_perform() |>
  resp_body_json()

assistant_reply <- messages_response$data[[1]]$content[[1]]$text$value
cat("Assistant回复:", assistant_reply, "\n")

关键注意事项

  • 必须确保assistant_id与你在OpenAI平台创建的自定义Assistant完全匹配。
  • 线程机制支持多轮对话,后续添加消息可直接复用同一个thread_id,无需重复创建。
  • 轮询间隔时间可根据实际需求调整,避免过于频繁的API请求。

内容的提问来源于stack exchange,提问作者Mikael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 08:24:59