AI Data Analyst con Gemini

Build a Python CLI that uses Gemini AI to analyze CSV data and generate insights.

Introduction

30 Second Summary

Every business has spreadsheets full of numbers, but turning that raw data into actual decisions takes hours of manual analysis. What if you could point an AI at your data and get a written report in seconds?

In this project, you will build a command-line Python script that reads a CSV file, crunches the numbers, and uses Gemini to generate written business insights in natural language.

What You'll Build

You run the script, point it at a sales spreadsheet, and within seconds get back a structured analysis that names top performers, spots trends, flags a problem, and makes a concrete recommendation.

By the end of this project, you'll have:

  • A reusable script you can run against any CSV file to get AI-generated business insights printed to your terminal in seconds.
  • Hands-on experience calling the Gemini API from Python using the official Google GenAI SDK. The pattern you learn transfers directly to any LLM provider.
  • First-hand proof that data preprocessing with pandas and structured prompts make the difference between useless AI output and genuinely useful analysis.
  • Secret Mission: An interactive conversation mode where you ask follow-up questions about your data and the AI remembers context across turns.

Are there any prerequisites?

None. This guide walks you through installing Python, getting your API key, and setting up every library from scratch. All you need is a computer running Windows with VS Code installed.

Before We Start

Before we dive in, let's lock in what you're about to build and why it matters. This quick checkpoint helps you connect the project to your own goals, so every step ahead has a clear purpose.

Set Up Your First AI Call

Your environment is set up. Python, the Gemini libraries, and your API key are all ready to go.

Before working with data files, you need to confirm your connection to Gemini actually works. A single API call that returns a response proves your key is valid and shows you the core pattern that every AI app is built on.

In this step, get ready to:
  • Write a Python script that calls the Gemini API.
  • Run the script and see AI-generated text in your terminal.
  • Understand the reusable pattern behind every LLM call.
Create your AI script

Every LLM application follows the same four-part loop: create a client, pick a model, send content, read the response. You are about to write all four parts in a single file.

  • In VS Code, create a new file called ai_analyst.py by clicking File in the top menu bar, then New File.
  • Save it immediately to your Desktop by pressing Ctrl+S, navigating to your Desktop, typing ai_analyst.py as the file name, and clicking Save.
  • Paste the following code into ai_analyst.py:
from google import genai
from google.genai import types

API_KEY = 'your-api-key-here'

client = genai.Client(api_key=API_KEY)

response = client.models.generate_content(
    model='gemini-3.6-flash',
    contents='What is data analysis?',
)
print(response.text)
  • Replace your-api-key-here with the actual Gemini API key you copied in Step 1. Keep the quotes around it.

What does this code do?

  • from google import genai loads the Google GenAI SDK, which handles all communication with the Gemini API.
  • from google.genai import types imports configuration options you will use in later steps.
  • client = genai.Client(api_key=API_KEY) creates an authenticated connection to Gemini using your key.
  • client.models.generate_content() sends your question to the gemini-3.6-flash model and waits for a response.
  • response.text holds the AI-generated answer as a plain string.

