Templates › Customer feedback with Cortex AI

Customer feedback sentiment analysis with Snowflake Cortex AI (Streamlit template)

Score reviews, tickets or survey answers with Snowflake Cortex AI, sentiment, topics and an AI summary of the complaints. A free Streamlit template.

General purposeStreamlitRuns in Snowflake167 lines of Python
Live demo: the real app, running in your browser on generated sample data

Click Run to start the app here.

The first start downloads Python for the browser (about 30 MB) and takes 10–30 seconds.

What it answers

What are customers unhappy about, and is it getting better or worse? This template scores every comment (reviews, support tickets, survey answers) with Snowflake Cortex AI inside your account: a sentiment from -1 to +1 with SNOWFLAKE.CORTEX.SENTIMENT, and a topic from a list you choose with AI_CLASSIFY.

It shows the weekly trend, which topics draw the complaints, which sources are most negative, and the latest negative comments. One click summarises the last 30 days' complaints with AI_SUMMARIZE_AGG.

What's in it

  • Sentiment of every comment, scored in Snowflake with SNOWFLAKE.CORTEX.SENTIMENT
  • Topics assigned with AI_CLASSIFY from a list you set
  • Weekly sentiment trend, topics by sentiment, sentiment by source
  • The latest negative comments, filterable by topic and source
  • A one-click AI summary of the last 30 days' complaints (AI_SUMMARIZE_AGG)

The data it needs

Feedback

One row per comment (review, support ticket, survey answer) with its date and where it came from. The query scores sentiment and topic with Cortex AI; the role needs SNOWFLAKE.CORTEX_USER.

ColumnTypeAlso matches columns named
FEEDBACK_DATEdatedate, created_at, review_date, submitted_at, ticket_date, response_date
SOURCEtextchannel, platform, origin, survey, app_store, site
FEEDBACK_TEXTtextcomment, review, text, body, message, feedback, response, description

The query it starts from (FEEDBACK_SQL):

SELECT FEEDBACK_DATE, SOURCE, FEEDBACK_TEXT,
       SNOWFLAKE.CORTEX.SENTIMENT(FEEDBACK_TEXT) AS SENTIMENT,
       AI_CLASSIFY(FEEDBACK_TEXT, ['Delivery', 'Price', 'Product quality', 'Support', 'Ease of use']):labels[0]::STRING AS TOPIC
FROM YOUR_DATABASE.YOUR_SCHEMA.FEEDBACK
WHERE FEEDBACK_DATE >= DATEADD(day, -90, CURRENT_DATE())
ORDER BY FEEDBACK_DATE DESC
LIMIT 5000

Using it on your data

Point the query at your table with a date, a source and the comment text, and change the topic list in the query to the ones that matter to you. Cortex bills per token, so the query keeps the last 90 days and at most 5,000 comments, and the results are cached for an hour. The role needs the database role SNOWFLAKE.CORTEX_USER.

In StreamGen you don't edit any of this by hand: the agent looks at your tables, matches columns by name and type (including the names above), shows you the mapping, and checks the app on your live data before you deploy it.

Three ways to use it

Try it in StreamGen

Two hours on sample data in a ready-made Snowflake sandbox. No sign-up, nothing to install.

Start the 2-hour try

Install in your Snowflake

StreamGen is a Snowflake Native App: it runs inside your account, and your data stays there.

Open the Marketplace listing

Copy the code

It's a plain Streamlit app. Paste it into Streamlit in Snowflake, set DEMO = False and point the query at your table.

Show the code

The code

All of it, as it runs in the demo above. The data section at the top is the only part that changes for your tables.

Show all 167 lines
"""Customer feedback with Cortex AI — sentiment and topics of reviews, tickets
or survey answers, scored in Snowflake, with an AI summary of the complaints."""

import numpy as np
import pandas as pd
import plotly.express as px
import streamlit as st

