Spaces:
Sleeping
Sleeping
File size: 13,297 Bytes
7c09d90 176c35a 7c09d90 ffd8374 bdc5888 176c35a 7c09d90 8d999b2 338dd05 8d999b2 d9a89ae 7c09d90 ffd8374 7c09d90 931789f 7c09d90 931789f 7c09d90 931789f 7c09d90 931789f 7c09d90 931789f 7c09d90 6513205 7c09d90 bdc5888 7c09d90 bdc5888 7c09d90 bdc5888 6513205 bdc5888 931789f 7c09d90 bdc5888 7c09d90 bdc5888 7c09d90 bdc5888 7c09d90 bdc5888 931789f 7c09d90 6513205 7c09d90 6513205 7c09d90 931789f 7c09d90 931789f 7c09d90 931789f 7c09d90 931789f 7c09d90 931789f 7c09d90 931789f 7c09d90 931789f 7c09d90 931789f 7c09d90 931789f 7c09d90 665d4f7 931789f 6513205 931789f 665d4f7 0a63321 7c09d90 665d4f7 7c09d90 931789f 7c09d90 931789f 715a234 931789f 7c09d90 931789f dcc4d70 a38d48e 7c09d90 ffd8374 7c09d90 bdc5888 7c09d90 bdc5888 7c09d90 | 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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | from dotenv import load_dotenv
import streamlit as st
from openai import OpenAI
import json
import os
import csv
from datetime import datetime
from pypdf import PdfReader
from chatbot_data.system_promt import system_prompt
from css_input import STREAMLIT_CSS
from email_utils import send_user_welcome_email, send_unknown_question_email
# Load environment variables
load_dotenv()
# App version for deployment tracking
__version__ = "1.0.5"
# Page configuration with light theme enforcement
st.set_page_config(
page_title="Blue Bean Data - AI Assistant",
page_icon="☕",
layout="centered",
initial_sidebar_state="collapsed"
)
st.markdown(STREAMLIT_CSS, unsafe_allow_html=True)
def load_knowledge_base():
"""Load and combine all knowledge base files"""
knowledge_base = ""
# Load FAQ data
try:
with open('src/chatbot_data/faq_blue_bean_data.md', 'r', encoding='utf-8') as file:
faq_content = file.read()
knowledge_base += faq_content + "\n\n"
except FileNotFoundError:
st.error("FAQ file not found.")
knowledge_base += "FAQ data not available.\n\n"
# Load PDF CV
try:
reader = PdfReader('src/chatbot_data/kristof_linkedin_cv.pdf')
kristof_cv = ""
for page in reader.pages:
kristof_cv += page.extract_text()
knowledge_base += f"# Kristof's Professional Background\n{kristof_cv}\n\n"
except FileNotFoundError:
st.error("Kristof's CV file not found.")
except Exception as e:
st.error(f"Error reading PDF: {str(e)}")
return knowledge_base
def generate_conversation_summary(messages):
"""Generate an AI summary of the conversation for context"""
try:
# Filter out system messages and get only user/assistant exchanges
conversation_messages = [msg for msg in messages if msg["role"] in ["user", "assistant"]]
if len(conversation_messages) <= 2: # Just welcome message and one exchange
return "Brief initial inquiry about Blue Bean Data services."
# Create a prompt for summarization
conversation_text = ""
for msg in conversation_messages:
role = "Customer" if msg["role"] == "user" else "Assistant"
conversation_text += f"{role}: {msg['content']}\n\n"
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
summary_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": (
"You are an assistant tasked with summarizing a conversation between a customer and Blue Bean Data's AI assistant. "
"Write a clear, professional summary (3-4 sentences) that covers: "
"1) What the customer is interested in, "
"2) Their main questions or challenges, "
"3) Any relevant business context they mentioned. "
"The summary should be actionable for a sales or support follow-up. "
"Only include information explicitly stated in the conversation, and avoid assumptions or internal notes. "
"Do not include anything that a user cannot see or that was not visible to the user in the conversation."
)
},
{
"role": "user",
"content": f"Summarize this conversation:\n\n{conversation_text}"
}
],
max_tokens=150
)
return summary_response.choices[0].message.content.strip()
except Exception as e:
print(f"Error generating conversation summary: {str(e)}")
# Fallback: create a simple summary from user messages
user_messages = [msg["content"] for msg in messages if msg["role"] == "user"]
if user_messages:
return f"Customer inquired about: {'; '.join(user_messages[-2:])}" # Last 2 user messages
return "Customer expressed interest in Blue Bean Data services."
def record_user_details(email, name="Name not provided", notes="not provided"):
"""Send welcome email to user and notification to company"""
try:
# Send emails using SMTP
email_sent = send_user_welcome_email(email, name, notes)
if email_sent:
# Show success message to user - handle name display properly
if name and name.strip() and name.lower() not in ['name not provided', 'not provided', '']:
st.success(f"✅ Thank you {name}! I've sent a welcome email to {email}. Someone from our team will reach out to you soon.")
else:
st.success(f"✅ Thank you! I've sent a welcome email to {email}. Someone from our team will reach out to you soon.")
return {"recorded": "ok"}
else:
st.error("There was an issue sending the email. Please try again or contact us directly at info@bluebeandata.com")
return {"recorded": "error", "message": "Email sending failed"}
except Exception as e:
st.error(f"Error processing your request: {str(e)}")
return {"recorded": "error", "message": str(e)}
def record_unknown_question(question):
"""Send unknown question to company email"""
try:
# Send email to company
email_sent = send_unknown_question_email(question)
if email_sent:
return {"recorded": "ok"}
else:
return {"recorded": "error", "message": "Email sending failed"}
except Exception as e:
st.error(f"Error recording unknown question: {str(e)}")
return {"recorded": "error", "message": str(e)}
# Tool definitions for OpenAI function calling
record_user_details_json = {
"name": "record_user_details",
"description": "Use this tool to record that a user is interested in being in touch and provided an email address. Always provide a meaningful summary of the conversation context.",
"parameters": {
"type": "object",
"properties": {
"email": {
"type": "string",
"description": "The email address of this user"
},
"name": {
"type": "string",
"description": "The user's name, if they provided it"
},
"notes": {
"type": "string",
"description": "A brief summary of what the user is interested in, their main questions, and business context from the conversation"
}
},
"required": ["email"]
}
}
record_unknown_question_json = {
"name": "record_unknown_question",
"description": "Use this to record questions that cannot be answered based on the knowledge base",
"parameters": {
"type": "object",
"properties": {
"question": {
"type": "string",
"description": "The question that couldn't be answered"
}
},
"required": ["question"]
}
}
def get_chatbot_response(messages, knowledge_base):
"""Get response from OpenAI with function calling capabilities"""
try:
# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# Create session ID for tracking (could be user's session)
session_id = st.session_state.get('session_id', f"session_{datetime.now().strftime('%Y%m%d_%H%M%S')}")
if 'session_id' not in st.session_state:
st.session_state.session_id = session_id
# Add system message with knowledge base
system_message = {
"role": "system",
"content": f"{system_prompt}\n\nKNOWLEDGE BASE:\n{knowledge_base}"
}
full_messages = [system_message] + messages
# Call OpenAI API with function calling
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=full_messages,
tools=[
{"type": "function", "function": record_user_details_json},
{"type": "function", "function": record_unknown_question_json}
],
tool_choice="auto",
user=session_id # Track sessions for OpenAI usage analytics
)
# Handle function calls and prepare response
assistant_message = response.choices[0].message
response_content = assistant_message.content
if assistant_message.tool_calls:
for tool_call in assistant_message.tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
if function_name == "record_user_details":
# Generate conversation summary and enhance notes
conversation_summary = generate_conversation_summary(messages)
# If notes from AI are minimal, use the generated summary
original_notes = function_args.get("notes", "")
if not original_notes or original_notes.lower() in ["not provided", "none", ""]:
function_args["notes"] = conversation_summary
else:
# Combine AI notes with conversation summary
function_args["notes"] = f"{original_notes}\n\nConversation Summary: {conversation_summary}"
record_user_details(**function_args)
elif function_name == "record_unknown_question":
record_unknown_question(**function_args)
# If there's no content but there were function calls, provide a default response
if not response_content:
response_content = "Thank you! I've recorded your information and notified our team. We'll follow up soon and update our knowledge base as needed. Is there anything else I can assist you with?"
# Ensure we always return a string, never None/null
return response_content or "I'm here to help! What would you like to know about Blue Bean Data?"
except Exception as e:
st.error(f"Error getting response: {str(e)}")
return "I'm sorry, I'm having trouble connecting right now. Please try again later."
def main():
"""Main Streamlit application"""
# Header
st.markdown('<div class="main-header">', unsafe_allow_html=True)
st.title("Blue Bean Data AI Assistant ☕")
st.markdown("*We help you grow.*")
st.markdown('</div>', unsafe_allow_html=True)
# Initialize session state
if "messages" not in st.session_state:
st.session_state.messages = []
if "knowledge_base" not in st.session_state:
with st.spinner("Loading knowledge base..."):
st.session_state.knowledge_base = load_knowledge_base()
# Display welcome message
if not st.session_state.messages:
welcome_msg = (
"👋 **Welcome to Blue Bean Data!**\n\n"
"I'm your AI assistant. Ask me about:\n"
"- Our data consulting services & expertise \n"
"- The Blue Bean Data team \n"
"- Or leave your contact details for a follow-up\n\n"
"How can I assist you today?"
)
st.session_state.messages.append({"role": "assistant", "content": welcome_msg})
# Display chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
if prompt := st.chat_input("Type your question here..."):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message
with st.chat_message("user"):
st.markdown(prompt)
# Get and display assistant response
with st.chat_message("assistant"):
with st.spinner("💡 Thinking... (aka. AI at work)"):
response = get_chatbot_response(
st.session_state.messages.copy(),
st.session_state.knowledge_base
)
st.markdown(response)
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": response})
# Sidebar with information
with st.sidebar:
st.markdown("### About Blue Bean Data")
st.markdown("""
We're a data solutions company based in the Netherlands, founded by brothers Kristof and Marton.
**Our Services:**
- Data Strategy & Consulting
- BI & Dashboards
- Data Pipeline Development
- AI & Automation
- Predictive Modeling & Analytics
- Database Design & Optimization
**Get Started:**
Contact us for a free consultation!
""")
if st.button("Clear Chat History"):
st.session_state.messages = []
st.rerun()
if __name__ == "__main__":
main()
|