File size: 7,018 Bytes
07c2907
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# StatAgent Shiny UI (bslib). Talks to the FastAPI agent service (default http://127.0.0.1:8000).
library(shiny); library(bslib); library(httr2); library(ggplot2); library(DT)

API <- Sys.getenv("STATAGENT_API", "http://127.0.0.1:8000")
call <- function(path, body = NULL, method = "GET") {
  req <- request(paste0(API, path)) |> req_timeout(150)
  if (!is.null(body)) req <- req |> req_body_json(body, auto_unbox = TRUE) |> req_method(method)
  req |> req_perform() |> resp_body_json(simplifyVector = FALSE)
}

SAMPLES <- c(
  "Is sensor_542 in the secom dataset drifting? If so when, and what should we test next?",
  "Fit the ryegrass dose-response data: what is the EC50 with uncertainty, and which dose should we test next?",
  "How much of the variation in paste strength is batch-to-batch, and what does that imply for sampling?"
)

ui <- page_sidebar(
  title = "StatAgent - agentic biostatistics",
  theme = bs_theme(version = 5, bootswatch = "flatly", primary = "#0b6e99"),
  sidebar = sidebar(
    width = 340,
    p(class = "small text-muted", "Ask a question about built-in real datasets (UCI SECOM process data, ryegrass dose-response, paste-strength batches). The agent calls validated R statistics, cites FDA/PubMed text, and queues experiments for human approval."),
    textAreaInput("q", "Question", SAMPLES[1], rows = 4),
    actionButton("ask", "Ask", class = "btn-primary w-100"),
    hr(), strong("Sample questions"),
    lapply(seq_along(SAMPLES), function(i) actionLink(paste0("s", i), SAMPLES[i], class = "d-block small my-2")),
    hr(), p(class = "small text-muted", "Demo data only - do not enter confidential data. AI output must be reviewed by a qualified statistician.")
  ),
  navset_card_tab(
    nav_panel("Answer", uiOutput("answer")),
    nav_panel("Chart", plotOutput("chart", height = 420)),
    nav_panel("Tool trace", uiOutput("trace")),
    nav_panel("Approval queue", uiOutput("queue")),
    nav_panel("Audit log", DTOutput("audit"))
  )
)

