Spaces:
Runtime error
Runtime error
Update hybrid_search.py
Browse files10 unmodified lines11121314151617187 unmodified lines262728293031323 unmodified lines3637383940414243444546474814 unmodified lines6364656667686917 unmodified lines8788899091929333 unmodified lines1271281291301311321334 unmodified lines13813914014114214314429 unmodified lines17417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723835 unmodified lines2742752762772782792806 unmodified lines2872882892902912922932942952 unmodified lines29829930030130230330430530630716 unmodified lines32432532632732832933038 unmodified lines3693703713723733743751 unmodified line3773783793803813823833843853863873883893901 unmodified line39239339439539639739839940040140240322 unmodified lines42642742842943043143210 unmodified linesfrom langchain_core.runnables import RunnablePassthroughfrom langchain_core.output_parsers import StrOutputParserfrom langchain_huggingface import HuggingFaceEmbeddings#from langchain_chroma import Chromaimport osfrom langchain_groq import ChatGroq7 unmodified linesself.documents_path = documents_pathself.persist_directory = persist_directoryself.model_name = model_nameself.base_url = "http://127.0.0.1:11434"self.enable_web_search = enable_web_searchself.documents = []3 unmodified linesprint("π Initializing Arlo RAG Pipeline with Safety Guardrails...")def check_groq_connection(self) -> bool:"""Check if Groq API key is available"""import osreturn bool(os.getenv("GROQ_API_KEY"))def load_documents(self):"""Load documents from JSON file"""print("\nπ Loading documents...")14 unmodified lines))print(f"β Loaded {len(self.documents)} documents")def create_vectorstore(self):"""Generate embeddings and create ChromaDB vector store"""print("π§ Generating embeddings (HuggingFace)...")17 unmodified lines)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"""33 unmodified lines'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',4 unmodified lines# Integrations'alexa', 'google home', 'smartthings', 'homekit', 'ifttt']is_arlo_related = any(keyword in question_lower for keyword in arlo_keywords)29 unmodified lines'is_sensitive': is_sensitive}def 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 RAGdef search_web(self, query: str, max_results: int = 3) -> List[Document]:"""Search web using DuckDuckGo with content filtering"""print(f" π Searching web for: {query}")35 unmodified linesprint(f" β οΈ Web search failed: {e}")return []def should_search_web(self, question: str) -> bool:"""Determine if question needs web search"""web_keywords = [6 unmodified linesreturn any(keyword in question.lower() for keyword in web_keywords)def setup_rag_chain(self):"""Initialize Ollama LLM"""print(f"π€ Setting up LLM ({self.model_name})...")self.llm = ChatGroq(model=self.model_name,2 unmodified lines)print(f"β LLM ready")def build(self):"""Build the complete RAG pipeline"""if not self.check_ollama_connection():return Falseself.load_documents()16 unmodified linesreturn Truedef query(self, question: str):"""Query the RAG system with safety layer"""if not self.vectorstore or not self.llm:38 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)22 unmodified linesrag = ArloRAGPipeline(documents_path="data/complete_arlo_docs.json",persist_directory="data/chromadb",model_name="llama3.1",enable_web_search=True)10 unmodified lines111213141516177 unmodified lines252627282930313 unmodified lines3536373839404142434414 unmodified lines59606162636417 unmodified lines82838485868733 unmodified lines1211221231241251261274 unmodified lines13213313413513613729 unmodified lines16716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721835 unmodified lines2542552562572582596 unmodified lines2662672682692702712722732 unmodified lines27627727827928028128228328428516 unmodified lines30230330430530630738 unmodified lines3463473483493503511 unmodified line3533543553563573583593603613623633641 unmodified line36636736836937037137237337422 unmodified lines39739839940040140240310 unmodified linesfrom langchain_core.runnables import RunnablePassthroughfrom langchain_core.output_parsers import StrOutputParserfrom langchain_huggingface import HuggingFaceEmbeddingsfrom langchain_chroma import Chroma # β Uncommentedfrom langchain_groq import ChatGroq7 unmodified linesself.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 = []3 unmodified linesprint("π 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...")14 unmodified lines))print(f"β Loaded {len(self.documents)} documents")def create_vectorstore(self):"""Generate embeddings and create ChromaDB vector store"""print("π§ Generating embeddings (HuggingFace)...")17 unmodified lines)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"""33 unmodified lines'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',4 unmodified lines# Integrations'alexa', 'google home', 'smartthings', 'homekit', 'ifttt']is_arlo_related = any(keyword in question_lower for keyword in arlo_keywords)29 unmodified lines'is_sensitive': is_sensitive}def 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 RAGdef search_web(self, query: str, max_results: int = 3) -> List[Document]:"""Search web using DuckDuckGo with content filtering"""print(f" π Searching web for: {query}")35 unmodified linesprint(f" β οΈ Web search failed: {e}")return []def should_search_web(self, question: str) -> bool:"""Determine if question needs web search"""web_keywords = [6 unmodified linesreturn 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,2 unmodified lines)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()16 unmodified linesreturn Truedef query(self, question: str):"""Query the RAG system with safety layer"""if not self.vectorstore or not self.llm:38 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)22 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)
hybrid_search.py+13-42