Preprint
Article

This version is not peer-reviewed.

Data Analysis Using LLMs: Tools, Sandboxes and Data Agents

Submitted:

15 October 2026

Posted:

16 October 2026

You are already at the latest version

Abstract
Large language models (LLMs) are increasingly being used to support data analysis and have the potential to make statistical methods more accessible to clinicians and medical researchers with limited programming experience. However, the rapid development of technologies surrounding LLMs has introduced new concepts and workflows that may be unfamiliar to potential users. In particular, tool calling, sandboxing, and data science agents provide different mechanisms through which LLMs can perform statistical analyses, yet the distinctions between these approaches are often unclear. This paper introduces and compares these three developments from the perspective of statistical data analysis. Tool calling allows an LLM to access predefined statistical functions, sandboxing provides a controlled computational environment in which model-generated code can be executed, and data science agents extend these capabilities by combining reasoning, tools, memory, planning, and execution environments to pursue analytical objectives through multi-step workflows. Their application is illustrated using the R programming language together with the ellmer and securer packages. Examples demonstrate how statistical analyses can be performed using predefined functions, code execution within a sandbox, and a simple biostatistics agent. The advantages, limitations, and verification requirements of each approach are discussed, with particular emphasis on transparency, reproducibility, and human oversight. This paper aims to provide clinicians, researchers, and statisticians with an accessible introduction to these emerging technologies and their potential role in LLM-assisted data analysis.
Keywords: 
;  ;  ;  ;  ;  

1. Introduction

Data analysis has become an indispensable tool across many fields as almost every aspect of society becomes increasingly digitized. In the clinical sciences, for example, hospitals use data to monitor patients' health, while clinical researchers analyse data to determine whether treatments are effective. More broadly, data analysis provides much of the evidence on which advances in the clinical sciences are based. Without appropriate analysis, it would be difficult to determine whether observed differences are real, whether treatments work, or whether research findings are supported by the available data.
Despite its importance, data analysis is often perceived as a demanding task with a considerable entry barrier. It typically requires knowledge of statistics as well as familiarity with statistical software or programming languages. The emergence of large language models (LLMs) has the potential to lower some of these barriers. Users can interact with an LLM using natural language, making data analysis more accessible to researchers with limited training in statistics or computer programming [7]. However, the use of LLMs for data analysis is not without challenges. An LLM may produce an answer that appears convincing but is statistically incorrect. In addition, providing LLMs with sensitive medical or patient data raises important concerns about data privacy and security.
The technologies surrounding LLMs have developed rapidly in recent years. Several of these developments are particularly relevant to data analysis, including tool or function calling, tool learning, chatbots and data science agents. These developments have attracted considerable research attention. For example, Wang et al. 2026 [1] reviewed more than ten previous survey papers that examined different aspects of function calling, tool use and LLM-based agents, demonstrating the growing body of literature in this area. However, much of this literature has focused on the technical development, capabilities and evaluation of these technologies, while their practical use in specialized fields remains less well documented. In particular, there is limited accessible guidance showing how these recent developments can be used in statistical data analysis and what they mean for researchers who may not have extensive training in statistics or computer science. Keeping pace with these developments can therefore be difficult, particularly for clinicians and medical researchers. There is a need for accessible guidance that brings these developments together, demonstrates their practical use, and explains their relevance, limitations and implications for medical research.
This paper introduces recent developments in LLM-assisted data analysis, with particular emphasis on tool/function calling, sandboxing and data science agents. Where appropriate, their application to statistical analysis is demonstrated using the R programming language and the ellmer package. The aim is not to provide a technical treatment of the underlying computer science, but rather to explain these developments from the perspective of clinicians and medical researchers. In doing so, the paper aims to help readers understand how these tools can be used for data analysis, as well as the limitations and precautions that should be considered when using them.

2. Tools/Function Calling

The term tool has a broad meaning in the context of augmentation. Mialon et al. (2023) [2], for example, describe a tool as an external object that can be used to alter the form, position, or condition of another object more efficiently. In the context of LLMs, however, a more specific definition is useful. Wang et al. (2026) [1] define an LLM-used tool as a function interface to a computer program that runs outside the LLM, where the LLM generates the function call and the arguments required to use the tool. This paper adopts the latter definition because it closely reflects how tools are used for data analysis in the examples that follow.
The terms tool calling and function calling will be used interchangeably throughout this paper. More specifically, the tools considered here are R functions used to perform statistical analyses. The R functions are therefore external to the LLM. The LLM does not perform the statistical computation itself; instead, it can request that an appropriate R function be called and provide the arguments needed by that function.
The process can be understood as follows. When a request is sent to a chat model, one or more available tools can be made known to the model. Each tool is usually described by its function name, what it does, and the arguments it requires. Based on the user's request, the model determines whether a tool is needed and, if so, selects an appropriate tool and supplies the required arguments. The function is then executed outside the LLM, and its result is returned to the model. The model can use this result to formulate its response or, if necessary, request another tool. More broadly, the function-calling process can be divided into three stages: pre-call, on-call and post-call. In the pre-call stage, the LLM interprets the user's request, may break a complex task into smaller tasks, and identifies suitable functions from those available. During the on-call stage, the LLM determines whether a function is actually required and, when necessary, selects and triggers one or more appropriate functions. This decision is important because not every request requires a tool; some questions can be answered through ordinary dialogue. Finally, in the post-call stage, the LLM receives the results returned by the function and uses them to produce the final response or to determine whether another function is required [1].
An important point is that the LLM does not directly execute the external tool. Rather, it requests that the tool be executed, and the result is subsequently returned to it. This distinction is particularly important in data analysis because it separates the LLM's role in understanding the user's request and selecting a tool from the actual statistical computation performed by R. Figure 1 provides a schematic representation of this process.
Figure 1 shows a simple way of understanding tool calling. The user sends a request to the LLM that requires a statistical calculation. The LLM recognizes that an available R function can be used, selects the appropriate function, and provides the arguments required by that function. The function is then executed outside the LLM, and the result is returned to the LLM. Finally, the LLM uses the returned result to formulate an answer for the user [8].
For performing data analysis using tool calling via the R package ellmer, the following steps are undertaken.
  • Create the R function that will perform the required statistical analysis. For example, a simple function may calculate the mean of a numeric variable. For more complex analyses, functions could perform a t-test, chi-square test, regression analysis or other statistical procedure. The output should be returned in a form that can be passed back to the LLM, such as a character string, atomic vector or JSON object.
  • Define the function as a tool. The R function is then converted into a tool using the tool() function. A description is provided to tell the LLM what the function does, together with descriptions of the arguments that the function requires. This information is important because the LLM uses it to determine whether the tool is appropriate for the user's request and what values should be supplied as arguments.
  • Register the tool with the chat model. The tool is made available to the LLM by registering it with the chat object using register_tool(). Once registered, the model knows that the R function is available and can request its use when responding to an appropriate data-analysis question.
  • Submit the data-analysis request. The user can then describe the required analysis in natural language. If the LLM determines that a registered tool is required, it generates a tool request containing the appropriate arguments. ellmer handles the interaction required to execute the R function and return its result to the LLM. The LLM then uses the result to formulate its final response to the user. Additional tools can be requested if they are required to complete the task.

