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

Shiny应用中reactivePoll状态变更时未触发valueFunc问题

问题分析

你的代码存在两个核心问题,导致valueFunc未在状态变为completed时触发:

  1. 递归调用错误:在valueFunc中直接调用runStatusPoll()会触发自身的响应式逻辑,形成循环依赖,直接打断valueFunc的正常执行流程。reactivePoll的valueFunc无需主动调用自身来获取状态,应基于checkFunc的返回结果处理逻辑。
  2. 响应式未激活:reactivePoll作为响应式对象,只有在被其他响应式上下文(如observe)依赖时才会启动执行。如果没有触发这个依赖,整个轮询逻辑会处于休眠状态。
修复方案

调整valueFunc逻辑并添加触发依赖的代码,具体修改如下:

runStatusPoll <- reactivePoll(5000, session,
  checkFunc = function() {
    if (!is.null(runID()) && waitingForRun() == TRUE) {
      tryCatch({
        status <- my_python_script$get_run_status(run_id = runID(), thread_id = thread_ID())
        print(paste0("This is the run status: ", status))
        return(status)
      }, error = function(e) {
        print(paste("Error fetching run status:", e$message))
        return("error")
      })
    } else {
      return(NULL)
    }
  },
  valueFunc = function() {
    # 直接获取checkFunc的最新返回值,避免递归调用
    current_status <- checkFunc()
    if (current_status == "completed") {
      threads <- my_python_script$get_messages(thread_id = thread_ID())
      if (length(threads) > 0 && !is.null(threads[[1]]$content[[1]]$text$value)) {
        assistant_reply <- threads[[1]]$content[[1]]$text$value
        append_message("Assistant", assistant_reply)
        session$sendCustomMessage('typeWriter', list(text = assistant_reply))
      }
      waitingForRun(FALSE)
    } else if (current_status == "error") {
      waitingForRun(FALSE)
    }
    # 返回状态值,保证响应式逻辑完整
    return(current_status)
  }
)

# 添加observe触发轮询逻辑,确保reactivePoll启动运行
observe({
  runStatusPoll()
})
补充说明
  • reactivePoll的运行逻辑:每隔指定时间(此处为5000ms)执行checkFunc,若返回值与上次不同,则触发valueFunc执行。
  • 当waitingForRun(FALSE)被设置后,checkFunc会返回NULL,后续轮询将自动停止状态检查,符合你的业务需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:22:45