Spaces:
Sleeping
Sleeping
configured with openrouter
Browse filesFiles changed (2)
2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404 unmodified lines454647484950515253545556575859609 unmodified lines707172737475767778798081825 unmodified lines888990919293949516 unmodified lines11211311411511611711814 unmodified lines1331341351361371381397 unmodified lines14714814915015115215315440 unmodified lines1951961971981992002017 unmodified lines2092102112122132142 unmodified linesfrom dotenv import load_dotenvfrom langchain_core.documents import Documentfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_openai import OpenAIEmbeddings, OpenAIfrom langchain.chains.question_answering import load_qa_chainfrom langchain_community.vectorstores import Chromafrom langchain.chains import LLMChainfrom langchain.prompts import PromptTemplateload_dotenv()CHROMA_HOST = os.getenv("CHROMA_HOST", "localhost")COLLECTION_NAME = "company_docs_collection"vector_store = Nonecompany_qa_chain = Nonequery_router_chain = Nonecybersecurity_chain = Nonellm = OpenAI(temperature=0)def initialize_pipelines():"""Initializes all required models, chains, and the vector store."""global vector_store, company_qa_chain, query_router_chain, cybersecurity_chain, llmtry:embeddings = OpenAIEmbeddings()# Initialize ChromaDB clienttry:chroma_client = chromadb.HttpClient(host=CHROMA_HOST, port=8000)chroma_client.heartbeat() # Heartbeat check to confirm the connectionprint("Successfully connected to ChromaDB.")except Exception as e:print(f"FATAL: Could not connect to ChromaDB at {CHROMA_HOST}:8000. Please ensure the ChromaDB server is running.")print(f"Error details: {e}")raise ConnectionError("Failed to connect to ChromaDB.") from e# Initialize vector store4 unmodified lines)# Query Router Chainrouter_template = """You are a query classifier. Classify the following query into one of these categories:- COMPANY: Questions about company policies, procedures, documents, or internal information- CYBERSECURITY: Questions about cybersecurity, security threats, best practices, or vulnerabilities- OFF_TOPIC: Questions that don't fit the above categoriesQuery: {query}Respond with only the category name (COMPANY, CYBERSECURITY, or OFF_TOPIC):"""router_prompt = PromptTemplate(input_variables=["query"],9 unmodified linescompany_qa_chain = load_qa_chain(llm, chain_type="stuff")# Cybersecurity Chaincybersecurity_template = """You are a cybersecurity expert. Answer the following cybersecurity question based on your knowledge:Question: {question}Provide a comprehensive and accurate answer about cybersecurity:"""cybersecurity_prompt = PromptTemplate(input_variables=["question"],5 unmodified linesprompt=cybersecurity_prompt)print("All pipelines initialized successfully!")except Exception as e:print(f"Error initializing pipelines: {e}")raise16 unmodified linesprint("Document was empty after splitting, not adding to ChromaDB.")return Falseprint(f"Adding {len(docs)} document chunks to ChromaDB...")vector_store.add_documents(docs)print("Successfully added documents.")return True14 unmodified linesroute_result = query_router_chain.run(query)route = route_result.strip().upper()print(f"Query routed to: {route}")# 2. Route to appropriate logicif "CYBERSECURITY" in route:7 unmodified lineselif "COMPANY" in route:# Perform similarity search on ChromaDBdocs = vector_store.similarity_search(query, k=3)print(f"Found {len(docs)} relevant documents.")print(f"Documents: {[doc.metadata.get('source', 'Unknown') for doc in docs]}")if not docs:return {40 unmodified lines"vector_store": vector_store is not None,"company_qa_chain": company_qa_chain is not None,"query_router_chain": query_router_chain is not None,"cybersecurity_chain": cybersecurity_chain is not None}return {7 unmodified lines"error": str(e)}# Initialize pipelines on module importtry:initialize_pipelines()2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061624 unmodified lines67686970717273747576777879809 unmodified lines909192939495969798991005 unmodified lines10610710810911011111216 unmodified lines12913013113213313414 unmodified lines1491501511521531547 unmodified lines16216316416516616740 unmodified lines2082092102112122132142157 unmodified lines2232242252262272282292302312322332342352362372382392402412422 unmodified linesfrom dotenv import load_dotenvfrom langchain_core.documents import Documentfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom langchain_community.llms import OpenAIfrom langchain.chains.question_answering import load_qa_chainfrom langchain_community.vectorstores import Chromafrom langchain.chains import LLMChainfrom langchain.prompts import PromptTemplatefrom langchain.chat_models import ChatOpenAIload_dotenv()CHROMA_HOST = os.getenv("CHROMA_HOST", "localhost")COLLECTION_NAME = "company_docs_collection"# OpenRouter configurationOPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")vector_store = Nonecompany_qa_chain = Nonequery_router_chain = Nonecybersecurity_chain = Nonellm = Nonedef initialize_pipelines():"""Initializes all required models, chains, and the vector store."""global vector_store, company_qa_chain, query_router_chain, cybersecurity_chain, llmtry:# Check for required API keysif not OPENROUTER_API_KEY:raise ValueError("OPENROUTER_API_KEY environment variable is required")# Initialize LLM with OpenRouterllm = ChatOpenAI(model="meta-llama/llama-3.3-70b-instruct:free",openai_api_key=OPENROUTER_API_KEY,openai_api_base="https://openrouter.ai/api/v1",temperature=0,max_tokens=2048,)embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2",model_kwargs={'device': 'cpu'},encode_kwargs={'normalize_embeddings': True} # Normalize embeddings for better similarity search)# Initialize ChromaDB clienttry:chroma_client = chromadb.HttpClient(host=CHROMA_HOST, port=8000)chroma_client.heartbeat() # Heartbeat check to confirm the connectionexcept Exception as e:raise ConnectionError("Failed to connect to ChromaDB.") from e# Initialize vector store4 unmodified lines)# Query Router Chainrouter_template = """You are a query classifier. Classify the following query into one of these categories:- COMPANY: Questions about company policies, procedures, documents, or internal information- CYBERSECURITY: Questions about cybersecurity, security threats, best practices, or vulnerabilities- OFF_TOPIC: Questions that don't fit the above categoriesQuery: {query}Respond with only the category name (COMPANY, CYBERSECURITY, or OFF_TOPIC):"""router_prompt = PromptTemplate(input_variables=["query"],9 unmodified linescompany_qa_chain = load_qa_chain(llm, chain_type="stuff")# Cybersecurity Chaincybersecurity_template = """You are a cybersecurity expert. Answer the following cybersecurity question based on your knowledge without claiming yourself as expert:Question: {question}Provide a comprehensive and accurate answer about cybersecurity:"""cybersecurity_prompt = PromptTemplate(input_variables=["question"],5 unmodified linesprompt=cybersecurity_prompt)except Exception as e:print(f"Error initializing pipelines: {e}")raise16 unmodified linesprint("Document was empty after splitting, not adding to ChromaDB.")return Falsevector_store.add_documents(docs)print("Successfully added documents.")return True14 unmodified linesroute_result = query_router_chain.run(query)route = route_result.strip().upper()# 2. Route to appropriate logicif "CYBERSECURITY" in route:7 unmodified lineselif "COMPANY" in route:# Perform similarity search on ChromaDBdocs = vector_store.similarity_search(query, k=3)if not docs:return {40 unmodified lines"vector_store": vector_store is not None,"company_qa_chain": company_qa_chain is not None,"query_router_chain": query_router_chain is not None,"cybersecurity_chain": cybersecurity_chain is not None,"llm": llm is not None}return {7 unmodified lines"error": str(e)}# Test function to verify OpenRouter connectiondef test_openrouter_connection():"""Test the OpenRouter API connection."""try:if not llm:initialize_pipelines()# Simple test querytest_response = llm("Say 'Hello, OpenRouter is working!'")return Trueexcept Exception as e:print(f"OpenRouter connection test failed: {e}")return False# Initialize pipelines on module importtry:initialize_pipelines()
27 unmodified lines2829303127 unmodified linesPyPDF2tiktokenchromadblangchain_chroma27 unmodified lines28293031323327 unmodified linesPyPDF2tiktokenchromadblangchain_chromasentence-transformerstf-keras
features/rag_chatbot/rag_pipeline.py+58-30
requirements.txt+3-1