Suppose we want to find the region with the highest revenue. In Pandas, we can group the orders by region and sum the revenue. How can we let someone run that calculation just by asking a question?
In this tutorial, I’ll show you how to build a simple data analyst that runs on your machine. We’ll use a local language model to understand the question and pandas to do the calculation. Then we’ll create a Streamlit page to try it out.
Let’s get into it.
Setting Up Python and Ollama
Let’s start by installing Ollama to run the model locally. Open Ollama after installation. On Linux, use ollama serve in a separate terminal if it isn’t already running.
For this example, I’m using Gemma 3 1B. We can download the model and list the available models with the following commands.
ollama pull gemma3:1b
ollama listIf the download is complete, you should see gemma3:1b in the list as shown below.

Next, create a folder for the application. I used Python 3.11 and saved the dependencies in a file called requirements.txt.
pandas==2.2.3
pydantic==2.12.4
streamlit==1.53.0Open a terminal in the project folder. If you’re using Windows PowerShell, run the following commands to create a virtual environment and install the packages.
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txtOn macOS or Linux, run these commands.
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txtOllama’s source code uses the MIT license. The model weights have their own Gemma Terms of Use.
Building the Data Analyst
We’ll build the application in one Python file. Create app.py in the project folder. Copy the Python blocks into that file in the order they appear and leave a blank line between them.
Preparing the Data
For the dataset, I’m using fictional sales orders. We can use the same table to compare revenue by region or see which products sold the most units. Let’s create it with the following code.
import json
import os
from datetime import date, timedelta
from random import Random
from typing import Literal
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
import pandas as pd
import streamlit as st
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
MODEL = os.getenv("OLLAMA_MODEL", "gemma3:1b")
OLLAMA_CHAT_URL = os.getenv("OLLAMA_URL", "http://127.0.0.1:11434").rstrip("/") + "/api/chat"
PRODUCTS = [
("Wireless Mouse", "Electronics", 29),
("Mechanical Keyboard", "Electronics", 89),
("USB-C Hub", "Electronics", 49),
("Desk Lamp", "Home Office", 39),
("Laptop Stand", "Home Office", 55),
("Desk Mat", "Home Office", 22),
("Notebook Set", "Stationery", 15),
("Gel Pen Pack", "Stationery", 10),
]
def make_orders(count: int = 800) -> pd.DataFrame:
rng = Random(42)
customers = {
f"C{i:03}": (
rng.choices(["Consumer", "Small Business", "Enterprise"], [6, 3, 1])[0],
rng.choices(["North", "South", "East", "West"], [4, 3, 2, 1])[0],
)
for i in range(1, 121)
}
rows = []
for order_number in range(1, count + 1):
customer_id = rng.choice(list(customers))
segment, region = customers[customer_id]
product, category, unit_price = rng.choice(PRODUCTS)
quantity = rng.randint(1, 5 if segment == "Enterprise" else 3)
rows.append({
"order_id": f"O{order_number:04}",
"order_date": date(2026, 1, 1) + timedelta(days=rng.randrange(181)),
"customer_id": customer_id,
"customer_segment": segment,
"region": region,
"product": product,
"product_category": category,
"quantity": quantity,
"unit_price": unit_price,
"revenue": quantity * unit_price,
})
orders = pd.DataFrame(rows)
orders["order_date"] = pd.to_datetime(orders["order_date"])
return orders.sort_values("order_date", kind="stable").reset_index(drop=True)The make_orders() function gives us the same orders every time we run it. Here’s a preview of the first six rows.
Each row represents one order. That’s why taking the mean of revenue gives us the average order value. If your own dataset has several rows per order, sum the revenue by order ID before taking the mean.
Using the Model to Plan the Analysis
Let’s use the revenue question from the introduction. To find the region with the highest revenue, we need to sum revenue for each region. We then sort the totals from highest to lowest and keep the first row. Those are the instructions we want the model to return.
We can describe the instructions with a Pydantic class called AnalysisPlan. It defines the fields we expect and the values each field accepts. For example, we can group by region or product and use either sum or mean as the aggregation. Add the following class to app.py.
GroupColumn = Literal["region", "product", "product_category", "customer_id", "customer_segment", "month"]
Metric = Literal["revenue", "quantity"]
class AnalysisPlan(BaseModel):
model_config = ConfigDict(extra="forbid")
operation: Literal["groupby", "unsupported"]
group_by: GroupColumn | None = None
metric: Metric | None = None
aggregation: Literal["sum", "mean"] | None = None
sort: Literal["ascending", "descending"] = "descending"
limit: int | None = Field(default=None, ge=1, le=50, strict=True)
chart: Literal["none", "bar", "line"] = "none"
@model_validator(mode="after")
def validate_plan(self):
if self.operation == "unsupported":
return self
if self.group_by is None or self.metric is None or self.aggregation is None:
raise ValueError("A grouped analysis needs a column, metric, and aggregation.")
if self.chart == "line" and self.group_by != "month":
raise ValueError("Line charts require monthly data.")
if self.group_by == "month" and (self.limit is not None or self.sort != "ascending"):
raise ValueError("Monthly results must include all months in chronological order.")
return selfWe also need to tell the model how to interpret the question. Take “What are the best-selling products?” That could mean units sold or revenue. In this example we’ll use units sold unless the question specifies revenue. Add the prompt and make_plan() below the class.
SYSTEM_PROMPT = """
You map a sales question to a JSON plan. Return JSON only.
Supported task: group by one column and sum or average one metric.
Grouping columns: region, product, product_category, customer_id, customer_segment, month.
Metrics: revenue (USD), quantity (units sold). Every row is one order.
Average order value means mean of revenue. Best-selling means sum of quantity
unless the question explicitly says by revenue. Use sum for total sales or revenue.
Use descending for highest/top and ascending for lowest/bottom.
Set limit only for a requested ranking count. Highest or lowest alone means limit 1.
Use null for limit when the user asks for each group or does not ask for a ranking.
For monthly questions use group_by month, sort ascending, and set limit to null.
Use chart line for a requested monthly chart, bar for another requested chart,
and none if a chart was not requested. Use operation unsupported for forecasts,
filters (including date ranges), multiple grouping columns, and unsupported metrics.
Examples:
Which region generates the highest revenue?
{"operation":"groupby","group_by":"region","metric":"revenue","aggregation":"sum","sort":"descending","limit":1,"chart":"none"}
What are the five best-selling products by units sold?
{"operation":"groupby","group_by":"product","metric":"quantity","aggregation":"sum","sort":"descending","limit":5,"chart":"none"}
What is the average order value for each customer segment?
{"operation":"groupby","group_by":"customer_segment","metric":"revenue","aggregation":"mean","sort":"descending","limit":null,"chart":"none"}
Show me a chart of monthly revenue.
{"operation":"groupby","group_by":"month","metric":"revenue","aggregation":"sum","sort":"ascending","limit":null,"chart":"line"}
Predict revenue for next year.
{"operation":"unsupported"}
""".strip()
def make_plan(question: str) -> AnalysisPlan:
request_body = {
"model": MODEL,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": question},
],
"format": AnalysisPlan.model_json_schema(),
"stream": False,
"think": False,
"options": {"temperature": 0, "num_ctx": 4096, "num_predict": 256},
}
request = Request(
OLLAMA_CHAT_URL,
data=json.dumps(request_body).encode("utf-8"),
headers={"Content-Type": "application/json"},
)
try:
with urlopen(request, timeout=90) as response:
payload = json.load(response)
except HTTPError as error:
if error.code == 404:
raise RuntimeError(f"The model is unavailable. Run ollama pull {MODEL}.") from error
raise RuntimeError(f"Ollama returned HTTP {error.code}.") from error
except (URLError, TimeoutError) as error:
raise RuntimeError("Start Ollama and try again. A cold model can take longer to load.") from error
return AnalysisPlan.model_validate_json(payload["message"]["content"])The function sends the prompt and question to Ollama’s chat endpoint. We pass our schema with the request so the model can return the plan as JSON. Ollama calls this structured output. The sales rows stay in our pandas DataFrame.
Here’s what Gemma returned when I asked which region generates the highest revenue.
We can see that group_by is region and aggregation is sum. The limit of 1 means we’ll get one region back. Pydantic can reject a column that our app doesn’t support. The model can still select a valid metric that answers a different question. We’ll display the plan in the app so we can see what it chose.
Calculating the Result With pandas
Now that we have the plan, we can use it to calculate the result. Add the analyze() function below make_plan(). It reads the grouping column and aggregation from the plan and passes them to pandas groupby().
def analyze(orders: pd.DataFrame, plan: AnalysisPlan) -> pd.DataFrame:
if plan.operation == "unsupported":
return pd.DataFrame()
group_column = plan.group_by
if group_column == "month":
orders = orders.assign(month=orders["order_date"].dt.to_period("M").dt.to_timestamp())
if group_column not in orders or plan.metric not in orders:
raise ValueError("The requested grouping column or metric is missing.")
result = (
orders.groupby(group_column, as_index=False)[plan.metric]
.agg(plan.aggregation)
)
if group_column == "month":
return result.sort_values("month").reset_index(drop=True)
result = result.sort_values(
[plan.metric, group_column],
ascending=[plan.sort == "ascending", True],
)
if plan.limit is not None:
result = result.head(plan.limit)
return result.reset_index(drop=True)We can use this same function for a question about average order value. The plan would group by customer_segment and take the mean of revenue. Monthly totals work in much the same way. We just need to get the month from order_date before grouping.
Creating the Streamlit Interface
Let’s create a function to display the result. When we call show_result(), it gets a plan from the model and shows it in the Model instructions panel. Then it runs the calculation and displays the table.
EXAMPLES = [
"Which region generates the highest revenue?",
"What are the five best-selling products by units sold?",
"What is the average order value for each customer segment?",
"Show me a chart of monthly revenue.",
]
def show_result(orders: pd.DataFrame, question: str) -> None:
try:
plan = make_plan(question)
with st.expander("Model instructions"):
st.json(plan.model_dump(exclude_none=True))
if plan.operation == "unsupported":
st.info("Try a grouped total, an average, a top-N ranking, or a monthly trend.")
return
result = analyze(orders, plan)
except ValidationError:
st.error("The model returned an invalid plan. Try naming the metric and grouping column.")
return
except (RuntimeError, ValueError, KeyError) as error:
st.error(str(error))
return
if result.empty:
st.info("There are no results for this question.")
return
display = result.copy()
if plan.group_by == "month":
display["month"] = display["month"].dt.strftime("%Y-%m")
if plan.chart == "line":
st.line_chart(
display, x="month", y=plan.metric, x_label="Month",
y_label="Revenue (USD)" if plan.metric == "revenue" else "Units",
color="#2E75B6", height=320,
)
elif plan.chart == "bar":
st.bar_chart(display, x=plan.group_by, y=plan.metric, color="#2E75B6")
number_format = (
"$%.2f" if plan.metric == "revenue"
else "%.2f" if plan.aggregation == "mean"
else "%d"
)
st.dataframe(
display,
hide_index=True,
width="stretch",
column_config={plan.metric: st.column_config.NumberColumn(plan.metric, format=number_format)},
)If the plan asks for a chart, Streamlit uses the same DataFrame as the table. This lets us see the pattern in the chart and read the exact values in the table.
Now add the code for the page itself. The question field can take an example from the menu or a question you type in. Clicking Analyze passes the question to show_result().
def main() -> None:
st.set_page_config(page_title="AI-Powered Data Analyst", page_icon="📊", layout="wide")
st.markdown(
"<style>h1,h2,h3{color:#1F3A5F!important}</style>",
unsafe_allow_html=True,
)
st.title("AI-Powered Data Analyst")
st.caption(f"800 synthetic e-commerce orders · January–June 2026 · {MODEL}")
orders = make_orders()
st.selectbox("Example questions", options=["Write my own question", *EXAMPLES], key="example")
question = st.text_input(
"Ask a question about the orders",
value="" if st.session_state.example == "Write my own question" else st.session_state.example,
key=f"question_{st.session_state.example}",
max_chars=400,
placeholder="Which region generates the highest revenue?",
)
if st.button("Analyze", type="primary"):
if question.strip():
with st.spinner("Analyzing the orders…"):
show_result(orders, question.strip())
else:
st.info("Enter a question or pick one of the examples.")
with st.expander("Dataset preview", expanded=True):
st.dataframe(
orders.head(6),
hide_index=True,
width="stretch",
column_config={"order_date": st.column_config.DateColumn(format="YYYY-MM-DD")},
)
if __name__ == "__main__":
main()Running the Data Analyst
With Ollama running, open a terminal in the project folder and start Streamlit. Use the following command on Windows PowerShell.
.\.venv\Scripts\python.exe -m streamlit run app.py --theme.base light --theme.primaryColor "#2E75B6"On macOS or Linux, use this command instead.
.venv/bin/python -m streamlit run app.py --theme.base light --theme.primaryColor "#2E75B6"Open the local URL printed in the terminal. You should see the question field and a preview of the sales data.
Let’s try “Which region generates the highest revenue?” In my run, the app returned North with $25,898 in revenue. You can open Model instructions to see the plan behind that result.

What happens if we ask “What is the total revenue by region?” We’re still summing revenue. This time we want every region, so the model should leave the limit empty.
Let’s try one more example. Ask “Show me a chart of monthly revenue.” The app returns a line chart and a table of monthly totals.
Conclusion
We built a simple AI-powered data analyst in Python. The local model turns a question into instructions. pandas carries out the calculation, and Streamlit gives us a place to ask the question and see the result.
You can use the same approach with your own CSV. Replace make_orders() with a function that reads your file. Then update the schema and prompt to match your columns. Start with a question you already know how to answer in pandas and compare the results.
Continue Learning with Non-Brand Data
If you’d like help choosing your next project, working through a technical challenge, or deciding what to learn next, I offer 1-on-1 mentorship through MentorCruise. We can use this roadmap to plan your next step based on what you already know and what you want to build.






