Upload folder using huggingface_hub
Browse filesFiles changed (2)
- __pycache__/app.cpython-314.pycAdded
- app.py+59-73
123456789101154 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221232 unmodified lines126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195import osimport warningsimport loggingwarnings.filterwarnings('ignore')logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")logger = logging.getLogger(__name__)# Fix for ChromaDB sqlite3 version requirement on HuggingFace Spacestry:__import__('pysqlite3')54 unmodified linesmessages: listcategory: str # e.g., "Data Privacy", "Model Governance", etc.retrieved_context: strsources: listresponse: str# Core Retrieval NodeRELEVANCE_THRESHOLD = 0.3def retrieve(state: State):category = state["category"]messages = state["messages"]query = messages[-1].contentlogger.info(f"[RETRIEVE] Category: {category!r} | Query: {query!r}")if category in vector_stores:results = vector_stores[category].similarity_search_with_relevance_scores(query, k=2)logger.info(f"[RETRIEVE] Raw scores: {[(round(score, 3), doc.metadata.get('source', '?')) for doc, score in results]}")relevant = [(doc, score) for doc, score in results if score >= RELEVANCE_THRESHOLD]if relevant:context = "\n\n".join(doc.page_content for doc, _ in relevant)sources = list({doc.metadata.get("source", "Unknown") for doc, _ in relevant})logger.info(f"[RETRIEVE] {len(relevant)} chunk(s) above threshold. Sources: {sources}")else:context = ""sources = []logger.warning(f"[RETRIEVE] No chunks above threshold {RELEVANCE_THRESHOLD}; scores were {[round(s, 3) for _, s in results]}")else:context = ""sources = []logger.warning(f"[RETRIEVE] No vector store found for category: {category!r}")return {"retrieved_context": context, "sources": sources}# Expert Agent Node (Generates response based on exact match context)def generate(state: State):category = state["category"]context = state["retrieved_context"]sources = state.get("sources", [])messages = state["messages"]query = messages[-1].contentlogger.info(f"[GENERATE] Category: {category!r} | Context length: {len(context)} chars")if not context:logger.info("[GENERATE] Empty context — returning fallback without calling LLM.")return {"response": "I'm sorry, our official policy document does not cover this exact scenario, or your query did not match any relevant policy content."}system_prompt = f"""You are the {category} expert for Policy Navigator.You MUST rely STRICTLY on the following excerpt from our internal policies to answer the user.If the answer is NOT present in the excerpt, reply: "I'm sorry, our official policy document does not cover this exact scenario."Do not hallucinate external information.EXCERPT:{context}"""2 unmodified linesSystemMessage(content=system_prompt),HumanMessage(content=query)])response = msg.contentlogger.info(f"[GENERATE] Response length: {len(response)} chars")if sources:source_names = ", ".join(os.path.basename(s) for s in sorted(sources))response += f"\n\n---\n**Sources:** {source_names}"return {"response": response}# Build LangGraphgraph_builder = StateGraph(State)graph_builder.add_node("retrieve", retrieve)graph_builder.add_node("generate", generate)graph_builder.add_edge(START, "retrieve")graph_builder.add_edge("retrieve", "generate")graph_builder.add_edge("generate", END)policy_graph = graph_builder.compile()# Build Gradio UIdef process_query(category, query):if not query.strip():return "Please enter a specific question about our policy.", ""if not category:return "Please select a specific policy category to search.", ""initial_state = {"messages": [HumanMessage(content=query)],"category": category,"retrieved_context": "","sources": [],"response": ""}try:result_state = policy_graph.invoke(initial_state)response = result_state["response"]retrieved = result_state.get("retrieved_context", "")debug_info = retrieved if retrieved else "(no chunks met the relevance threshold)"return response, debug_infoexcept Exception as e:error_msg = f"An error occurred: {str(e)}\nPlease check if GOOGLE_API_KEY is configured in your space Secrets."return error_msg, ""categories = list(policy_files.keys())with gr.Blocks(title="Policy Navigator", theme=gr.themes.Monochrome()) as demo:gr.Markdown("# 🧭 Policy Navigator Chatbot")gr.Markdown("Select a policy category and ask an exact query. I will strictly reference our internal knowledge base.")with gr.Row():category_dropdown = gr.Dropdown(choices=categories, label="Select Policy Category (Agent)", value=categories[0] if categories else None)with gr.Row():user_input = gr.Textbox(placeholder="e.g., How many days can I work remotely?", label="Your Question")with gr.Row():submit_btn = gr.Button("Search Policy")output_text = gr.Textbox(label="Policy Answer", lines=5, interactive=False)debug_text = gr.Textbox(label="Retrieved Context (Debug)", lines=5, interactive=False)submit_btn.click(fn=process_query, inputs=[category_dropdown, user_input], outputs=[output_text, debug_text])user_input.submit(fn=process_query, inputs=[category_dropdown, user_input], outputs=[output_text, debug_text])# Docker-based HuggingFace Spaces require binding to 0.0.0.0:7860demo.launch(server_name="0.0.0.0", server_port=7860)123456754 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241252 unmodified lines128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181import osimport warningswarnings.filterwarnings('ignore')# Fix for ChromaDB sqlite3 version requirement on HuggingFace Spacestry:__import__('pysqlite3')54 unmodified linesmessages: listcategory: str # e.g., "Data Privacy", "Model Governance", etc.retrieved_context: strresponse: str# Routing Nodedef route_query(state: State):messages = state["messages"]query = messages[-1].contentcategories = 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 into one of the following exact policy categories:{categories_str}If the query does not clearly fall into any of these categories, respond with "Unknown".Respond ONLY with the exact category name or "Unknown"."""msg = llm.invoke([SystemMessage(content=system_prompt),HumanMessage(content=query)])category = msg.content.strip()if category not in categories:category = "Unknown"return {"category": category}# Core Retrieval Nodedef retrieve(state: State):category = state["category"]messages = state["messages"]query = messages[-1].contentif category in vector_stores:retriever = vector_stores[category].as_retriever(search_kwargs={"k": 2})retrieved_docs = retriever.invoke(query)context = "\\n\\n".join(doc.page_content for doc in retrieved_docs)else:context = "No relevant policy documents found for this category."return {"retrieved_context": context}# Expert Agent Node (Generates response based on exact match context)def generate(state: State):category = state["category"]context = state["retrieved_context"]messages = state["messages"]query = messages[-1].contentif category == "Unknown":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."}system_prompt = f"""You are the {category} expert for Policy Navigator.You MUST rely STRICTLY on the following excerpt from our internal policies to answer the user.If the answer is NOT present in the excerpt, reply: "I'm sorry, our official policy document does not cover this exact scenario."Do not hallucinate external information.EXCERPT:{context}"""2 unmodified linesSystemMessage(content=system_prompt),HumanMessage(content=query)])return {"response": msg.content}# Build LangGraphgraph_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 UIdef process_query(query):if not query.strip():return "Please enter a specific question about our policy.", "None"initial_state = {"messages": [HumanMessage(content=query)],"category": "","retrieved_context": "","response": ""}try:result_state = policy_graph.invoke(initial_state)category_used = result_state.get("category", "Unknown")return result_state["response"], category_usedexcept 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()
__pycache__/app.cpython-314.pycAdded
app.py+59-73