Upload folder using huggingface_hub
Browse filesFiles changed (2)
- __pycache__/app.cpython-314.pycAdded
- app.py+59-73
1233467856754 unmodified lines6263646965667273676869707172737475767778798081828384858687888990919293949596977980819899838485868788899091929394100101102103969798991001041051061071081091101111061121131091101111121131141141151161171181191201211201221231241252 unmodified lines128129130129130131132133134135136137131132133134135136137138143139140141142143144145149146147151152153154148149150151157152153159154155162156157158165166167168159160161170171172173162163164165177166167168180169170171172183184185186173174175189190191192176177178179194195180181import 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 lines messages: list category: str # e.g., "Data Privacy", "Model Governance", etc. retrieved_context: str sources: list response: str
# Core Retrieval NodeRELEVANCE_THRESHOLD = 0.3# Routing Nodedef 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 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].content
logger.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]}") 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 = "" sources = [] logger.warning(f"[RETRIEVE] No vector store found for category: {category!r}")
return {"retrieved_context": context, "sources": sources} 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"] sources = state.get("sources", []) messages = state["messages"] query = messages[-1].content
logger.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."} if 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 lines SystemMessage(content=system_prompt), HumanMessage(content=query) ])
response = msg.content logger.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} 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, "retrieve")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(category, query):def process_query(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.", ""
return "Please enter a specific question about our policy.", "None" initial_state = { "messages": [HumanMessage(content=query)], "category": 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_info category_used = result_state.get("category", "Unknown") return result_state["response"], category_used except 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()) 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("Select a policy category and ask an exact query. I will strictly reference our internal knowledge base.") gr.Markdown("Ask a question about company policies. The appropriate policy agent will be automatically selected to answer your query.") with gr.Row(): category_dropdown = gr.Dropdown(choices=categories, label="Select Policy Category (Agent)", value=categories[0] if categories else None) 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(): 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") policy_source = gr.Textbox(label="Policy Source", interactive=False) 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]) 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])
# Docker-based HuggingFace Spaces require binding to 0.0.0.0:7860demo.launch(server_name="0.0.0.0", server_port=7860)# Launch for HuggingFace spaces (doesn't need server_name/port configurations explicitly)demo.launch()__pycache__/app.cpython-314.pycAdded
app.py+59-73