Danleon56's picture
fixed memory leak issue
ad58750
Raw History Blame Contribute Delete
17.2 kB
# 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 = """
<style>
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600&family=DM+Mono:wght@400;500&display=swap');
#MainMenu, footer, header { visibility: hidden; }
.block-container { padding: 0 !important; max-width: 100% !important; }
[data-testid="stAppViewContainer"] { background: #090D12 !important; font-family: 'DM Sans', sans-serif; }
[data-testid="stMain"] { background: #0D1117 !important; }
::-webkit-scrollbar { width: 4px; }
::-webkit-scrollbar-thumb { background: #30363D; border-radius: 4px; }
.pa-header {
background: #0D1117; border-bottom: 1px solid #21262D;
padding: 0 24px; height: 60px; display: flex; align-items: center;
gap: 14px; position: sticky; top: 0; z-index: 200;
}
.pa-logo {
width: 34px; height: 34px;
background: linear-gradient(135deg, #238636 0%, #2EA043 100%);
border-radius: 8px; display: flex; align-items: center; justify-content: center;
font-size: 16px; box-shadow: 0 0 0 1px rgba(35,134,54,0.4), 0 4px 12px rgba(35,134,54,0.25);
}
.pa-header-name { font-size: 16px; font-weight: 600; color: #F0F6FC; }
.pa-header-sub { font-size: 13px; color: #B1BAC4; }
.pa-online { margin-left: auto; display: flex; align-items: center; gap: 6px; font-size: 12px; color: #3FB950; font-weight: 500; }
.pa-online-dot { width: 7px; height: 7px; border-radius: 50%; background: #3FB950; animation: pulse-dot 2s ease-in-out infinite; }
@keyframes pulse-dot { 0%,100%{opacity:1;} 50%{opacity:0.7;} }
[data-testid="stChatMessage"] { background: transparent !important; border: none !important; padding: 4px 0 !important; max-width: 780px !important; margin: 0 auto !important; }
[data-testid="chatAvatarIcon-assistant"] { background: linear-gradient(135deg,#238636,#2EA043) !important; border-radius: 8px !important; }
[data-testid="chatAvatarIcon-user"] { background: #1C2128 !important; border: 1px solid #30363D !important; border-radius: 8px !important; }
.pa-badge { display: inline-flex; align-items: center; gap: 5px; font-size: 10.5px; font-weight: 600; padding: 3px 10px; border-radius: 20px; margin-bottom: 6px; font-family: 'DM Mono', monospace; }
.pa-badge.policy { background: rgba(35,134,54,0.15); color: #3FB950; border: 1px solid rgba(35,134,54,0.3); }
.pa-badge.general { background: rgba(121,192,255,0.1); color: #79C0FF; border: 1px solid rgba(121,192,255,0.25); }
[data-testid="stExpander"] { background: #0D1117 !important; border: 1px solid #21262D !important; border-radius: 8px !important; margin-top: 6px !important; }
.pa-source-item { display: flex; gap: 12px; align-items: flex-start; padding: 10px 0; border-top: 1px solid #21262D; }
.pa-source-item:first-child { border-top: none; }
.pa-source-name { font-size: 13px; font-weight: 600; color: #F0F6FC; font-family: 'DM Mono', monospace; margin-bottom: 3px; }
.pa-source-excerpt { font-size: 13px; color: #B1BAC4; line-height: 1.55; }
.pa-thinking { display: inline-flex; gap: 5px; align-items: center; padding: 10px 16px; background: #161B22; border: 1px solid #21262D; border-radius: 2px 12px 12px 12px; }
.pa-dot { width: 5px; height: 5px; border-radius: 50%; background: #3FB950; animation: pa-pulse 1.4s ease-in-out infinite; }
.pa-dot:nth-child(2){animation-delay:0.2s;} .pa-dot:nth-child(3){animation-delay:0.4s;}
@keyframes pa-pulse { 0%,80%,100%{opacity:0.25;transform:scale(0.8);} 40%{opacity:1;transform:scale(1);} }
[data-testid="stChatInputContainer"] { background: #0D1117 !important; border-top: 1px solid #21262D !important; padding: 12px 24px !important; }
[data-testid="stChatInput"] { background: #161B22 !important; border: 1px solid #30363D !important; border-radius: 10px !important; color: #F0F6FC !important; font-size: 14px !important; }
.pa-welcome-card {
background: linear-gradient(135deg,#161B22 0%,#1C2128 100%);
border: 1px solid #21262D; border-radius: 12px; padding: 24px 28px;
position: relative; overflow: hidden;
}
.pa-welcome-card::before { content:''; position:absolute; top:0; left:0; width:100%; height:3px; background:linear-gradient(90deg,#238636,#2EA043,#56D364); }
.pa-welcome-title { font-size: 19px; font-weight: 600; color: #F0F6FC; margin-bottom: 6px; }
.pa-welcome-sub { font-size: 14px; color: #B1BAC4; line-height: 1.6; }
</style>
"""
# ── 3. UI helpers ──────────────────────────────────────────────────────────────
def _render_header():
st.markdown("""
<div class="pa-header">
<div class="pa-logo">🏒</div>
<div>
<div class="pa-header-name">Policy Assistant</div>
<div class="pa-header-sub">Powered by your internal documents</div>
</div>
<div class="pa-online"><div class="pa-online-dot"></div>Online</div>
</div>""", unsafe_allow_html=True)
def _render_badge(route: str):
if route == "policy":
st.markdown('<span class="pa-badge policy">β—† POLICY MATCH</span>', unsafe_allow_html=True)
else:
st.markdown('<span class="pa-badge general">β—‡ GENERAL REPLY</span>', 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"""
<div class="pa-source-item">
<div>
<div class="pa-source-name">πŸ“„ {c['name']}</div>
<div class="pa-source-excerpt">{c['excerpt']}…</div>
</div>
</div>""", unsafe_allow_html=True)
def _render_thinking():
st.markdown("""
<div class="pa-thinking">
<div class="pa-dot"></div><div class="pa-dot"></div><div class="pa-dot"></div>
</div>""", unsafe_allow_html=True)
def _render_welcome_and_chips():
st.markdown("""
<div style="max-width:780px;margin:32px auto 0;padding:0 24px;">
<div class="pa-welcome-card">
<div class="pa-welcome-title">Good to see you πŸ‘‹</div>
<div class="pa-welcome-sub">
Ask me anything about company policies β€” PTO, remote work, expenses,
travel, security, onboarding, benefits, and more.
</div>
</div>
</div>""", unsafe_allow_html=True)
st.markdown('<div style="max-width:780px;margin:16px auto 0;padding:0 24px;font-size:10px;color:#9198A1;font-family:monospace;text-transform:uppercase;letter-spacing:0.1em;">Try asking</div>', 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('<div style="height:8px"></div>', 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('<div style="height:16px"></div>', 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()