Illustration

To illustrate the use of tool calling for statistical analysis, consider the data from [3] The dataset consists of two independent groups representing motor performance durations.
Group1:
77, 87, 88, 114, 151, 210, 219, 246, 253, 262, 296, 299, 306, 376, 428, 515, 666, 1310, 2611
Group2:
59, 106, 174, 207, 219, 237, 313, 365, 458, 497, 515, 529, 557, 615, 625, 645, 973, 1065, 3215
The aim of the analysis is to determine whether motor performance differs between the two groups. For this illustration, three R functions were made available to the LLM as tools: a function for calculating the mean, a function for assessing normality, and a function for performing a trimmed mean t-test using the DescTools package. The tool definitions were generated with the assistance of Copilot and then registered with the chat model.
The ellmer package also provides the create_tool_def() function, which can use an LLM to generate a tool definition from an existing R function. Alternatively, the researcher can define the tool directly. Regardless of how the tool is created, its definition should be reviewed before use to ensure that the function, arguments and description are appropriate for the intended analysis. The ellmer documentation similarly recommends reviewing tool definitions generated by create_tool_def().
To demonstrate what happens during tool calling, we first asked the LLM to calculate the mean of Group 1. The interaction was recorded as follows:
── user ───────────────────────────────────────────────
calculate the mean of g1
── assistant ──────────────────────────────────────────
[tool request\]:
calculate_mean(
data_vector = c(77, 87, 88, 114, 151, 210, 219, ...)
)
── user ───────────────────────────────────────────────
[tool result\]:
The calculated mean is: 448.105263157895
── assistant ──────────────────────────────────────────
The mean of Group 1 is 448.11.
This output illustrates the different roles played by the LLM and the R function. The LLM interpreted the user's request and selected the registered calculate_mean() tool. The calculation itself was then performed by the R function, which returned a mean of 448.1053. The LLM received this result and presented it to the user as 448.11. This distinction is important: the LLM determines which available tool to use and what arguments to provide, while the statistical computation is performed externally in R. The complete analysis is shown below.
### Normality Test (Shapiro-Wilk)
- **Group 1**: W = 0.5813, p-value = 2.891e-06
- **Group 2**: W = 0.6048, p-value = 4.972e-06
Both groups have p-values < 0.05, indicating that the data significantly deviates from a normal distribution.
### Mean Calculation
- **Group 1 Mean**: 448.11
- **Group 2 Mean**: 598.63
### Yuen's Trimmed T-Test
- **Test Statistic**: -2.2143
- **p-value**: 0.03773
- **95% Confidence Interval**: [-314.08, -10.07]
- **Difference of Trimmed Means**: -162.08
The p-value of 0.03773 suggests a significant difference between the groups at the 5% significance level. The confidence interval does not include zero, further supporting this difference.
The registered R tools identified departures from normality in both groups and a significant difference. The complete analysis was performed from a simple natural-language prompt, with the statistical computations carried out using predefined R functions.
Compared with prompting the LLM without tools, tool calling provided greater control over which statistical procedures were performed and reported. The complete code for this analysis is found in Appendix A.
The performance of function calling should also be evaluated, particularly when it is used for data analysis. A successful function call requires the LLM to recognize when a function is needed, select the correct function, and provide the appropriate arguments; the returned result should also be used correctly in the final response. Evaluation can therefore consider measures such as the proportion of successful calls, accuracy of function selection and parameter extraction, response quality, and the time required to complete a call. Function calling is not without limitations. The LLM may fail to call a function when one is required, call an unnecessary or incorrect function, provide missing or invalid arguments, or even request a function that does not exist. In more complex tasks, errors may also arise when several functions must be called in sequence or when the execution of a correctly selected function fails. For medical data analysis, these limitations mean that the use of predefined statistical functions can improve control over the analysis, but does not guarantee that the LLM will select or use those functions correctly. The resulting analysis should therefore still be checked by the researcher [1].

3. Sandboxing

