Data analysis is becoming more than writing SQL queries, building dashboards, and creating visualisations. With the development of artificial intelligence, it is now possible to build applications that can understand analytical questions, inspect datasets, perform calculations, and explain findings with minimal manual intervention.
Imagine uploading a CSV file and asking:
- What is the average monthly revenue?
- Which product generates the highest sales?
- Are there any missing values in this dataset?
- What were the sales trends over the last six months?
- Which region has the highest customer spending?
Instead of manually writing Python code for every question, an AI-powered application could interpret the request, select the appropriate analytical operation, execute it, and explain the result.
This is the idea behind a Data Analyst Agent.
A data analyst agent is an AI-powered application designed to assist with data analysis tasks. It combines a language model with Python functions, data processing libraries, and other tools to investigate datasets and answer questions.
In this tutorial, you will learn how to build a simple data analyst agent using Python, pandas, and the OpenAI API. You will also learn how tool calling works, how to allow the agent to inspect datasets, and how to generate visualisations.
By the end, you will have a foundation for building an application that can answer natural-language questions about structured data.
1. What Is a Data Analyst Agent?
A data analyst agent is an AI application that can interpret analytical requests and use external tools to complete data-related tasks.
Unlike a traditional chatbot that mainly generates text, an agent can interact with data processing functions, retrieve information, perform calculations, and return results.
For example, a traditional chatbot might explain how to calculate average revenue in Python.
A data analyst agent can receive a dataset, calculate the average revenue, and explain the result.
A typical data analyst agent may perform tasks such as:
- Loading CSV and Excel files.
- Understanding dataset structures.
- Identifying missing values.
- Calculating descriptive statistics.
- Grouping and aggregating records.
- Identifying trends and patterns.
- Creating charts and visualisations.
- Answering questions about business performance.
- Generating summaries and recommendations.
The important distinction is that an agent does not need to perform every calculation itself. It can delegate calculations to reliable Python functions and use an AI model to interpret requests and explain the results.
How does it differ from a traditional data analysis script?
| Traditional Python script | Data analyst agent |
|---|---|
| Usually follows predefined instructions | Interprets natural-language requests |
| Requires users to know available operations | Can select from available analytical tools |
| Often performs a fixed sequence of tasks | Can choose different tools depending on the question |
| May return predefined outputs | Can explain results conversationally |
| Requires code changes for new workflows | Can support new questions using existing tools |
An agent still needs carefully designed functions and constraints. It should not be given unrestricted access to execute arbitrary code or modify business data.
2. Understanding the Architecture of a Data Analyst Agent
Before writing Python code, it is important to understand the components that make the application work.
A basic data analyst agent contains five major components.
2.1 Large language model (LLM)
The language model interprets questions and determines which analytical operation is appropriate.
For example, when a user asks, “Which product generated the highest revenue?”, the model can identify that it needs to group sales by product and calculate the total revenue for each group.
2.2 Data processing engine
This component performs the actual calculations.
Python libraries such as pandas and NumPy are useful because they provide functions for data cleaning, aggregation, statistical analysis, and transformation.
2.3 Tools or functions
Tools give the language model access to operations it cannot perform directly.
Examples include:
- Inspecting a dataset.
- Calculating summary statistics.
- Counting missing values.
- Grouping records.
- Creating visualisations.
The application defines these tools, executes them when requested, and returns their results to the model.
2.4 Memory or conversation state
Conversation state allows the application to maintain relevant information across interactions.
For example, after a user asks about total sales, they may follow up with:
“Break that down by region.”
The application should understand what “that” refers to and continue the analysis using the same dataset.
For a first version, you can maintain a simple conversation history or use the API’s supported conversation-state features.
2.5 User interface
The interface allows users to upload datasets, submit questions, and view results.
You can use Streamlit to build a simple interface without developing a complete frontend application.
Basic architecture
User
|
v
Data Analyst Interface
|
v
AI Language Model
|
v
Tool Selection
|
+----------------------+
| |
v v
Dataset Inspection Data Analysis
| |
+----------+-----------+
|
v
Python / Pandas
|
v
Analysis Results
|
v
AI Interpretation
|
v
User Response
The language model decides which available tool is appropriate, while Python performs the actual data operations.
3. Tools and Libraries Required
We will use a few Python libraries to build the agent.
| Tool | Purpose |
|---|---|
| Python | Main programming language |
| pandas | Data manipulation and analysis |
| NumPy | Numerical operations |
| Matplotlib | Data visualisation |
| OpenAI Python SDK | Connects the application to a language model |
| Streamlit | Optional user interface |
We will use the OpenAI Responses API with function calling. This allows a model to request that your application execute specific Python functions and return their outputs.
For new OpenAI API integrations, the Responses API is the recommended starting point. https://developers.openai.com/api/docs/guides/migrate-to-responses.
4. Set Up Your Python Environment
Start by creating a project directory.
mkdir data-analyst-agent
cd data-analyst-agent
Create a virtual environment:
python -m venv venv
Activate it on Windows:
venv\Scripts\activate
On macOS or Linux:
source venv/bin/activate
Install the required libraries:
pip install pandas numpy matplotlib openai python-dotenv
If you plan to build a web interface, install Streamlit as well:
pip install streamlit
Create a .env file in your project directory:
OPENAI_API_KEY=your_api_key_here
OPENAI_MODEL=gpt-6-astra
Replace the API key placeholder with your actual API key and use a model available to your API account.
Never publish your API key or commit the .env file to a public repository.
5. Prepare a Dataset for Analysis
For this tutorial, we will use a simple sales dataset.
Create a CSV file called sales_data.csv.
It should contain columns such as:
| Date | Product | Region | Units Sold | Revenue |
|---|---|---|---|---|
| 2026-01-05 | Laptop | Lagos | 4 | 3200 |
| 2026-01-08 | Phone | Abuja | 10 | 5000 |
| 2026-01-12 | Tablet | Lagos | 6 | 1800 |
| 2026-02-03 | Laptop | Abuja | 3 | 2400 |
| 2026-02-11 | Phone | Lagos | 8 | 4000 |
| 2026-02-17 | Tablet | Port Harcourt | 5 | 1500 |
| 2026-03-02 | Laptop | Lagos | 5 | 4000 |
| 2026-03-09 | Phone | Port Harcourt | 7 | 3500 |
You can add more rows to make the analysis more interesting.
Save the file inside your project directory.
Our agent will use this dataset to answer questions about revenue, products, regions, and sales performance.
6. Load the Dataset With Pandas
The first function should load the CSV file into a pandas DataFrame.
Create a Python file called agent.py.
import os
import json
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
DATA_PATH = "sales_data.csv"
df = pd.read_csv(DATA_PATH)
print(df.head())
The read_csv() function loads the sales data into a DataFrame.
A DataFrame is a two-dimensional data structure containing rows and columns. It allows us to inspect, clean, transform, and analyse structured information.
Before allowing the AI model to analyse the dataset, we should provide it with basic information about the available columns.
Create a function:
def get_dataset_overview():
return {
"rows": len(df),
"columns": list(df.columns),
"data_types": {
column: str(dtype)
for column, dtype in df.dtypes.items()
},
"missing_values": {
column: int(count)
for column, count in df.isnull().sum().items()
},
"sample_data": df.head(5).to_dict(
orient="records"
)
}
This function provides the model with information about the dataset without sending every row.
That is important because large datasets may exceed practical context limits and unnecessarily increase API costs.
7. Build the Data Analysis Functions
The next step is creating the tools the AI agent can use.
We will start with four operations:
- Dataset overview.
- Descriptive statistics.
- Missing-value analysis.
- Grouped aggregation.
Function 1: Dataset overview
def inspect_dataset():
overview = {
"total_rows": len(df),
"total_columns": len(df.columns),
"column_names": list(df.columns),
"missing_values": {
col: int(value)
for col, value in df.isnull().sum().items()
}
}
return overview
This function helps the agent understand the structure of the dataset.
Function 2: Summary statistics
def get_summary_statistics(column):
if column not in df.columns:
return {"error": "Column not found"}
if not pd.api.types.is_numeric_dtype(df[column]):
return {"error": "Column must be numeric"}
return {
"column": column,
"mean": float(df[column].mean()),
"median": float(df[column].median()),
"minimum": float(df[column].min()),
"maximum": float(df[column].max()),
"standard_deviation": float(
df[column].std()
)
}
This function calculates descriptive statistics for numerical columns.
For example, the agent can use it to answer:
“What is the average revenue?”
Function 3: Missing-value analysis
def get_missing_values():
missing = df.isnull().sum()
return {
column: int(value)
for column, value in missing.items()
}
This function identifies missing values in the dataset.
It can help answer questions such as:
“Are there any incomplete records in this file?”
Function 4: Grouped analysis
def grouped_analysis(column, group_by):
if column not in df.columns:
return {"error": "Analysis column not found"}
if group_by not in df.columns:
return {"error": "Grouping column not found"}
if not pd.api.types.is_numeric_dtype(df[column]):
return {"error": "Analysis column must be numeric"}
result = (
df.groupby(group_by)[column]
.agg(["sum", "mean", "count"])
.reset_index()
)
return result.to_dict(orient="records")
This function groups data by a selected column and calculates the total, average, and number of records.
For example, if the agent receives:
“Calculate total revenue by region.”
It can call the function using Revenue as the numerical column and Region as the grouping column.
8. Connect the Python Functions to an AI Model
This is where the application becomes an agent.
Instead of manually selecting the function for every question, we will provide the model with descriptions of the available tools.
The model can then decide which function should be called.
This process is known as function calling, also called tool calling.
Step 1: Define the available tools
Add the following code to agent.py.
tools = [
{
"type": "function",
"name": "inspect_dataset",
"description": "Return the structure and quality overview of the loaded dataset.",
"parameters": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": False
},
"strict": True
},
{
"type": "function",
"name": "get_summary_statistics",
"description": "Calculate descriptive statistics for a numeric dataset column.",
"parameters": {
"type": "object",
"properties": {
"column": {
"type": "string",
"description": "Name of the numeric column."
}
},
"required": ["column"],
"additionalProperties": False
},
"strict": True
},
{
"type": "function",
"name": "get_missing_values",
"description": "Return the number of missing values in each column.",
"parameters": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": False
},
"strict": True
},
{
"type": "function",
"name": "grouped_analysis",
"description": "Calculate sum, mean, and count for a numeric column grouped by another column.",
"parameters": {
"type": "object",
"properties": {
"column": {
"type": "string"
},
"group_by": {
"type": "string"
}
},
"required": ["column", "group_by"],
"additionalProperties": False
},
"strict": True
}
]
Each function definition tells the model:
- What the function does.
- What information it requires.
- Which arguments it can accept.
- What structure the arguments should follow.
The strict setting helps ensure that function arguments follow the defined schema.
Step 2: Create a function dispatcher
The model can request a function, but your Python application must execute it.
Create a dispatcher that maps the requested function name to the corresponding Python function.
def execute_tool(name, arguments):
if name == "inspect_dataset":
return inspect_dataset()
elif name == "get_summary_statistics":
return get_summary_statistics(
arguments["column"]
)
elif name == "get_missing_values":
return get_missing_values()
elif name == "grouped_analysis":
return grouped_analysis(
arguments["column"],
arguments["group_by"]
)
return {"error": "Unknown function"}
This dispatcher ensures that the model can only access the operations explicitly provided by your application.
It should never use eval() or exec() to execute arbitrary Python code generated by the model.
Step 3: Build the agent interaction loop
Now we can connect everything.
def ask_data_analyst(question):
instructions = """
You are a professional data analyst assistant.
Answer questions using the available dataset.
Use the provided tools whenever calculations
or dataset inspection are required.
Never invent numerical results.
Explain findings clearly and identify any
limitations in the available data.
"""
response = client.responses.create(
model=os.getenv(
"OPENAI_MODEL",
"gpt-6-astra"
),
instructions=instructions,
input=question,
tools=tools
)
while True:
function_calls = [
item for item in response.output
if item.type == "function_call"
]
if not function_calls:
return response.output_text
tool_outputs = []
for call in function_calls:
arguments = json.loads(call.arguments)
result = execute_tool(
call.name,
arguments
)
tool_outputs.append({
"type": "function_call_output",
"call_id": call.call_id,
"output": json.dumps(
result,
default=str
)
})
response = client.responses.create(
model=os.getenv(
"OPENAI_MODEL",
"gpt-6-astra"
),
instructions=instructions,
previous_response_id=response.id,
input=tool_outputs,
tools=tools
)
Let’s understand the process.
- The user submits a question.
- The model receives the question and available tool definitions.
- The model decides whether it needs to call a function.
- Python executes the requested function.
- The result is sent back to the model.
- The model interprets the result and generates a response.
The loop allows the model to request additional tools when necessary.
This is the central mechanism that makes the application agentic rather than simply a chatbot that generates explanations.
The approach follows the Responses API function-calling workflow documented by OpenAI: https://developers.openai.com/api/docs/guides/function-calling.
9. Test Your Data Analyst Agent
We can now test the application with different analytical questions.
Add the following code:
if __name__ == "__main__":
while True:
question = input(
"\nAsk your data analyst: "
)
if question.lower() in ["exit", "quit"]:
break
answer = ask_data_analyst(question)
print("\nAnalysis:")
print(answer)
Run the application:
python agent.py
You can now ask questions such as:
What columns are available in this dataset?
What is the average revenue?
Which region generated the highest total revenue?
Are there missing values in the dataset?
Compare average revenue across products.
The model will select the relevant functions, receive the results, and explain them in natural language.
10. Add Data Visualisation Capabilities
A useful data analyst agent should do more than calculate numerical results.
It should also be able to create visualisations that make patterns easier to understand.
Let’s create a simple chart-generation function.
def create_visualisation(
column,
chart_type="histogram"
):
if column not in df.columns:
return {"error": "Column not found"}
plt.figure(figsize=(10, 6))
if chart_type == "histogram":
if not pd.api.types.is_numeric_dtype(df[column]):
plt.close()
return {
"error": "Histogram requires a numeric column"
}
df[column].dropna().plot(
kind="hist",
bins=20
)
elif chart_type == "bar":
if pd.api.types.is_numeric_dtype(df[column]):
plt.close()
return {
"error": "Bar chart requires a categorical column"
}
df[column].value_counts().plot(
kind="bar"
)
else:
plt.close()
return {"error": "Unsupported chart type"}
plt.title(f"{chart_type.title()} of {column}")
plt.xlabel(column)
plt.ylabel("Frequency")
plt.tight_layout()
filename = "analysis_chart.png"
plt.savefig(filename)
plt.close()
return {
"message": "Chart created successfully",
"file": filename
}
This function supports two chart types:
- Histogram: Useful for understanding the distribution of numerical values.
- Bar chart: Useful for comparing the frequency of categories.
You can register this function as another tool using the same function-calling process.
For a more advanced implementation, you could support scatter plots, line charts, box plots, and correlation heatmaps.
The important thing is to validate the selected columns and chart types before generating a visualisation.
11. Build a Simple Interface With Streamlit
A command-line application is useful for testing, but a graphical interface makes the agent easier to use.
Streamlit allows you to create an interactive application using Python.
Create a file called app.py.
import streamlit as st
from agent import ask_data_analyst
st.set_page_config(
page_title="AI Data Analyst",
page_icon="📊",
layout="wide"
)
st.title("AI Data Analyst Agent")
st.write(
"Upload your dataset and ask questions "
"about your data."
)
uploaded_file = st.file_uploader(
"Upload a CSV file",
type=["csv"]
)
if uploaded_file is not None:
st.success("Dataset uploaded successfully!")
if st.button("Analyse Dataset"):
question = (
"Give me an overview of the dataset, "
"including its structure and missing values."
)
st.write(
ask_data_analyst(question)
)
user_question = st.text_input(
"Ask a question about your data"
)
if st.button("Submit Question"):
if user_question:
st.write(
ask_data_analyst(user_question)
)
This is a basic interface illustration. To make file uploads work correctly, the agent must be updated to load the uploaded file into the active DataFrame instead of always reading the fixed sales_data.csv path.
You should also ensure that the uploaded file is validated before analysis.
Run the interface with:
streamlit run app.py
You now have the foundation for a web-based data analyst application.
12. Security and Best Practices
An AI data analyst agent can access business information and execute operations on datasets. This makes security and validation important parts of its design.
Consider the following practices before using the application with real business data.
1. Restrict available tools
Only expose functions the agent actually needs.
For example, a basic analytical assistant may need permission to inspect datasets and calculate statistics. It does not necessarily need permission to delete tables or update customer records.
2. Validate every function argument
Never assume that a model-generated column name exists.
Check that requested columns are available and that the selected operation is appropriate for the column’s data type.
3. Avoid unrestricted code execution
Do not allow the model to generate Python code and execute it directly using eval() or exec().
Use predefined functions with validated inputs instead.
4. Protect sensitive information
Customer names, email addresses, financial records, and other confidential information should not automatically be sent to an external model.
Apply data minimisation, access controls, masking, and appropriate organisational privacy policies.
5. Handle errors properly
Your application should handle missing columns, unsupported operations, malformed files, API failures, and unexpected data types.
A useful agent should explain when it cannot complete an analysis instead of inventing a result.
6. Verify analytical results
Language models can misunderstand questions or misinterpret numerical outputs.
Perform calculations using reliable Python functions and ensure that the model’s explanation accurately reflects the returned results.
7. Track tool usage
Record which tools were called, which dataset was analysed, and whether an operation succeeded.
This improves debugging, monitoring, and accountability.
8. Set resource limits
Large datasets can consume significant memory and processing time.
Set reasonable file-size limits, query timeouts, and execution boundaries before allowing users to analyse arbitrary files.
13. Ideas for Improving Your Data Analyst Agent
The application we built is a starting point. You can expand it into a more advanced analytical assistant by adding additional capabilities.
| Feature | What it adds |
|---|---|
| SQL integration | Allows the agent to analyse database tables |
| Excel support | Enables analysis of spreadsheet files |
| Automated data cleaning | Identifies and handles selected data quality issues |
| Statistical testing | Performs hypothesis tests and statistical comparisons |
| Forecasting | Estimates future values using time-series models |
| Anomaly detection | Identifies unusual patterns in data |
| Dashboard generation | Creates visual summaries of business performance |
| Report generation | Produces downloadable analytical reports |
| Conversation memory | Supports follow-up questions using previous context |
| Data validation | Checks schema, data types, and quality rules |
You could also connect the application to PostgreSQL, MySQL, or a cloud data warehouse.
For larger projects, consider using an agent framework such as the OpenAI Agents SDK to organise tool definitions, agent instructions, and execution workflows.
The best approach is to add capabilities gradually and test each one against known analytical questions.
Conclusion
Building a data analyst agent with Python demonstrates how artificial intelligence can work alongside traditional data analysis tools.
By combining a language model with pandas, NumPy, Matplotlib, and function calling, you can create an application that understands analytical questions, selects appropriate operations, performs calculations, and explains the results.
The most important part of the architecture is the separation between interpretation and execution. The language model understands what the user wants, while controlled Python functions perform the actual analysis.
You can start with simple operations such as dataset inspection, summary statistics, and grouped analysis before expanding into SQL integration, automated reporting, forecasting, and interactive dashboards.
As AI continues to influence data analytics, understanding how to build applications that combine language models with reliable analytical tools is becoming an increasingly valuable skill for data analysts and data engineers.
Frequently Asked Questions
1. What is a data analyst agent?
A data analyst agent is an AI-powered application that interprets analytical questions and uses tools such as Python functions, databases, and visualisation libraries to analyse data and explain findings.
2. Can I build an AI data analyst using Python?
Yes. Python provides libraries such as pandas, NumPy, Matplotlib, and Streamlit for data processing and application development. You can connect these tools to a language model using an API and function calling.
3. What is the difference between an AI chatbot and a data analyst agent?
An AI chatbot primarily responds to user messages, while a data analyst agent can select and execute predefined tools to inspect datasets, perform calculations, and retrieve analytical results before generating its response.
4. Which Python libraries are useful for building a data analyst agent?
Useful libraries include pandas for data manipulation, NumPy for numerical operations, Matplotlib for visualisation, Streamlit for interfaces, and the OpenAI Python SDK for connecting to a language model.
5. Can a data analyst agent analyse Excel and SQL databases?
Yes. You can extend the agent to read Excel files using pandas, connect to SQL databases using SQLAlchemy or database drivers, and provide controlled functions for querying and analysing the available data.