Spaces:
Runtime error

agents / app.py
hengds2f's picture
Upload folder using huggingface_hub
9db7920 verified
Raw History Blame
6.83 kB
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
category: str # e.g., "Data Privacy", "Model Governance", etc.
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 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 Node
def retrieve(state: State):
category = state["category"]
messages = state["messages"]
query = messages[-1].content
if 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].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}
"""
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)],
"category": "",
"retrieved_context": "",
"response": ""
}
try:
result_state = policy_graph.invoke(initial_state)
category_used = result_state.get("category", "Unknown")
return result_state["response"], category_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()