Sandboxing provides another way of extending the computational capabilities of an LLM. A code sandbox can be understood as an isolated computing environment in which programs can be executed without directly operating in the user's main computing environment. Sandboxes may provide access to a programming language, files and other computational resources, depending on how the environment is configured. Cheng et al. (2025) [4], for example, describe a code sandbox as a virtual computer in which an LLM can execute code and interact with files and other computing resources while remaining isolated from the host system. For statistical data analysis, a sandbox can therefore provide an LLM with access to a statistical programming environment, such as R, in which code generated by the LLM can be executed
Sandboxing is closely related to the function calling described in the previous section, but the two concepts should not be treated as synonymous. Both approaches extend the capabilities of an LLM by allowing computation to take place outside the model. In function calling, however, the functions are typically defined in advance and made available to the LLM. The LLM determines whether a function is required, selects an appropriate function from those available, and supplies the necessary arguments. In sandbox-based execution, the LLM can instead generate the code required to perform the task and have that code executed in the sandbox. The distinction is therefore important: function calling generally constrains the LLM to predefined functions, whereas sandboxing can provide a more general environment in which the LLM constructs and executes its own analytical code.
Consider, for example, a researcher who asks an LLM to compare an outcome between two independent groups. Using the function-calling approach illustrated in the previous section, functions for assessing normality and performing a suitable statistical test were created in advance and registered with the chat model. The LLM could select and use these functions, but the underlying statistical procedures had already been implemented by the developer. With access to an R sandbox, the LLM could instead generate R code for examining the data, assessing relevant assumptions and performing an appropriate statistical test. The code is then executed in R, the results are returned to the LLM, and the model can use those results to formulate its response. If further analysis is required, the LLM can generate and execute additional code. This creates an iterative process in which the LLM can use results from one computational step to determine what should be done next. Similar iterative interaction is described by [5], where the model generates an action, receives the result from the sandbox and uses that information to decide its subsequent action.
The term sandbox is important because allowing model-generated code to execute without restriction would introduce additional risks. The purpose of the sandbox is to separate the execution environment from the host computing environment and to place boundaries around what the generated code can access or modify. Cheng et al. (2025) [4] describe the containerized nature of their sandbox as providing isolation from the host system, thereby allowing model-generated code to be executed within a separate environment. The exact restrictions, however, depend on how a particular sandbox is configured. A sandbox may, for example, place limits on available files, computational resources, network access or execution time. Sandboxing should therefore not be interpreted simply as code execution; isolation and control of the execution environment are central features of the approach. Figure 2 shows an example of a sandbox in data analysis.
Function calling and sandboxing can also be used together. In fact, access to a sandbox may itself be provided to the LLM through a function call. This is illustrated by the securer package for R, which provides as_ellmer_tool() to wrap a secure R session as an ellmer tool. The LLM can submit R code through this tool, the code is executed in the sandbox, and the resulting output is returned to the LLM. The implementation supports OS-level sandboxing and can also impose resource limits and execution timeouts. Thus, the important distinction is not whether a tool call occurs somewhere in the process, but what capability is provided by that call. Calling a predefined statistical function gives the LLM access to a specific operation, whereas calling a code-execution sandbox gives it access to a more general computational environment in which it can generate different analyses as required.
This greater flexibility has both advantages and disadvantages for biostatistical analysis. A sandbox reduces the need to anticipate every analysis and create a separate function beforehand. An LLM with access to R could potentially generate code for data exploration, hypothesis testing, regression, simulation and other analyses within the same environment. More generally, sandbox research has shown that LLMs can use these environments not only for computation but also for file management and other multi-step tasks [4]. However, greater flexibility also transfers more responsibility for constructing the analysis to the LLM. With predefined function calling, the researcher can restrict the model to statistical functions that have already been reviewed and tested. In a sandbox, the LLM may generate inappropriate or incorrect R code, choose an unsuitable statistical method, misuse a function or incorrectly interpret the computational output. Isolation can reduce risks associated with executing generated code, but it does not guarantee that the statistical analysis itself is correct. For medical research, sandbox-generated analyses should therefore still be reviewed and, where necessary, independently validated.
How the LLM is prompted to use the sandbox is also important. Rather than allowing the model to rely on natural-language reasoning for calculations, the system prompt can explicitly encourage it to use the computational environment. Cheng et al. 2026 [5] describe this as prompting for exploration, in which the model is encouraged to use computational tools, derive answers through actual program execution rather than hardcoding results, and explore different approaches within the isolated environment. A similar approach was adopted in the illustration below. The LLM was instructed to perform statistical calculations by executing R code in the sandbox, not to hardcode numerical results, and to inspect the resulting outputs and revise its code when necessary. This prompting strategy encourages the LLM to use the sandbox as an active computational environment rather than merely as an additional source of information.

Illustration

To illustrate sandbox-based statistical analysis, the same two-group dataset used in the previous section was saved as an Excel file and subsequently imported into R. This reflects a more realistic data-analysis workflow in which the observations are stored in an external data file rather than written directly into the prompt. Data can be made available to a sandbox in different ways. For a small dataset, the observations could be included directly in the prompt. Alternatively, the data can first be imported into R and then made available to the sandbox through a controlled tool. The latter approach was used in this illustration.
The Excel file was imported using the readxl package and contained two numeric variables, Group 1 and Group 2, each with 19 observations. A simple function was created to return the imported dataset and was made available within the sandbox as fetch_group_data(). The securer package was then used with ellmer to provide the LLM with an R code-execution environment. Unlike the preceding function-calling illustration, statistical functions for calculating descriptive statistics, assessing normality and performing the trimmed mean t-test were not individually defined for the LLM. Instead, the LLM was instructed in natural language to retrieve the dataset and use R to perform the required analyses. The sandbox interface allows LLM-generated R code to be executed in a separate environment and the resulting output to be returned to the conversation.
The LLM retrieved the data, calculated descriptive statistics, performed Shapiro-Wilk tests and used DescTools::YuenTTest() to compare the groups using a 20% trimmed mean t-test. The analysis identified strong departures from normality in both groups and produced a significant difference between the trimmed means (t = -2.2143, p = 0.0377), consistent with the analysis in the preceding function-calling illustration. Importantly, several R code calls were generated during the analysis as the LLM inspected the data, performed calculations and used the returned results to continue the analysis. This illustrates the more iterative nature of sandbox-based execution, in which the LLM can generate code, observe the result and decide what computation to perform next.
For researchers with some knowledge of R, inspecting the generated tool calls provides an important opportunity to verify how the analysis was performed. The final natural-language response alone may appear reasonable even when the underlying code contains an error or an inappropriate statistical procedure. Examining the generated R code can therefore help determine whether the correct variables, functions and arguments were used. Sandboxing gives the LLM greater flexibility to construct an analysis, but this flexibility does not remove the need to verify that the statistical analysis itself is appropriate and correctly implemented. The analysis results are shown below and the complete code is in Appendix B.
## Data preview
The data were retrieved with `dataset <- fetch_group_data()`and converted from a list of observations into a data frame for analysis. The variable names are **`Group 1`** and
**`Group 2`**.
The first six observations are:
| Observation | Group 1 | Group 2 |
|---:|---:|---:|
| 1 | 77 | 59 |
| 2 | 87 | 106 |
| 3 | 88 | 174 |
| 4 | 114 | 207 |
| 5 | 151 | 219 |
| 6 | 210 | 237 |
## Descriptive statistics
All statistics were calculated in R.
| Group | n | Mean | Median | Standard deviation | IQR |
|---|---:|---:|---:|---:|---:|
| Group 1 | 19 | 448.1053 | 262 | 594.6295 | 221.5 |
| Group 2 | 19 | 598.6316 | 497 | 688.3342 | 392.0 |
Group 2 has a higher mean and median, as well as greater variability. In both groups, the mean exceeds the median, suggesting right-skewed distributions.
## Shapiro–Wilk normality tests
| Group | W | p-value |
|---|---:|---:|
| Group 1 | 0.58135 | 2.891 × 10⁻⁶ |
| Group 2 | 0.60480 | 4.972 × 10⁻⁶ |
Both p-values are below 0.05, providing strong evidence against normality in each group.
## 20% trimmed mean t-test
The R package is named **`DescTools`** (case-sensitive); it was already installed. I used its two-sided Yuen test:
```r
DescTools::YuenTTest(dataset[[1]], dataset[[2]], trim = 0.2)
```R returned:
```text
Yuen Two Sample t-test
t = -2.2143, df = 21.503, trim = 0.200, p-value = 0.03773
95 percent confidence interval:
-314.07950 -10.07434
sample estimates:
trimmed mean of x trimmed mean of y
282.6923 444.7692
```
**Interpretation:** At the 5% significance level, there is evidence that the groups’ population 20% trimmed means differ. Group 2’s estimated trimmed mean is about **162.08 units higher** than Group 1’s. The 95% confidence interval for **Group 1 minus Group 2** is **[−314.08, −10.07]**, excluding zero.This test reduces the influence of extreme observations and assumes the two groups are independent. If the rows represent matched pairs, an independent-samples Yuen test would not account for that pairing.
The sandbox illustration already demonstrates some characteristics of agentic behaviour, as the LLM can generate code, observe the results and determine subsequent computational steps. However, a data science agent extends this capability by taking greater responsibility for planning and managing the analytical workflow itself.