Before you run this, what do you think will happen? Will the script print a paragraph about data analysis, or will it error out?

  • Save the file with Ctrl+S.
  • Open a terminal in VS Code by pressing Ctrl+` (backtick key, top-left of your keyboard).
  • Navigate to your Desktop by running:
cd ~/Desktop
  • Run your script by entering:
python ai_analyst.py

You should see a few sentences from Gemini explaining what data analysis is. The exact wording varies each time, but you will get a clear, readable answer.

Seeing an error instead of a response?

  • If you see API key not valid. Please pass a valid API key. then double-check you replaced your-api-key-here with the key you copied from AI Studio. Make sure the key is inside the single quotes.
  • If you see ModuleNotFoundError: No module named 'google' then the library did not install correctly. Run pip install google-genai again and retry.
  • If the command python is not found, try python3 ai_analyst.py instead. Help me fix my Python command

✔️ Awesome, I've got everything!

Great. Make sure you have saved ai_analyst.py before moving on.

ⓧ I'd like to double check the full code

from google import genai
from google.genai import types

API_KEY = 'your-api-key-here'

client = genai.Client(api_key=API_KEY)

response = client.models.generate_content(
    model='gemini-3.6-flash',
    contents='What is data analysis?',
)
print(response.text)
Try a different prompt

The power of this pattern is that you can ask anything. Changing the contents string is all it takes to get a completely different response.

  • In ai_analyst.py, find this line:
    contents='What is data analysis?',
  • Replace the question with something different, so the line looks like this:
    contents='What are three common mistakes in data analysis?',
  • Save and run the script again:
python ai_analyst.py

You get a completely different answer. Same four parts (client, model, contents, response), different result. This is the fundamental loop behind every AI application.

Why does this matter?

Every AI product you have ever used follows this same pattern. ChatGPT, Copilot, and Gemini in the browser are all sending a prompt to a model and reading back response.text. Now you can do the same thing from your own code.

  • Change contents back to 'What is data analysis?' and save the file before moving to the next step.

You have a working AI connection. Next up, you will feed real data into this pipeline and see what Gemini does with raw information.

Load Data and Send It Raw

You have a working AI connection. You can ask Gemini anything, and it answers. Now you want it to analyze real data.

The obvious approach is to dump raw CSV data into the prompt and hope for the best. In this step, you will try exactly that and see what happens when you give an AI a wall of numbers with no structure or context.

In this step, get ready to:
  • Create a sample sales dataset with 20 rows of product data.
  • Send raw CSV data to Gemini and observe the quality of its response.
Create the sample sales dataset

You need some data to analyze. You will build a function that generates a realistic sales CSV with dates, products, quantities, and prices.

  • In VS Code, open ai_analyst.py and replace the entire file content with the following code:
import pandas as pd
from google import genai
from google.genai import types

API_KEY = 'your-api-key-here'

client = genai.Client(api_key=API_KEY)


def create_sample_data():
    """Create a sample sales CSV for analysis."""
    data = {
        'data': [
            '2024-01-15', '2024-01-22', '2024-02-03', '2024-02-18',
            '2024-03-05', '2024-03-12', '2024-03-28', '2024-04-02',
            '2024-04-15', '2024-04-22', '2024-05-01', '2024-05-18',
            '2024-06-03', '2024-06-15', '2024-06-28', '2024-07-05',
            '2024-07-12', '2024-07-25', '2024-08-02', '2024-08-18',
        ],
        'prodotto': [
            'Laptop', 'Mouse', 'Tastiera', 'Monitor', 'Laptop',
            'Cuffie', 'Mouse', 'Laptop', 'Monitor', 'Tastiera',
            'Cuffie', 'Laptop', 'Mouse', 'Monitor', 'Laptop',
            'Tastiera', 'Cuffie', 'Laptop', 'Mouse', 'Monitor',
        ],

What is this data?

This is an Italian sales dataset. The 'data' key holds sale dates spanning January to August 2024. The 'prodotto' key lists product names (Laptop, Mouse, Tastiera/Keyboard, Monitor, Cuffie/Headphones).

  • Directly below the 'prodotto' list (still inside the data dictionary), continue pasting the rest of the function:
        'quantita': [
            2, 15, 8, 3, 4, 10, 20, 1, 5, 12,
            7, 3, 18, 2, 5, 9, 15, 2, 22, 4,
        ],
        'prezzo_unitario': [
            999.99, 29.99, 79.99, 349.99, 999.99,
            59.99, 29.99, 1299.99, 349.99, 79.99,
            59.99, 999.99, 29.99, 449.99, 999.99,
            79.99, 59.99, 1299.99, 29.99, 349.99,
        ],
    }
    df = pd.DataFrame(data)
    df['ricavo'] = df['quantita'] * df['prezzo_unitario']
    df['mese'] = pd.to_datetime(df['data']).dt.month_name()
    df.to_csv('vendite.csv', index=False)
    print('File vendite.csv creato con successo!')
    return df


create_sample_data()

What does this code do?

The 'quantita' key holds quantities sold per transaction. The 'prezzo_unitario' key holds the unit price for each sale.

After defining the data, pd.DataFrame(data) converts it into a table. The code calculates revenue (ricavo = quantity times price), extracts the month name, and saves everything to vendite.csv. The final line calls the function immediately so the file gets created when you run the script.

  • Make sure your API key is in place where it says 'your-api-key-here'.
  • Save ai_analyst.py and run it in the terminal:
python ai_analyst.py

You should see the message File vendite.csv creato con successo! printed in your terminal.

  • Confirm the CSV was created by running:
ls

You should see vendite.csv listed alongside ai_analyst.py.

Don't see vendite.csv?

  • Make sure you saved the file before running. Unsaved changes in VS Code show a dot on the file tab.
  • Check that import pandas as pd is the very first line in your file. If pandas is not imported, you will see a NameError.
  • Verify that the indentation inside the function uses spaces, not tabs. Python is sensitive to mixed indentation.

Still stuck? Help me debug why vendite.csv is not being created when I run ai_analyst.py

Send raw data to Gemini

Your CSV exists. Now you will load it, convert the entire table to a text string, and send it straight to Gemini with a vague prompt. This is the most obvious thing to try.

  • At the bottom of ai_analyst.py, directly below the create_sample_data() call, add the following code:
df = pd.read_csv('vendite.csv')
raw_data = df.to_string()
response = client.models.generate_content(
    model='gemini-3.6-flash',
    contents='Analyze this data: ' + raw_data,
)
print(response.text)

What does this code do?

The pd.read_csv('vendite.csv') line loads the CSV back into a DataFrame. Then df.to_string() converts the entire table into one big text block with all 20 rows.

That raw text string gets concatenated to a minimal prompt ('Analyze this data: ') and sent to Gemini. No structure, no specific question, no context about what the data represents.

  • Save ai_analyst.py.

Before you run this, what kind of analysis do you think Gemini will produce? Will it identify specific business problems, or just describe what the columns contain?

  • Run the script:
python ai_analyst.py

Read the AI's response carefully. The analysis is generic. It restates what the columns are, maybe notes some obvious facts like which product appears most often, but gives no real business insight.

Why is the output so vague?

Gemini received a wall of raw numbers with no context about what matters. It does not know if you care about revenue trends, product performance, or seasonal patterns.

The prompt 'Analyze this data' gives the AI no direction. Without a specific task, role, or output format, the model defaults to surface-level observations. This is the core lesson: garbage in, garbage out.

Seeing an API error instead of a response?

  • If you see a 400 error, your API key may be invalid. Double-check you pasted it correctly in the API_KEY variable.
  • If you see a rate limit error, wait 60 seconds and try again. The free tier has per-minute request limits.

Need more help? Help me fix an API error when sending data to Gemini

✔️ Awesome, I've got everything!

Great. Make sure you have saved ai_analyst.py and that vendite.csv exists in the same folder.

ⓧ I'd like to double check the full code

Scroll up and confirm your file has these sections in order:

  • The import line import pandas as pd at the very top, followed by the genai imports.
  • The API_KEY and client setup.
  • The full create_sample_data() function with all four data keys (data, prodotto, quantita, prezzo_unitario) plus the DataFrame processing lines.
  • The create_sample_data() call on its own line.
  • The load-and-send block: pd.read_csv, df.to_string(), the generate_content call, and print(response.text).

You now have proof that dumping raw data into an AI prompt produces weak, surface-level output. Next up, you will preprocess the data with pandas and craft a structured prompt that gives Gemini specific context, a role, and a clear output format.

Build Smart Analysis with Structured Prompts

In the last step, you sent raw CSV data to Gemini and got back a generic, unfocused response. The AI had no idea what mattered in your data because you gave it everything and asked for nothing specific.

The fix is to preprocess your data into meaningful statistics with pandas, then craft a prompt that gives Gemini context, structure, and a specific task. This is the difference between a useless AI demo and a genuinely useful tool.

In this step, get ready to:
  • Preprocess CSV data into statistics, top products, and monthly trends with pandas.
  • Build a structured prompt with role context and specific output format.
  • Wire everything into a clean main function and run the complete analysis.
Replace the raw data dump with pandas aggregations

Instead of sending all 20 rows as a wall of text, you will compute the statistics that actually matter and send those. Pandas can crunch the numbers down to summaries that give the AI something meaningful to work with.

  • In VS Code, open ai_analyst.py.
  • Find and delete the loose code at the bottom of the file (everything below the create_sample_data function). This is the code that starts with create_sample_data() and ends with print(response.text).
  • Add the following load_and_analyze function below the create_sample_data function by copying this code:
def load_and_analyze(filepath):
    """Load CSV and generate structured statistics."""
    df = pd.read_csv(filepath)

    # Overall numeric summary
    stats = df.describe().to_string()

    # Revenue ranked by product
    top_products = (
        df.groupby('prodotto')['ricavo']
        .sum()
        .sort_values(ascending=False)
        .head(5)
        .to_string()
    )

    # Revenue ranked by month
    monthly_trend = (
        df.groupby('mese')['ricavo']
        .sum()
        .sort_values(ascending=False)
        .to_string()
    )

    return stats, top_products, monthly_trend

What does this code do?

This function takes a CSV file path and returns three digestible summaries instead of the entire raw dataset:

  • df.describe() calculates count, mean, min, max, and standard deviation for every numeric column.
  • groupby('prodotto')['ricavo'].sum() totals revenue per product so you can see which products drive the business.
  • groupby('mese')['ricavo'].sum() totals revenue per month so you can spot trends over time.
  • Save ai_analyst.py.
  • Run the script to confirm there are no syntax errors:
python ai_analyst.py

You should see no output and no errors. The script now only defines functions without calling them, so it exits silently. A clean exit confirms your new function has no typos.

Seeing a SyntaxError or IndentationError?

  • Make sure you deleted ALL of the old loose code at the bottom. Leftover lines like df = pd.read_csv('vendite.csv') sitting outside a function cause errors.
  • Check that every line inside load_and_analyze is indented with 4 spaces. Mixing tabs and spaces causes IndentationError.
  • help me debug a SyntaxError in my ai_analyst.py file
Build the structured prompt and API helper

Now you need two more functions: one to construct a prompt that tells Gemini exactly what role to play and what output format to follow, and one to send that prompt to the API with focused settings.

  • Add the build_prompt function below load_and_analyze by copying this code:
def build_prompt(stats, top_products, monthly_trend):
    """Build a structured analysis prompt."""
    prompt = f"""Sei un analista dati esperto. Analizza questi dati di vendita e fornisci insights utili e concreti.

STATISTICHE GENERALI:
{stats}

TOP PRODOTTI PER RICAVO TOTALE:
{top_products}

RICAVI PER MESE:
{monthly_trend}

Basandoti su questi dati, fornisci:
1. I 3 pattern piu importanti che noti
2. Un possibile problema da investigare
3. Una raccomandazione concreta per il business
"""
    return prompt

Why does prompt structure matter?

In Step 3, you sent raw rows with a vague "Analyze this data" instruction. This prompt does three things differently: it assigns a role ("expert data analyst"), provides preprocessed data in labeled sections, and requests a specific output format (3 patterns, 1 problem, 1 recommendation).

This is prompt engineering in action. The more specific and structured your prompt, the more focused and useful the AI response becomes.

  • Now add the ask_gemini function below build_prompt:
def ask_gemini(prompt):
    """Send prompt to Gemini and return the response text."""
    response = client.models.generate_content(
        model='gemini-3.6-flash',
        contents=prompt,
        config=types.GenerateContentConfig(
            temperature=0.3,
            max_output_tokens=1000,
        ),
    )
    return response.text

What is temperature?

The temperature parameter controls how creative or focused the AI's output is. A value of 0.3 keeps responses tight and analytical. Higher values (like 0.9) make output more varied and creative.

For data analysis you want consistency, not creativity. Low temperature means the AI sticks to patterns it's confident about.

  • Save ai_analyst.py and run it again to confirm no errors:
python ai_analyst.py

Again, no output and no errors. You now have four functions defined. The final piece is a main function to call them all in sequence.

Seeing a NameError or IndentationError?

  • Confirm that build_prompt and ask_gemini are at the top indentation level (not nested inside another function).
  • Check the f-string in build_prompt: it uses triple quotes f"""...""". Make sure you have exactly three quotes at the start and end.
  • help me debug my build_prompt or ask_gemini function
Wire everything together and run the analysis

All the pieces are ready. The main function will orchestrate the full pipeline: create sample data, preprocess it, build the prompt, call Gemini, and print the result.

  • Add the main function and the entry point below ask_gemini:
def main():
    print('=== AI DATA ANALYST ===\n')

    # Create sample data
    create_sample_data()

    # Load and analyze
    stats, top_products, monthly_trend = load_and_analyze('vendite.csv')

    # Build prompt and get AI analysis
    prompt = build_prompt(stats, top_products, monthly_trend)
    print('\nAnalisi in corso...\n')
    analysis = ask_gemini(prompt)

    print('=== ANALISI AI DEI DATI DI VENDITA ===\n')
    print(analysis)


if __name__ == '__main__':
    main()

What does if __name__ == '__main__' do?

This line checks whether the script is being run directly (not imported as a module). When you type python ai_analyst.py, Python sets __name__ to '__main__', so main() runs.

This is a standard Python pattern that keeps your code organized and reusable.

  • Save ai_analyst.py.

Before you run this, think back to Step 3. That version produced vague, generic output. What do you expect this version to produce instead?

  • Run the complete script:
python ai_analyst.py

You should see a structured analysis that identifies specific patterns (like which product dominates revenue), names a concrete problem to investigate, and makes an actionable recommendation. Compare this to Step 3's output. Night and day.

Why is this output so much better?

Three things changed: you gave the AI preprocessed statistics instead of raw rows, you assigned it a specific role ("expert data analyst"), and you told it exactly what output format you want. The data is the same. The difference is entirely in how you prepared and asked.

Getting a 400 error or empty response?

  • Confirm your API key is correct in the API_KEY variable at the top of the file. It should be the key you copied from Google AI Studio.
  • Check your internet connection. The script needs to reach Google's servers.
  • If you see a rate limit error, wait 60 seconds and try again. The free tier has per-minute limits.
  • help me fix a Gemini API error in my data analyst script

✔️ Awesome, I've got everything!

Great. Double check you have saved ai_analyst.py and that the output mentions specific products, revenue figures, and a recommendation.

ⓧ I'd like to double check the full code

Your ai_analyst.py should contain these sections in order. Scroll through your file and confirm each one is present:

  • Imports (pandas, genai, types) and API_KEY + client setup at the top.
  • create_sample_data() function that builds the DataFrame and saves vendite.csv.
  • load_and_analyze(filepath) function that returns stats, top_products, monthly_trend.
  • build_prompt(stats, top_products, monthly_trend) function with the Italian structured prompt.
  • ask_gemini(prompt) function using gemini-3.6-flash and temperature=0.3.
  • main() function that orchestrates everything.
  • if __name__ == '__main__': block at the very bottom.

Your AI Data Analyst is complete. You now have a reusable script that transforms any CSV into structured business intelligence. Next up, the Secret Mission challenges you to make it interactive.

Secret mission

Interactive Data Conversation

Your AI analyst gives you a one-shot report and stops. What if you could ask follow-up questions? Add a conversation loop that maintains context across turns, so you can drill into the data like you're chatting with a real analyst.

Clean Up Your Resources

Clean Up Your Resources

This project runs entirely locally and uses the Gemini API free tier, so there are no ongoing costs. Your API key remains active but costs nothing when not in use.

Resources you used:

  • Project files (ai_analyst.py, vendite.csv).
  • Python packages (google-genai, pandas).
  • Gemini API key in Google AI Studio.

Keep everything running

No action needed. Choose this if you plan to keep experimenting with Gemini or pandas in other projects.

  • Your project files stay where they are.
  • Your installed packages remain available for future Python projects.
  • Your API key stays active and costs nothing on the free tier.

Pause - I'll come back to this later

Nothing is running in the background, so there is nothing to pause. Your files and packages are already idle on disk.

  • Close VS Code when you are done.
  • Everything will be exactly as you left it when you reopen the project.

Delete - I don't want to use this again

Remove all project files, uninstall the packages, and delete your API key.

  • Delete your project files by running this command in the VS Code terminal from the folder where your files are saved:

macOS

rm ai_analyst.py vendite.csv

Windows

del ai_analyst.py, vendite.csv
  • Uninstall the Python packages by running:
pip uninstall google-genai pandas -y

Nice Work!

Nice Work!

You just built a fully functional AI Data Analyst from scratch. You can now point a Python script at any CSV file and get structured, actionable business insights powered by Gemini.

Here's what you accomplished:

  • Installed Python and set up a local development environment with VS Code on Windows.
  • Made your first LLM API call using the Google GenAI SDK and saw Gemini respond in your terminal.
  • Discovered firsthand why raw data dumps produce generic AI output, then fixed it by building a pandas preprocessing pipeline that feeds structured statistics into a crafted prompt.
  • Created a reusable AI Data Analyst script that works with any CSV file and produces patterns, problems, and recommendations.
  • Secret Mission: Added interactive multi-turn conversation so you can ask follow-up questions about your data with full context memory.

Ready to quiz yourself?