LLM Agents for Data Analysis and Research Report Generation

    Learn how to build an LLM agent workflow that combines task planning, deterministic calculations, data-driven charts, and research report generation. This article covers data validation, intermediate artifacts, citation management, prompt constraints, evaluation criteria, and engineering safeguards for reproducible, auditable analysis.

    1. Why Data Analysis Requires More Than Direct Model Answers

    Large language models are well suited to natural language understanding, task decomposition, report writing, and tool use. However, they have inherent limitations in precise numerical computation, complex structured data processing, and reproducible analysis.

    Financial and quantitative tasks—such as quantiles, year-over-year and period-over-period changes, weighted returns, risk exposure, and factor attribution—often require sorting, interpolation, grouping, missing-value handling, and joins across multiple tables. If a model performs calculations directly or infers results from context, its response may sound professional while containing decimal errors, inconsistent calculation conventions, or incorrect conclusions.

    The underlying issue is straightforward: language models generate text probabilistically rather than execute strict mathematical rules. A model may understand the definition of a quantile without reliably performing the required sorting and interpolation every time. When working with structured tables, it may also confuse field definitions, time ranges, or sample filters.

    A more reliable approach is to let the agent act as a programmer. The model interprets the request, breaks it into tasks, and writes or invokes scripts. Deterministic scripts read the data, calculate results, generate charts, and export reports. This preserves the flexibility of natural language interaction while placing critical calculations in an auditable, reproducible execution environment.

    2. An End-to-End Agent Workflow for Data Analysis

    A practical workflow should not attempt to produce the final answer in a single step. It should include task decomposition, data loading, metric calculation, information retrieval, chart generation, report assembly, and result verification.

    2.1 Task Decomposition and a Checklist

    The agent first converts the user’s objective into executable tasks. For example, generating a daily strategy report might involve:

    • Reading spreadsheet data.
    • Validating fields.
    • Calculating inventory and basis quantiles.
    • Retrieving relevant news and information.
    • Generating charts.
    • Drafting the report.
    • Combining text and charts into a formatted document.
    • Running final checks.

    Each task should specify its inputs, outputs, and failure-handling procedure. A checklist makes execution observable and helps prevent the model from losing track of the objective.

    2.2 Data Loading and Field Validation

    Scripts should handle structured data ingestion. They need to check field types, date formats, missing values, duplicate records, and outliers.

    After loading the data, the script should produce a profile that includes row and column counts, the covered time range, and missing-value rates for key fields.

    For financial research, sample filters must also match the intended methodology. Data with different frequencies or price-adjustment conventions should not be mixed inadvertently.

    2.3 Metric Calculation and Intermediate Artifacts

    All critical numerical results should be calculated by script functions, with intermediate results saved as structured files.

    For quantile calculations, explicitly define:

    • The sorting convention.
    • The interpolation method.
    • The sample range.
    • The grouping dimensions.

    Save metric tables, grouped statistics, and anomalous records separately to support review. When every number in the final report can be traced to an intermediate result, the analysis becomes substantially easier to verify.

    2.4 Information Retrieval and Citation Management

    Depending on the task, an agent may search a local information repository or retrieve information online. Retrieved material should serve as narrative context, not as a substitute for calculated results.

    Retain the source, publication time, and summary for each citation. Keep retrieved information separate from computed metrics so the model does not blur the distinction between external reporting and data analysis.

    Information with an unconfirmed source should be marked as requiring verification rather than presented as a conclusion.

    2.5 Chart Generation and Report Assembly

    Charts should be generated by scripts from actual data points, not drawn by a generative image model in response to a prompt. Script-based plotting keeps axes, ticks, legends, units, time ranges, and plotted values aligned with the underlying data.

    Report assembly can follow a template:

    • Scripts populate metric tables.
    • Scripts insert generated charts.
    • The model writes the narrative using the metrics and citations.
    • The workflow exports a formatted document containing text and charts.

    Retain the source data, scripts, and intermediate files alongside the final report.

    A simplified pseudocode workflow is:

    1. def run_analysis(task):
    2. todo = plan_tasks(task)
    3. data = load_table(task.data_path)
    4. data_profile = validate_schema(data, task.schema)
    5. metrics = calculate_metrics(data, task.metric_spec)
    6. save_intermediate(metrics, task.work_dir)
    7. citations = search_knowledge(task.query, task.source_scope)
    8. chart = render_chart(metrics, task.chart_spec)
    9. report_text = compose_report(metrics, chart, citations, task.template)
    10. document = export_document(report_text, chart, task.output_format)
    11. checks = verify_numbers(document, metrics)
    12. return document, checks

    3. Prompt and Output Constraints: Make Execution Explicit

    Agent performance depends heavily on how clearly the prompt defines the work. Specify task decomposition, data paths, calculation conventions, chart requirements, report structure, export format, and verification rules.

    For example:

    1. Complete the following tasks:
    2. 1. Break the objective into a checklist and execute it step by step.
    3. 2. Read the specified spreadsheet and report the field-validation results.
    4. 3. Calculate all numerical values using scripts; do not calculate them directly.
    5. 4. For quantiles, state the sample range, sorting convention, and interpolation method.
    6. 5. Generate charts from data points using scripts and save the chart files.
    7. 6. Include metric tables, charts, conclusions, and information sources in the report.
    8. 7. Combine the text and charts into a formatted document and export it.
    9. 8. List intermediate files, verification checks, and failure/retry records at the end.

    These constraints separate model generation from script execution: the model handles planning and writing, while scripts handle calculation and plotting.

    For complex tasks, require the agent to report the current step, inputs, outputs, and validation results at each stage. This makes spot checks easier.

    4. Why Script-Based Charts Suit Professional Research Reports

    Generative image models are useful for visual creation, but their output is probabilistically generated imagery. They do not guarantee that every data point, tick mark, or legend corresponds to real data.

    Charts in professional research reports must be reproducible, auditable, and editable. Each point should come from a specific calculation. Axis ranges should have a clear basis. Legends and units should remain consistent, and charts should be regenerated automatically when the data changes.

    For financial, quantitative, and enterprise analysis, an agent calling a general-purpose plotting library is therefore more appropriate than asking an image model to draw a chart.

    Script-based plotting also supports consistent presentation standards, including fixed colors, fonts, grids, source annotations, and time ranges. This reduces visual variation across reports.

    However, a chart is not automatically trustworthy simply because a script generated it. Reviewers still need to check sample definitions, outliers, truncated axes, and whether the title accurately describes the data.

    5. A Framework for Comparing Agent Approaches

    Evaluating an agent’s data analysis capabilities requires more than judging how fluent its writing sounds. A useful assessment should cover multiple dimensions.

    The following table groups common approaches into four broad categories. These are conceptual comparisons, not fixed ratings for specific products.

    Dimension Approach A: Script-Based Agent Approach B: Search-Augmented Agent Approach C: Cloud UI-Based Agent Approach D: Lightweight Agent
    Structured data ingestion Strong; suitable for tables and multi-table joins Moderate; depends on the toolchain Moderate; constrained by interface capabilities Basic
    Numerical calculation Deterministic script execution May combine scripts with direct model calculation Depends on tool support Higher risk of direct model calculation
    Chart generation Scripts plot actual data points May mix plotting with generative images May use image generation Usually simplified charts
    Report export Can export formatted documents with text and charts Limited support Platform-dependent Limited
    Reproducibility High when scripts and intermediate results are retained Moderate Moderate Lower
    Editability High; modify the script and rerun Moderate Constrained by usage allowances and the interface Basic
    Cost control Depends on execution time and call volume Depends on retrieval and model calls Depends on free allowances or subscription plans Lower cost, but limited capabilities

    When different approaches directly produce a quantile for the same metric, their answers may differ substantially. Recalculating with scripts can narrow those differences to the underlying calculation conventions.

    This distinction matters: differences between model answers do not always reflect differences in analytical ability. They may instead reflect whether deterministic computation was actually performed.

    For research reporting, prioritize approaches that preserve scripts, intermediate results, and verification records.

    6. Engineering Recommendations and Risk Controls

    Enterprise deployments should run agents in controlled sandboxes, with restrictions on file access and network activity. Pin dependency versions to reduce result drift caused by environment changes.

    For each execution, retain:

    • Execution logs.
    • Input snapshots.
    • Output files.
    • Verification reports.

    Sensitive data should be processed only after de-identification or within an appropriately access-isolated environment.

    For long-running tasks, object storage can preserve intermediate artifacts, logging services can record the execution chain, and monitoring and alerts can surface retries and unusually long runtimes.

    General infrastructure capabilities offered by Baidu AI Cloud may be considered during enterprise infrastructure selection. The specific architecture should still be designed around data security, auditability, and reproducibility.

    Finally, human review remains essential. Agents can improve efficiency, but key conclusions, anomalous metrics, and externally published research still require human confirmation.

    A reliable workflow closes the loop between model planning, script-based calculation, chart generation, report assembly, and human review. That is what turns an LLM agent into a dependable data analysis assistant rather than a generator of polished but probabilistic answers.