# app.py
import os
import re
from dotenv import load_dotenv
load_dotenv()
# Auto-run ingestion if chroma_db is missing or empty
if not os.path.exists("./chroma_db") or not os.listdir("./chroma_db"):
from ingestion import run_ingestion
run_ingestion()
import streamlit as st
# ── 1. Configuration ───────────────────────────────────────────────────────────
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
POLICY_GUIDANCE = (
"I can help with company policy questions about PTO, remote work, expenses, "
"travel, security, onboarding, benefits, and related internal procedures."
)
SOCIAL_RESPONSES = {
"greeting": f"Hi! {POLICY_GUIDANCE} What policy question can I help with today?",
"thanks": f"You're welcome. {POLICY_GUIDANCE}",
"capability": POLICY_GUIDANCE,
"wellbeing": f"I'm ready to help. {POLICY_GUIDANCE}",
}
SOCIAL_WORD_LIMIT = 12
POLICY_KEYWORDS = {
"acceptable use", "benefit", "code of conduct", "company", "data privacy",
"employee", "expense", "holiday", "laptop", "leave", "onboarding", "parental",
"performance", "policy", "pto", "remote", "review", "safety", "security",
"sick", "travel", "work",
}
SOCIAL_INTENT_PATTERNS = {
"thanks": (r"\b(thanks?|thank\s+you|thx|appreciate(?:\s+it)?)\b",),
"capability": (
r"\b(what\s+can\s+you\s+do|what\s+do\s+you\s+do|who\s+are\s+you)\b",
r"\b(can\s+you\s+help(?:\s+me)?|help\s+me|help)\b",
),
"wellbeing": (
r"\b(how\s+are\s+(you|u)|how'?s\s+it\s+going|how\s+is\s+it\s+going)\b",
r"\b(hope\s+(you'?re|you\s+are)\s+(well|good|doing\s+well))\b",
r"\b(what'?s\s+up|wassup|sup|howdy)\b",
),
"greeting": (
r"\b(hi|hello|hey|hiya|greetings|yo)\b",
r"\b(good\s+)?(morning|afternoon|evening|day)\b",
),
}
SUGGESTION_CHIPS = [
"How many PTO days do I get?",
"What is the remote work policy?",
"How do I submit an expense report?",
"What are the travel booking guidelines?",
"What happens during onboarding?",
]
SYSTEM_PROMPT = (
"You are an assistant for question-answering tasks focused entirely on company policies.\n"
"Use the following pieces of retrieved context to answer the question. "
"Answer based strictly on the context provided — do not make up facts or extrapolate. "
"If the answer is genuinely not present in the context, say: "
"'I can only answer about our policies.'\n"
"Always cite the source document names/IDs accurately at the end of your response.\n\n"
"Context:\n{context}"
)
# ── 2. Custom CSS ──────────────────────────────────────────────────────────────
CUSTOM_CSS = """
"""
# ── 3. UI helpers ──────────────────────────────────────────────────────────────
def _render_header():
st.markdown("""
""", unsafe_allow_html=True)
def _render_badge(route: str):
if route == "policy":
st.markdown('◆ POLICY MATCH', unsafe_allow_html=True)
else:
st.markdown('◇ GENERAL REPLY', unsafe_allow_html=True)
def _docs_to_citations(docs: list) -> list[dict]:
"""Serialize only the display fields needed from Document objects."""
return [
{"name": os.path.basename(d.metadata.get("source", f"Document {i+1}")),
"excerpt": d.page_content[:220].strip()}
for i, d in enumerate(docs)
]
def _render_sources_expander(citations: list):
if not citations:
return
label = f"📎 {len(citations)} source{'s' if len(citations) > 1 else ''} referenced"
with st.expander(label):
for c in citations:
st.markdown(f"""
📄 {c['name']}
{c['excerpt']}…
""", unsafe_allow_html=True)
def _render_thinking():
st.markdown("""
""", unsafe_allow_html=True)
def _render_welcome_and_chips():
st.markdown("""
Good to see you 👋
Ask me anything about company policies — PTO, remote work, expenses,
travel, security, onboarding, benefits, and more.
""", unsafe_allow_html=True)
st.markdown('Try asking
', unsafe_allow_html=True)
cols = st.columns(len(SUGGESTION_CHIPS))
for col, chip_text in zip(cols, SUGGESTION_CHIPS):
with col:
if st.button(chip_text + " ↗", key=f"chip_{chip_text}", use_container_width=True):
st.session_state.pending_chip = chip_text
def _replay_history():
for msg in st.session_state.messages:
role = msg["role"]
with st.chat_message(role):
if role == "assistant":
_render_badge(msg.get("route", "policy"))
st.write(msg["content"])
if role == "assistant":
_render_sources_expander(msg.get("citations", []))
# ── 4. Intent routing ─────────────────────────────────────────────────────────
def normalize_query(user_query: str) -> str:
return " ".join(re.findall(r"[a-z0-9']+", user_query.lower()))
def has_policy_intent(normalized: str) -> bool:
return any(kw in normalized for kw in POLICY_KEYWORDS)
def get_general_response(user_query: str):
normalized = normalize_query(user_query)
if not normalized or has_policy_intent(normalized):
return None
if len(normalized.split()) > SOCIAL_WORD_LIMIT:
return None
for intent, patterns in SOCIAL_INTENT_PATTERNS.items():
if any(re.search(p, normalized) for p in patterns):
return SOCIAL_RESPONSES[intent]
return None
# ── 5. RAG system ─────────────────────────────────────────────────────────────
@st.cache_resource(show_spinner="Loading policy index…")
def init_rag_system():
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_chroma import Chroma
from langchain_openai import ChatOpenAI
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
vector_store = Chroma(persist_directory="./chroma_db", embedding_function=embeddings)
retriever = vector_store.as_retriever(search_kwargs={"k": 3})
llm = ChatOpenAI(
openai_api_base="https://openrouter.ai/api/v1",
openai_api_key=OPENROUTER_API_KEY,
model="openrouter/auto",
temperature=0.0,
max_tokens=512,
)
return retriever, llm
def format_docs(docs) -> str:
return "\n\n".join(doc.page_content for doc in docs)
_PROMPT_TEMPLATE = None
def _build_prompt(context_str: str, question: str):
global _PROMPT_TEMPLATE
if _PROMPT_TEMPLATE is None:
from langchain_core.prompts import ChatPromptTemplate
_PROMPT_TEMPLATE = ChatPromptTemplate.from_messages([
("system", SYSTEM_PROMPT),
("human", "{input}"),
])
return _PROMPT_TEMPLATE.invoke({"context": context_str, "input": question})
# ── 6. Process & render ───────────────────────────────────────────────────────
def _process_and_render(user_query: str):
st.session_state.messages.append({"role": "user", "content": user_query})
with st.chat_message("user"):
st.write(user_query)
general = get_general_response(user_query)
with st.chat_message("assistant"):
route = "general" if general else "policy"
_render_badge(route)
try:
if general:
st.write(general)
answer, citations = general, []
else:
thinking_slot = st.empty()
with thinking_slot:
_render_thinking()
retriever, llm = init_rag_system()
context_docs = retriever.invoke(user_query)
prompt_value = _build_prompt(format_docs(context_docs), user_query)
thinking_slot.empty()
def token_stream():
for chunk in llm.stream(prompt_value):
yield chunk.content
citations = _docs_to_citations(context_docs)
answer = st.write_stream(token_stream())
_render_sources_expander(citations)
except Exception:
answer = (
"The policy retrieval system is currently unavailable. "
"Please check your OPENROUTER_API_KEY, network access, and document ingestion."
)
citations, route = [], "general"
st.write(answer)
st.session_state.messages.append({
"role": "assistant",
"content": answer,
"route": route,
"citations": citations,
})
# ── 7. answer_question — used by evaluation.py ────────────────────────────────
def answer_question(user_query: str) -> dict:
general = get_general_response(user_query)
if general:
return {"answer": general, "context": [], "route": "general"}
retriever, llm = init_rag_system()
docs = retriever.invoke(user_query)
prompt_value = _build_prompt(format_docs(docs), user_query)
try:
response = llm.invoke(prompt_value).content
except Exception:
response = "I can only answer about our policies."
return {"answer": response, "context": docs, "route": "policy"}
# ── 8. App entry point ────────────────────────────────────────────────────────
def render_app():
if st.query_params.get("endpoint") == "health":
st.json({"status": "healthy"})
st.stop()
if st.query_params.get("endpoint") == "chat":
query = st.query_params.get("q", "")
if not query:
st.json({"error": "Missing required query parameter: q"})
st.stop()
try:
result = answer_question(query)
citations = [
os.path.basename(d.metadata.get("source", f"Doc {i+1}"))
for i, d in enumerate(result["context"])
]
st.json({"answer": result["answer"], "citations": citations, "route": result["route"]})
except Exception:
st.json({"error": "Policy assistant is unavailable."})
st.stop()
st.set_page_config(page_title="Policy Assistant", page_icon="🏢", layout="wide", initial_sidebar_state="collapsed")
st.markdown(CUSTOM_CSS, unsafe_allow_html=True)
_render_header()
if "messages" not in st.session_state:
st.session_state.messages = []
if "pending_chip" not in st.session_state:
st.session_state.pending_chip = None
st.markdown('', unsafe_allow_html=True)
if not st.session_state.messages:
_render_welcome_and_chips()
else:
_, mid, _ = st.columns([1, 3, 1])
with mid:
_replay_history()
st.markdown('', unsafe_allow_html=True)
if st.session_state.pending_chip:
chip_query = st.session_state.pending_chip
st.session_state.pending_chip = None
_, mid, _ = st.columns([1, 3, 1])
with mid:
_process_and_render(chip_query)
st.rerun()
if user_query := st.chat_input("Ask about PTO, expenses, travel, onboarding…"):
_, mid, _ = st.columns([1, 3, 1])
with mid:
_process_and_render(user_query)
st.rerun()
if __name__ == "__main__":
render_app()