Spaces:
Running
Running
Update chatbot.py
Browse files- chatbot.py +89 -122
chatbot.py
CHANGED
@@ -3,143 +3,110 @@ import streamlit as st
|
|
3 |
import pandas as pd
|
4 |
import os
|
5 |
import tempfile
|
6 |
-
|
7 |
-
|
8 |
-
import google.generativeai as genai
|
9 |
-
GEMINI_AVAILABLE = True
|
10 |
-
except ImportError:
|
11 |
-
GEMINI_AVAILABLE = False
|
12 |
|
13 |
class ChatbotManager:
|
14 |
def __init__(self):
|
15 |
-
|
16 |
-
|
17 |
-
self.model = genai.GenerativeModel('gemini-pro')
|
18 |
-
else:
|
19 |
-
self.model = None
|
20 |
-
|
21 |
self.initialize_chat()
|
22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
def initialize_chat(self):
|
24 |
"""Initialize chat session state variables"""
|
25 |
-
if 'uploaded_df' not in st.session_state:
|
26 |
-
st.session_state.uploaded_df = None
|
27 |
if 'chat_history' not in st.session_state:
|
28 |
st.session_state.chat_history = []
|
29 |
-
|
30 |
-
def render_chat(self):
|
31 |
-
"""Main chat interface compatible with your pages.py structure"""
|
32 |
-
st.header("💬 AI Business Mentor")
|
33 |
-
|
34 |
-
# File upload section
|
35 |
-
uploaded_file = st.file_uploader("Upload your business data (CSV)", type=['csv'])
|
36 |
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
-
def
|
47 |
-
"""
|
|
|
|
|
|
|
|
|
48 |
try:
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
st.session_state.uploaded_df = df
|
55 |
-
st.success("Data loaded successfully!")
|
56 |
-
|
57 |
-
with st.expander("View Data Preview"):
|
58 |
-
st.dataframe(df.head())
|
59 |
-
|
60 |
-
# Clean up temp file
|
61 |
-
os.unlink(tmp_path)
|
62 |
-
|
63 |
-
# Initial analysis if Gemini is available
|
64 |
-
if self.model:
|
65 |
-
initial_prompt = (
|
66 |
-
f"Provide a 2-3 sentence overview of this dataset with {len(df)} rows and {len(df.columns)} columns. "
|
67 |
-
"Then suggest 3 specific business insights we could extract."
|
68 |
)
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
})
|
74 |
-
|
75 |
except Exception as e:
|
76 |
-
|
77 |
|
78 |
-
def
|
79 |
-
"""
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
|
|
|
|
90 |
|
91 |
-
def
|
92 |
-
"""
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
response
|
104 |
-
st.markdown(response)
|
105 |
-
|
106 |
-
# Add assistant response to chat history
|
107 |
-
st.session_state.chat_history.append({"role": "assistant", "content": response})
|
108 |
-
|
109 |
-
def _generate_response(self, prompt: str) -> str:
|
110 |
-
"""Generate response using available backend"""
|
111 |
-
df = st.session_state.uploaded_df
|
112 |
|
113 |
-
|
114 |
-
# Use Gemini if available
|
115 |
-
try:
|
116 |
-
data_summary = (
|
117 |
-
f"Dataset shape: {df.shape}\n"
|
118 |
-
f"Columns: {', '.join(df.columns)}\n"
|
119 |
-
f"First 3 rows:\n{df.head(3).to_markdown()}"
|
120 |
-
)
|
121 |
-
full_prompt = (
|
122 |
-
"You're a business data analyst. The user has uploaded this data:\n"
|
123 |
-
f"{data_summary}\n\n"
|
124 |
-
f"User question: {prompt}\n\n"
|
125 |
-
"Provide a detailed, professional response with actionable insights. "
|
126 |
-
"If appropriate, include:\n"
|
127 |
-
"- Key statistics\n"
|
128 |
-
"- Business implications\n"
|
129 |
-
"- Recommended visualizations\n"
|
130 |
-
"- Potential next steps"
|
131 |
-
)
|
132 |
-
response = self.model.generate_content(full_prompt)
|
133 |
-
return response.text
|
134 |
-
except Exception as e:
|
135 |
-
return f"⚠️ Analysis error: {str(e)}"
|
136 |
-
else:
|
137 |
-
# Fallback basic analysis
|
138 |
-
if "summary" in prompt.lower():
|
139 |
-
return f"📊 Basic Statistics:\n{df.describe().to_markdown()}"
|
140 |
-
elif "columns" in prompt.lower():
|
141 |
-
return f"📋 Columns:\n{', '.join(df.columns)}"
|
142 |
-
elif "missing" in prompt.lower():
|
143 |
-
return f"🔍 Missing Values:\n{df.isnull().sum().to_markdown()}"
|
144 |
-
else:
|
145 |
-
return "💡 Ask me about: data summary, columns, or missing values"
|
|
|
3 |
import pandas as pd
|
4 |
import os
|
5 |
import tempfile
|
6 |
+
import google.generativeai as genai
|
7 |
+
from typing import List, Dict, Optional
|
|
|
|
|
|
|
|
|
8 |
|
9 |
class ChatbotManager:
|
10 |
def __init__(self):
|
11 |
+
# Configure Gemini
|
12 |
+
self.configure_gemini()
|
|
|
|
|
|
|
|
|
13 |
self.initialize_chat()
|
14 |
|
15 |
+
def configure_gemini(self):
|
16 |
+
"""Configure the Gemini API"""
|
17 |
+
try:
|
18 |
+
# Try to get API key from environment variable
|
19 |
+
api_key = os.getenv('GEMINI_API_KEY')
|
20 |
+
if not api_key:
|
21 |
+
# Fallback to Streamlit secrets if available
|
22 |
+
try:
|
23 |
+
api_key = st.secrets['GEMINI_API_KEY']
|
24 |
+
except:
|
25 |
+
pass
|
26 |
+
|
27 |
+
if api_key:
|
28 |
+
genai.configure(api_key=api_key)
|
29 |
+
self.model = genai.GenerativeModel('gemini-pro')
|
30 |
+
self.chat = self.model.start_chat(history=[])
|
31 |
+
else:
|
32 |
+
self.model = None
|
33 |
+
self.chat = None
|
34 |
+
st.warning("Gemini API key not found. Using limited functionality mode.")
|
35 |
+
except Exception as e:
|
36 |
+
st.error(f"Error configuring Gemini: {str(e)}")
|
37 |
+
self.model = None
|
38 |
+
self.chat = None
|
39 |
+
|
40 |
def initialize_chat(self):
|
41 |
"""Initialize chat session state variables"""
|
|
|
|
|
42 |
if 'chat_history' not in st.session_state:
|
43 |
st.session_state.chat_history = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
+
# Initialize Gemini chat if not already done
|
46 |
+
if self.model and not hasattr(self, 'chat'):
|
47 |
+
self.chat = self.model.start_chat(history=[])
|
48 |
+
|
49 |
+
def clear_chat(self):
|
50 |
+
"""Clear the chat history"""
|
51 |
+
st.session_state.chat_history = []
|
52 |
+
if self.model:
|
53 |
+
self.chat = self.model.start_chat(history=[])
|
54 |
+
st.success("Chat history cleared!")
|
55 |
+
|
56 |
+
def add_message(self, role: str, content: str):
|
57 |
+
"""Add a message to the chat history"""
|
58 |
+
st.session_state.chat_history.append({
|
59 |
+
"role": role,
|
60 |
+
"content": content
|
61 |
+
})
|
62 |
|
63 |
+
def get_chat_history(self) -> List[Dict]:
|
64 |
+
"""Get the chat history"""
|
65 |
+
return st.session_state.chat_history
|
66 |
+
|
67 |
+
def generate_business_response(self, prompt: str) -> str:
|
68 |
+
"""Generate a response to a business-related prompt"""
|
69 |
try:
|
70 |
+
if self.chat:
|
71 |
+
# Use Gemini chat for contextual responses
|
72 |
+
response = self.chat.send_message(
|
73 |
+
self._create_business_prompt(prompt),
|
74 |
+
stream=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
)
|
76 |
+
return "".join([chunk.text for chunk in response])
|
77 |
+
else:
|
78 |
+
# Fallback response if Gemini isn't available
|
79 |
+
return self._generate_fallback_response(prompt)
|
|
|
|
|
80 |
except Exception as e:
|
81 |
+
return f"⚠️ Error generating response: {str(e)}"
|
82 |
|
83 |
+
def _create_business_prompt(self, user_input: str) -> str:
|
84 |
+
"""Create a detailed prompt for business-related queries"""
|
85 |
+
return f"""You are an expert business advisor AI. Provide detailed, actionable advice in response to the following query.
|
86 |
+
|
87 |
+
Rules:
|
88 |
+
- Always maintain a professional tone
|
89 |
+
- Break complex concepts into simple terms
|
90 |
+
- Provide concrete examples when possible
|
91 |
+
- Structure responses with clear sections when appropriate
|
92 |
+
- Suggest next steps or additional considerations
|
93 |
+
|
94 |
+
User query: {user_input}
|
95 |
+
|
96 |
+
Please provide a comprehensive response that addresses the user's needs:"""
|
97 |
|
98 |
+
def _generate_fallback_response(self, prompt: str) -> str:
|
99 |
+
"""Generate a fallback response when Gemini isn't available"""
|
100 |
+
business_topics = {
|
101 |
+
"strategy": "For business strategy, consider analyzing your market position, competitors, and unique value proposition.",
|
102 |
+
"marketing": "Marketing tips: Focus on your target audience, create valuable content, and measure campaign performance.",
|
103 |
+
"finance": "Financial planning should include budgeting, cash flow management, and scenario planning.",
|
104 |
+
"product": "Product development should start with customer needs validation before building."
|
105 |
+
}
|
106 |
|
107 |
+
prompt_lower = prompt.lower()
|
108 |
+
for topic, response in business_topics.items():
|
109 |
+
if topic in prompt_lower:
|
110 |
+
return response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
111 |
|
112 |
+
return "I can provide advice on business strategy, marketing, finance, and product development. Please ask a specific question about one of these areas."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|