Yesterday we built a voice assistant around a tight latency budget. Today we build an AI data analyst: a system that takes a question in plain English, pulls the right data, analyzes it, draws charts, and explains what it found, with one firm rule throughout. The numbers come from code, never from the model.

Save this sheet. The rest of this note walks through it section by section.
What We Are Building
The analyst understands natural-language questions about data, analyzes it, creates charts, runs calculations, spots trends and patterns, makes recommendations, and exports reports and dashboards.
This is a general analysis copilot that works over files and databases: a CSV someone uploads, an Excel export from finance, a Google Sheet, a Postgres table. On Day 15 we build a narrower system focused purely on turning questions into safe SQL over a warehouse. Today is about the whole analysis loop: load, explore, compute, chart, and explain.
The core insight is that language models are good at deciding what to compute and bad at computing it. Ask a model to add up a column and you'll get a confident, plausible, wrong number. Ask it to write the pandas code that adds up the column and you get something you can run, check, and show.
System Architecture
data sources (CSV, Excel, DBs, APIs, Sheets)
-> ingestion: load + profile (columns, types, ranges, nulls)
-> processing: clean, transform, prepare
-> AI analysis: LLM plans and writes code; sandbox executes it
-> visualization: charts from the computed results
-> insight generation: LLM explains computed results
-> export & share: report, dashboard, file
-> feedback loop
The LLM touches the pipeline twice: once to write the analysis code and once to explain the results. Between those two calls, everything is deterministic computation.
Key Components
| Component | Job |
|---|---|
| Data connectors | Pandas readers, SQLAlchemy for databases, API clients |
| Data processing | Pandas, NumPy, or Polars for cleaning and transforms |
| LLM | Plans the analysis, writes code, and narrates results |
| Analysis engine | Executes code in a sandbox, plus stats and ML libraries |
| Visualization | Plotly or Matplotlib |
| Memory | Conversation history and dataset context for follow-ups |
| Report generator | PDF, Excel, or a dashboard |
The analysis engine is the component people underestimate. Running model-written code on your server is remote code execution by design. It needs a sandbox: a separate container or process with no network, no secrets, a read-only copy of the data, and CPU and time limits.
Data Flow Step by Step
- The user asks a question in plain language.
- The system works out the question and intent, and which dataset it refers to.
- The data is retrieved and profiled, and the profile goes to the model, not the raw rows.
- The LLM writes analysis code, the sandbox runs it, and errors get fed back for a retry.
- Charts and summary tables are built from the results.
- The LLM writes insights and recommendations from the computed numbers only.
- Reports and dashboards are exported or shared, and feedback is captured.
Step 3 is what makes step 4 work. The model needs to know the shape of the data without seeing all of it:
import pandas as pd
def profile(df: pd.DataFrame, sample_rows: int = 5) -> str:
lines = [f"rows: {len(df)}"]
for col in df.columns:
s = df[col]
info = f"{col}: {s.dtype}, nulls={s.isna().sum()}"
if pd.api.types.is_numeric_dtype(s):
info += f", min={s.min()}, max={s.max()}"
else:
info += f", examples={s.dropna().unique()[:5].tolist()}"
lines.append(info)
lines.append(df.head(sample_rows).to_csv(index=False))
return "\n".join(lines)
ANALYST_PROMPT = (
"You are a data analyst. Write Python using pandas on a DataFrame named df "
"to answer the question. Store the answer table in a variable named result. "
"Do not hardcode numbers you have not computed.\n\nDataset profile:\n{profile}"
)
Sending a profile instead of the full table keeps prompts small, works for millions of rows, and limits how much raw data leaves your environment.
A Minimal Tech Stack
| Layer | Choice |
|---|---|
| Frontend | Next.js, React, or Streamlit |
| Backend | Python with FastAPI |
| LLM | A current OpenAI GPT or Anthropic Claude model |
| Data processing | Pandas, NumPy, Polars |
| Visualization | Plotly, Matplotlib, Seaborn |
| Database | PostgreSQL or MySQL |
| Vector DB | Pinecone or Chroma, for dataset and column descriptions |
| Data sources | CSV, Excel, Google Sheets, APIs, SQL databases |
| Deployment | Docker, Vercel, AWS |
Example Input and Output
The sheet's question: "What are the top 5 products by revenue in the last quarter?" over sales_data.csv with orders, products, revenue, date, region, and quantity.
The output is a ranked table (Product A at $125,430 down to Product E at $54,890), a horizontal bar chart of revenue by product, and a key insight that Product A leads by a clear margin, with a recommendation to consider increasing inventory for Product B.
Look at what each part needs. The table and chart come straight from code. The insight's numbers have to come from code too. If it says what share of total revenue Product A holds, that percentage must be computed over the full dataset, not estimated by a model eyeballing the top five rows. The recommendation is the one part that is genuinely the model's judgment, so label it as a suggestion.
Production Concerns
Evaluation
Build a set of questions with known answers over a fixed dataset, computed by a human analyst. Check two things separately: whether the code produced the right numbers, and whether the narrative stated them faithfully. A useful automatic check is to extract every number from the narrative and confirm it appears in the computed results.
Cost
Most cost is in code generation retries. Feed execution errors back once or twice, then stop and show the error rather than looping. Cache profiles per dataset version so you aren't re-profiling on every question.
Failure Modes
- Hallucinated numbers. The model writes a figure in the narrative that no code produced. Enforce the number check above.
- Ambiguous questions. "Last quarter" depends on fiscal calendars, and "revenue" might be gross or net. Ask a clarifying question or state the assumption in the output.
- Dirty data. Mixed date formats, currency strings, and duplicate rows quietly break aggregates. Profile first, clean explicitly, and show which cleaning steps ran.
- Unsafe code. Model-written code that reads files, opens sockets, or runs forever. Sandbox everything.
- Misleading charts. Truncated axes and odd scales. Use chart templates with sane defaults instead of fully free-form plotting code.
Extensions Worth Adding
From the sheet: predictive analytics and forecasting, anomaly detection, machine learning models, automated data cleaning, real-time analysis, multi-user dashboards, data alerts, and integration with BI tools. Alerts are a good early win, turning a one-off question into a scheduled check that pings you when a metric moves.
Key Takeaways
- The LLM decides what to compute and explains the result. Code computes it.
- Send a data profile to the model, not raw data. It scales better and leaks less.
- Run model-written code in a sandbox with no network, no secrets, and hard limits.
- Verify every number in the narrative against the computed results.
FAQs
Can't the model just read a small CSV and answer?
For tiny tables it'll often be right, but you can't tell when it's wrong. Code execution gives you an answer you can check and reproduce.
How is this different from text-to-SQL?
Text-to-SQL is one tool inside it, focused on safe queries over a warehouse. We cover it on Day 15. The analyst also cleans data, runs statistics, builds charts, and writes the narrative.
Do I need a vector database here?
Only when you have many datasets or tables and need to find the right one for a question. Embedding column and table descriptions helps with that routing.
Up Next
Tomorrow is Day 9, the AI Code Reviewer System: a reviewer that reads pull request diffs with repository context, combines static analysis with LLM judgment, and posts focused comments back to the PR. If your team wants an analysis assistant over your own data, let's talk.




Letters to the editor
No letters yet. Questions and counterpoints are welcome.