Spaces:
Runtime error
Runtime error
manasmaskar commited on
Commit Β·
9242a52
1
Parent(s): f760934
Initial deployment: AI Agent
Browse filesFiles changed (5)
- README.md+64-20
- app.pyAdded+50
- data/complete_arlo_docs.jsonAdded
- hybrid_search.pyAdded+427
- templates/index.htmlAdded+199
1234567891011121314151617181920---title: Customer AI AGENTemoji: πcolorFrom: redcolorTo: redsdk: dockerapp_port: 8501tags:- streamlitpinned: falseshort_description: Streamlit template spacelicense: apache-2.0---# Welcome to Streamlit!Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364Arlo AI Support AgentA secure RAG-based customer support assistant for Arlo products using LangChain, HuggingFace, and ChromaDB.Featuresπ‘οΈ Safety guardrails for customer supportπ Hybrid search (Knowledge Base + Web Search)π€ Powered by Llama 3.1 via HuggingFace Inference APIπ Vector search with ChromaDBπ Real-time web search with DuckDuckGoπ¬ Interactive web interfaceDeveloperManas Maskar - Software Engineer & ML SpecialistHow It WorksUser asks a question about Arlo productsSystem classifies query for safety (blocks off-topic, complaints, etc.)Retrieves relevant documents from vector databaseOptionally searches web for latest informationLLM generates helpful, professional responseAPI EndpointsGET / - Web interfaceGET /health - Health checkPOST /query - Query the RAG systemjson{"question": "How do I reset my Arlo camera?"}Environment VariablesHF_TOKEN - HuggingFace API token (required) - Add in Space Settings β Repository secretsLocal Developmentbash# Install dependenciespip install -r requirements.txt# Set HF tokenexport HF_TOKEN=your_token_here# Run apppython app.pyTech StackBackend: Flask, LangChainLLM: Meta Llama 3.1 (via HuggingFace)Vector DB: ChromaDBEmbeddings: sentence-transformers/all-MiniLM-L6-v2Web Search: DuckDuckGo Search API
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950from flask import Flask, render_template, request, jsonifyfrom hybrid_search import ArloRAGPipelineimport threading
app = Flask(__name__)
# Initialize RAG on startup (happens once)print("π Initializing RAG Pipeline...")rag = ArloRAGPipeline(enable_web_search=True)rag.build()print("β
RAG Ready!")
@app.route('/')def home(): return render_template('index.html')
@app.route('/health')def health(): return jsonify({"status": "healthy", "rag_ready": rag.vectorstore is not None})
@app.route('/query', methods=['POST'])def query(): question = request.json.get('question', '') if not question: return jsonify({"error": "No question provided"}), 400
# Capture RAG output import io import sys old_stdout = sys.stdout sys.stdout = buffer = io.StringIO()
rag.query(question)
output = buffer.getvalue() sys.stdout = old_stdout
# Extract answer if "π‘ Answer:" in output: answer = output.split("π‘ Answer:")[1].strip() else: answer = output
return jsonify({ "question": question, "answer": answer })
if __name__ == '__main__': app.run(host='0.0.0.0', port=7860)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427import osfrom dotenv import load_dotenv
# Load environment variables from .env fileload_dotenv()
import jsonimport shutilimport requestsfrom typing import List, Dictfrom duckduckgo_search import DDGSfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_core.documents import Documentfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.output_parsers import StrOutputParserfrom langchain_huggingface import HuggingFaceEmbeddingsfrom langchain_chroma import Chromafrom langchain_openai import ChatOpenAI
class ArloRAGPipeline: def __init__(self, documents_path: str = "data/complete_arlo_docs.json", persist_directory: str = "data/chromadb", model_name: str = "gpt-3.5-turbo", enable_web_search: bool = True): self.documents_path = documents_path self.persist_directory = persist_directory self.model_name = model_name self.enable_web_search = enable_web_search self.documents = [] self.chunks = [] self.vectorstore = None self.llm = None print("π Initializing Arlo RAG Pipeline with Safety Guardrails...")
def load_documents(self): """Load documents from JSON file""" print("\nπ Loading documents...") if not os.path.exists(self.documents_path): print(f"β οΈ {self.documents_path} not found.") return with open(self.documents_path, 'r', encoding='utf-8') as f: docs_data = json.load(f) for doc in docs_data: self.documents.append(Document( page_content=doc.get('content', ''), metadata={ 'title': doc.get('title', 'Untitled'), 'source': 'knowledge_base' } )) print(f"β Loaded {len(self.documents)} documents")
def create_vectorstore(self): """Generate embeddings and create ChromaDB vector store""" print("π§ Generating embeddings (HuggingFace)...") embeddings = HuggingFaceEmbeddings( model_name="sentence-transformers/all-MiniLM-L6-v2" ) if os.path.exists(self.persist_directory): shutil.rmtree(self.persist_directory) text_splitter = RecursiveCharacterTextSplitter( chunk_size=600, chunk_overlap=100 ) self.chunks = text_splitter.split_documents(self.documents) self.vectorstore = Chroma.from_documents( documents=self.chunks, embedding=embeddings, persist_directory=self.persist_directory ) print(f"β Vector store ready with {len(self.chunks)} chunks")
def classify_query(self, question: str) -> dict: """Classify if query is safe and on-topic""" question_lower = question.lower() # 1. Check if Arlo-related arlo_keywords = [ # Brand / Models 'arlo', 'arlo pro', 'arlo ultra', 'arlo essential', 'arlo go', 'arlo doorbell', 'arlo baby', 'arlo q', # Devices & Hardware 'camera', 'cameras', 'doorbell', 'floodlight', 'spotlight', 'smarthub', 'base station', 'hub', 'chime', 'mount', 'charger', 'cable', 'solar panel', 'battery', 'rechargeable battery', # Features 'video', 'recording', 'live view', 'motion', 'motion detection', 'alert', 'notification', 'audio', 'two way audio', 'night vision', 'spotlight', 'siren', 'zoom', 'activity zone', 'geofencing', 'smart detection', 'ai detection', 'package detection', # App / Software 'app', 'ios', 'android', 'firmware', 'update', 'account', 'login', 'password', 'two factor', '2fa', 'cloud', # Subscription / Plans 'subscription', 'plan', 'trial', 'arlo secure', 'arlo safe', 'cloud storage', 'local storage', 'sd card', 'usb storage', # Setup / Installation 'setup', 'install', 'pair', 'sync', 'add device', 'connect', 'wifi', 'network', 'router', 'signal', 'offline', # Modes / Automations 'mode', 'routine', 'automation', 'schedule', 'arm', 'disarm', 'home mode', 'away mode', 'rules', # Troubleshooting 'reset', 'restart', 'not working', 'won\'t connect', 'not charging', 'battery drain', 'offline', 'blinking light', 'amber light', 'blue light', 'no video', 'no recording', # Security / Privacy 'encryption', 'privacy', 'security', 'secure', 'data', 'video access', 'sharing', 'grant access', # Integrations 'alexa', 'google home', 'smartthings', 'homekit', 'ifttt' ] is_arlo_related = any(keyword in question_lower for keyword in arlo_keywords) # 2. Check for negative/complaint patterns complaint_keywords = [ 'terrible', 'worst', 'awful', 'scam', 'hate', 'disappointed', 'refund', 'lawsuit', 'cancel', 'useless', 'garbage', 'rip off', 'ripped off', 'don\'t buy', 'avoid' ] is_complaint = any(keyword in question_lower for keyword in complaint_keywords) # 3. Check for competitor mentions competitor_keywords = [ 'ring', 'nest', 'blink', 'wyze', 'eufy', 'reolink', 'simplisafe', 'google nest' ] has_competitor = any(keyword in question_lower for keyword in competitor_keywords) # 4. Check for sensitive topics sensitive_keywords = [ 'hack', 'breach', 'lawsuit', 'privacy violation', 'data leak', 'security flaw', 'exploit' ] is_sensitive = any(keyword in question_lower for keyword in sensitive_keywords) return { 'is_arlo_related': is_arlo_related, 'is_complaint': is_complaint, 'has_competitor': has_competitor, 'is_sensitive': is_sensitive }
def get_safe_response(self, question: str, classification: dict) -> str: """Generate appropriate response based on query classification""" # Off-topic questions if not classification['is_arlo_related']: return """I'm an Arlo customer support assistant specialized in helping with Arlo products, features, and services.
Your question doesn't appear to be related to Arlo. I'd be happy to help you with:
β’ Arlo camera setup and troubleshootingβ’ Subscription plans and featuresβ’ Battery and device informationβ’ Modes, Routines, and Automationsβ’ Account and app support
How can I assist you with Arlo today?"""
# Complaints - empathetic redirect if classification['is_complaint']: return """I understand you're experiencing frustration, and I sincerely want to help resolve your issue.
For immediate assistance with account-specific concerns or technical problems, please contact our dedicated support team:
π **Arlo Support**: 1-408-638-3750π¬ **Live Chat**: https://www.arlo.com/supportπ§ **Email**: support@arlo.com
Our support specialists can access your account details and provide personalized solutions.
Is there a specific technical issue I can help troubleshoot in the meantime?"""
# Competitor comparisons - neutral redirect if classification['has_competitor']: return """I specialize in Arlo products and can provide detailed information about Arlo's features, capabilities, and support.
I'd be happy to help you understand:
β’ Arlo's unique features and technologyβ’ Which Arlo camera best fits your needsβ’ Subscription plans and their valueβ’ Setup and optimization tipsβ’ Integration capabilities
What specific Arlo features or capabilities would you like to learn about?"""
# Sensitive topics - professional redirect if classification['is_sensitive']: return """For questions regarding security, privacy, or legal matters, please visit our official resources:
π **Privacy Policy**: https://www.arlo.com/privacy-policyπ‘οΈ **Security Information**: https://www.arlo.com/securityπ **Official Support**: https://www.arlo.com/support
Arlo takes security and privacy seriously. For specific concerns, our official support channels can provide accurate, up-to-date information.
Is there a technical or product-related question I can help you with?""" return None # Proceed with normal RAG
def search_web(self, query: str, max_results: int = 3) -> List[Document]: """Search web using DuckDuckGo with content filtering""" print(f" π Searching web for: {query}") try: ddgs = DDGS() # Prioritize official Arlo sources safe_query = f"{query} site:arlo.com OR site:kb.arlo.com" results = list(ddgs.text(safe_query, max_results=max_results)) web_docs = [] for result in results: content = result.get('body', '') # Filter out negative content negative_terms = [ 'terrible', 'worst', 'scam', 'avoid', 'don\'t buy', 'disappointed', 'awful', 'useless' ] if any(term in content.lower() for term in negative_terms): continue # Skip negative results web_docs.append(Document( page_content=content, metadata={ 'title': result.get('title', ''), 'url': result.get('href', ''), 'source': 'web_search' } )) print(f" β Found {len(web_docs)} verified web sources") return web_docs except Exception as e: print(f" β οΈ Web search failed: {e}") return []
def should_search_web(self, question: str) -> bool: """Determine if question needs web search""" web_keywords = [ 'latest', 'newest', 'current', 'today', 'recent', '2026', '2025', 'new', 'price', 'cost', 'buy', 'purchase', 'where to buy', 'compared to', 'vs', 'versus', 'comparison', 'reviews', 'ratings', 'best' ] return any(keyword in question.lower() for keyword in web_keywords)
def setup_rag_chain(self): """Initialize OpenAI LLM""" print(f"π€ Setting up LLM ...") # Get OpenAI API key from environment openai_key = os.getenv("OPENAI_API_KEY") if not openai_key: raise ValueError("β OPENAI_API_KEY not found in environment variables!") self.llm = ChatOpenAI( model=self.model_name, temperature=0.3, max_tokens=1200, api_key=openai_key ) print(f"β LLM ready")
def build(self): """Build the complete RAG pipeline""" self.load_documents() self.create_vectorstore() self.setup_rag_chain() print("\n" + "="*60) print("β
ARLO RAG PIPELINE READY WITH SAFETY GUARDRAILS!") print("="*60) print("\nπ‘οΈ Safety Features Enabled:") print(" β’ Off-topic question filtering") print(" β’ Complaint handling & escalation") print(" β’ Competitor mention redirection") print(" β’ Sensitive topic protection") print(" β’ Negative content filtering") print("\nπ Web Search:", "Enabled" if self.enable_web_search else "Disabled") print("π Documents:", len(self.documents)) print("π¦ Chunks:", len(self.chunks)) print("\nπ― Ready to answer Arlo questions safely!\n") return True
def query(self, question: str): """Query the RAG system with safety layer""" if not self.vectorstore or not self.llm: print("β Pipeline not initialized.") return print(f"\nβ Query: {question}") # STEP 1: Safety classification print("π Checking query safety...") classification = self.classify_query(question) # STEP 2: Check if we need a safe/canned response safe_response = self.get_safe_response(question, classification) if safe_response: print("π‘οΈ Safety filter triggered") print(f"\nπ‘ Answer:\n{safe_response}\n") return # STEP 3: Proceed with normal RAG (question is safe and on-topic) print("β
Query is safe and on-topic") # Get KB results kb_results = self.vectorstore.similarity_search(question, k=8) # Check if we need web search all_docs = kb_results if self.enable_web_search and self.should_search_web(question): print("π Enhancing with web search...") web_docs = self.search_web(question, max_results=3) all_docs = kb_results + web_docs else: print("π Using knowledge base only") # Format context context = "\n\n---\n\n".join([ f"[{doc.metadata.get('source', 'unknown').upper()}] {doc.metadata.get('title', 'Untitled')}\n{doc.page_content}" for doc in all_docs ]) # Build prompt with safety instructions template = """You are an expert Arlo customer support assistant. Provide clear, helpful, professional answers.
IMPORTANT SAFETY RULES:β’ Stay positive and professional at all timesβ’ Focus on solutions, not problemsβ’ If you don't know something, say "Please contact Arlo Support for account-specific assistance"β’ Never speculate about security issues, bugs, or company policiesβ’ Always cite official Arlo sourcesβ’ Do not acknowledge or repeat negative comments
ANSWER FORMAT RULES:β’ For yes/no questions: Start with "Yes." or "No." then explain whyβ’ For how-to questions: Use numbered steps with clear instructionsβ’ For tips/best practices: Use bullet points with emojis (β
, β οΈ, π‘) where helpfulβ’ For troubleshooting: Explain the issue, then provide the solutionβ’ Always add brief context on WHY something works/matters
CONTENT RULES:β’ Synthesize information from ALL provided context chunksβ’ Structure your answer with clear sections if the topic is complexβ’ Use formatting: **bold** for key terms, bullets for listsβ’ Be conversational but professionalβ’ If multiple solutions exist, present the best one firstβ’ End with citation: (Source: [document title])
Context from Arlo documentation:
{context}
Question: {question}
Helpful, well-formatted, professional answer:""" prompt = ChatPromptTemplate.from_template(template) # Generate answer try: response = (prompt | self.llm | StrOutputParser()).invoke({ "context": context, "question": question }) print(f"\nπ‘ Answer:\n{response}\n") except Exception as e: print(f"β Query failed: {e}") print("\nPlease try again or contact Arlo Support for assistance.")
if __name__ == "__main__": print("="*60) print("π ARLO SECURE RAG ASSISTANT") print("="*60) print("\nInitializing secure customer support system...\n") # Initialize with web search enabled and safety features rag = ArloRAGPipeline( documents_path="data/complete_arlo_docs.json", persist_directory="data/chromadb", model_name="gpt-3.5-turbo", enable_web_search=True ) if rag.build(): print("\n" + "="*60) print("π¬ INTERACTIVE MODE") print("="*60) print("Ask questions about Arlo products and support.") print("Type 'q' or 'exit' to quit.\n") while True: try: q = input("\nπ― Ask Arlo (or 'q' to quit): ").strip() if q.lower() in ['q', 'exit', 'quit']: print("\nπ Thank you for using Arlo Support Assistant. Goodbye!") break if q: rag.query(q) print("\n" + "-"*60) else: print("β οΈ Please enter a question.") except KeyboardInterrupt: print("\n\nπ Goodbye!") break except Exception as e: print(f"\nβ Error: {e}") print("Please try again.") else: print("\nβ Failed to initialize pipeline. Please check your setup.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199<!DOCTYPE html><html><head> <title>Arlo AI Agent - Manas Maskar</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; } .container { max-width: 900px; margin: 0 auto; background: white; border-radius: 20px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); overflow: hidden; } .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; } .header h1 { font-size: 2em; margin-bottom: 10px; } .header p { opacity: 0.9; font-size: 0.9em; } .developer { background: rgba(255,255,255,0.1); padding: 10px; border-radius: 10px; margin-top: 15px; font-size: 0.85em; } .chat-container { padding: 30px; min-height: 400px; max-height: 500px; overflow-y: auto; } .message { margin-bottom: 20px; padding: 15px; border-radius: 15px; max-width: 80%; } .user-message { background: #667eea; color: white; margin-left: auto; text-align: right; } .assistant-message { background: #f1f3f4; color: #333; } .input-container { padding: 20px; background: #f8f9fa; border-top: 1px solid #e0e0e0; display: flex; gap: 10px; } #questionInput { flex: 1; padding: 15px; border: 2px solid #e0e0e0; border-radius: 25px; font-size: 1em; outline: none; transition: border 0.3s; } #questionInput:focus { border-color: #667eea; } button { padding: 15px 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 25px; cursor: pointer; font-weight: bold; transition: transform 0.2s; } button:hover { transform: scale(1.05); } button:disabled { opacity: 0.5; cursor: not-allowed; } .loading { display: none; color: #667eea; padding: 10px; } .examples { padding: 20px; background: #f8f9fa; border-top: 1px solid #e0e0e0; } .examples h3 { margin-bottom: 10px; font-size: 1em; color: #666; } .example-btn { display: inline-block; margin: 5px; padding: 8px 15px; background: white; border: 1px solid #ddd; border-radius: 15px; cursor: pointer; font-size: 0.85em; transition: all 0.2s; } .example-btn:hover { background: #667eea; color: white; border-color: #667eea; } </style></head><body> <div class="container"> <div class="header"> <h1>π Arlo AI Support Agent</h1> <p>Powered by Retrieval-Augmented Generation (RAG)</p> <div class="developer"> π¨βπ» Developed by <strong>Manas Maskar</strong> | Software Engineer & ML Specialist </div> </div>
<div class="examples"> <h3>Try these questions:</h3> <span class="example-btn" onclick="askQuestion('Does Arlo support a trial plan?')">Trial Plan</span> <span class="example-btn" onclick="askQuestion('What battery does Arlo Pro 3 use?')">Battery Info</span> <span class="example-btn" onclick="askQuestion('How do I factory reset my camera?')">Factory Reset</span> <span class="example-btn" onclick="askQuestion('What are Arlo Modes and Routines?')">Modes & Routines</span> </div>
<div class="chat-container" id="chatContainer"></div>
<div class="input-container"> <input type="text" id="questionInput" placeholder="Ask anything about Arlo products..." onkeypress="if(event.key==='Enter') sendQuestion()" /> <button onclick="sendQuestion()" id="sendBtn">Send</button> </div> <div class="loading" id="loading">π€ Thinking...</div> </div>
<script> function addMessage(content, isUser) { const chatContainer = document.getElementById('chatContainer'); const messageDiv = document.createElement('div'); messageDiv.className = `message ${isUser ? 'user-message' : 'assistant-message'}`; messageDiv.innerHTML = content.replace(/\n/g, '<br>'); chatContainer.appendChild(messageDiv); chatContainer.scrollTop = chatContainer.scrollHeight; }
function askQuestion(question) { document.getElementById('questionInput').value = question; sendQuestion(); }
async function sendQuestion() { const input = document.getElementById('questionInput'); const question = input.value.trim(); if (!question) return; // Show user message addMessage(question, true); input.value = ''; // Show loading const loading = document.getElementById('loading'); const sendBtn = document.getElementById('sendBtn'); loading.style.display = 'block'; sendBtn.disabled = true; try { const response = await fetch('/query', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ question }) }); const data = await response.json(); addMessage(data.answer, false); } catch (error) { addMessage('β Error: Could not process your question. Please try again.', false); } finally { loading.style.display = 'none'; sendBtn.disabled = false; } }
// Show welcome message window.onload = () => { addMessage('π Hello! I\'m the Arlo AI Support Agent. Ask me anything about Arlo cameras, subscriptions, setup, or troubleshooting!', false); }; </script></body></html>README.md+64-20
app.pyAdded+50
data/complete_arlo_docs.jsonAdded
hybrid_search.pyAdded+427
templates/index.htmlAdded+199