4. Data Science and Biostatistics Agents

A data science agent can be understood as an LLM-based system that is given an analytical objective and can take actions to plan, execute and adapt a data-analysis workflow in pursuit of that objective. Rather than responding only with generated text or executing a statistical procedure specified in advance, the agent can interact iteratively with a computational environment, use tools, observe the results of its actions and use those results to determine subsequent steps. This makes the execution environment particularly important. Li et al. (2026) [6] describe the execution environment as the infrastructure in which an agent's actions are physically carried out and identify sandboxing as a central component of this environment. They argue that sandboxing serves not only as a security boundary for model-generated actions but also supports reproducibility by providing a resettable computational environment and enables greater autonomy by defining a bounded space within which an agent can act. A data science agent can therefore build directly on the sandboxing described in the preceding section: the sandbox provides the controlled computational environment in which statistical code can be executed, while the agent adds greater responsibility for deciding what analyses should be performed, in what sequence, and how intermediate results should influence subsequent analytical decisions. Figure 3 shows a conceptual architecture of a data science agent.
The capabilities of LLM agents have evolved considerably. Early agents were largely based on reasoning-action loops, in which the model alternated between reasoning, taking an action and observing the result before deciding what to do next. Subsequent developments expanded this basic loop through greater use of external tools, memory, coordination between agents and mechanisms for evaluating their actions. More recently, attention has shifted beyond the LLM itself to the broader infrastructure that supports sustained agent operation, commonly referred to as the agent harness [6]. The harness provides mechanisms for such functions as tool use, context and state management, execution, monitoring, verification and control. This evolution is important for data analysis because an agent must do more than generate statistical code: it needs an environment in which that code can be executed, access to relevant analytical resources, mechanisms for maintaining progress across steps, and feedback from previous actions to guide subsequent analytical decisions.
An agent therefore consists of more than the LLM itself. Li et al. (2026) [6] describe the surrounding infrastructure as an agent harness and organize it into seven interacting components: execution environment, tool interface, context and memory management, lifecycle and orchestration, observability, verification and evaluation, and governance and security. The execution environment determines where the agent's actions are carried out, while the tool interface defines the external capabilities that the agent can access. Context and memory determine what information is available to the model and how relevant information is maintained across interactions, whereas lifecycle and orchestration manage the sequence of actions, state, failures and completion of the task. Observability makes the agent's actions available for inspection, verification and evaluation provide mechanisms for assessing whether those actions and their outcomes are appropriate, and governance and security place boundaries around what the agent is permitted to do. These components work together rather than independently: the LLM provides the reasoning capability, while the surrounding harness provides the infrastructure through which its decisions are translated into controlled, observable and verifiable actions.
In data analysis, these general components take on more specific roles. The execution environment may be a sandbox containing R or another statistical programming language, while tools can provide controlled access to datasets, statistical functions, documentation and other analytical resources. Context includes the research question, study design, variable information and results obtained during the analysis, while lifecycle and orchestration allow the agent to plan the workflow, maintain progress and use the outcome of one analytical step to determine what should be done next. Observability is particularly important because the generated code, tool calls, statistical outputs and errors provide an inspectable record of how the analysis was conducted. Verification can be used to assess whether the selected methods and resulting conclusions adequately address the analytical objective, while governance can restrict access to data, files, network resources and other capabilities. In this sense, a data science agent can build directly on the sandbox described in the preceding section: the sandbox provides the controlled environment in which analytical actions are executed, whereas the broader agent harness enables the LLM to plan and manage those actions as part of a goal-directed analytical workflow. This distinction is particularly relevant in biostatistics, where greater autonomy can make complex analyses more accessible, but also increases the importance of ensuring that the statistical decisions made by the agent remain transparent and open to verification [7].

Illustration

