"""Streamlit prototype UI for the agentic RAG policy assistant.
Shows the final answer plus an expandable step-by-step trace of which graph nodes ran,
what they decided, and how long each took - so the agentic/RAG machinery behind the answer
is visible, not just the answer itself.
"""
from __future__ import annotations
import html
import sys
import uuid
from pathlib import Path
import streamlit as st
import streamlit.components.v1 as components
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from app.config import OLLAMA_BASE_URL, OLLAMA_MODEL # noqa: E402
from app.graph import build_graph # noqa: E402
from app.llm import generate_followups, get_chat_llm # noqa: E402
from app.rag.ingest import load_markdown_files # noqa: E402
from app.rag.vectorstore import load_or_build_index # noqa: E402
st.set_page_config(page_title="Policy Assistant", layout="wide")
# Streamlit's own "Deploy" button isn't relevant for this prototype; hide only that one
# toolbar element via its test id, so the rest of the native menu (incl. the light/dark
# theme switch under Settings) stays intact.
st.markdown(
'',
unsafe_allow_html=True,
)
CHAT_INPUT_PLACEHOLDER = "Ask about company policy, your PTO balance, or open a ticket..."
EXAMPLE_QUESTIONS = [
"How many PTO days can I carry over?",
"I was hired 2022-01-01, took 5 days off, how many are left as of 2024-01-01?",
"Please open a ticket, I lost my laptop.",
]
@st.cache_resource(show_spinner="Loading agent (building FAISS index, connecting to Ollama)...")
def get_graph(force_rebuild: bool = False):
store = load_or_build_index(force_rebuild=force_rebuild)
return build_graph(store=store), store
@st.cache_resource(show_spinner=False)
def get_followup_llm():
return get_chat_llm()
def _new_session() -> dict:
return {"history": []}
def _init_sessions() -> None:
if "sessions" not in st.session_state:
session_id = str(uuid.uuid4())
st.session_state["sessions"] = {session_id: _new_session()}
st.session_state["active_session_id"] = session_id
def _session_title(session: dict) -> str:
if not session["history"]:
return "New chat"
first_query = session["history"][0]["query"]
return first_query if len(first_query) <= 40 else first_query[:40] + "…"
def render_trace(state: dict) -> None:
trace = state.get("trace", [])
with st.expander(f"Agent trace ({len(trace)} steps)"):
for step in trace:
st.markdown(f"- **{step['node']}** — {step['detail']} _({step['duration_ms']} ms)_")
results = state.get("results", {})
if "policy_question" in results:
r = results["policy_question"]
with st.expander(f"RAG sources (confidence: {r['confidence']})"):
for src in r.get("sources", []):
st.markdown(f"- `{src}`")
if "create_ticket" in results:
t = results["create_ticket"]
st.info(
f"Support ticket **{t['ticket_id']}** opened — category `{t['category']}`, "
f"priority `{t['priority']}`"
)
if state.get("escalate"):
st.warning(f"Auto-escalated: {state.get('escalate_reason')}")
def render_sidebar() -> None:
with st.sidebar:
st.markdown("### My Chats")
for session_id, session in reversed(list(st.session_state["sessions"].items())):
is_active = session_id == st.session_state["active_session_id"]
title_col, delete_col = st.columns([5, 1])
with title_col:
if st.button(
_session_title(session),
key=f"session_{session_id}",
use_container_width=True,
type="primary" if is_active else "secondary",
):
st.session_state["active_session_id"] = session_id
st.rerun()
with delete_col:
if st.button(
"",
key=f"delete_{session_id}",
icon=":material/delete:",
help="Delete this chat",
):
del st.session_state["sessions"][session_id]
if not st.session_state["sessions"]:
new_id = str(uuid.uuid4())
st.session_state["sessions"][new_id] = _new_session()
st.session_state["active_session_id"] = new_id
elif st.session_state["active_session_id"] == session_id:
st.session_state["active_session_id"] = next(
iter(st.session_state["sessions"])
)
st.rerun()
if st.button("+ New chat", key="new_chat_btn", use_container_width=True):
session_id = str(uuid.uuid4())
st.session_state["sessions"][session_id] = _new_session()
st.session_state["active_session_id"] = session_id
st.rerun()
@st.dialog("Config")
def show_config_dialog(docs: list) -> None:
st.markdown(f"Model: `{OLLAMA_MODEL}`")
st.markdown(f"Ollama URL: `{OLLAMA_BASE_URL}`")
st.markdown(f"Policy documents indexed: {len(docs)}")
for name, _ in docs:
st.markdown(f"- {name}")
if st.button("Rebuild index"):
get_graph.clear()
st.session_state["_force_rebuild"] = True
st.rerun()
def render_question_chips(label: str, questions: list[str]) -> None:
"""Shared renderer for clickable example/follow-up question cards.
``st.markdown(unsafe_allow_html=True)`` sanitizes out ``