Large Language Model Agents for Data Analysis and Research Report Generation

    This article explains why asking a large language model to perform numerical calculations on tables directly is unreliable, and presents a more robust engineering pattern: treating the model as a programmer rather than a calculator. It covers the core Agent workflow of planning, tool invocation, observation, and re-planning; why code-based plotting is preferred over generative image models for professional reports; how to write prompts as executable acceptance criteria; and how to add deterministic guardrails such as assertions, dual-path verification, and audit trails. Practical deployment advice on runtime isolation, cost quotas, artifact hosting, and template reuse is also included.

    1. Background: Why Letting the Model “Do the Math” on Tables Is Unreliable

    In structured data analysis, one conclusion keeps proving itself: when a large language model is asked to compute quantiles, year-over-year and period-over-period changes, basis, and similar values directly from a table, the results should generally be treated as approximations. The reason is that the model is fundamentally a predictor of the next token. It “guesses” a number that looks plausible based on its training distribution and contextual cues, rather than executing strict mathematical rules. The wider the table, the more fields it contains, and the higher the precision requirement, the more pronounced this deviation becomes.

    A more reliable engineering paradigm is to position the model as a “programmer” rather than a “calculator”: it generates and invokes scripts to read data, perform calculations, draw charts, and assemble documents. Every step of a script is deterministic, and the same input always yields the same output. This eliminates probabilistic memory bias and makes the entire process reproducible and auditable.

    A schematic view of the execution logic:

    1. # The model only generates code and parameters; computation is handled by a deterministic runtime
    2. import pandas as pd
    3. df = pd.read_excel("data.xlsx")
    4. q_current = df["inventory"].quantile(0.5) # quantiles are computed precisely by library functions
    5. q_basis = df["basis"].quantile(0.5)
    6. print(f"current={q_current:.4f}, basis={q_basis:.4f}")

    2. The Core of Agent Mode: From “Outputting Text” to “Completing Tasks”

    The difference between Agent mode and a regular conversational mode is that an agent is allowed to use tools and form a closed loop: plan, invoke, observe results, and re-plan. A typical workflow usually includes the following stages:

    1. Task decomposition: first generate a to-do list, breaking “write a daily report” into subtasks such as reading data, computing metrics, retrieving news, plotting, and layout composition.
    2. Data access: read local tables or files in object storage via scripts, completing field identification and missing-value checks.
    3. Information enrichment: search the web or recall relevant information from a local knowledge base, cross-checking it against the numerical results.
    4. Visualization: call plotting libraries to generate charts, where every point comes from a specific computation result.
    5. Document assembly: merge text and charts into a portable document format, producing a deliverable with both text and visuals.

    The key value of this chain is that it is “replaceable and verifiable.” If any stage fails, it can be located and retried individually, rather than producing a single long piece of text that cannot be traced.

    3. Why Use Code-Based Plotting Instead of Generative Image Models

    Code-based plotting and generative imagery are two entirely different technical paths. The former relies on a deterministic mapping from data to coordinates, where axes, ticks, and legends can all be strictly derived from the data, making it suitable for professional analysis. The latter generates pixels probabilistically; it may look visually appealing, but it cannot guarantee numerical correctness and does not support error tracing.

    In professional research reports, charts serve as evidence. If the chart itself is untrustworthy, the persuasiveness of the entire conclusion suffers. The recommended practice is therefore to produce all figures from scripts and to annotate the data source, calculation methodology, and generation time in the document for easy review.

    4. Prompt Design: Writing Output Requirements as Executable Acceptance Criteria

    In practice, the most effective one-sentence constraint is to state the deliverable form clearly, for example: “automatically call a plotting library to generate figures, and merge the body text and figures into a document.” Going further, you can make the acceptance criteria explicit:

    • Define the calculation methodology: which field and which time window are used for quantiles, means, and basis.
    • Define precision requirements: how many decimal places to keep and how units are labeled.
    • Define the chart list: how many charts are needed and what conclusion each one conveys.
    • Define the failure strategy: whether to annotate an explanation or terminate the workflow when data is missing.

    5. Result Validation: Adding Deterministic Guardrails to Probabilistic Steps

    Even when computation is delegated to scripts, the model can still make mistakes in parameter selection and field mapping. Three types of guardrails are recommended:

    1. Assertion checks: set reasonable ranges and monotonicity assertions for key metrics, raising an error as soon as a value is out of bounds.
    2. Dual-path verification: cross-validate the same metric using two implementations (for example, a library function and a manual formula).
    3. Audit trail: save scripts, parameters, original data versions, and run logs to form a traceable chain.

    6. Recommendations for Engineering Deployment

    • Runtime isolation: run code execution in a controlled sandbox with restricted network and file system permissions.
    • Cost and quotas: set step and invocation limits for long workflows to avoid exhausting the quota, which could cause an interruption that cannot be resumed.
    • Artifact hosting: store intermediate charts and final documents in object storage, combined with logging services and monitoring alerts for quality observation.
    • Template reuse: solidify high-frequency analysis scenarios into reusable templates to reduce variability caused by prompt drift.

    7. Conclusion

    The real advantage of large language model agents in data analysis and research report generation is not “more accurate calculation,” but “correctly dividing uncertain reasoning from deterministic computation.” Assign numbers to scripts, structure to planning, and expression to the model, then add assertions, verification, and audit trails, and you get a stable, professional, and auditable intelligent analysis pipeline.