To illustrate a simple biostatistics agent, the sandbox developed in the preceding section was extended by adding persistent execution, access to statistical documentation, and instructions that gave the LLM greater responsibility for planning and verifying the analysis. The study data remained in the host R environment and were made available through the controlled function as above. The agent could also access R help documentation through a separate tool when information about a statistical function was required. A persistent sandbox session allowed the agent to execute successive R commands and use the results of earlier steps to inform subsequent actions. This reflects the agent-harness view in [6], where execution, tools, context, lifecycle management, observability, verification and governance operate together to support sustained agent behaviour. Unlike the previous sandbox illustration, the statistical procedure was not specified in the user prompt. The agent was given only the analytical objective: to determine whether motor performance differed between the two independent groups. It first retrieved and inspected the dataset, encountered and resolved the structure in which the data were returned, calculated descriptive statistics, examined missing values and distributional characteristics, and performed Shapiro-Wilk tests. Based on the marked right-skewness and extreme observations, it independently selected a two-sided Wilcoxon rank-sum test. The agent obtained W = 130 and p = 0.144 and concluded that there was insufficient evidence at the 5% level of a difference between the groups. Importantly, the choice of the Wilcoxon test arose from the agent's analytical workflow rather than from a procedure prescribed by the user. The sequence of data inspection, computation, observation and subsequent decision-making illustrates the reasoning-action loop characteristic of agent systems. The R output from this analysis is shown below and the entire code that produced this analysis is in Appendix C.
### Approach
The groups were analyzed as **independent samples**, not paired observations. Each contained 19 measurements, with no missing values. Both distributions were strongly right-skewed and included extreme high values,so I used a **two-sided Wilcoxon rank-sum (Mann–Whitney) test** rather than a normal-theory comparison. The test used a tie-adjusted normal approximation with continuity correction.
### Results
| Group | n | Median | Interquartile range |
|---|---:|---:|---:|
| Group 1 | 19 | 262 | 180.5–402 |
| Group 2 | 19 | 497 | 228–620 |
The rank-sum test gave **W = 130, p = 0.144**.
### Interpretation
Although Group 2 had a higher observed median, there is **insufficient evidence at the 5% significance level that motor performance differs between the groups**.
This does not establish that the groups are equivalent, particularly with these modest sample sizes.The rank-sum test compares the distributions through their ranks; without assuming similarly shaped distributions, it should not be interpreted solely as a test of equal medians. The measurement’s direction is unspecified, so higher values cannot necessarily be interpreted as better performance.

5. Conclusion

This paper introduced three closely related developments that are increasingly influencing LLM-assisted data analysis: tool calling, sandboxing and data science agents. Tool calling enables an LLM to access predefined external functions and use them to perform computations that lie beyond the model itself. Sandboxing extends this capability by providing a controlled computational environment in which model-generated code can be executed. Data science agents build on these foundations by combining LLM reasoning, tools, memory, planning and execution environments to pursue analytical objectives through a multi-step workflow. Although these concepts are related, they differ in scope and autonomy. Tool calling provides access to specific predefined capabilities, sandboxing provides a general execution environment, and data agents add mechanisms that allow analytical tasks to be planned, executed, monitored and adapted over time.
The examples presented in this paper also demonstrate that statistical data can be supplied to an LLM in different ways. For small examples, data may be passed directly through the prompt. In more realistic analytical settings, data can be imported into R using conventional workflows and then made available to the LLM through tools or sandbox environments. The choice depends on the size of the data, privacy considerations and the analytical objectives.
Despite rapid progress, autonomous data agents remain an active area of research. Important challenges include reliable statistical reasoning, tool selection, verification of results, state management, reproducibility, transparency and the safe handling of sensitive data. Consequently, human oversight remains essential, particularly in clinical and medical research settings. Much of the current literature on tool use, sandboxing and agents has been developed and illustrated using Python-based ecosystems. By contrast, practical guidance for implementing these ideas within R remains relatively limited. This paper therefore contributes an R-based perspective by demonstrating how recent advances in LLM-assisted data analysis can be implemented using tools such as ellmer and securer, thereby helping clinicians, researchers and statisticians better understand both the opportunities and limitations of these emerging technologies.

Appendix A. R Code for Tool Calling

library(ellmer)
library(WRS2) # Required for the trimmed mean t-test (yuen)
library(DescTools)
# ==============================================================================
# STEP 1: Create the R Functions
# ==============================================================================
# 1. Mean calculation
calculate_mean <- function(data_vector, na_rm = TRUE) {
  data_vector <- as.numeric(data_vector)
  res <- mean(data_vector, na.rm = na_rm)
  return(paste("The calculated mean is:", res))
}
# 2. Shapiro-Wilk Normality Test
run_shapiro_test <- function(data_vector) {
  data_vector <- as.numeric(data_vector)
  test_res <- shapiro.test(data_vector)
  out <- paste0(
    "Shapiro-Wilk normality test result: ",
    "W = ", round(test_res$statistic, 4), ", ",
    "p-value = ", format.pval(test_res$p.value, digits = 4), ". ",
    "Interpretation: If p < 0.05, the data significantly deviates from a normal distribution."
  )
  return(out)
}
# 3. Trimmed Mean T-Test (Yuen's Test)
run_trimmed_ttest <- function(group1_vector, group2_vector, tr = 0.2) {
  g1 <- as.numeric(group1_vector)
  g2 <- as.numeric(group2_vector)
  # DescTools allows passing vectors directly
  test_res <- DescTools::YuenTTest(x = g1, y = g2, trim = tr)
  # Format the text output exactly like the original function
  out <- paste0(
    "Yuen's test on trimmed means (trim = ", tr, "): ",
    "Test Statistic = ", round(test_res$statistic, 4), ", ",
    "p-value = ", format.pval(test_res$p.value, digits = 4), ", ",
    "95% CI = [", round(test_res$conf.int[1], 4), ", ", round(test_res$conf.int[2], 4), "]. ",
    "Diff of trimmed means = ", round(test_res$estimate[1] - test_res$estimate[2], 4)
  )
  return(out)
}
# ==============================================================================
# STEP 2: Define the Functions as Tools
# ==============================================================================
tool_mean <- tool(
  calculate_mean,
  description = "Calculates the arithmetic mean of a numeric vector.",
  arguments = list(
    data_vector = type_array(
      items = type_number(),
      description = "A numeric vector containing the dataset to average."
    ),
    na_rm = type_boolean(
      description = "Logical value indicating whether to strip NA values before computing."
    )
  )
)
tool_shapiro <- tool(
  run_shapiro_test,
  description = "Performs a Shapiro-Wilk test to check if a numeric dataset is normally distributed.",
  arguments = list(
    data_vector = type_array(
      items = type_number(),
      description = "A numeric vector containing the data to test."
    )
  )
)
tool_trimmed_ttest <- tool(
  run_trimmed_ttest,
  description = "Performs Yuen's test for a trimmed mean t-test to compare two independent groups robustly.",
  arguments = list(
    group1_vector = type_array(
    items = type_number(),
    description = "A numeric vector representing the data for the first group."
    ),
    group2_vector = type_array(
      items = type_number(),
      description = "A numeric vector representing the data for the second group."
    ),
    tr = type_number(
      description = "The proportion of predicted outliers to trim from each end of the data. Defaults to 0.2 (20%)."
    )
  )
)
# ==============================================================================
# STEP 3 & 4: Register Tools and Initialize Chat
# ==============================================================================
chat <- chat_openai(model = "gpt-4o")
chat$register_tool(tool_mean)
chat$register_tool(tool_shapiro)
chat$register_tool(tool_trimmed_ttest)
# ==============================================================================
# DATA ASSIGNMENT & EXECUTION
# ==============================================================================
g1 <- c(
  77, 87, 88, 114, 151, 210, 219, 246, 253, 262,
  296, 299, 306, 376, 428, 515, 666, 1310, 2611
)
g2 <- c(
  59, 106, 174, 207, 219, 237, 313, 365, 458, 497,
  515, 529, 557, 615, 625, 645, 973, 1065, 3215
)
prompt_text <- paste0(
  "Please analyze and compare (test) the groups in the following dataset for me.\n",
  "Group 1 data: ", paste(g1, collapse = ", "), "\n",
  "Group 2 data: ", paste(g2, collapse = ", ")
  )