st.set_page_config(page_title="Customer feedback", layout="wide")

# ── DATA ──────────────────────────────────────────────────────────────────────
# DEMO = True runs on generated comments with ready-made scores. Set
# DEMO = False to score your own table with Cortex AI in Snowflake (the role
# needs the database role SNOWFLAKE.CORTEX_USER; Cortex bills per token, so
# the query keeps the last 90 days and at most 5,000 comments).
DEMO = True
FEEDBACK_SQL = """
SELECT FEEDBACK_DATE, SOURCE, FEEDBACK_TEXT,
       SNOWFLAKE.CORTEX.SENTIMENT(FEEDBACK_TEXT) AS SENTIMENT,
       AI_CLASSIFY(FEEDBACK_TEXT, ['Delivery', 'Price', 'Product quality', 'Support', 'Ease of use']):labels[0]::STRING AS TOPIC
FROM {{DATABASE}}.{{SCHEMA}}.FEEDBACK
WHERE FEEDBACK_DATE >= DATEADD(day, -90, CURRENT_DATE())
ORDER BY FEEDBACK_DATE DESC
LIMIT 5000
"""
SUMMARY_SQL = """
SELECT AI_SUMMARIZE_AGG(FEEDBACK_TEXT)
FROM {{DATABASE}}.{{SCHEMA}}.FEEDBACK
WHERE FEEDBACK_DATE >= DATEADD(day, -30, CURRENT_DATE())
  AND SNOWFLAKE.CORTEX.SENTIMENT(FEEDBACK_TEXT) < -0.3
"""
# ──────────────────────────────────────────────────────────────────────────────

COLORS = {"Negative": "#d62728", "Neutral": "#9aa5b1", "Positive": "#2ca02c"}
PHRASES = {
    "Delivery": (["Parcel arrived a week late and nobody told me.", "Courier left it in the rain, box soaked."],
                 ["Arrived a day early, well packed.", "Tracking was spot on, delivery on time."]),
    "Price": (["Too expensive for what you get.", "Shipping costs doubled the price."],
              ["Fair price for the quality.", "Great value, cheaper than the shop down the road."]),
    "Product quality": (["Broke after two weeks.", "The zip came off on the first day."],
                        ["Feels solid and well made.", "Still works perfectly after months of daily use."]),
    "Support": (["Waited 40 minutes on the phone, then got cut off.", "Three emails and still no answer."],
                ["Support sorted it in five minutes, thank you.", "Friendly agent, refund the same day."]),
    "Ease of use": (["The app keeps logging me out.", "Setup instructions make no sense."],
                    ["Set up in two minutes, very easy.", "The new app is much simpler to use."]),
}
DEMO_SUMMARY = ("Most complaints in the last 30 days are about late or damaged deliveries and slow support replies: "
                "customers mention parcels arriving days late without notice and waiting a long time on the phone. "
                "A smaller group finds shipping costs too high, and a few report products breaking within weeks.")


def demo_feedback() -> pd.DataFrame:
    rng = np.random.default_rng(5)
    n = 1400
    topics = rng.choice(list(PHRASES), n, p=[0.3, 0.15, 0.2, 0.25, 0.1])
    days = pd.Timestamp.today().normalize() - pd.to_timedelta(rng.integers(0, 90, n), unit="D")
    trend = (days - days.min()).days.to_numpy() / 90          # complaints about delivery grow over time
    rows = []
    for t, d, tr in zip(topics, days, trend):
        p_neg = 0.35 + (0.25 * tr if t == "Delivery" else 0)
        negative = rng.random() < p_neg
        text = rng.choice(PHRASES[t][0 if negative else 1])
        score = rng.uniform(-0.95, -0.35) if negative else rng.uniform(0.2, 0.95)
        if rng.random() < 0.15:
            score = rng.uniform(-0.25, 0.25)
        rows.append((d, rng.choice(["App store", "Website", "Support tickets", "Survey"]), text, round(score, 3), t))
    return pd.DataFrame(rows, columns=["FEEDBACK_DATE", "SOURCE", "FEEDBACK_TEXT", "SENTIMENT", "TOPIC"])


