Spaces:
Runtime error
Runtime error
Update hybrid_search_.py
Browse files3 unmodified lines4567789101113141516121314151916171822192024212223282430252627283529303839404131323334463536373810 unmodified lines495051635253546667685556575859736061756263647865666768693 unmodified lines737475897677781 unmodified line8081829783848586102878889909110892939411295969711698991001201011021031241041051061071291081091101331111121136 unmodified lines1201211221461231241251261511271281291541301311321331591341351361621371381395 unmodified lines1451461471741481491501511521531541551561571581591601851611621631641651661671681911921931691701711721731741951751761771781791801811821831841851861871882061891901911922102112121931941951961971981992002012021 unmodified line20420520622120720822420921022721121221322 unmodified lines2362372382562392402412422432442622452462472482492502682512522532722542552742752762772562572582592602612622632642652662672682692702712832842852862722732741 unmodified line2762772782942792802812823 unmodified lines28628728830428929029110 unmodified lines3023033043213053233063073083095 unmodified lines3153163173353183193209 unmodified lines3303313323333343353361 unmodified line3383393403413423433443453463473483493503511 unmodified line3533543553563573583593603613623633643654 unmodified lines3703713723843733863743753769 unmodified lines38638738840238939039139216 unmodified lines4094104114254264124134144154163 unmodified linesimport requestsfrom typing import List, Dictfrom duckduckgo_search import DDGS
from 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 ChatGroq
from langchain_huggingface import HuggingFaceEmbeddings, HuggingFaceEndpointfrom langchain_chroma import Chroma
class ArloRAGPipeline: def __init__(self, def __init__(self, documents_path: str = "data/complete_arlo_docs.json", persist_directory: str = "data/chromadb", model_name: str = "llama-3.1-70b-versatile", model_name: str = "meta-llama/Llama-3.1-8B-Instruct", enable_web_search: bool = True): self.documents_path = documents_path self.persist_directory = persist_directory self.model_name = model_name # REMOVED: self.base_url = "http://127.0.0.1:11434" 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 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.") print(f"β οΈ {self.documents_path} not found.") return with open(self.documents_path, 'r', encoding='utf-8') as f:10 unmodified lines print(f"β Loaded {len(self.documents)} documents")
def create_vectorstore(self): """Generate embeddings and create ChromaDB vector store""" """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} 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_size=600, chunk_overlap=100 ) self.chunks = text_splitter.split_documents(self.documents) self.chunks = text_splitter.split_documents(self.documents) self.vectorstore = Chroma.from_documents( documents=self.chunks, embedding=embeddings,3 unmodified lines
def 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 mentions competitor_keywords = [ 'ring', 'nest', 'blink', 'wyze', 'eufy', 'reolink', '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', '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 lines
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](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. π¬ **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](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)
π **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 RAG1 unmodified line 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 = []22 unmodified lines return web_docs except Exception as e: print(f" β οΈ Web search failed: {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', '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""" """Initialize HuggingFace 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") # Get HF token from environment hf_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""" if not self.check_groq_connection(): # β Changed from check_ollama_connection print("β GROQ_API_KEY not found!") return False self.load_documents() self.create_vectorstore() self.setup_rag_chain()1 unmodified line print("\n" + "="*60) print("β
ARLO RAG PIPELINE READY WITH SAFETY GUARDRAILS!") print("="*60) print("\nπ‘οΈ Safety Features Enabled:") print("\nπ‘οΈ Safety Features Enabled:") print(" β’ Off-topic question filtering") print(" β’ Complaint handling & escalation") print(" β’ Competitor mention redirection")3 unmodified lines 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):10 unmodified lines # 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("π‘οΈ Safety filter triggered") print(f"\nπ‘ Answer:\n{safe_response}\n") return 5 unmodified lines # 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)9 unmodified lines # 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 problems1 unmodified lineβ’ 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 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 lines rag = ArloRAGPipeline( documents_path="data/complete_arlo_docs.json", persist_directory="data/chromadb", model_name="llama-3.1-70b-versatile", # β Changed model_name="meta-llama/Llama-3.1-8B-Instruct", enable_web_search=True ) 16 unmodified lines rag.query(q) print("\n" + "-"*60) else: print("β οΈ Please enter a question.") print("β οΈ Please enter a question.") except KeyboardInterrupt: print("\n\nπ Goodbye!") breakhybrid_search.py+60-73