File size: 2,257 Bytes
8c7ba12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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.")