Spaces:
Runtime error
Runtime error
Update hybrid_search_.py
Browse files3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484910 unmodified lines60616263646566676869707172737475767778798081823 unmodified lines868788899091921 unmodified line9495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351366 unmodified lines1431441451461471481491501511521531541551561571581591601611621631641655 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152161 unmodified line21821922022122222322422522622722822923022 unmodified lines2532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882891 unmodified line2912922932942952962973 unmodified lines30130230330430530630710 unmodified lines3183193203213223233243253265 unmodified lines3323333343353363373389 unmodified lines3483493503513523531 unmodified line3553563573583593603613623633643653661 unmodified line3683693703713723733743753764 unmodified lines3813823833843853863873883899 unmodified lines39940040140240340440516 unmodified lines4224234244254264274284293 unmodified linesimport 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.runnables import RunnablePassthroughfrom langchain_core.output_parsers import StrOutputParserfrom langchain_huggingface import HuggingFaceEmbeddingsfrom langchain_chroma import Chroma # β Uncommentedfrom langchain_groq import ChatGroqclass ArloRAGPipeline:def __init__(self,documents_path: str = "data/complete_arlo_docs.json",persist_directory: str = "data/chromadb",model_name: str = "llama-3.1-70b-versatile",enable_web_search: bool = True):self.documents_path = documents_pathself.persist_directory = persist_directoryself.model_name = model_name# REMOVED: self.base_url = "http://127.0.0.1:11434"self.enable_web_search = enable_web_searchself.documents = []self.chunks = []self.vectorstore = Noneself.llm = Noneprint("π Initializing Arlo RAG Pipeline with Safety Guardrails...")def check_groq_connection(self) -> bool:"""Check if Groq API key is available"""return bool(os.getenv("GROQ_API_KEY"))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.")returnwith open(self.documents_path, 'r', encoding='utf-8') as f:10 unmodified linesprint(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",model_kwargs={'device': 'cpu'},encode_kwargs={'normalize_embeddings': True})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,3 unmodified linesdef classify_query(self, question: str) -> dict:"""Classify if query is safe and on-topic"""question_lower = question.lower()# 1. Check if Arlo-related1 unmodified line# 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']6 unmodified lines'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 mentionscompetitor_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 topicssensitive_keywords = ['hack', 'breach', 'lawsuit', 'privacy violation','data leak', 'security flaw', 'exploit']is_sensitive = any(keyword in question_lower for keyword in sensitive_keywords)return {5 unmodified linesdef get_safe_response(self, question: str, classification: dict) -> str:"""Generate appropriate response based on query classification"""# Off-topic questionsif 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 supportHow can I assist you with Arlo today?"""# Complaints - empathetic redirectif 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](https://www.arlo.com/support)π§ **Email**: [support@arlo.com](mailto: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 redirectif 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 capabilitiesWhat specific Arlo features or capabilities would you like to learn about?"""# Sensitive topics - professional redirectif 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](https://www.arlo.com/privacy-policy)π‘οΈ **Security Information**: [https://www.arlo.com/security](https://www.arlo.com/security)π **Official Support**: [https://www.arlo.com/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 RAG1 unmodified linedef 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 sourcessafe_query = f"{query} site:arlo.com OR site:kb.arlo.com"results = list(ddgs.text(safe_query, max_results=max_results))web_docs = []22 unmodified linesreturn web_docsexcept 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 Groq LLM"""print(f"π€ Setting up LLM ({self.model_name})...")self.llm = ChatGroq(model=self.model_name,temperature=0,groq_api_key=os.getenv("GROQ_API_KEY"))print(f"β LLM ready")def build(self):"""Build the complete RAG pipeline"""if not self.check_groq_connection(): # β Changed from check_ollama_connectionprint("β GROQ_API_KEY not found!")return Falseself.load_documents()self.create_vectorstore()self.setup_rag_chain()1 unmodified lineprint("\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")3 unmodified linesprint("π Documents:", len(self.documents))print("π¦ Chunks:", len(self.chunks))print("\nπ― Ready to answer Arlo questions safely!\n")return Truedef query(self, question: str):10 unmodified lines# STEP 2: Check if we need a safe/canned responsesafe_response = self.get_safe_response(question, classification)if safe_response:print("π‘οΈ Safety filter triggered")print(f"\nπ‘ Answer:\n{safe_response}\n")return5 unmodified lines# Check if we need web searchall_docs = kb_resultsif self.enable_web_search and self.should_search_web(question):print("π Enhancing with web search...")web_docs = self.search_web(question, max_results=3)9 unmodified lines# Build prompt with safety instructionstemplate = """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 problems1 unmodified lineβ’ Never speculate about security issues, bugs, or company policiesβ’ Always cite official Arlo sourcesβ’ Do not acknowledge or repeat negative commentsANSWER 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/mattersCONTENT RULES:β’ Synthesize information from ALL provided context chunksβ’ Structure your answer with clear sections if the topic is complex1 unmodified lineβ’ 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)4 unmodified lines"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.")9 unmodified linesrag = ArloRAGPipeline(documents_path="data/complete_arlo_docs.json",persist_directory="data/chromadb",model_name="llama-3.1-70b-versatile", # β Changedenable_web_search=True)16 unmodified linesrag.query(q)print("\n" + "-"*60)else:print("β οΈ Please enter a question.")except KeyboardInterrupt:print("\n\nπ Goodbye!")break3 unmodified lines456789101112131415161718192021222324252627282930313233343536373810 unmodified lines4950515253545556575859606162636465666768693 unmodified lines7374757677781 unmodified line80818283848586878889909192939495969798991001011021031041051061071081091101111121136 unmodified lines1201211221231241251261271281291301311321331341351361371381395 unmodified lines1451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012021 unmodified line20420520620720820921021121221322 unmodified lines2362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732741 unmodified line2762772782792802812823 unmodified lines28628728828929029110 unmodified lines3023033043053063073083095 unmodified lines3153163173183193209 unmodified lines3303313323333343353361 unmodified line3383393403413423433443453463473483493503511 unmodified line3533543553563573583593603613623633643654 unmodified lines3703713723733743753769 unmodified lines38638738838939039139216 unmodified lines4094104114124134144154163 unmodified linesimport 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.runnables import RunnablePassthroughfrom langchain_core.output_parsers import StrOutputParserfrom langchain_huggingface import HuggingFaceEmbeddings, HuggingFaceEndpointfrom langchain_chroma import Chromaclass ArloRAGPipeline:def __init__(self,documents_path: str = "data/complete_arlo_docs.json",persist_directory: str = "data/chromadb",model_name: str = "meta-llama/Llama-3.1-8B-Instruct",enable_web_search: bool = True):self.documents_path = documents_pathself.persist_directory = persist_directoryself.model_name = model_nameself.enable_web_search = enable_web_searchself.documents = []self.chunks = []self.vectorstore = Noneself.llm = Noneprint("π 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.")returnwith open(self.documents_path, 'r', encoding='utf-8') as f:10 unmodified linesprint(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,3 unmodified linesdef classify_query(self, question: str) -> dict:"""Classify if query is safe and on-topic"""question_lower = question.lower()# 1. Check if Arlo-related1 unmodified line# 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']6 unmodified lines'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 mentionscompetitor_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 topicssensitive_keywords = ['hack', 'breach', 'lawsuit', 'privacy violation','data leak', 'security flaw', 'exploit']is_sensitive = any(keyword in question_lower for keyword in sensitive_keywords)return {5 unmodified linesdef get_safe_response(self, question: str, classification: dict) -> str:"""Generate appropriate response based on query classification"""# Off-topic questionsif 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 supportHow can I assist you with Arlo today?"""# Complaints - empathetic redirectif 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.comOur 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 redirectif 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 capabilitiesWhat specific Arlo features or capabilities would you like to learn about?"""# Sensitive topics - professional redirectif 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/supportArlo 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 RAG1 unmodified linedef 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 sourcessafe_query = f"{query} site:arlo.com OR site:kb.arlo.com"results = list(ddgs.text(safe_query, max_results=max_results))web_docs = []22 unmodified linesreturn web_docsexcept 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 HuggingFace LLM"""print(f"π€ Setting up LLM ({self.model_name})...")# Get HF token from environmenthf_token = os.getenv("HF_TOKEN")if not hf_token:print("β οΈ Warning: HF_TOKEN not found in environment variables")self.llm = HuggingFaceEndpoint(repo_id=self.model_name,temperature=0.1,max_new_tokens=512,huggingfacehub_api_token=hf_token)print(f"β LLM ready")def build(self):"""Build the complete RAG pipeline"""self.load_documents()self.create_vectorstore()self.setup_rag_chain()1 unmodified lineprint("\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")3 unmodified linesprint("π Documents:", len(self.documents))print("π¦ Chunks:", len(self.chunks))print("\nπ― Ready to answer Arlo questions safely!\n")return Truedef query(self, question: str):10 unmodified lines# STEP 2: Check if we need a safe/canned responsesafe_response = self.get_safe_response(question, classification)if safe_response:print("π‘οΈ Safety filter triggered")print(f"\nπ‘ Answer:\n{safe_response}\n")return5 unmodified lines# Check if we need web searchall_docs = kb_resultsif self.enable_web_search and self.should_search_web(question):print("π Enhancing with web search...")web_docs = self.search_web(question, max_results=3)9 unmodified lines# Build prompt with safety instructionstemplate = """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 problems1 unmodified lineβ’ Never speculate about security issues, bugs, or company policiesβ’ Always cite official Arlo sourcesβ’ Do not acknowledge or repeat negative commentsANSWER 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/mattersCONTENT RULES:β’ Synthesize information from ALL provided context chunksβ’ Structure your answer with clear sections if the topic is complex1 unmodified lineβ’ 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)4 unmodified lines"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.")9 unmodified linesrag = ArloRAGPipeline(documents_path="data/complete_arlo_docs.json",persist_directory="data/chromadb",model_name="meta-llama/Llama-3.1-8B-Instruct",enable_web_search=True)16 unmodified linesrag.query(q)print("\n" + "-"*60)else:print("β οΈ Please enter a question.")except KeyboardInterrupt:print("\n\nπ Goodbye!")break
hybrid_search.py+60-73