A Practical Guide to LLM Agent-Based Data Analysis
This guide explains why chat-only interactions with large language models fall short for precise data analysis and how Agent mode solves the problem by generating and executing deterministic scripts. It breaks down the core Agent workflow, compares Agent mode with general chat mode, provides a reusable prompt template, and shares engineering best practices for building reproducible analysis pipelines.
1. Background: Why Data Analysis Cannot Rely on Chat Alone
When introducing large language models into data analysis, the most common mistake is treating them as a “question-answering machine that can do math.” In reality, LLMs are fundamentally probabilistic generators: they predict the next most likely token based on training data and context, and they do not inherently follow exact mathematical rules. As a result, when a task involves metrics that require strict decimal precision—such as quantiles, basis, or inventory cycles—pure chat mode tends to produce values that only “look reasonable.” Different models can also drift noticeably from one another.
A more reliable engineering approach is to have the model act as a programmer: it automatically generates and executes scripts, using code to handle parsing, calculation, and visualization. Script execution is deterministic—the same input always produces the same output—which eliminates memory bias and numerical hallucination at the root.
A schematic execution pipeline looks like this:
# Pseudocode: skeleton of an analysis script generated and executed by an Agentimport pandas as pdimport matplotlib.pyplot as pltdf = pd.read_excel("data.xlsx") # 1. Load structured dataquantile = df["value"].quantile(0.25) # 2. Deterministically compute a quantilebase = df["base"].mean() # 3. Compute a baseline metricfig, ax = plt.subplots() # 4. Plot with real dataax.plot(df["date"], df["value"], label="value")ax.axhline(quantile, linestyle="--", label="q25")fig.savefig("chart.png", dpi=150) # 5. Export the image, then assemble a document
2. Core Capabilities of Agent Mode
Mainstream LLMs today generally support Agent mode, and their workflows are highly similar. They can be abstracted into four stages:
- Task planning: automatically decompose the goal and generate a to-do list (read data, retrieve information, compute metrics, plot, assemble a document).
- Tool invocation: call a code interpreter, web search, or local knowledge base retrieval as needed.
- Result validation: check intermediate outputs, for example whether fields are missing or values are null.
- Deliverable output: produce charts, tables, or even a complete document.
The most critical difference lies in how visualization and document generation are handled. With a code-based plotting library, every point in a chart is computed from specific data—precise, reproducible, and auditable. In contrast, approaches that rely on generative image models are essentially probabilistic pixel generation; they cannot guarantee that axis ticks strictly correspond to values, making them unsuitable for professional scenarios. Similarly, deliverables should prioritize structured document formats synthesized directly by scripts rather than stitched-together screenshots.
3. Comparing Agent Mode with General Chat Mode
To evaluate how different models perform in Agent mode, fix the same dataset and the same set of prompts, change only the model variable, and compare across these dimensions:
- Numerical consistency: the output deviation of the same metric (such as the current inventory quantile or the current basis quantile) across different models.
- Computational reproducibility: whether a script is actually executed rather than “calculated verbally.”
- Chart compliance: whether deterministic plotting is used and whether axes and legends are complete.
- Document completeness: whether a fully illustrated deliverable can be produced in one pass.
An empirical observation is that in chat mode, the quantile results from different models are close to each other and all tend to be “rough,” often showing a tendency toward integer rounding. In Agent mode, because a real computation path is taken, results diverge—which precisely shows that the former is guessing while the latter is calculating. It must be emphasized that any specific value must be based on the output of your own data script and should not cite someone else’s conclusions.
4. Reusable Prompt Template
Please complete the daily report by following these steps:1. Read the local spreadsheet file and describe its fields and sample size;2. Compute the quantiles and baseline values of the specified metrics, keeping 4 decimal places;3. Automatically call a deterministic plotting library to generate the chart;4. Merge the textual conclusions and the chart, and output a structured document;5. List all intermediate artifact filenames for easy review.
5. Engineering Implementation Recommendations
- Environment isolation: provide a sandbox and read-only data mounts for code execution to prevent accidental writes.
- Artifact traceability: archive scripts, data snapshots, charts, and documents together to meet audit requirements.
- Failure retry: set timeouts and retry policies for tool invocations to prevent long-running tasks from being interrupted.
- Cost control: layer retrieval and computation to reduce reliance on long contexts.
In summary, the value of Agent mode lies not in “being better at chatting” but in replacing an uncertain generation process with a deterministic computation process. If an enterprise wants to implement similar capabilities in its own environment, it can build a reproducible analysis pipeline based on general cloud product capabilities such as the container platform, object storage, and log monitoring offered by Baidu AI Cloud.