chat <- chat_openai(model = "gpt-6.1-sol")
# 4. Stream the analysis directly to your R console
chat$chat(prompt_text)

Appendix B. R Code for Sandboxing

library(readxl)
library(securer)
library(ellmer)
# ----------------------------------------------------
# 1. Read the data in the host R environment
# ----------------------------------------------------
my_data <- read_excel(
  "C:/Users/Desktop/LLMS/groups_g1_g2.xlsx"
)
# Check the data
head(my_data)
# ----------------------------------------------------
# 2. Create a host-side function that supplies the data
# ----------------------------------------------------
get_my_groups <- function() {
  my_data
}
# ----------------------------------------------------
# 3. Make the function available to the sandbox
# ----------------------------------------------------
tools <- list(
  securer_tool(
    name = "fetch_group_data",
    description = paste(
      "Returns the study dataset.",
      "The dataset contains two numeric variables:",
      "'Group 1' and 'Group 2'."
    ),
    fn = get_my_groups,
    args = list()
  )
)
# ----------------------------------------------------
# 4. Create the sandbox interpreter WITH the tool
# ----------------------------------------------------
code_interpreter <- as_ellmer_tool(
  tools = tools,
  sandbox = TRUE
  )
# ----------------------------------------------------
# 5. Create the LLM
# ----------------------------------------------------
system_prompt_sys <- "
Use the sandbox as your computational environment. Perform calculations
by writing and executing R code rather than through natural-language
reasoning or hardcoded results. You may inspect intermediate outputs
and revise your code when necessary. Base your final response only on
results obtained from executed R code.
"
chat <- chat_openai(model = "gpt-6.1-sol",
        system_prompt = system_prompt_sys )
chat$register_tool(code_interpreter)
# ----------------------------------------------------
# 6. Send the analysis request
# ----------------------------------------------------
analysis_prompt <- "
Use the R code execution environment to analyse the dataset.
The sandbox provides a function called fetch_group_data().
Use that function from your R code to obtain the dataset.
Perform the following analysis:
1. Store the returned data as an object called dataset.
2. Display the first few observations and variable names.
3. Calculate the mean, median, standard deviation, and IQR
    separately for the two groups.
4. Perform a Shapiro-Wilk normality test separately for each group.
5. Perform a 20% trimmed mean t-test using desctools (install desctools if missing) to compare the two groups.
6. Report the R results and briefly interpret them.
Use R for all statistical calculations.
"
chat$chat(analysis_prompt)

Appendix C. R Code for Data Agent

