""" Advanced Business AI Assistant - Streamlit App Deployed on Hugging Face Spaces This comprehensive business assistant provides intelligent answers about your business, integrates with multiple AI providers, and includes support ticket functionality. """ import streamlit as st import time import json import os import requests from datetime import datetime, timedelta from typing import Dict, List, Optional, Any import uuid import hashlib # Import the streaming system try: from streaming import AdvancedStreamingSystem, StreamProvider, StreamingConfig STREAMING_AVAILABLE = True except ImportError: STREAMING_AVAILABLE = False # Page configuration st.set_page_config( page_title="AgentAI Business Assistant", page_icon="š¢", layout="wide", initial_sidebar_state="expanded" ) # Business Information Database BUSINESS_INFO = { "company_name": "AgentAI Solutions", "tagline": "Advanced AI Development & Consulting", "description": "We specialize in cutting-edge AI solutions, machine learning implementations, and intelligent automation systems for businesses worldwide.", "contact": { "phone": "+1 (555) 123-4567", "email": "info@agentai-solutions.com", "support_email": "support@agentai-solutions.com", "website": "https://agentai-solutions.com", "linkedin": "https://linkedin.com/company/agentai-solutions" }, "location": { "address": "123 Innovation Drive, Tech District", "city": "San Francisco", "state": "CA", "zip": "94105", "country": "USA", "timezone": "PST (UTC-8)", "coordinates": {"lat": 37.7749, "lon": -122.4194} }, "hours": { "monday": {"open": "9:00 AM", "close": "6:00 PM", "timezone": "PST"}, "tuesday": {"open": "9:00 AM", "close": "6:00 PM", "timezone": "PST"}, "wednesday": {"open": "9:00 AM", "close": "6:00 PM", "timezone": "PST"}, "thursday": {"open": "9:00 AM", "close": "6:00 PM", "timezone": "PST"}, "friday": {"open": "9:00 AM", "close": "6:00 PM", "timezone": "PST"}, "saturday": {"open": "10:00 AM", "close": "4:00 PM", "timezone": "PST"}, "sunday": "Closed", "holidays": "Closed on major US holidays" }, "services": [ { "name": "AI Development", "description": "Custom AI solutions, machine learning models, and intelligent automation systems", "duration": "2-12 weeks", "price_range": "$10,000 - $100,000+" }, { "name": "AI Consulting", "description": "Strategic AI planning, feasibility studies, and implementation roadmaps", "duration": "1-4 weeks", "price_range": "$5,000 - $25,000" }, { "name": "Model Training", "description": "Custom model training, fine-tuning, and optimization services", "duration": "1-6 weeks", "price_range": "$3,000 - $50,000" }, { "name": "AI Integration", "description": "Seamless integration of AI solutions into existing business systems", "duration": "2-8 weeks", "price_range": "$7,500 - $75,000" } ], "team": [ {"name": "Alex Chen", "role": "CEO & AI Architect", "expertise": "Machine Learning, Deep Learning"}, {"name": "Sarah Johnson", "role": "CTO & Lead Developer", "expertise": "MLOps, Cloud Architecture"}, {"name": "Dr. Michael Rodriguez", "role": "Head of Research", "expertise": "NLP, Computer Vision"}, {"name": "Emily Zhang", "role": "AI Consultant", "expertise": "Business Strategy, AI Ethics"} ], "support": { "response_time": "24 hours for general inquiries, 4 hours for urgent issues", "channels": ["Email", "Phone", "Live Chat", "Support Tickets"], "emergency_contact": "+1 (555) 123-4567 ext. 911" } } # Custom CSS for professional styling st.markdown(""" """, unsafe_allow_html=True) # Session state initialization def initialize_session_state(): """Initialize session state variables.""" if 'conversation' not in st.session_state: st.session_state.conversation = [] if 'support_tickets' not in st.session_state: st.session_state.support_tickets = [] if 'business_assistant' not in st.session_state: st.session_state.business_assistant = None if 'user_session_id' not in st.session_state: st.session_state.user_session_id = str(uuid.uuid4()) if 'chat_analytics' not in st.session_state: st.session_state.chat_analytics = [] class BusinessKnowledgeBase: """Advanced business knowledge base with intelligent query processing.""" def __init__(self, business_info: Dict): self.business_info = business_info self.knowledge_patterns = self._build_knowledge_patterns() def _build_knowledge_patterns(self) -> Dict[str, Any]: """Build patterns for intelligent query matching.""" return { "hours": { "keywords": ["hours", "open", "close", "time", "schedule", "when", "operating", "business hours", "opening", "closing"], "context": "business hours and schedule" }, "location": { "keywords": ["location", "address", "where", "directions", "map", "office", "find", "located", "place"], "context": "business location and address" }, "contact": { "keywords": ["phone", "email", "contact", "call", "reach", "number", "telephone", "reach", "communicate"], "context": "contact information" }, "services": { "keywords": ["services", "what", "offer", "do", "provide", "solutions", "products", "work", "help", "ai", "development"], "context": "services and offerings" }, "team": { "keywords": ["team", "staff", "who", "people", "employees", "founders", "ceo", "cto", "about"], "context": "team information" }, "support": { "keywords": ["support", "help", "assistance", "problem", "issue", "ticket", "emergency"], "context": "support and assistance" }, "pricing": { "keywords": ["price", "cost", "pricing", "fee", "rates", "budget", "expensive", "cheap", "money"], "context": "pricing information" }, "general": { "keywords": ["hello", "hi", "hey", "what", "who", "company", "business", "about"], "context": "general information" } } def search_knowledge(self, query: str) -> Dict[str, Any]: """Search knowledge base for relevant information.""" query_lower = query.lower() matches = {} for category, pattern in self.knowledge_patterns.items(): score = sum(1 for keyword in pattern["keywords"] if keyword in query_lower) if score > 0: matches[category] = { "score": score, "context": pattern["context"], "data": self._get_category_data(category) } return dict(sorted(matches.items(), key=lambda x: x[1]["score"], reverse=True)) def _get_category_data(self, category: str) -> Any: """Get data for a specific category.""" category_mapping = { "hours": self.business_info["hours"], "location": self.business_info["location"], "contact": self.business_info["contact"], "services": self.business_info["services"], "team": self.business_info["team"], "support": self.business_info["support"], "pricing": [service for service in self.business_info["services"]] } return category_mapping.get(category, {}) def generate_business_context(self) -> str: """Generate comprehensive business context for AI queries.""" context_parts = [ f"Company: {self.business_info['company_name']}", f"Description: {self.business_info['description']}", f"Location: {self.business_info['location']['address']}, {self.business_info['location']['city']}, {self.business_info['location']['state']}", f"Phone: {self.business_info['contact']['phone']}", f"Email: {self.business_info['contact']['email']}", f"Website: {self.business_info['contact']['website']}", "", "Business Hours:", ] for day, hours in self.business_info["hours"].items(): if day != "holidays": if isinstance(hours, dict): context_parts.append(f" {day.title()}: {hours['open']} - {hours['close']} {hours['timezone']}") else: context_parts.append(f" {day.title()}: {hours}") context_parts.extend([ "", "Services:", ]) for service in self.business_info["services"]: context_parts.append(f" - {service['name']}: {service['description']} (Duration: {service['duration']}, Price: {service['price_range']})") return "\n".join(context_parts) class SupportTicketManager: """Advanced support ticket management system.""" def __init__(self): self.ticket_categories = [ "General Inquiry", "Technical Support", "Billing Question", "Service Request", "Bug Report", "Feature Request", "Emergency" ] self.priorities = ["Low", "Medium", "High", "Critical"] def create_ticket(self, title: str, description: str, category: str, priority: str, contact_info: Dict, user_session_id: str) -> Dict[str, Any]: """Create a new support ticket.""" ticket = { "id": self._generate_ticket_id(), "title": title, "description": description, "category": category, "priority": priority, "status": "Open", "created_at": datetime.now(), "updated_at": datetime.now(), "contact_info": contact_info, "user_session_id": user_session_id, "responses": [] } # Simulate external ticket system integration self._integrate_with_external_systems(ticket) return ticket def _generate_ticket_id(self) -> str: """Generate unique ticket ID.""" timestamp = datetime.now().strftime("%Y%m%d%H%M%S") random_suffix = hashlib.md5(str(time.time()).encode()).hexdigest()[:6] return f"TKT-{timestamp}-{random_suffix.upper()}" def _integrate_with_external_systems(self, ticket: Dict) -> bool: """Simulate integration with external ticket systems.""" try: # Simulate GitHub Issues integration github_issue = self._create_github_issue(ticket) # Simulate Jira integration jira_ticket = self._create_jira_ticket(ticket) # Simulate Trello integration trello_card = self._create_trello_card(ticket) ticket["external_integrations"] = { "github": github_issue, "jira": jira_ticket, "trello": trello_card } return True except Exception as e: st.warning(f"External integration warning: {e}") return False def _create_github_issue(self, ticket: Dict) -> Dict: """Simulate GitHub issue creation.""" return { "platform": "GitHub", "url": f"https://github.com/agentai-solutions/support/issues/{ticket['id']}", "issue_number": len(st.session_state.support_tickets) + 1, "status": "created", "labels": [ticket["category"].lower().replace(" ", "-"), ticket["priority"].lower()] } def _create_jira_ticket(self, ticket: Dict) -> Dict: """Simulate Jira ticket creation.""" return { "platform": "Jira", "url": f"https://agentai-solutions.atlassian.net/browse/{ticket['id']}", "key": ticket['id'], "status": "Open", "project": "SUPPORT" } def _create_trello_card(self, ticket: Dict) -> Dict: """Simulate Trello card creation.""" return { "platform": "Trello", "url": f"https://trello.com/c/{ticket['id'][:8]}", "board": "Customer Support", "list": "New Tickets", "card_id": ticket['id'][:8] } class BusinessAIAssistant: """Advanced AI-powered business assistant.""" def __init__(self): self.knowledge_base = BusinessKnowledgeBase(BUSINESS_INFO) self.ticket_manager = SupportTicketManager() if STREAMING_AVAILABLE: try: self.streaming_system = AdvancedStreamingSystem() self.ai_available = True except Exception as e: st.warning(f"AI streaming not available: {e}") self.ai_available = False else: self.ai_available = False def process_query(self, query: str, use_ai: bool = True) -> Dict[str, Any]: """Process user query with knowledge base and AI assistance.""" # Search knowledge base knowledge_matches = self.knowledge_base.search_knowledge(query) # Always try to provide a helpful response if use_ai and self.ai_available: try: ai_response = self._get_ai_response(query, knowledge_matches) return { "type": "ai_enhanced", "response": ai_response, "knowledge_matches": knowledge_matches, "confidence": "high" } except Exception as e: # Fall back to enhanced response pass # Use enhanced response logic enhanced_response = self._create_enhanced_response(query, knowledge_matches) return { "type": "enhanced", "response": enhanced_response, "knowledge_matches": knowledge_matches, "confidence": "medium" if knowledge_matches else "low" } def _get_ai_response(self, query: str, knowledge_matches: Dict) -> str: """Get AI-enhanced response using streaming system.""" try: # Create context-aware prompt business_context = self.knowledge_base.generate_business_context() # Prepare AI messages with more specific instructions messages = [ { "role": "system", "content": f"""You are a helpful business assistant for {BUSINESS_INFO['company_name']}. Business Information: {business_context} Instructions: - Always provide helpful responses based on the business information above - Be professional, friendly, and informative - Use the business hours, contact info, location, and services from the context - If asked about something not in the business info, acknowledge it politely and suggest contacting support - Keep responses conversational but informative - Always try to be helpful even for general questions""" }, { "role": "user", "content": query } ] # Use streaming system for AI response if self.streaming_system and hasattr(self.streaming_system, 'streamers') and self.streaming_system.streamers: provider = list(self.streaming_system.streamers.keys())[0] config = StreamingConfig( model="gemini-1.5-flash", temperature=0.3, max_tokens=500, show_timing=False ) # Use a simpler streaming approach for Streamlit streamer = self.streaming_system.streamers[provider] content_parts = [] for chunk in streamer.stream_completion(messages, config): content_parts.append(chunk.content) full_response = ''.join(content_parts) if full_response.strip(): return full_response.strip() except Exception as e: # Log the error but don't show to user import logging logging.warning(f"AI response error: {e}") # Enhanced fallback response return self._create_enhanced_response(query, knowledge_matches) def _create_enhanced_response(self, query: str, knowledge_matches: Dict) -> str: """Create enhanced response with better query understanding.""" query_lower = query.lower() # Always try to provide helpful information if knowledge_matches: return self._create_structured_response(knowledge_matches) # Smart fallback responses based on query patterns if any(word in query_lower for word in ['hello', 'hi', 'hey', 'greetings']): return f"Hello! Welcome to {BUSINESS_INFO['company_name']}. How can I help you today? You can ask about our business hours, location, services, or contact information." elif any(word in query_lower for word in ['help', 'assist', 'support']): return f"I'm here to help! I can provide information about {BUSINESS_INFO['company_name']} including:\n\n⢠š Business hours and schedule\n⢠š Location and directions\n⢠š¼ Services and offerings\n⢠š Contact information\n⢠š„ Our team\n\nWhat would you like to know?" elif any(word in query_lower for word in ['who', 'what', 'company', 'business']): return f"**About {BUSINESS_INFO['company_name']}**\n\n{BUSINESS_INFO['description']}\n\nš **Location:** {BUSINESS_INFO['location']['city']}, {BUSINESS_INFO['location']['state']}\nš **Phone:** {BUSINESS_INFO['contact']['phone']}\nš§ **Email:** {BUSINESS_INFO['contact']['email']}\n\nWould you like to know more about our services or how to contact us?" elif any(word in query_lower for word in ['thank', 'thanks']): return f"You're welcome! Is there anything else you'd like to know about {BUSINESS_INFO['company_name']}? I'm here to help with information about our services, hours, location, or anything else!" else: # General helpful response return f"I'd be happy to help you with information about {BUSINESS_INFO['company_name']}! While I don't have specific information about '{query}', I can help you with:\n\n⢠š **Business Hours:** When we're open\n⢠š **Location:** Where to find us\n⢠š¼ **Services:** What we offer\n⢠š **Contact:** How to reach us\n⢠š„ **Team:** Who we are\n\nWhat would you like to know more about?" def _create_structured_response(self, knowledge_matches: Dict) -> str: """Create structured response from knowledge base matches.""" if not knowledge_matches: return "I don't have specific information about that. Please contact our support team for assistance." response_parts = [] for category, match in list(knowledge_matches.items())[:2]: # Top 2 matches data = match["data"] if category == "hours": response_parts.append("š **Business Hours:**") for day, hours in data.items(): if day != "holidays": if isinstance(hours, dict): response_parts.append(f" ⢠{day.title()}: {hours['open']} - {hours['close']} {hours['timezone']}") else: response_parts.append(f" ⢠{day.title()}: {hours}") elif category == "location": response_parts.append(f"š **Location:**") response_parts.append(f" ⢠Address: {data['address']}") response_parts.append(f" ⢠City: {data['city']}, {data['state']} {data['zip']}") response_parts.append(f" ⢠Timezone: {data['timezone']}") elif category == "contact": response_parts.append("š **Contact Information:**") response_parts.append(f" ⢠Phone: {data['phone']}") response_parts.append(f" ⢠Email: {data['email']}") response_parts.append(f" ⢠Website: {data['website']}") elif category == "services": response_parts.append("š¼ **Our Services:**") for service in data[:3]: # Top 3 services response_parts.append(f" ⢠**{service['name']}**: {service['description']}") response_parts.append("") # Add spacing return "\n".join(response_parts) def display_business_header(): """Display business header with key information.""" st.markdown(f'
{BUSINESS_INFO["tagline"]}
', unsafe_allow_html=True) # Business card st.markdown(f"""š Phone: {BUSINESS_INFO["contact"]["phone"]}
š§ Email: {BUSINESS_INFO["contact"]["email"]}
š Website: {BUSINESS_INFO["contact"]["website"]}
š Location: {BUSINESS_INFO["location"]["city"]}, {BUSINESS_INFO["location"]["state"]}
Status: {ticket['status']}
Priority: {ticket['priority']}
Category: {ticket['category']}
Created: {ticket['created_at'].strftime('%Y-%m-%d %H:%M:%S')}
Expected Response: {BUSINESS_INFO['support']['response_time']}
You will receive updates at: {email}
ID: {ticket['id']}
Status: {ticket['status']}
Priority: {ticket['priority']} | Category: {ticket['category']}
Created: {ticket['created_at'].strftime('%Y-%m-%d %H:%M:%S')}
Description: {ticket['description'][:200]}...
Description: {BUSINESS_INFO['description']}
Tagline: {BUSINESS_INFO['tagline']}
Address: {BUSINESS_INFO['location']['address']}
City: {BUSINESS_INFO['location']['city']}, {BUSINESS_INFO['location']['state']} {BUSINESS_INFO['location']['zip']}
Country: {BUSINESS_INFO['location']['country']}
Timezone: {BUSINESS_INFO['location']['timezone']}
Phone: {BUSINESS_INFO['contact']['phone']}
Email: {BUSINESS_INFO['contact']['email']}
Support Email: {BUSINESS_INFO['contact']['support_email']}
Website: {BUSINESS_INFO['contact']['website']}
LinkedIn: Company Profile
Response Time: {BUSINESS_INFO['support']['response_time']}
Channels: {', '.join(BUSINESS_INFO['support']['channels'])}
Emergency: {BUSINESS_INFO['support']['emergency_contact']}
Description: {service['description']}
Duration: {service['duration']}
Price Range: {service['price_range']}
Role: {member['role']}
Expertise: {member['expertise']}