@st.cache_data(ttl=3600, show_spinner="Scoring feedback with Cortex AI…")
def load_feedback() -> pd.DataFrame:
    if DEMO:
        df = demo_feedback()
    else:
        from snowflake.snowpark.context import get_active_session
        df = get_active_session().sql(FEEDBACK_SQL).to_pandas()
        df.columns = [c.upper() for c in df.columns]
    df["FEEDBACK_DATE"] = pd.to_datetime(df["FEEDBACK_DATE"], errors="coerce")
    df["SENTIMENT"] = pd.to_numeric(df["SENTIMENT"], errors="coerce").fillna(0.0)
    for c in ("SOURCE", "TOPIC", "FEEDBACK_TEXT"):
        df[c] = df[c].fillna("Unknown").astype(str).str.strip('"')
    df["MOOD"] = np.select([df["SENTIMENT"] < -0.3, df["SENTIMENT"] > 0.3], ["Negative", "Positive"], default="Neutral")
    return df.dropna(subset=["FEEDBACK_DATE"])


@st.cache_data(ttl=3600, show_spinner="Summarising with Cortex AI…")
def complaint_summary() -> str:
    if DEMO:
        return DEMO_SUMMARY
    from snowflake.snowpark.context import get_active_session
    rows = get_active_session().sql(SUMMARY_SQL).collect()
    return str(rows[0][0]) if rows and rows[0][0] else "No negative feedback in the last 30 days."


st.title("Customer feedback")
if DEMO:
    st.caption("Showing generated comments with ready-made scores — set DEMO = False in the DATA section to score your own with Cortex AI.")

try:
    data = load_feedback()
except Exception as e:
    st.error(f"Could not load feedback: {e}. Scoring needs the database role SNOWFLAKE.CORTEX_USER and Cortex AI in your region.")
    st.stop()
if data.empty:
    st.info("No feedback in the last 90 days.")
    st.stop()

with st.sidebar:
    st.header("Filters")
    sources = st.multiselect("Source", sorted(data["SOURCE"].unique()))
    topics = st.multiselect("Topic", sorted(data["TOPIC"].unique()))

view = data
if sources:
    view = view[view["SOURCE"].isin(sources)]
if topics:
    view = view[view["TOPIC"].isin(topics)]
if view.empty:
    st.info("Nothing matches the filters.")
    st.stop()

recent = view[view["FEEDBACK_DATE"] > view["FEEDBACK_DATE"].max() - pd.Timedelta(days=30)]
earlier = view[view["FEEDBACK_DATE"] <= view["FEEDBACK_DATE"].max() - pd.Timedelta(days=30)]
neg_recent = (recent["MOOD"] == "Negative").mean() if len(recent) else 0
neg_earlier = (earlier["MOOD"] == "Negative").mean() if len(earlier) else None
k = st.columns(4)
k[0].metric("Comments", f"{len(view):,}")
k[1].metric("Average sentiment", f"{view['SENTIMENT'].mean():+.2f}", help="From -1 (very negative) to +1 (very positive).")
k[2].metric("Negative, last 30 days", f"{neg_recent:.0%}",
            f"{(neg_recent - neg_earlier) * 100:+.0f} pts" if neg_earlier is not None else None, delta_color="inverse")
k[3].metric("Most mentioned topic", view["TOPIC"].mode().iat[0])

weekly = (view.assign(WEEK=view["FEEDBACK_DATE"].dt.to_period("W").dt.start_time)
          .groupby(["WEEK", "MOOD"], as_index=False).size())
