Using AI Agents and Scripts for Reliable Data Analysis

    Large language models are powerful at understanding analytical intent and orchestrating workflows, but they are not deterministic calculation engines. This guide explains how to combine AI agents with executable scripts to perform accurate, reproducible data analysis, generate data-driven charts, and produce auditable PDF reports. It covers workflow design, quantile calculation, reproducibility, common engineering pitfalls, validation, and delivery requirements.

    1. The Root Problem: Language Models Are Not Calculation Engines

    Large language models are fundamentally probabilistic sequence predictors. When generating each token, they rely on patterns in their training data and similarities within the current context rather than on strict mathematical rules. As a result, when a task involves multi-step arithmetic, sorting, grouping, aggregation, or quantile calculation, a model may produce a value that looks reasonable instead of the uniquely correct result.

    This approximation is unacceptable in structured data analysis. A deviation of only a few percentage points in metrics such as inventory quantiles or basis quantiles can reverse the direction of a conclusion. The correct engineering approach is therefore not to keep refining prompts in an attempt to make the model “calculate more accurately.” Instead, responsibilities should be separated:

    • The model interprets intent, decomposes tasks, and orchestrates the workflow.
    • Deterministic scripts perform calculations and generate visualizations.

    2. Separation of Responsibilities: The Agent as a Programmer, Not a Calculator

    The core value of an agent is its ability to execute code and call tools. In this setting, it behaves more like a programmer than a calculator: it reads data, writes processing logic, runs scripts, checks outputs, fixes errors, and produces the final deliverable.

    This is fundamentally different from image-generation models. In a script-generated chart, every data point is calculated from specific source data. Axes, legends, and error ranges can all be traced back to the original table. Generative image creation, by contrast, produces visually plausible pixels through probabilistic synthesis; visual similarity does not guarantee numerical meaning.

    For professional research reports, financial analysis, and operational daily reports, where results must be auditable, the accuracy and traceability of script-based charts are decisive advantages.

    Scripts can also directly assemble structured documents such as PDFs. This makes it possible to combine written conclusions and charts into a complete, self-contained deliverable.

    3. A Typical Workflow: A Five-Stage Pipeline Driven by a Task Checklist

    A mature agent workflow is similar to those used by modern AI coding tools. It can be summarized in five stages:

    1. Task planning: Generate a checklist and break an ambiguous request into verifiable subtasks.
    2. Data acquisition: Run scripts to read local or cloud-based tables. When necessary, retrieve background information through network searches or a local information repository.
    3. Data processing: Apply the defined methodology for cleaning, aggregation, quantile segmentation, and factor calculation.
    4. Visualization: Generate charts from source code so that the charts and the underlying data share the same computational source.
    5. Document assembly: Combine the report text and charts into a PDF research report.

    A prompt can often guide the agent to complete this orchestration by explicitly stating: “Automatically call the visualization capability to generate charts, then combine the report text and charts into a PDF report.”

    Illustrative pseudocode is shown below. Library names should be replaced according to the actual execution environment:

    1. # 1. Read structured data
    2. df = read_table("inventory.csv")
    3. # 2. Calculate quantiles with an explicit methodology
    4. # to prevent methodological drift
    5. q_cur = quantile(df["current_stock"], 0.5, method="linear")
    6. q_base = quantile(df["base_stock"], 0.5, method="linear")
    7. # 3. Generate charts from the same data source
    8. plot_hist(df["current_stock"], bins=50, title="Current Inventory Distribution")
    9. plot_vline(q_cur, label="Current Inventory Quantile")
    10. # 4. Assemble the deliverable
    11. render_pdf("Report Body", charts=["dist.png"], out="daily_report.pdf")

    4. Comparing Accuracy: A Reproducible Experimental Design

    To quantify the difference between approaches, use the same dataset and the same quantile methodology in a controlled comparison. Ask both a direct question-and-answer system and an agent using scripts to produce the results, then compare them with values generated by a reference script.

    The following internal test record is illustrative only. It demonstrates the evaluation method and is not intended to assess any specific product:

    Execution mode Tested model Current inventory quantile Current basis quantile
    Direct question answering Model A 26.3% 55.0%
    Direct question answering Model B 21.2% 55.2%
    Agent with scripts Model C 27.4% 68.0%
    Agent with scripts Model D Approximately 30% Approximately 30%

    The results show that entering agent mode alone does not eliminate errors. If the model estimates the answer instead of actually executing the script, deviations remain. Results converge toward the reference value only when the calculation is performed by a deterministic script.

    The key variable is therefore not simply model capability. It is whether deterministic computation is genuinely executed.

    5. Common Pitfalls and Engineering Constraints

    • Floating-point precision: Binary floating-point formats cannot represent most decimal fractions exactly. Financial amounts and ratio calculations should use fixed-point or high-precision decimal types when appropriate, with a consistent number of output decimal places.
    • Inconsistent quantile definitions: Linear interpolation, nearest-rank methods, and differences in whether data is deduplicated can all produce different results. The same method must be fixed in both the prompt and the code.
    • Randomness and lack of reproducibility: Direct answers may vary with context. Script-based workflows should fix random seeds, lock dependency versions, and record data snapshots.
    • Resource and quota limits: Cloud-based agent environments with graphical interfaces may provide limited usage quotas. Long-running tasks can be interrupted when quotas are exhausted, so the workflow should support resuming from checkpoints and persisting intermediate outputs.
    • Auditability: Intermediate results should be written to object storage when possible, together with logging and monitoring alerts, so that outputs can be traced and issues investigated.

    6. Production Acceptance Checklist

    1. For calculation-related tasks, require the agent to “write and execute the script before producing the conclusion.” Mental arithmetic should not be accepted.
    2. Generate charts with data-processing scripts. Do not use generative image creation as a replacement for analytical visualization.
    3. Before delivery, perform a cross-check against a reference script. If the deviation exceeds the defined threshold, return to the calculation stage.
    4. Fix the methodology, dependency versions, and random seeds to ensure reproducibility.
    5. Deliver a PDF that allows the text and charts to be checked together, and include the calculation scripts for independent review.

    The key step in bringing AI agents into professional data analysis is to treat precision as an engineering architecture problem rather than solely as a model capability problem.