File size: 7,861 Bytes
07c2907 dd394fe 07c2907 da5759b 07c2907 da5759b 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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | ---
pretty_name: StatAgent
language:
- en
tags:
- biostatistics
- r
- rag
- agents
- mcp
---
<div align="center">
# StatAgent
[](https://github.com/mnoorchenar/StatAgent)
[](https://github.com/mnoorchenar/StatAgent) [](https://huggingface.co/datasets/mnoorchenar/StatAgent)
[](https://mnoorchenar.github.io/)
      
Ask a plain-English question about experiment or manufacturing data. The agent retrieves FDA and PubMed evidence, runs validated R statistics, states the uncertainty, and proposes the next experiment for a human to approve.
[](#features) [](#how-it-works) [](#results) [](#documentation) [](#disclaimer) [](#author)
<img src="docs/demo.gif" width="100%" alt="Screen recording of the app: a drift question, the answer with citations, the R tool trace and the approval queue">
<sub>Recorded from the running app on the built-in SECOM dataset (first sample question).</sub>
</div>
| 125 | 8 / 8 | 4 / 4 | 16 |
|:---:|:---:|:---:|:---:|
| cited regulatory and PubMed passages | retrieval hit@5 on the eval set | statistical checks passing | automated tests (9 R, 7 Python) |
## Features
| Capability | Detail |
|---|---|
| Statistical tools in R | Control-chart drift with bootstrap changepoint CI, four-parameter dose-response (EC50 CI), mixed-model batch variance, power and factorial design |
| Retrieval with citations | BM25 and LSA hybrid over 21 CFR Parts 11, 211 and 820 and PubMed abstracts; answers cite passage ids |
| Human approval gate | The agent cannot run experiments; proposals wait in a queue for Approve or Reject |
| Audit trail | Every question, tool call and decision is stored in SQLite with a hash of each tool result |
| MCP server | The same tools are exposed as typed MCP tools for any MCP client |
| Resilience | Model fallback, retries, prompt-injection sanitiser, and a replayed saved run if the LLM is rate-limited |
## How it works
<img src="docs/architecture.svg" width="100%" alt="Architecture: Shiny UI to FastAPI agent, which calls the Groq LLM, the RAG index and the R stats tools; proposals go to human approval and the audit log">
## Results
<img src="docs/results.svg" width="100%" alt="Evaluation scores">
Measured with `python eval/run_eval.py`. The eval sets are small (8 retrieval queries, 4 statistical checks, 5 tool-call questions; one tool-call run hit the Groq free-tier rate limit and is counted as a miss), so treat the scores as a regression guard, not a benchmark.
## Documentation
<details><summary>Getting started</summary>
```bash
pip install -r requirements.txt
Rscript -e 'install.packages(c("shiny","bslib","httr2","commonmark","DT","ggplot2","lme4","drc","pwr","plumber","jsonlite"))'
cp .env.example .env # add GROQ_API_KEY
Rscript r/run_api.R & # stats tools, port 8001
python -m uvicorn statagent.api:app --port 8000 &
Rscript scripts/run_app.R # UI, port 7860
```
Docker: `docker build -t statagent . && docker run -p 7860:7860 -e GROQ_API_KEY=... statagent`
</details>
<details><summary>Engineering decisions</summary>
| Decision | Reason |
|---|---|
| Statistics in R, orchestration in Python | Reference-quality packages (lme4, drc) stay the single source of numbers; the LLM never computes statistics |
| Residual bootstrap for the changepoint CI | Resampling raw values would destroy the shift being estimated |
| BM25 and LSA instead of a neural embedder | Small corpus, no model download, runs on a laptop CPU |
| Tools return units notes | An early run misread the shift size; explicit units fixed it |
| Real public data only | Synthetic data is used only in tests with a known truth |
</details>
<details><summary>Limitations</summary>
- The statistical tools run on three built-in datasets; upload mode is not implemented.
- The Bayesian (brms) model from the plan is not included.
- The corpus holds U.S. regulations and PubMed abstracts, not the ICH guideline texts.
- SECOM sensors are anonymised, so a detected drift has no physical explanation here.
- There is no hosted demo: Hugging Face now requires a PRO plan for Docker Spaces, so the app is run locally or with the Dockerfile. The Hugging Face dataset repository is a mirror of the code.
- The free Groq tier limits tokens per minute; a saved example run is shown when it is exceeded.
- No automated check that the model's prose matches the tool numbers; review answers against the Tool trace tab.
</details>
<details><summary>Configuration</summary>
| Variable | Default | Purpose |
|---|---|---|
| `GROQ_API_KEY` | none | Required for live answers |
| `GROQ_MODEL` | `openai/gpt-oss-120b` | Primary model; `gpt-oss-20b` is the fallback |
| `R_API_URL` | `http://127.0.0.1:8001` | R plumber service |
| `STATAGENT_API` | `http://127.0.0.1:8000` | Agent service used by the UI |
| `STATAGENT_DB` | `audit.db` | SQLite audit and proposal store |
</details>
<details><summary>API</summary>
`POST /ask`, `GET /datasets`, `GET /series/{dataset}/{column}`, `GET /proposals`, `POST /proposals/{id}`, `GET /audit`, `GET /health`. MCP: `python -m statagent.mcp_server`.
</details>
<details><summary>Tests and project structure</summary>
```bash
cd r/tests && Rscript -e 'testthat::test_dir(".")' # includes known-truth coverage tests
python -m pytest tests
python eval/run_eval.py --offline
```
```
r/R/ drift, dose-response, mixed model, design
r/plumber.R HTTP wrapper for the R tools
statagent/ rag, tools, agent loop, audit, FastAPI, MCP server
app/app.R Shiny UI
corpus/ fetched 21 CFR and PubMed passages
data/ small real datasets (see data/README.md)
eval/ evaluation harness
```
</details>
## Disclaimer
A portfolio demonstration. It is not validated for GxP use, and its output is not regulatory or medical advice. Do not enter confidential data. A qualified statistician should review any result before it is acted on.
## Author
<table><tr>
<td><a href="https://mnoorchenar.github.io/"><img src="https://github.com/mnoorchenar.png" width="90" alt="mnoorchenar"></a></td>
<td><a href="https://mnoorchenar.github.io/"><b>mnoorchenar</b></a><br>Data science, biostatistics and AI engineering<br><a href="https://github.com/mnoorchenar"><img src="https://img.shields.io/badge/GitHub-181717?logo=github&logoColor=white" alt="GitHub"></a> <a href="https://huggingface.co/mnoorchenar"><img src="https://img.shields.io/badge/Hugging%20Face-FFD21E?logo=huggingface&logoColor=black" alt="Hugging Face"></a></td>
</tr></table>
|