Module 10 · Lesson 4 · 18 min read

Building a data analysis agent

Building a Data Analysis Agent

Introduction

Language models are good at understanding the question and writing the explanation, but they are not a reliable calculator. A good data analysis agent divides the work: the model understands the question and chooses the operation, and the tools compute accurately on the actual data. In this lesson we build an agent that answers questions about a course grade table without guessing a single number.

Learning objectives

  • Explain why numbers must be computed with tools and not by the model
  • Design analysis tools with defined operations instead of executing arbitrary code
  • Build a simple analysis agent in Python that reads CSV data and computes statistics
  • Handle missing data and protect individuals' privacy in the results

Dividing the work between the model and the tools

When a professor asks "What is the average midterm grade for section B?", there are three different tasks:

  1. Understanding: which column? which filter? which operation? This is the model's task.
  2. Computing: reading the actual rows and computing the average. This is the tool's task.
  3. Explaining: phrasing the result, stating the number of rows and any missing data. The two cooperate on this.

If we ask the model to compute the average itself from a table pasted into the context, it may give a plausible-looking but wrong number, especially with long tables. This is the same reason that led research such as Toolformer to study teaching models when to call tools such as a calculator.

1234567The userUserThe applicationApp / RuntimeThe modelModel + Tool SchemasCall request{"name","arguments"}Tool executionValidate → ExecuteTool resultFinal answer
Tool calling: the model executes nothing itself; it proposes a structured call, and the application validates it, executes it and returns the result.

Designing the tools: defined operations or free code?

There are two common approaches:

  • Tools with defined operations: describe_column, filter_rows, aggregate(column, op) where op comes from a fixed list such as mean, max and count. Safe and easy to test, but limited.
  • Executing code the model writes: very flexible, but it requires a real isolated environment, as we saw in the Permissions and isolation lesson.

For the educational project we start with the first approach. And we never use eval on text coming from the model.

Practical example: the course grades agent

We have a small CSV file of student grades, and some grades are missing. The following code works with the standard library only. The parse_question function plays the model's role in understanding, and returns a structured plan instead of a number:

python
import csv, io, statistics

DATA = '''student,section,midterm
s01,A,78
s02,B,85
s03,B,
s04,A,91
s05,B,66
'''

ROWS = list(csv.DictReader(io.StringIO(DATA)))
OPS = {"mean": statistics.mean, "max": max, "min": min, "count": len}

def aggregate(column, op, where=None):
    if op not in OPS:
        return {"isError": True, "message": f"Unsupported operation: {op}"}
    rows = [r for r in ROWS if not where or all(r[k] == v for k, v in where.items())]
    values = [float(r[column]) for r in rows if r[column].strip()]
    missing = len(rows) - len(values)
    if not values:
        return {"isError": True, "message": "There are no valid values"}
    return {"isError": False, "value": round(OPS[op](values), 2),
            "n": len(values), "missing": missing}

def parse_question(q):
    # In the real agent the model generates this plan in JSON format
    return {"column": "midterm", "op": "mean", "where": {"section": "B"}}

plan = parse_question("What is the average midterm grade for section B?")
res = aggregate(**plan)
print(f"The average is {res['value']} from {res['n']} students, and missing grades: {res['missing']}")

Notice that the result carries the number of values used and the number of missing values. A good agent states this in its answer: "The average is computed from two students, and one grade has not been recorded". This transparency prevents the professor from making a decision based on a misleading number.

Privacy in analysis results

Student data is personal. Put clear rules in the tool, not only in the instructions:

  • Individual rows with student names are shown only to those who have permission.
  • Statistics for a very small group that would reveal a specific individual, such as the average of a section with a single student, are not shown.
  • Every analysis operation is recorded in the trace together with the identity of whoever requested it.

An example of a good answer

If the professor asks "What is the highest grade in section A?", the structured plan is {"column": "midterm", "op": "max", "where": {"section": "A"}}, and the tool returns the value together with the number of rows. But if they ask "Who has the highest grade?", the agent first checks whether the person asking has permission to see names before calling any tool that shows individual rows.

Evaluating the agent

Create evaluation cases in which the correct answer is computed in advance from the data, so grading becomes an exact numerical match. Add edge cases: a column that does not exist, a section with no data, an unsupported operation such as "the geometric median". The success criterion here is that the agent returns a clear message, not an invented number.

Summary

The data analysis agent divides the work: the model understands the question and turns it into a structured plan, and the tools compute on the actual data. Tools with defined operations are safe and easy to test, whereas executing free code needs an isolated environment, and eval is never used on the model's text. A good result states the number of values used and missing. Individuals' privacy is protected by rules inside the tool, and the agent is evaluated with answers computed in advance and edge cases.

Terms

TermEnglishDefinition
Data analysis agentData Analysis AgentAn agent that answers questions about data with computations performed by tools
AggregationAggregationComputing a single value from a set of values, such as the average or the count
Missing valuesMissing ValuesEmpty cells in the data that must be reported, not silently ignored
Structured planStructured PlanRepresenting the question with defined fields such as the column, the operation and the filter
Code executionCode ExecutionRunning code the model writes, which requires strict isolation

Review questions

  1. Why do we not ask the model to compute the average directly from a table in the context?
  2. Compare tools with defined operations and free code execution in terms of safety and flexibility.
  3. Why should the answer state the number of missing values?
  4. Name two privacy-protection rules that are applied inside the analysis tool.

References