AI Agent Data Analysis and Research Report Generation: A Practical Guide

    This article explains why large language models alone are unreliable for data analysis and how an AI agent can produce accurate, reproducible reports. It covers a four-layer execution pipeline (planning, tool calls, visualization, and document composition), the root causes of precision issues and how to govern them, prompt design as an output contract, and common engineering risks with practical recommendations. The goal is to build production-ready data analysis agents that compute accurately, reproduce results, and deliver finished documents.

    1. Background: Why Data Analysis Cannot Rely on Text Generation Alone

    Once large language models entered the data analysis space, a recurring problem surfaced: the model does not actually perform mathematical operations. It produces a probabilistic approximation of an answer based on its training distribution and the given context. For tasks with strict requirements such as quantiles, basis, decimal precision, and consistent definitions, letting the model simply “state the result” is unreliable.

    A more robust engineering pattern is to have the agent generate and execute scripts, let the runtime perform the exact computation, and limit the model to planning, orchestration, and explanation. The essence of this shift is replacing probabilistic generation with deterministic computation.

    A schematic flow looks like this:

    1. # Pseudocode: agent-driven deterministic computation flow
    2. plan = agent.plan(task="Compute inventory and basis quantiles")
    3. for step in plan.steps:
    4. if step.type == "load":
    5. df = run_python(step.script) # Load structured data
    6. elif step.type == "compute":
    7. result = run_python(step.script) # Interpreter performs exact computation
    8. elif step.type == "visualize":
    9. fig = run_python(step.script) # Generate vector/raster chart
    10. elif step.type == "compose":
    11. pdf = merge_text_and_figures(result, fig)

    2. Core Mechanism: How an Agent Completes End-to-End Analysis

    A mature agent execution chain typically has four layers.

    The first layer is task planning. The agent first decomposes the goal into a to-do list, for example “load data - clean - compute metrics - retrieve news - plot - compose document.” Making a complex task explicit reduces the probability of drift during long execution chains.

    The second layer is tool invocation. Reading tables, retrieving local or online information, executing scripts, and generating charts are all done through standardized tool interfaces. The value of tool invocation is to converge uncertainty into deterministic components.

    The third layer is visualization. When generating figures with a mature plotting library, every point is derived from concrete data. This is fundamentally different from probability-based pixel generation: the former is recomputable, traceable, and reproducible, while the latter only guarantees visual similarity, not numerical correctness. In professional settings such as finance, industry, and operations, recomputability often matters more than aesthetics.

    The fourth layer is document composition. Text conclusions and charts are merged into a distributable document (such as a PDF), producing an illustrated deliverable. In practice, it is recommended to write “plotting” and “composition” into the output constraints, for example:

    1. Automatically call the plotting library to generate figures, and merge the report body with the figures into a PDF document;
    2. All numbers must be computed by scripts; directly stating uncomputed numbers is prohibited.

    3. Root Causes and Governance of Precision Issues

    A key observation is that different execution modes produce quantile results with deviations, and decimal handling is inconsistent. The root cause is not complex: when the model bypasses computation and answers directly, the output is an approximation; when the model calls a script, the result is determined by the interpreter, and precision depends on the data and the algorithm implementation.

    Governance measures include:

    • Enforce externalized computation: all metrics must come from script output, and the model must not fill in numbers itself.
    • Unify definitions: the quantile interpolation method, basis definition, and time alignment rules must be fixed to the same implementation.
    • Keep an audit trail: save the scripts, input data versions, and output results to form an auditable chain.
    • Cross-validation: recompute the same metric with two implementation paths, and trigger an alert if the deviation exceeds a threshold.
    1. import numpy as np
    2. def quantile_check(series, q, method="linear"):
    3. return float(np.quantile(series, q, method=method))
    4. # Cross-validation with two implementations
    5. a = quantile_check(data, 0.25, "linear")
    6. b = quantile_check(data, 0.25, "weibull")
    7. assert abs(a - b) < 1e-6, "Quantile definitions are inconsistent; unify the interpolation method"

    4. Prompt and Output Contract Design

    To make the agent reliably produce professional deliverables, the prompt should be designed as an “output contract” that includes at least four types of constraints:

    1. Computation constraints: numbers must come from scripts; mental arithmetic is prohibited.
    2. Tool constraints: specify the available tools and invocation order, such as chart generation and document composition.
    3. Format constraints: section structure, figure numbering, and unit and decimal rules.
    4. Validation constraints: require an output validation summary listing the computation method and data range for key metrics.

    A reusable template snippet:

    1. Role: Data analysis engineer
    2. Input: Structured table + optional information library
    3. Steps: Load -> Clean -> Compute -> Plot -> Compose document
    4. Rules: All numbers produced by scripts; charts generated by the plotting library; final delivery as PDF
    5. Output: Body text + figures + metric definition notes + validation summary

    5. Common Risks and Engineering Recommendations

    • Hallucination risk: most likely to appear where structured information is dense; scripts should serve as the computational fallback.
    • Environment risk: missing dependencies can cause plotting or computation to fail; it is recommended to pin dependency versions and pre-provision the runtime environment.
    • Resource risk: long tasks may consume significant quota or compute; segmented execution and resume-from-checkpoint should be set up.
    • Delivery risk: a document composition failure can make all the work unusable; it is recommended to treat composition as an independent, retryable step.

    For cloud execution, general cloud product categories can carry the workload: object storage holds data and artifacts, a container platform runs the script environment, logging and monitoring/alerting track task status, and a message queue handles task decoupling and retries. Baidu AI Cloud typically provides support in such scenarios through a combination of the general capabilities above.

    6. Conclusion

    The real value of an agent in data analysis and research report generation lies not in “sounding right” but in “computing accurately, being reproducible, and being deliverable.” Only by handing computation to the interpreter, plotting to a professional plotting library, and composition to a deterministic flow, and by constraining model behavior with output contracts and cross-validation, can you build a data analysis agent that is ready for production.