Chat with Netflix Data and Auto-Generate Charts Using AI (No Coding Needed)

Build a Smart Netflix Dashboard That Answers You with Charts

What if you could ask a dataset a question—and get back a chart? In this beginner-friendly tutorial, you’ll create a Streamlit app that does exactly that:
  • Loads Netflix data into your browser
  • Lets you ask questions using plain English
  • Uses AI to answer your question and dynamically generate a chart
No coding experience? No problem. Follow these steps and you'll have it running locally in minutes.

🧰 What You’ll Need

  1. Python installed from python.org
  2. Netflix dataset from Kaggle - Netflix Shows
  3. A free OpenAI API key from platform.openai.com
    You may need to pre-purchase credits to use the API in this sample app.

πŸ“ Setup Instructions

  1. Create a folder called netflix-ai-dashboard
  2. Place netflix_titles.csv inside that folder
  3. Install the required Python libraries:
    pip install streamlit pandas matplotlib openai

πŸ“„ Full App Code (app.py)

Create a new file called app.py inside your folder and paste this entire code:
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
from openai import OpenAI
import io
import re
import textwrap

st.set_page_config(page_title="Netflix AI Chart Assistant", layout="centered")
st.title("πŸ“Ί Ask AI to Analyze Netflix Data & Generate Charts")

# Load Netflix dataset
@st.cache_data
def load_data():
    df = pd.read_csv("netflix_titles.csv")
    df.dropna(subset=["type", "release_year", "country"], inplace=True)
    return df

df = load_data()

# Dataset preview
with st.expander("πŸ” Preview Netflix Data"):
    st.dataframe(df.head(20))

# User inputs
st.subheader("πŸ€– Ask AI About the Netflix Data")

api_key = st.text_input("Enter your OpenAI API Key", type="password")
st.caption("Don't have a key? Get one at [platform.openai.com](https://platform.openai.com/account/api-keys)")
st.markdown(":warning: **Note:** If you see a quota or billing error, you may need to [add credits to your OpenAI account](https://platform.openai.com/account/billing).")

question = st.text_area("Ask a question about the dataset", placeholder="e.g. What countries produce the most Netflix content?")

# Ask AI and Generate Chart
if st.button("Ask AI and Generate Chart"):
    if not api_key or not question:
        st.warning("Please enter both your API key and a question.")
    else:
        with st.spinner("Asking AI..."):
            try:
                client = OpenAI(api_key=api_key)

                # Limit data sent to AI for performance
                data_csv = df.head(100).to_csv(index=False)

                # Compose the prompt
                prompt = f"""
You are a helpful data analyst. Based on the Netflix data sample below:

{data_csv}

Answer this question: "{question}"

Your response should include:
1. A short written answer
2. A markdown summary table (max 10 rows)
3. A Python matplotlib code block to generate a relevant chart using the sample data (assume it's in a DataFrame called df)

Only include one chart. Return the Python code as a single code block.
"""

                response = client.chat.completions.create(
                    model="gpt-3.5-turbo",
                    messages=[{"role": "user", "content": prompt}],
                    temperature=0.5
                )

                reply = response.choices[0].message.content
                st.markdown("### 🧠 AI Analysis:")
                st.markdown(reply)

                # Extract and execute chart code
                code_blocks = re.findall(r"```(?:python)?\n(.*?)```", reply, re.DOTALL)
                if code_blocks:
                    st.markdown("### πŸ“Š AI-Generated Chart:")
                    try:
                        exec_globals = {"df": df.head(100), "plt": plt}
                        exec(textwrap.dedent(code_blocks[0]), exec_globals)
                        st.pyplot(plt)
                        plt.clf()
                    except Exception as chart_error:
                        st.error(f"Chart code could not be run: {chart_error}")
                else:
                    st.warning("No Python chart code found in AI's response.")
            except Exception as e:
                st.error(f"Something went wrong: {e}")

▶️ Run the App

In your terminal, navigate to the project folder and run:
streamlit run app.py
Then visit http://localhost:8501 in your browser.

🧠 Sample Questions to Try

  • What are the top 5 genres in this sample?
  • Which countries produce the most Netflix content?
  • How many movies vs TV shows are there?
  • Can you plot releases by year?

πŸ› ️ Best Practices

  • Send only 50–100 rows to the AI for speed and cost efficiency
  • Always wrap AI-generated Python in a try block
  • Don’t hardcode or share your API key—treat it like a password

πŸŽ‰ What You Built

You now have an AI-powered data assistant that:
  • Loads and filters real Netflix data
  • Answers questions in plain English
  • Generates custom summary tables and charts from your data
This is a great foundation for dashboards, research assistants, or even business tools!

What’s the best chart AI made for you? Share it below!

Comments

Popular posts from this blog

Turn Prompts into Reusable Templates: Build Your AI Toolkit

Create Your First AI Assistant Using Prompt Engineering

Beginner's Guide to Prompt Engineering