fig = px.bar(weekly, x="WEEK", y="size", color="MOOD", color_discrete_map=COLORS,
             category_orders={"MOOD": ["Negative", "Neutral", "Positive"]},
             labels={"size": "Comments", "WEEK": "", "MOOD": ""}, title="Comments per week by sentiment")
fig.update_layout(margin=dict(t=50, b=10))
st.plotly_chart(fig, width="stretch")

left, right = st.columns(2)
by_topic = view.groupby(["TOPIC", "MOOD"], as_index=False).size()
fig = px.bar(by_topic, x="size", y="TOPIC", color="MOOD", orientation="h", color_discrete_map=COLORS,
             category_orders={"MOOD": ["Negative", "Neutral", "Positive"]},
             labels={"size": "Comments", "TOPIC": "", "MOOD": ""}, title="Topics by sentiment")
fig.update_layout(margin=dict(t=50, b=10))
left.plotly_chart(fig, width="stretch")
by_source = view.groupby("SOURCE", as_index=False)["SENTIMENT"].mean().sort_values("SENTIMENT")
fig = px.bar(by_source, x="SENTIMENT", y="SOURCE", orientation="h", range_x=[-1, 1],
             color="SENTIMENT", color_continuous_scale=["#d62728", "#e5e7eb", "#2ca02c"], range_color=[-1, 1],
             labels={"SENTIMENT": "Average sentiment", "SOURCE": ""}, title="Sentiment by source")
fig.update_layout(margin=dict(t=50, b=10), coloraxis_showscale=False)
right.plotly_chart(fig, width="stretch")

st.subheader("What people complain about")
if st.button("Summarise the last 30 days' complaints"):
    try:
        st.info(complaint_summary())
    except Exception as e:
        st.warning(f"Could not summarise: {e}")
negative = view[view["MOOD"] == "Negative"].sort_values("FEEDBACK_DATE", ascending=False)
st.dataframe(negative[["FEEDBACK_DATE", "SOURCE", "TOPIC", "SENTIMENT", "FEEDBACK_TEXT"]].head(200).reset_index(drop=True),
             width="stretch", column_config={
                 "FEEDBACK_DATE": st.column_config.DateColumn("Date"), "SOURCE": "Source", "TOPIC": "Topic",
                 "SENTIMENT": st.column_config.NumberColumn("Sentiment", format="%.2f"), "FEEDBACK_TEXT": "Comment"})
st.download_button("Download scored feedback", view.drop(columns=["MOOD"]).to_csv(index=False), "feedback_scored.csv", "text/csv")

Questions

Does the text leave Snowflake?

No. Cortex AI functions run inside Snowflake, so the comments are scored where they are stored.

What does it cost?

Cortex AI functions are billed per token processed, so cost grows with the number and length of comments. That is why the query is capped and cached; check Snowflake's Cortex pricing for your region before scoring large volumes.

Can it handle comments in other languages?

SNOWFLAKE.CORTEX.SENTIMENT is tuned for English. For other languages, test a sample of your own comments first, or translate them in the query with SNOWFLAKE.CORTEX.TRANSLATE.

Can I use the code without StreamGen?

Yes. It is a plain Streamlit app. In Snowsight, create a Streamlit app, paste the code, add plotly to its packages, set DEMO = False and point the query at your table. StreamGen does that mapping, the checks and the deploy for you, and keeps the app working afterwards.

Does my data leave Snowflake?

No. In Snowflake the app runs inside your account and queries your tables there. The live demo on this page runs in your browser on generated sample data; nothing is sent anywhere.

Warehouse or container runtime?

Both work. The template only needs pandas, numpy and plotly, which both Streamlit in Snowflake runtimes provide.

Related templates

All templates · Guides

Build it on your own Snowflake data

In StreamGen you pick this template, the agent matches it to your tables, checks it, and deploys it to Snowflake with roles, approvals and an audit trail. Then ask for changes in plain words.

No sign-up for the 2-hour try. The Native App is free to install, with a free 7-day trial key.