Pranav0111 commited on
Commit
0ee3833
·
verified ·
1 Parent(s): 34a309c

Update chatbot.py

Browse files
Files changed (1) hide show
  1. 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
- try:
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
- if GEMINI_AVAILABLE and 'GEMINI_API_KEY' in os.environ:
16
- genai.configure(api_key=os.environ['GEMINI_API_KEY'])
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
- if uploaded_file is not None:
38
- self._process_uploaded_file(uploaded_file)
39
-
40
- # Chat interface
41
- if st.session_state.uploaded_df is not None:
42
- self._render_chat_window()
43
- else:
44
- st.info("Upload a CSV file to chat with your data")
 
 
 
 
 
 
 
 
 
45
 
46
- def _process_uploaded_file(self, uploaded_file):
47
- """Process the uploaded CSV file"""
 
 
 
 
48
  try:
49
- with tempfile.NamedTemporaryFile(delete=False, suffix='.csv') as tmp:
50
- tmp.write(uploaded_file.getvalue())
51
- tmp_path = tmp.name
52
-
53
- df = pd.read_csv(tmp_path)
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
- response = self._generate_response(initial_prompt)
70
- st.session_state.chat_history.append({
71
- "role": "assistant",
72
- "content": response
73
- })
74
-
75
  except Exception as e:
76
- st.error(f"Error processing file: {str(e)}")
77
 
78
- def _render_chat_window(self):
79
- """Render the chat conversation window"""
80
- st.subheader("Chat About Your Business Data")
81
-
82
- # Display chat history
83
- for message in st.session_state.chat_history:
84
- with st.chat_message(message["role"]):
85
- st.markdown(message["content"])
86
-
87
- # User input
88
- if prompt := st.chat_input("Ask about your business data..."):
89
- self._handle_user_input(prompt)
 
 
90
 
91
- def _handle_user_input(self, prompt):
92
- """Handle user input and generate response"""
93
- # Add user message to chat history
94
- st.session_state.chat_history.append({"role": "user", "content": prompt})
95
-
96
- # Display user message
97
- with st.chat_message("user"):
98
- st.markdown(prompt)
99
 
100
- # Generate and display assistant response
101
- with st.chat_message("assistant"):
102
- with st.spinner("Analyzing..."):
103
- response = self._generate_response(prompt)
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
- if self.model:
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."