CoolFace
Apppublic

swsthik/Auralis_Schema

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py125 linesDownload Raw Back to root
1import streamlit as st2import pandas as pd3from agent import mquery_agent   # conversational agent4 5st.set_page_config(page_title="Customer Support Copilot", layout="wide")6st.title("πŸ›  Customer Support Copilot ")7 8# Initialize session state containers9if "messages" not in st.session_state:10    st.session_state.messages = []11 12if "logs" not in st.session_state:13    st.session_state.logs = []14 15# ----------------------------16# Ticket Dashboard (top)17# ----------------------------18st.subheader("πŸ“Š Ticket Dashboard")19 20def _normalize_classification(c):21    """Return a safe dict for classification (handle 'N/A' string cases)."""22    if not isinstance(c, dict):23        return {}24    return c25 26def _truncate(text: str, length: int = 120):27    if not isinstance(text, str):28        return ""29    return (text[:length] + "…") if len(text) > length else text30 31if st.session_state.logs:32    table_rows = []33    for log in st.session_state.logs:34        classification = _normalize_classification(log.get("Classification", {}))35        assistant_resp = log.get("Assistant Response")36        # Fallbacks37        if assistant_resp is None:38            assistant_resp = log.get("Content", "")39 40        table_rows.append({41            "Ticket ID": log.get("Ticket ID", "-"),42            "Topic": classification.get("topic", "-"),43            "Sentiment": classification.get("sentiment", "-"),44            "Priority": classification.get("priority", "-"),45            "Response": _truncate(assistant_resp, 120),46            "Should Escalate": log.get("Should Escalate", False),47        })48 49    df = pd.DataFrame(table_rows)50 51    # Apply color coding based on escalation52    def highlight_escalation(row):53        if row.get("Should Escalate"):54            return ['background-color: #ffcccc; color: black;'] * len(row)  # light red55        else:56            return ['background-color: #ccffcc; color: black;'] * len(row)  # light green57 58    styled_df = df.style.apply(highlight_escalation, axis=1)59 60    # Hide the helper column if you don’t want to show it in the UI61    styled_df = styled_df.hide(axis="columns", subset=["Should Escalate"])62 63    st.dataframe(styled_df, use_container_width=True)64else:65    st.info("No tickets generated yet. Start a conversation to see tickets here!")66 67# ----------------------------68# Support Agent (below dashboard)69# ----------------------------70st.subheader("πŸ€– Support Agent")71 72# Display past conversation73for msg in st.session_state.messages:74    if msg["role"] == "user":75        st.markdown(f"πŸ§‘ **You:** {msg['content']}")76    else:77        st.markdown(f"πŸ€– **Agent:** {msg['content']}")78 79# Input box (preserve input with a key)80user_query = st.text_input("Enter your message:", key="user_input")81 82if st.button("Send") and user_query and user_query.strip():83    # Append user message84    st.session_state.messages.append({"role": "user", "content": user_query})85 86    with st.spinner("Agent is thinking..."):87        # Get response + structured log from the multi-query agent88        # handle_message returns (response, log) when return_log=True89        result = mquery_agent.handle_message(user_query, return_log=True)90        # Some variations of the wrapper may return just response (older versions).91        if isinstance(result, tuple) and len(result) == 2:92            response, log_entry = result93        else:94            response = result95            log_entry = {}96 97    # Ensure log_entry is a dict98    if log_entry is None:99        log_entry = {}100 101    # Add assistant's final response into log so dashboard shows the final reply102    log_entry["Assistant Response"] = response103 104    # Normalize missing keys to avoid issues in dashboard rendering105    if "Classification" not in log_entry:106        log_entry["Classification"] = "N/A"107    if "Ticket ID" not in log_entry:108        # preserve existing None if present; otherwise set None109        log_entry["Ticket ID"] = log_entry.get("Ticket ID", None)110 111    # Save assistant response + structured log112    st.session_state.messages.append({"role": "assistant", "content": response})113    st.session_state.logs.append(log_entry)114 115    # Refresh UI116    st.rerun()117 118# ----------------------------119# Sidebar: Raw conversation logs120# ----------------------------121st.sidebar.header("Conversation Logs (raw)")122for i, log in enumerate(st.session_state.logs, 1):123    st.sidebar.markdown(f"**Turn {i}:**")124    st.sidebar.json(log)125