Skip to contents

Modular Neuro-Symbolic App Architecture

specshiny ships three composable bslib/Shiny modules that share a single reactive source of truth (spec_rv, holding a validated spec_ir) and a change-diff channel (last_diff_rv, holding the latest spec_diff):

Module Role
mod_spec_composer_ui() / mod_spec_composer_server() Natural-language prompt compilation, presets, iterative conversational refinement, clarification questions, and defaults rationale viewer
mod_spec_controls_ui() / mod_spec_controls_server() Dynamically renders only active bslib controls, pushes IR changes to widgets, validates UI edits through guardrails, and renders visual diff badges
mod_spec_preview_ui() / mod_spec_preview_server() Live mathematical summary, YAML/JSON IR inspector, deterministic R script, quick preview runner, Quarto .qmd report, and download handlers

1. Launching the Bundled Flagship Demo

The fastest way to explore the complete workflow interactively is to run the bundled reference application:

Or inspect the shiny.appobj directly:

library(specshiny)
app <- specshiny_demo_app()
class(app)
#> [1] "shiny.appobj"

2. Composing a Custom bslib Application

Embedding specshiny inside your own bslib dashboard requires only wiring the shared reactiveVal pair across the modules:

library(shiny)
library(bslib)
library(specshiny)

# Swap translator_rule() for translator_openai() or translator_ollama() when desired
translator <- translator_rule()
initial <- nl_to_spec(
  "2-level power study with 50 schools, 20 students per school, ICC 0.2, treatment effect 0.4",
  translator = translator
)$spec

ui <- page_sidebar(
  title = "Custom Multilevel Study Studio",
  theme = bs_theme(version = 5, bootswatch = "flatly"),
  sidebar = sidebar(
    width = 380,
    mod_spec_composer_ui("composer")
  ),
  layout_columns(
    col_widths = c(6, 6),
    mod_spec_controls_ui("controls"),
    mod_spec_preview_ui("preview")
  )
)

server <- function(input, output, session) {
  spec_rv <- reactiveVal(initial)
  last_diff_rv <- reactiveVal(NULL)

  mod_spec_composer_server("composer", spec_rv = spec_rv, translator = translator, last_diff_rv = last_diff_rv)
  mod_spec_controls_server("controls", spec_rv = spec_rv, last_diff_rv = last_diff_rv)
  mod_spec_preview_server("preview", spec_rv = spec_rv, last_diff_rv = last_diff_rv)
}

shinyApp(ui, server)

3. Verifying Bidirectional Sync with shiny::testServer()

Because all state transitions pass through validated spec_ir objects and idempotent diff checks, bidirectional synchronization between conversational refinements and visual widget tweaks is straightforward to test automatically with shiny::testServer():

init_spec <- nl_to_spec(
  "2-level power study with 50 schools, 20 students per school, ICC 0.2, treatment effect 0.35, random slope for x1, 15% MAR missingness"
)$spec

spec_rv <- shiny::reactiveVal(init_spec)
diff_rv <- shiny::reactiveVal(NULL)

shiny::testServer(
  mod_spec_controls_server,
  args = list(spec_rv = spec_rv, last_diff_rv = diff_rv),
  {
    # 1. Visual slider/numeric tweak updates IR and populates semantic diff
    session$setInputs(n_clusters = 75)
    cat("After UI tweak -> n_clusters:", spec_rv()$hierarchy$n_clusters, "\n")
    cat("Live diff summary:", format_diff_summary(diff_rv()), "\n")

    # 2. Invalid edit (cluster_size = 2 with 2 random effects) is blocked by guardrails
    session$setInputs(cluster_size = 2)
    cat("Blocked edit kept cluster_size at:", spec_rv()$hierarchy$cluster_size, "\n")
    cat("Guardrail message:", session$returned$guardrail_error()$errors$message[[1L]], "\n")

    # 3. Structural edit (turning off missingness) immediately prunes missingness controls
    session$setInputs(missing_mechanism = "none")
    cat("Missingness rate control still present?",
        "missing_rate" %in% session$returned$descriptor()$control_ids, "\n")

    # 4. Undo reverts missingness back to MAR cleanly
    session$setInputs(undo_btn = 1)
    cat("After Undo -> missingness mechanism:", spec_rv()$missingness$mechanism, "\n")
  }
)
#> Loading required package: shiny
#> After UI tweak -> n_clusters: 75 
#> Live diff summary: hierarchy.n_clusters: 50 -> 75 
#> Blocked edit kept cluster_size at: 20 
#> Guardrail message: Model has 2 random effect(s) per cluster, requiring cluster_size > 2 (got 2) for identifiability. 
#> Missingness rate control still present? FALSE 
#> After Undo -> missingness mechanism: MAR