# SANDBOXED BIOSTATISTICS / DATA-ANALYSIS AGENT
#
# Conceptual structure based on ETCLOVG:
#
# E = Execution environment
# T = Tool interface
# C = Context and memory
# L = Lifecycle and orchestration
# O = Observability
# V = Verification
# G = Governance and security
#####################################################################
#####################################################################
# 0. REQUIRED PACKAGES
#####################################################################
library(readxl)
library(securer)
library(ellmer)
# Check that DescTools is available before starting the agent.
# The sandbox should use installed statistical packages rather than
# attempting uncontrolled package installation during the analysis.
if (!requireNamespace("DescTools", quietly = TRUE)) {
  stop(
    "The DescTools package is required. ",
    "Install it before starting the agent."
  )
}
#####################################################################
# E + G: HOST DATA AND CONTROLLED ACCESS
#
# E = Execution environment
# G = Governance
#
# The actual Excel file is read by the host R environment.
# The sandbox is not given unrestricted access to the user's files.
#####################################################################
my_data <- read_excel(
  "C:/Users/Desktop/LLMS/groups_g1_g2.xlsx"
)
# Optional host-side inspection
head(my_data)
#####################################################################
# T: DATA-ACCESS TOOL
#
# This is the controlled interface through which the sandbox can
# obtain the study data.
#
# The LLM does not need direct access to the Excel file or its path.
#####################################################################
get_my_groups <- function() {
my_data
}
#####################################################################
# T: GENERAL R HELP TOOL
#
# The agent is given access to R documentation.
#
# Importantly, this tool DOES NOT perform the statistical analysis.
# It returns an R help file so that the agent can learn how an
# available R function should be used.
#
# 'topic' = name of an R function/help topic
# 'package' = package containing that topic
#
# Examples:
#    get_r_help("shapiro.test", "stats")
#    get_r_help("YuenTTest", "DescTools")
#####################################################################
get_r_help <- function(topic, package) {
  # Check that the requested package is installed.
  if (!requireNamespace(package, quietly = TRUE)) {
    stop(
      paste0(
        "Package '", package,
        "' is not installed in the host R environment."
      )
    )
  }
  # Find the requested help topic.
  help_object <- utils::help(
    topic = topic,
    package = package,
    help_type = "text"
  )
  # Stop if the requested help topic cannot be found.
  if (length(help_object) == 0L) {
    stop(
      paste0(
        "No R help file was found for topic '",
        topic,
        "' in package '",
        package,
        "'."
      )
    )
  }
  # Obtain the underlying Rd help file.
  rd_file <- utils:::.getHelpFile(help_object)
  # Convert the Rd documentation to plain text so that it
  # can be returned through the tool interface.
  help_text <- capture.output(
  tools::Rd2txt(rd_file)
  )
  paste(help_text, collapse = "\n")
}
#####################################################################
# T + C: STATISTICAL DOCUMENTATION AVAILABLE TO THE AGENT
#
# These lines explicitly identify the statistical help files relevant
# to the present example.
#
# They are NOT instructions that the tests must necessarily be used.
# The agent should consult the documentation when relevant and decide
# whether the procedures are appropriate for the research question.
#####################################################################
statistical_help_files <- c(
  "stats::shapiro.test",
  "DescTools::YuenTTest"
)
#####################################################################
# T + G: REGISTER THE CONTROLLED TOOLS
#
# Two host-side capabilities are exposed:
#
# 1. fetch_group_data()
# Gives controlled access to the study dataset.
#
# 2. get_r_help(topic, package)
# Gives access to installed R help documentation.
#
# Statistical calculations themselves are NOT registered as tools.
# They must be written and executed by the agent inside the sandbox.
#####################################################################
tools <- list(
  securer_tool(
    name = "fetch_group_data",
    description = paste(
      "Returns the study dataset.",
      "The dataset contains two numeric variables:",
      "'Group 1' and 'Group 2'.",
      "The groups are independent."
    ),
    fn = get_my_groups,
    args = list()
  ),
  securer_tool(
    name = "get_r_help",
    description = paste(
    "Returns the official R help documentation for an installed",
    "R function or help topic.",
    "Use this tool when you need to determine how an R function",
    "works, what arguments it requires, what assumptions are",
    "relevant, or how its returned results should be interpreted.",
    "For example, documentation for the Shapiro-Wilk test can be",
    "requested with topic='shapiro.test', package='stats',",
    "and documentation for Yuen's test can be requested with",
    "topic='YuenTTest', package='DescTools'."
    ),
    fn = get_r_help,
    args = list(
      topic = "character",
      package = "character"
    )
  )
)
#####################################################################
# E + L: CREATE A PERSISTENT SANDBOX
#
# E = Execution environment
#    Generated R code executes in the sandbox.
#
# L = Lifecycle/state
#    A persistent SecureSession is deliberately created rather than
#    creating a new isolated R process for every analytical step.
#
# This allows objects created during the analysis, such as:
#
#    dataset
#
# to remain available during subsequent computational steps.
#
# verbose = TRUE also makes execution activity more inspectable.
#####################################################################
session <- SecureSession$new(
  tools = tools,
  sandbox = TRUE,
  verbose = TRUE
)
#####################################################################
# T: EXPOSE THE SANDBOX TO THE LLM
#
# The entire R execution environment becomes an ellmer tool.
#
# Notice the distinction:
#
# fetch_group_data() = specific data-access tool
# get_r_help() = documentation tool
# code_interpreter = general computational capability
#####################################################################
code_interpreter <- as_ellmer_tool(
  session = session
)
#####################################################################
# C + L + V + G: DEFINE THE AGENT'S BEHAVIOUR
#
# C = Context
#    Defines the role, research setting and available information.
#
# L = Lifecycle/orchestration
#    Requires planning, execution, observation and revision.
#
# V = Verification
#  vRequires the agent to check its method and results.
#
# G = Governance
#    Prevents fabrication and requires computation through the
# controlled R environment.
#####################################################################
system_prompt_agent <- "
You are a biostatistical data-analysis agent working in a sandboxed
R environment.
Your responsibility is to plan, execute, inspect, and verify the
statistical analysis required to answer the user's research question.
ANALYTICAL WORKFLOW
For each analysis:
1. Understand the research question before performing calculations.
2. Retrieve and inspect the study data.
3. Develop an appropriate statistical analysis plan based on the
    research question, study design, variable types, and observed data.
4. Determine what statistical information or assumptions need to
    be examined.
5. When uncertain about the use, arguments, or output of an R
    statistical function, consult its R help documentation using the
    available get_r_help() function before using it.
6. Write and execute the required R code in the sandbox.
7. Inspect the results returned by R.
8. If the R code produces an error, inspect the error, revise the
    code when appropriate, and execute it again.
9. Use the results of earlier computational steps to determine what
    analytical step should be performed next.
10. Before completing the task, verify that:
    - the statistical method is appropriate for the research question;
    - relevant assumptions or data characteristics have been examined;
    - reported numerical results came from executed R code; and
    - the final conclusion addresses the original research question.