server <- function(input, output, session) {
  rv <- reactiveVal(NULL); tick <- reactiveVal(0)
  sid <- paste0("s", as.integer(runif(1, 1e6, 9e6)))
  lapply(seq_along(SAMPLES), function(i) observeEvent(input[[paste0("s", i)]], updateTextAreaInput(session, "q", value = SAMPLES[i])))

  observeEvent(input$ask, {
    withProgress(message = "Agent is working (tools + retrieval)...", {
      res <- tryCatch(call("/ask", list(question = input$q, session = sid), "POST"),
                      error = function(e) list(answer = paste("Service error:", conditionMessage(e)), steps = list()))
    })
    rv(res); tick(tick() + 1)
  })

  output$answer <- renderUI({
    r <- rv(); if (is.null(r)) return(p(class = "text-muted", "Click Ask to run the agent."))
    HTML(commonmark::markdown_html(r$answer %||% ""))
  })

  output$trace <- renderUI({
    r <- rv(); req(r)
    if (!length(r$steps)) return(p("No tools were called."))
    tagList(lapply(r$steps, function(s) card(card_header(code(s$tool), " ", tags$small(jsonlite::toJSON(s$args, auto_unbox = TRUE))),
      tags$pre(style = "max-height:220px;overflow:auto;font-size:.75rem", jsonlite::toJSON(s$result, auto_unbox = TRUE, pretty = TRUE, null = "null")))))
  })

  output$chart <- renderPlot({
    r <- rv(); req(r)
    st <- Filter(function(s) s$tool %in% c("detect_drift", "fit_dose_response"), r$steps)
    validate(need(length(st) > 0, "Ask a drift or dose-response question to see a chart."))
    s <- st[[1]]
    if (s$tool == "detect_drift") {
      ser <- call(sprintf("/series/%s/%s", s$args$dataset, s$args$column))
      d <- data.frame(x = unlist(ser$x), y = vapply(ser$y, function(z) if (is.null(z)) NA_real_ else z, 0))
      x <- s$result
      ggplot(d, aes(x, y)) + geom_point(size = .6, alpha = .5, colour = "grey40") +
        geom_hline(yintercept = c(x$ucl, x$lcl), linetype = 2, colour = "#c0392b") + geom_hline(yintercept = x$center, colour = "#0b6e99") +
        annotate("rect", xmin = x$changepoint_ci95[[1]], xmax = x$changepoint_ci95[[2]], ymin = -Inf, ymax = Inf, fill = "#e67e22", alpha = .3) +
        geom_vline(xintercept = x$changepoint, colour = "#e67e22") +
        labs(title = sprintf("%s: changepoint at batch %s (95%% CI %s-%s)", s$args$column, x$changepoint, x$changepoint_ci95[[1]], x$changepoint_ci95[[2]]),
             subtitle = "Dashed = Phase-I 3-sigma limits (first 100 batches); orange band = changepoint CI", x = "Batch", y = "Sensor value") + theme_minimal(14)
    } else {
      d <- read.csv(Sys.getenv("RYEGRASS_CSV", "../data/ryegrass_dose_response.csv")); p <- s$result$params
      cur <- function(x) p[["lower:(Intercept)"]] + (p[["upper:(Intercept)"]] - p[["lower:(Intercept)"]]) / (1 + exp(p[["slope:(Intercept)"]] * (log(x) - log(p[["ec50:(Intercept)"]]))))
      xs <- exp(seq(log(.4), log(max(d$conc)), length.out = 200)); ci <- unlist(s$result$ci95[["ec50:(Intercept)"]])
      ggplot() + geom_point(data = d, aes(conc, rootl), size = 2) + geom_line(data = data.frame(x = xs, y = cur(xs)), aes(x, y), colour = "#0b6e99", linewidth = 1) +
        annotate("rect", xmin = ci[1], xmax = ci[2], ymin = -Inf, ymax = Inf, fill = "#e67e22", alpha = .25) +
        geom_vline(xintercept = s$result$next_dose, linetype = 3, colour = "#27ae60") + scale_x_log10() +
        labs(title = sprintf("EC50 = %.2f (95%% CI %.2f-%.2f)", s$result$ec50, ci[1], ci[2]), subtitle = "Orange = EC50 CI; green dotted = proposed next dose", x = "Concentration (log)", y = "Root length") + theme_minimal(14)
    }
  })

  output$queue <- renderUI({
    tick(); input$refresh
    ps <- Filter(function(p) p$status == "pending", tryCatch(call("/proposals"), error = function(e) list()))
    if (!length(ps)) return(p(class = "text-muted", "No pending proposals. Experiments proposed by the agent appear here and are never run without approval."))
    tagList(lapply(ps, function(p) card(card_header(p$title), p$body,
      div(class = "mt-2", actionButton(paste0("ok", p$id), "Approve", class = "btn-success btn-sm"), actionButton(paste0("no", p$id), "Reject", class = "btn-danger btn-sm")))))
  })
  observe({
    ps <- tryCatch(call("/proposals"), error = function(e) list())
    for (p in ps) local({ id <- p$id
      observeEvent(input[[paste0("ok", id)]], { call(paste0("/proposals/", id), list(approve = TRUE), "POST"); tick(tick() + 1) }, ignoreInit = TRUE, once = TRUE)
      observeEvent(input[[paste0("no", id)]], { call(paste0("/proposals/", id), list(approve = FALSE), "POST"); tick(tick() + 1) }, ignoreInit = TRUE, once = TRUE) })
  })

  output$audit <- renderDT({
    tick()
    a <- tryCatch(call("/audit?n=200"), error = function(e) list())
    if (!length(a)) return(datatable(data.frame(note = "empty")))
    d <- do.call(rbind, lapply(a, function(r) data.frame(time = format(as.POSIXct(r$ts), "%H:%M:%S"), session = r$session, event = r$event, detail = substr(r$detail, 1, 140), hash = r$data_hash %||% "")))
    datatable(d, options = list(pageLength = 10, dom = "tip"), rownames = FALSE)
  })
}

shinyApp(ui, server)