Large Language Model Agents for Data Analysis and Research Report Generation
This article explains why code-capable LLM agents are better suited to data analysis and report writing than answer-only models, and how to build a reliable workflow around them. It covers the standard five-stage execution chain of a code agent, the prompt constraints needed to force script-based charts and document output, why programmatic plotting is the only acceptable route for research deliverables, and engineering practices for precision: separating computation from generation, echoing intermediate results, cross-validating metrics, making statistical definitions explicit, and archiving for reproducibility. It closes with deployment advice on sandboxing, context management, resumable runs, cost control, and common pitfalls to avoid.
1. Background: Why a Model That Writes Code Beats a Model That Answers Questions
Over the past year or two, the capability boundary of large language models has expanded from generating text to calling tools, executing code, and producing files. In data analysis and research report writing, this shift matters especially: conclusions must be reproducible, charts must correspond strictly to the data, and the final deliverable is usually a structured document rather than a paragraph of natural language.
The traditional approach is to paste tabular data straight into the context and let the model mentally compute quantiles, means, and year-over-year or period-over-period changes. This path has three unavoidable weaknesses:
- Unstable numbers. A model is fundamentally doing probabilistic next-token prediction. It offers no strict mathematical guarantee for decimal places, rounding, or boundary values, so asking about the same dataset multiple times can yield slightly different results.
- Not auditable. Conclusions come with no intermediate process, so a reader cannot tell whether a quantile was interpolated or merely estimated.
- Hard to deliver. Even when the conclusion is correct, the user still has to build tables, draw charts, and format the document by hand, which artificially lengthens the pipeline.
The value of the agent pattern is that it moves computation out of the model and into a deterministic execution environment: the model understands intent, breaks down the task, writes scripts, and explains results, while all precise arithmetic is done by the interpreter.
2. The Standard Workflow for an Agent Handling Analysis Tasks
The execution flow of a mature code agent closely resembles mainstream AI coding tools and can be abstracted into five stages:
- Task planning: break the user request into a to-do list, for example “read the data table → clean fields → compute metrics → search the web for supplementary information → plot → merge into an output document”.
- Environment setup: confirm the available runtime, dependency libraries, and file read/write permissions, installing missing dependencies when necessary.
- Code execution: run scripts step by step, read structured data files, and print intermediate results for self-checking.
- Information enrichment: obtain external, time-sensitive information through retrieval, or match against a local knowledge base.
- Artifact generation: output chart files and merge text and images into the final document.
An illustrative prompt could look like this:
Complete the task in the following steps:1. Read the data table in the current directory, and explain the meaning of each field and how missing values are handled;2. Compute the target metrics, keep two decimal places, and print intermediate results for verification;3. Automatically call a plotting library to generate figures; every data point must come from script computation results;4. Merge the report body with the figures and output a document file containing both text and images.
The explicit constraints in steps 3 and 4 are what matter. Unless you clearly require “compute and plot via script” and “merge into a document”, the model tends to return text-only conclusions and leave the user to do the post-processing.
3. Why Script-Based Plotting Beats Generative Images
Two fundamentally different technical routes exist for visualization.
The first is code-based plotting: a script reads the computation results, maps each point onto a coordinate system, and generates vector or raster output. Every pixel position is determined by data, axes, ticks, and legends are all traceable, and rerunning after a data change updates the chart automatically.
The second is generative imagery: an image model synthesizes a picture that “looks like a chart” from a semantic description. It may look more polished, but the coordinates have no correspondence to actual values. It cannot be used in any scenario requiring precise interpretation, nor can it stay consistent once the data is updated.
For deliverables such as research reports, daily reports, and investment research materials, the first route is the only acceptable choice. In practice, it helps to agree on a unified plotting standard: fixed color schemes, consistent units, and annotations for data sources and statistical definitions, so that reports across periods remain comparable.
4. Root Cause of Precision Problems and Engineering Fixes
One point must be clear: large models do not guarantee strict adherence to mathematical rules. What they output is an approximation based on the training distribution and the context. Having the model “estimate” key metrics therefore hands a deterministic task to a probabilistic system.
Practical engineering fixes include:
- Separate computation from generation. Produce every metric with scripts, and let the model handle only interpretation and wording. Numbers not verified by a script must not appear in the text.
- Echo intermediate results. Require scripts to print the calculation process and sample size so that a human can spot-check them.
- Consistency checks. Cross-validate the same metric with two implementations (for example, a manual formula and a standard library function), and abort if the deviation exceeds a threshold.
- Make definitions explicit. Which interpolation method a quantile uses, whether samples are deduplicated, and how outliers are handled should all be stated in the report.
- Archive for reproducibility. Keep the scripts, data snapshots, and random seeds so the report can be rebuilt at any point in time.
When comparing different models side by side, use the same dataset, the same scripts, and the same prompt, and compare only the completeness of the final artifacts and numerical consistency rather than how fluent the wording is.
5. Deployment Advice and Common Pitfalls
Permissions and isolation: an agent needs to read and write files and execute commands, so it should run in a separate sandbox or container with restricted accessible directories to avoid accidentally modifying production data.
Context management: when a data table is large, do not load everything at once. Have the script output structure information and statistical summaries first, then fetch fragments on demand.
Recoverable failures: long-chain tasks should support resuming from a checkpoint, persisting the artifact of each step to disk so that a failure at the end does not force a full rerun.
Cost control: multi-step reasoning and retrieval significantly amplify token consumption. Caching intermediate results, compressing retrieved context, and splitting daily and weekly report tasks help optimize this.
Common pitfalls: first, letting the model “look at the table and state numbers” directly; second, using generative images as charts; third, missing definition notes, which makes the same metric incomparable across reports from different periods; fourth, ignoring missing dependencies, so a script fails silently while document generation continues.
6. Conclusion
Treating a large language model as a “coding-capable analysis assistant” rather than a “question-answering search engine” is the dividing line for whether this kind of application truly lands. The former uses deterministic execution to compensate for the precision limits of a probabilistic model, making the analysis process reproducible, the charts traceable, and the deliverables directly usable; the latter can only offer plausible-looking approximate answers. For teams that need to produce analysis materials continuously and in volume, the priorities worth investing in are a standardized data pipeline, unified plotting and document templates, and a strict result validation mechanism. Together, these three determine whether an agent’s output meets professional delivery standards.