11. Stop when the research question has been adequately addressed.
COMPUTATIONAL RULES
Use R for all statistical calculations.
Do not calculate statistical results through natural-language
reasoning.
Do not hardcode numerical results.
Do not invent observations, variables, statistical results, or
information that is not available from the study data.
Base numerical statements in the final response only on results
obtained from executed R code.
REPORTING
Briefly describe the analytical approach taken.
Report the important statistical results.
Provide a concise interpretation relevant to the research question.
Mention important limitations or assumptions when they affect the
interpretation.
"
#####################################################################
# C: CREATE THE STATEFUL LLM CONVERSATION
#
# The ellmer Chat object maintains the conversation, including
# messages and tool results.
#
# This provides conversational context across the analytical
# trajectory.
#####################################################################
chat <- chat_openai(
  model = "gpt-6.1-sol",
   system_prompt = system_prompt_agent
)
#####################################################################
# T: REGISTER THE R SANDBOX WITH THE CHAT MODEL
#####################################################################
chat$register_tool(code_interpreter)
#####################################################################
# O: OBSERVABILITY
#
# The analysis can be inspected through:
#
# - model messages;
# - generated tool requests;
# - R code sent to the sandbox;
# - returned R output;
# - errors and subsequent corrections;
# - verbose SecureSession information.
#
# This allows the researcher to examine the analytical trajectory,
# rather than evaluating only the final natural-language response.
#####################################################################
#####################################################################
# L: GIVE THE AGENT A GOAL, NOT A PREDEFINED ANALYSIS
#
# THIS IS THE IMPORTANT DIFFERENCE FROM THE SANDBOX EXAMPLE.
#
# We do NOT instruct the model:
#
#  run Shapiro-Wilk
#  run Yuen's test
#
# Instead, the researcher provides the analytical objective.
#
# The agent has responsibility for planning the analysis.
#####################################################################
analysis_prompt <- "
The sandbox provides a function called fetch_group_data() that returns
the study dataset.
The data consist of motor performance measurements from two independent
groups.
Determine whether there is evidence that motor performance differs
between the two groups.
Plan and carry out an appropriate statistical analysis using R.
You have access to R help documentation through get_r_help() if you
need information about statistical functions.
Explain the analytical approach and provide a concise interpretation
of the results.
"
#####################################################################
# L + E + T + V: START THE AGENTIC ANALYTICAL LOOP
#
# From this point the agent can:
#
#      PLAN
#      |
#      v
#     RETRIEVE DATA
#      |
#      v
#     INSPECT DATA
#      |
#      v
#     CONSULT R HELP IF REQUIRED
#      |
#      v
#     WRITE R CODE
#      |
#      v
#     EXECUTE IN SANDBOX
#      |
#      v
#     OBSERVE RESULT / ERROR
#      |
#      v
#     DECIDE NEXT STEP
#      |
#      v
#     VERIFY ANALYSIS
#      |
#      v
#     REPORT / STOP
#
#####################################################################
chat$chat(analysis_prompt)
#####################################################################
# OPTIONAL: CONTINUE THE SAME ANALYTICAL SESSION
#
# Because the same chat and SecureSession are retained, additional
# questions can continue from the previous analysis.
#
# For example:
#
# chat$chat(
#  "Review the analysis you performed and identify any important
#  statistical limitation that should be reported."
# )
#####################################################################
#####################################################################
# G + L: TERMINATE THE COMPUTATIONAL SESSION
#
# The researcher explicitly controls the lifetime of the sandbox.
#####################################################################
session$close()

References

  1. Wang, M.; Zhang, Y.; Yu, B.; Hao, B.; Peng, C.; Chen, Y.; Zhou, W.; Gu, J.; Zhuang, C.; Guo, R.; Wang, W. Function calling in large language models: Industrial practices, challenges, and future directions. ACM Comput. Surv. 2026, 58(9), 1–37. [Google Scholar] [CrossRef]
  2. Mialon, G.; Dessì, R.; Lomeli, M.; Nalmpantis, C.; Pasunuru, R.; Raileanu, R.; Rozière, B.; Schick, T.; Dwivedi-Yu, J.; Celikyilmaz, A.; Grave, E. Augmented language models: a survey. arXiv arXiv:2302.07842.
  3. Wilcox, R.R. Some results on the Tukey-McLaughlin and Yuen methods for trimmed means when distributions are skewed. Biom. Journal. 1994, 36(3), 259–273. [Google Scholar] [CrossRef]
  4. Chen, Y.C.; Hsu, P.C.; Hsu, C.J.; Shiu, D.S. Enhancing function-calling capabilities in LLMs: Strategies for prompt formats, data integration, and multilingual translation. InProceedings of the 2025 Conference of the Nations of the Americas Chapter of the Association for Computational Linguistics: Human Language Technologies 2025, Volume 3, 99–111. [Google Scholar] [CrossRef]
  5. Cheng, D.; Huang, S.; Gu, Y.; Song, H.; Chen, G.; Dong, L.; Zhao, W.X.; Wen, J.R.; Wei, F. LLM-in-sandbox elicits general agentic intelligence. arXiv E-Prints 2026, arXiv:2601. [Google Scholar]
  6. Li, J.; Xiao, X.; Zhang, Y.; Liu, C.; Zhao, L.; Liao, X.; Ji, Y.; Wang, J.; Gu, J.; Ge, Y.; Xu, W. Agent harness engineering: A survey; OpenReview, 2026. [Google Scholar]
  7. Sun, M.; Han, R.; Jiang, B.; Qi, H.; Sun, D.; Yuan, Y.; Huang, J. A survey on large language model-based agents for statistics and data science. Am. Stat. 2026, 80(3), 331–344. [Google Scholar] [CrossRef]
  8. Qu, C.; Dai, S.; Wei, X.; Cai, H.; Wang, S.; Yin, D.; Xu, J.; Wen, J.R. Tool learning with large language models: A survey. Front. Comput. Sci. 2025, 19(8), 198343. [Google Scholar] [CrossRef]
Figure 1. Tools/function calling.
Figure 1. Tools/function calling.
Preprints 238565 g001
Figure 2. An example of sandboxed code execution for statistical data analysis. The LLM interprets the user’s request and generates R code, which is executed within an isolated R sandbox.
Figure 2. An example of sandboxed code execution for statistical data analysis. The LLM interprets the user’s request and generates R code, which is executed within an isolated R sandbox.
Preprints 238565 g002
Figure 3. Conceptual architecture of a data science agent.
Figure 3. Conceptual architecture of a data science agent.
Preprints 238565 g003
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.
Copyright: This open access article is published under a Creative Commons CC BY 4.0 license, which permit the free download, distribution, and reuse, provided that the author and preprint are cited in any reuse.