A Practical Guide to LLM Agents for Data Analysis
This article explains why data analysis tasks should be delegated to LLM agents that write and execute code rather than to models that generate numbers directly. It covers the general agent workflow, script-based visualization, prompt design for defining calculation conventions, methods for comparing models, common failure modes, and engineering practices for reliable, auditable reporting.
1. Why Delegate Data Analysis to an Agent Instead of Asking the Model Directly
In structured data analysis, letting a model “do the math in its head” is the least reliable approach. An LLM is fundamentally a probabilistic language model: it outputs the most likely token sequence given the current context, not a result derived from strict mathematical rules. Once precise definitions come into play—quantiles, basis, ratios, decimal truncation—direct number generation produces two typical problems. The first is memory bias, where the model reproduces numbers from its training corpus that merely “look like answers.” The second is rule drift, where the model’s understanding of quantile interpolation methods or sample scope gradually shifts over a long context.
A more robust engineering pattern is to have the model act as a programmer: it generates and calls scripts to parse tables, and the interpreter performs the actual computation. Script output does not depend on probabilistic sampling; the same input reproduces the same output, which eliminates hallucination at the root. The idea can be summarized as a minimal loop:
# Pseudocode: the agent's "plan-execute-verify" loopplan = agent.plan("Compute quantiles of current inventory and basis, then plot")for task in plan.todo:result = sandbox.run(task.code) # real interpreter executionfacts.append(result.stdout) # feed only execution results back into contextreport = agent.compose(facts, charts=result.figures, fmt="pdf")
The key point: numbers come from stdout, and the narrative comes from the model. Separating these two responsibilities is the first safeguard for reliability.
2. The General Agent Workflow
Current mainstream agent implementations—including coding assistants and cloud-based coding hosts with a UI—have converged on essentially the same “task-list-driven” pattern:
- Requirement parsing and task decomposition: break “produce a daily report” into subtasks such as reading data, retrieving news, computing metrics, generating charts, and merging and exporting, forming a to-do list.
- Environment setup: verify dependencies in the sandbox, installing plotting and table-reading libraries if needed.
- Step-by-step execution and observation: after each subtask runs, read stdout and error traces; on failure, self-correct and retry.
- Result aggregation and writing: write verifiable facts and chart paths into structured intermediate artifacts, then generate the final document.
This flow is nearly identical to that of terminal-based coding agents; the differences show up mainly in tool-call permissions, sandbox isolation strength, and output artifact types.
3. Visualization: Why Script-Based Plotting Beats Pixel Generation
In research-report deliverables, charts are not decoration—they are evidence. Every point produced by a script-based plotting library (a common Python visualization approach in the industry) is computed from concrete data; axes, ticks, and legends are reproducible and auditable. A probabilistic pixel-generation model can only “look right”; it cannot guarantee numerical correctness, nor can it automatically redraw when the data is updated.
Engineering-wise, it helps to treat charts as part of a “data contract”:
import matplotlib.pyplot as pltdef draw_factor(series, title, out):fig, ax = plt.subplots(figsize=(8, 4))ax.plot(series.index, series.values, linewidth=1.2)ax.set_title(title); ax.grid(alpha=0.3)fig.tight_layout(); fig.savefig(out, dpi=200)return out
As long as the prompt explicitly states “automatically call the plotting library to generate charts, and merge the body text and charts into a PDF export,” the agent can render figures according to the source logic and lay out text and images together. Document generation should likewise be handed to scripts, avoiding direct binary assembly by the model.
4. Prompt Design: Encode the Conventions as Constraints
Most precision problems are not model capability problems but undefined conventions. It is worth explicitly fixing the following in the prompt:
- Data scope and time window, plus the missing-value handling strategy;
- Quantile algorithm and interpolation method, decimal places retained, and rounding rules;
- Basis definition (the scope of spot and futures, whether annualized);
- Deliverable list: number of charts, naming, resolution, and final file format.
Example:
Task: produce today's data daily reportConstraints:1) All metrics must be computed by scripts; mental math is forbidden;2) Quantiles use linear interpolation, with results rounded to one decimal place;3) Automatically call the plotting library to generate one chart per factor;4) Merge the body text and charts into a PDF whose filename contains the date.
5. How to Compare Multiple Models Properly
When comparing agent performance across models, avoid subjective conclusions like “which one is smarter” and use quantifiable dimensions instead: task completion rate, script first-pass rate, deviation of values from a baseline, chart reproducibility, long-task stability, and the number of self-recovery attempts after failures. Only by running batches on the same data, with the same prompts, in the same sandbox environment, and logging each subtask’s execution, can you reach reproducible conclusions.
From publicly observable behavior, implementations tend to land in a similar range on metrics like “current inventory quantile,” while differences widen markedly on “basis quantile,” indicating that basis conventions are more complex and more sensitive to constraint clarity. The takeaway: the more complex the convention, the more important it is to put the definition upfront in both the prompt and code comments.
6. Common Failure Modes and How to Avoid Them
- Hallucinated numbers: the model skips the script and gives figures directly. Avoid it by enforcing “no stdout, no conclusion” in the workflow.
- Missing dependencies: an uninstalled plotting or table library halts the run. Avoid it with a dependency self-check at startup.
- Long-context drift: an overly long task list causes early constraints to lose effect. Avoid it by executing in segments and periodically re-injecting the constraints.
- Corrupted deliverables: direct binary assembly produces an unreadable PDF. Avoid it by exporting everything through scripts.
- Sandbox overreach: overly broad read/write scope creates risk. Avoid it with least privilege and read-only mounts for input directories.
7. Recommendations for Production Deployment
To reuse this loop reliably in an enterprise environment, package it as a pipeline: a data ingestion layer handles fetching and validation, a compute layer runs scripts on a container platform, artifacts land uniformly in object storage, and task status and logs are tracked by logging and monitoring/alerting services, with automatic retries and an audit trail on failure. The model is responsible only for planning and narration; determinism and auditability are guaranteed by the engineering chain.
In short, the value of an agent in data analysis lies not in “being better at arithmetic” but in “writing code to compute, generating charts as evidence, and composing text for delivery.” State the conventions clearly, leave computation to the interpreter, and leave charts to scripts—that is the right way to make an agent produce trustworthy research reports.
