Spaces:
Running
Running
Update chatbot.py
Browse files- chatbot.py +107 -125
chatbot.py
CHANGED
@@ -1,139 +1,121 @@
|
|
1 |
import streamlit as st
|
2 |
-
import
|
3 |
-
|
4 |
-
import
|
|
|
5 |
|
|
|
|
|
|
|
|
|
6 |
|
7 |
-
class
|
8 |
def __init__(self):
|
|
|
|
|
9 |
if 'chat_history' not in st.session_state:
|
10 |
st.session_state.chat_history = []
|
11 |
-
if 'chat_initialized' not in st.session_state:
|
12 |
-
st.session_state.chat_initialized = False
|
13 |
|
14 |
-
def
|
15 |
-
"
|
16 |
-
|
17 |
-
welcome_message = {
|
18 |
-
"role": "assistant",
|
19 |
-
"content": "Hello! I'm your AI Business Mentor. I can help you with business strategy, market analysis, product development, marketing insights, and more. What would you like to discuss today?"
|
20 |
-
}
|
21 |
-
st.session_state.chat_history.append(welcome_message)
|
22 |
-
st.session_state.chat_initialized = True
|
23 |
-
|
24 |
-
def add_message(self, role: str, content: str):
|
25 |
-
"""Add a message to the chat history"""
|
26 |
-
message = {"role": role, "content": content}
|
27 |
-
st.session_state.chat_history.append(message)
|
28 |
-
|
29 |
-
def get_chat_history(self) -> List[Dict]:
|
30 |
-
"""Get the current chat history"""
|
31 |
-
return st.session_state.chat_history
|
32 |
-
|
33 |
-
def clear_chat(self):
|
34 |
-
"""Clear the chat history"""
|
35 |
-
st.session_state.chat_history = []
|
36 |
-
st.session_state.chat_initialized = False
|
37 |
-
|
38 |
-
def generate_business_response(self, user_input: str) -> str:
|
39 |
-
"""
|
40 |
-
Generate a business-focused response based on user input
|
41 |
-
This is a simple rule-based system that can be enhanced with actual AI models
|
42 |
-
"""
|
43 |
-
user_input_lower = user_input.lower()
|
44 |
-
|
45 |
-
# Business strategy keywords
|
46 |
-
if any(keyword in user_input_lower for keyword in ['strategy', 'plan', 'planning', 'roadmap']):
|
47 |
-
return """Great question about business strategy! Here are some key considerations:
|
48 |
-
|
49 |
-
1. **Market Analysis**: Understand your target market, competitors, and industry trends
|
50 |
-
2. **Value Proposition**: Clearly define what unique value you provide
|
51 |
-
3. **Resource Allocation**: Determine how to best use your time, money, and team
|
52 |
-
4. **Growth Strategy**: Plan for sustainable scaling and expansion
|
53 |
-
5. **Risk Management**: Identify potential challenges and mitigation strategies
|
54 |
-
|
55 |
-
What specific aspect of strategy would you like to dive deeper into?"""
|
56 |
|
57 |
-
#
|
58 |
-
|
59 |
-
return """Marketing is crucial for business success! Here's a framework to consider:
|
60 |
-
|
61 |
-
1. **Target Audience**: Define your ideal customer personas
|
62 |
-
2. **Channels**: Choose the right mix of digital and traditional channels
|
63 |
-
3. **Content Strategy**: Create valuable, engaging content
|
64 |
-
4. **Budget Allocation**: Distribute resources across channels effectively
|
65 |
-
5. **Metrics & Analytics**: Track performance and ROI
|
66 |
-
|
67 |
-
What's your current marketing challenge or goal?"""
|
68 |
|
69 |
-
|
70 |
-
|
71 |
-
return """Product development is exciting! Here's a structured approach:
|
72 |
-
|
73 |
-
1. **Market Research**: Validate demand and understand user needs
|
74 |
-
2. **MVP Strategy**: Start with core features and iterate
|
75 |
-
3. **User Feedback**: Continuously gather and incorporate feedback
|
76 |
-
4. **Competitive Analysis**: Learn from competitors' successes and failures
|
77 |
-
5. **Roadmap Planning**: Prioritize features based on impact and effort
|
78 |
-
|
79 |
-
What stage is your product in, and what specific guidance do you need?"""
|
80 |
|
81 |
-
#
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
-
#
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
1. **Hiring Strategy**: Define roles clearly and hire for culture fit
|
98 |
-
2. **Team Culture**: Foster collaboration and shared values
|
99 |
-
3. **Performance Management**: Set clear expectations and provide feedback
|
100 |
-
4. **Development**: Invest in training and career growth
|
101 |
-
5. **Retention**: Create an environment where people want to stay
|
102 |
-
|
103 |
-
What team-related challenges are you facing?"""
|
104 |
|
105 |
-
#
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
|
117 |
-
|
118 |
-
|
119 |
-
return f"""Thank you for your question about "{user_input}".
|
120 |
-
|
121 |
-
As your AI Business Mentor, I'm here to help with various aspects of business including:
|
122 |
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
• **Team & Leadership** - Hiring, culture building, management practices
|
128 |
-
|
129 |
-
Could you provide more specific details about what you'd like to explore? The more context you give me, the better I can tailor my advice to your situation."""
|
130 |
-
|
131 |
-
def format_message_for_display(self, message: Dict) -> str:
|
132 |
-
"""Format a message for display in the chat interface"""
|
133 |
-
role = message["role"]
|
134 |
-
content = message["content"]
|
135 |
-
|
136 |
-
if role == "user":
|
137 |
-
return f"**You:** {content}"
|
138 |
-
else:
|
139 |
-
return f"**AI Mentor:** {content}"
|
|
|
1 |
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
import os
|
4 |
+
from datetime import datetime
|
5 |
+
import google.generativeai as genai
|
6 |
|
7 |
+
# Configure Gemini
|
8 |
+
GEMINI_API_KEY = os.environ.get('GEMINI_API_KEY')
|
9 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
10 |
+
model = genai.GenerativeModel('gemini-pro')
|
11 |
|
12 |
+
class GeminiDataChatbot:
|
13 |
def __init__(self):
|
14 |
+
if 'uploaded_df' not in st.session_state:
|
15 |
+
st.session_state.uploaded_df = None
|
16 |
if 'chat_history' not in st.session_state:
|
17 |
st.session_state.chat_history = []
|
|
|
|
|
18 |
|
19 |
+
def render_interface(self):
|
20 |
+
st.title("📊 Data Analysis Chatbot")
|
21 |
+
st.write("Upload your CSV file and ask questions about your data")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
+
# File upload section
|
24 |
+
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
+
if uploaded_file is not None:
|
27 |
+
self._process_uploaded_file(uploaded_file)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
+
# Chat interface
|
30 |
+
if st.session_state.uploaded_df is not None:
|
31 |
+
self._render_chat_window()
|
32 |
+
|
33 |
+
def _process_uploaded_file(self, uploaded_file):
|
34 |
+
try:
|
35 |
+
df = pd.read_csv(uploaded_file)
|
36 |
+
st.session_state.uploaded_df = df
|
37 |
+
st.success("Data successfully loaded!")
|
38 |
+
|
39 |
+
with st.expander("View Data Preview"):
|
40 |
+
st.dataframe(df.head())
|
41 |
+
|
42 |
+
# Initial analysis prompt
|
43 |
+
initial_prompt = f"""
|
44 |
+
I have uploaded a dataset with {len(df)} rows and {len(df.columns)} columns.
|
45 |
+
Columns: {', '.join(df.columns)}.
|
46 |
+
First give a very brief (2-3 sentence) overview of what this data might contain.
|
47 |
+
Then suggest 3 specific questions I could ask about this data.
|
48 |
+
"""
|
49 |
+
|
50 |
+
with st.spinner("Analyzing your data..."):
|
51 |
+
response = self._generate_gemini_response(initial_prompt, df)
|
52 |
+
st.session_state.chat_history.append({
|
53 |
+
"role": "assistant",
|
54 |
+
"content": response
|
55 |
+
})
|
56 |
+
|
57 |
+
except Exception as e:
|
58 |
+
st.error(f"Error processing file: {str(e)}")
|
59 |
+
|
60 |
+
def _render_chat_window(self):
|
61 |
+
st.subheader("Chat About Your Data")
|
62 |
|
63 |
+
# Display chat history
|
64 |
+
for message in st.session_state.chat_history:
|
65 |
+
with st.chat_message(message["role"]):
|
66 |
+
st.markdown(message["content"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
+
# User input
|
69 |
+
if prompt := st.chat_input("Ask about your data..."):
|
70 |
+
# Add user message to chat history
|
71 |
+
st.session_state.chat_history.append({"role": "user", "content": prompt})
|
72 |
+
|
73 |
+
# Display user message
|
74 |
+
with st.chat_message("user"):
|
75 |
+
st.markdown(prompt)
|
76 |
+
|
77 |
+
# Generate and display assistant response
|
78 |
+
with st.chat_message("assistant"):
|
79 |
+
with st.spinner("Thinking..."):
|
80 |
+
response = self._generate_gemini_response(prompt, st.session_state.uploaded_df)
|
81 |
+
st.markdown(response)
|
82 |
+
|
83 |
+
# Add assistant response to chat history
|
84 |
+
st.session_state.chat_history.append({"role": "assistant", "content": response})
|
85 |
+
|
86 |
+
def _generate_gemini_response(self, prompt: str, df: pd.DataFrame) -> str:
|
87 |
+
"""Generate response using Gemini API with data context"""
|
88 |
+
try:
|
89 |
+
# Create data summary for context
|
90 |
+
data_summary = f"""
|
91 |
+
Data Summary:
|
92 |
+
- Shape: {df.shape}
|
93 |
+
- Columns: {', '.join(df.columns)}
|
94 |
+
- First 5 rows:
|
95 |
+
{df.head().to_markdown()}
|
96 |
+
"""
|
97 |
+
|
98 |
+
# Create prompt with context
|
99 |
+
full_prompt = f"""
|
100 |
+
You are a data analysis assistant. The user has uploaded a dataset with the following characteristics:
|
101 |
+
{data_summary}
|
102 |
+
|
103 |
+
User Question: {prompt}
|
104 |
+
|
105 |
+
Provide a detailed response answering their question about the data. If appropriate, include:
|
106 |
+
- Relevant statistics
|
107 |
+
- Potential visualizations that would help
|
108 |
+
- Any data quality issues to consider
|
109 |
+
- Business insights if applicable
|
110 |
+
"""
|
111 |
+
|
112 |
+
response = model.generate_content(full_prompt)
|
113 |
+
return response.text
|
114 |
|
115 |
+
except Exception as e:
|
116 |
+
return f"Sorry, I encountered an error processing your request: {str(e)}"
|
|
|
|
|
|
|
117 |
|
118 |
+
# Initialize and run the chatbot
|
119 |
+
if __name__ == "__main__":
|
120 |
+
chatbot = GeminiDataChatbot()
|
121 |
+
chatbot.render_interface()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|