3b. Interactive Preview Budget Guardrails

mod_spec_preview_server() enforces configurable iteration, sample-size, and wall-clock caps (max_preview_reps, max_preview_n, max_preview_seconds) so large simulation designs (e.g., n_reps = 50000) never freeze the Shiny event loop while preserving the full specification in downloaded .R scripts:

large_spec <- new_spec_ir(
  design_type = "monte_carlo_lm",
  hierarchy = list(levels = 1L, n_obs = 5000L),
  simulation = list(n_reps = 50000L, seed = 2026L)
)
large_rv <- shiny::reactiveVal(large_spec)

shiny::testServer(
  mod_spec_preview_server,
  args = list(spec_rv = large_rv, max_preview_reps = 5L, max_preview_n = 500L),
  {
    session$setInputs(run_preview = 1)
    print(session$returned$preview_results())
    cat("Warnings:", paste(session$returned$preview_warnings(), collapse = " | "), "\n")
  }
)
#>   n_reps n_converged true_effect mean_est   bias mean_se power coverage
#> 1      5           5         0.3   0.3115 0.0115  0.0451     1        1
#> Warnings: Replications capped from 50000 to 5 to keep Shiny responsive; download simulation.R for full execution. | Preview sample size scaled down from N = 5000 to fit the 500-observation interactive budget.

4. Configuring Cloud & Local LLM Translators

specshiny supports any OpenAI-compatible API (translator_openai()) as well as local Ollama models (translator_ollama()). Both adapters enforce JSON-only output using spec_system_prompt(), parse the JSON strictly with jsonlite::fromJSON() (never eval(parse())), and validate every returned specification through validate_spec_ir():

# Cloud API backend (reads OPENAI_API_KEY from environment by default)
openai_backend <- translator_openai(model = "gpt-4o-mini")
openai_backend
#> <spec_translator:openai>
#> model: gpt-4o-mini | endpoint: https://api.openai.com/v1
#> api_key: <unset> | timeout: 60s | max_bytes: 524288

# Local privacy-preserving Ollama backend
ollama_backend <- translator_ollama(model = "llama3.1", base_url = "http://localhost:11434")
ollama_backend
#> <spec_translator:ollama>
#> model: llama3.1 | endpoint: http://localhost:11434
#> timeout: 120s | max_bytes: 524288

To inspect the exact schema instructions sent to external LLMs:

cat(spec_system_prompt("create"))
#> You are a neuro-symbolic statistical specification compiler for the R package specshiny.
#> Translate the user's statistical or simulation study description into a valid spec_ir v1.0.0 JSON object.
#> CRITICAL RULES:
#> 1. Return ONLY a single valid JSON object with keys 'spec' (a valid spec_ir v1.0.0 object) and 'clarifications' (array of clarification objects).
#> 2. NEVER emit executable R code, shell commands, unknown extra JSON properties, or prose outside the JSON object.
#> 3. schema_version must be '1.0.0'. design_type must be one of: monte_carlo_lm, power_analysis, multilevel_sim, two_level_mlm.
#> 4. All variable identifiers must be pure ASCII matching ^[A-Za-z][A-Za-z0-9_]*$ (<= 64 chars) and avoid R reserved words.
#> 5. Enforce statistical sanity: positive SDs, ICC in [0, 1), positive-definite corr_matrix/predictor_corr, level-1 predictors only for random slopes, missingness rate in [0, 0.95).
#> 6. Document every inferred default in spec.defaults_rationale as dotted-path -> plain-language explanation.