Churn-chatbot / app.py
Shadatsh's picture
Update app.py
8c7ba12 verified
import streamlit as st
import pandas as pd
import openai
import os
from dotenv import load_dotenv
# Load API key from .env
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
# Load CSV file
df = pd.read_csv('churn_predictions.csv')
# Streamlit UI
st.set_page_config(page_title="Customer Churn Chatbot")
st.title("Customer Churn Chatbot")
st.markdown("Ask if a customer is predicted to churn and get GPT-based suggestions.")
# Input fields
customer_id = st.text_input("Enter Customer ID (optional):")
customer_name = st.text_input("Enter Customer Name (optional):")
if st.button("Check Churn"):
result = pd.DataFrame()
# Search by ID
if customer_id:
try:
customer_id = int(customer_id)
result = df[df["CustomerId"] == customer_id]
except ValueError:
st.error("Customer ID must be an integer.")
# Search by name
elif customer_name:
result = df[df["Customer"].str.lower() == customer_name.lower()]
if not result.empty:
row = result.iloc[0]
churn = row["PredictedChurn"]
# Basic suggestion
suggestion = (
"High risk of churn. Consider giving discounts, loyalty rewards."
if churn == 1 else
"Customer is stable. Maintain good service."
)
# GPT prompt
prompt = (
f"Customer: {row['Customer']}\n"
f"Churn Prediction: {'Yes' if churn else 'No'}\n"
"What actions should be taken to reduce churn or maintain retention?"
)
with st.spinner("Asking GPT..."):
try:
response = openai.ChatCompletion.create(
model="gpt-4", # or "gpt-3.5-turbo" if needed
messages=[{"role": "user", "content": prompt}]
)
gpt_reply = response.choices[0].message["content"]
except Exception as e:
gpt_reply = f" GPT request failed: {e}"
# Display output
st.success(f"Churn: {'Yes' if churn else 'No'}")
st.info(f"Suggestion: {suggestion}")
st.markdown(" GPT's Advice:")
st.write(gpt_reply)
else:
st.warning("Customer not found. Please check your input.")