import os import warnings warnings.filterwarnings('ignore') # Fix for ChromaDB sqlite3 version requirement on HuggingFace Spaces try: __import__('pysqlite3') import sys sys.modules['sqlite3'] = sys.modules.pop('pysqlite3') except ImportError: pass import gradio as gr from langchain_community.document_loaders import TextLoader from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_huggingface import HuggingFaceEmbeddings from langchain_chroma import Chroma from langchain_core.messages import HumanMessage, SystemMessage from langgraph.graph import StateGraph, START, END from typing_extensions import TypedDict from langchain_google_genai import ChatGoogleGenerativeAI # Define Knowledge Base Paths policy_files = { "Data Privacy": "data/policy/data_privacy.txt", "Model Governance": "data/policy/model_governance.txt", "IT Infrastructure": "data/policy/it_infrastructure.txt", "HR & Remote Work": "data/policy/hr_and_remote_work.txt", "Expense Reimbursement": "data/policy/expense_reimbursement.txt" } # Ensure directory exists for HF Space if you plan to upload data files correctly. # NOTE: Make sure the 'data/' folder and txt files are uploaded to the hugging face repository alongside app.py! embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2") vector_stores = {} for category, file_path in policy_files.items(): if not os.path.exists(file_path): print(f"Warning: {file_path} not found. Please upload it to your HF space.") continue loader = TextLoader(file_path) docs = loader.load() splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0) chunks = splitter.split_documents(docs) # In-memory ChromaDB for EXACT retrieval per agent vector_stores[category] = Chroma.from_documents(chunks, embeddings) print("Loaded vector stores for:", list(vector_stores.keys())) # Initialize LLM # Hugging Face Spaces manages secrets. Add GOOGLE_API_KEY to your Space's Settings -> Secrets. api_key = os.environ.get("GOOGLE_API_KEY") if not api_key: print("WARNING: GOOGLE_API_KEY is not set in environment.") llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", temperature=0) # Define State class State(TypedDict): messages: list categories: list # e.g., ["Data Privacy", "Model Governance"] retrieved_context: str response: str # Routing Node def route_query(state: State): messages = state["messages"] query = messages[-1].content categories = list(policy_files.keys()) categories_str = ", ".join(categories) system_prompt = f"""You are a routing assistant for the Policy Navigator. Your job is to classify the user's query (which may be a full question, a partial phrase, or a single keyword) into one or more of the following exact policy categories: {categories_str} Use your reasoning to map keywords or partial phrases to the most relevant categories. For example, if the user asks "Can I buy a laptop for my home office?", map it to "IT Infrastructure, Expense Reimbursement, HR & Remote Work". If the query cannot be logically mapped to any of these categories, respond with "Unknown". Respond ONLY with a comma-separated list of the exact category names or "Unknown".""" msg = llm.invoke([ SystemMessage(content=system_prompt), HumanMessage(content=query) ]) raw_categories = [c.strip() for c in msg.content.split(",")] valid_categories = [c for c in raw_categories if c in categories] if not valid_categories: valid_categories = ["Unknown"] return {"categories": valid_categories} # Core Retrieval Node def retrieve(state: State): categories = state["categories"] messages = state["messages"] query = messages[-1].content all_contexts = [] for category in categories: if category in vector_stores: retriever = vector_stores[category].as_retriever(search_kwargs={"k": 2}) retrieved_docs = retriever.invoke(query) context = f"--- From {category} Policy ---\n" + "\n\n".join(doc.page_content for doc in retrieved_docs) all_contexts.append(context) if not all_contexts: final_context = "No relevant policy documents found." else: final_context = "\n\n".join(all_contexts) return {"retrieved_context": final_context} # Expert Agent Node (Generates response based on exact match context) def generate(state: State): categories = state["categories"] context = state["retrieved_context"] messages = state["messages"] query = messages[-1].content if "Unknown" in categories and len(categories) == 1: return {"response": "I'm sorry, I cannot determine which policy category your question belongs to. Please try to be more specific or ask about Data Privacy, Model Governance, IT Infrastructure, HR & Remote Work, or Expense Reimbursement."} cats_str = ", ".join(categories) system_prompt = f"""You are the policy expert for: {cats_str}. You MUST rely STRICTLY on the following excerpts from our internal policies to answer the user. If the answer is NOT present in the excerpts, reply: "I'm sorry, our official policy documents do not cover this exact scenario." Do not hallucinate external information. EXCERPTS: {context} """ msg = llm.invoke([ SystemMessage(content=system_prompt), HumanMessage(content=query) ]) return {"response": msg.content} # Build LangGraph graph_builder = StateGraph(State) graph_builder.add_node("route", route_query) graph_builder.add_node("retrieve", retrieve) graph_builder.add_node("generate", generate) graph_builder.add_edge(START, "route") graph_builder.add_edge("route", "retrieve") graph_builder.add_edge("retrieve", "generate") graph_builder.add_edge("generate", END) policy_graph = graph_builder.compile() # Build Gradio UI def process_query(query): if not query.strip(): return "Please enter a specific question about our policy.", "None" initial_state = { "messages": [HumanMessage(content=query)], "categories": [], "retrieved_context": "", "response": "" } try: result_state = policy_graph.invoke(initial_state) categories_used = ", ".join(result_state.get("categories", ["Unknown"])) return result_state["response"], categories_used except Exception as e: return f"An error occurred: {str(e)}\nPlease check if GOOGLE_API_KEY is configured in your space Secrets.", "Error" with gr.Blocks(title="Policy Navigator", theme=gr.themes.Monochrome()) as demo: gr.Markdown("# 🧭 Policy Navigator Chatbot") gr.Markdown("Ask a question about company policies. The appropriate policy agent will be automatically selected to answer your query.") with gr.Row(): user_input = gr.Textbox(placeholder="e.g., How many days can I work remotely?", label="Your Question", scale=4) submit_btn = gr.Button("Search Policy", scale=1) with gr.Row(): policy_source = gr.Textbox(label="Policy Source", interactive=False) output_text = gr.Textbox(label="Policy Answer", lines=5, interactive=False) submit_btn.click(fn=process_query, inputs=[user_input], outputs=[output_text, policy_source]) user_input.submit(fn=process_query, inputs=[user_input], outputs=[output_text, policy_source]) # Launch for HuggingFace spaces (doesn't need server_name/port configurations explicitly) demo.launch()