Spaces:
Sleeping

agent-pulse / app.py
Eshitagoel21's picture
Upload 4 files
7a00796 verified
Raw History Blame Contribute Delete
32.5 kB
import os
import time
import json
import streamlit as st
from cogentiq_client import CogentiqClient
USER_ID = os.getenv("COGENTIQ_USER_ID", "9224d0f4b8734a279dd5ecf960343b15")
# Initialize session state for chat history
if "chats" not in st.session_state:
st.session_state.chats = [] # List of all chats
st.session_state.current_chat_id = None
if "processing" not in st.session_state:
st.session_state.processing = False
if "show_welcome" not in st.session_state:
st.session_state.show_welcome = True
# Initialize session state for menu actions
if "renaming_chat_id" not in st.session_state:
st.session_state.renaming_chat_id = None
if "deleting_chat_id" not in st.session_state:
st.session_state.deleting_chat_id = None
st.set_page_config(
page_title="Agent Pulse - Healthcare Intelligence",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS with professional styling and ChatGPT-like appearance
st.markdown("""
<style>
/* Import Inter font (ChatGPT uses this) */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Söhne:wght@300;400;500;600;700&display=swap');
/* Global font - Inter is used by ChatGPT */
* {
font-family: 'Inter', 'Söhne', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* Light Theme Variables */
:root {
--page-bg: #FAFAFB;
--main-text: #111827;
--sidebar-bg: #FFFFFF;
--sidebar-title: #1A1A1A;
--user-bubble-bg: #2563EB;
--user-bubble-text: #FFFFFF;
--assistant-bubble-bg: #F3F5F9;
--assistant-bubble-text: #1A1A1A;
--primary-btn-bg: #2563EB;
--primary-btn-text: #FFFFFF;
--secondary-btn-bg: #F3F5F9;
--secondary-btn-text: #1A1A1A;
--accent-color: #10B981;
--border-color: #E5E7EB;
--shadow: rgba(0,0,0,0.06);
}
/* Dark Theme Variables */
[data-theme="dark"] {
--page-bg: #0F1218;
--main-text: #EAEAEA;
--sidebar-bg: #1D232F;
--sidebar-title: #EAEAEA;
--user-bubble-bg: #3B82F6;
--user-bubble-text: #FFFFFF;
--assistant-bubble-bg: #1D232F;
--assistant-bubble-text: #EAEAEA;
--primary-btn-bg: #3B82F6;
--primary-btn-text: #FFFFFF;
--secondary-btn-bg: #1D232F;
--secondary-btn-text: #EAEAEA;
--accent-color: #22D3EE;
--border-color: #2A2F3A;
--shadow: rgba(0,0,0,0.35);
}
/* Page background */
.stApp {
background-color: var(--page-bg);
}
/* Main content text */
.stMarkdown, p, span, div {
color: var(--main-text);
}
/* Sidebar styling */
[data-testid="stSidebar"] {
background-color: var(--sidebar-bg);
border-right: 1px solid var(--border-color);
}
/* Sidebar title with logo */
.sidebar-header {
display: flex;
align-items: center;
gap: 10px;
padding: 1rem 0 0.5rem 0;
margin-bottom: 1rem;
}
.sidebar-title {
font-size: 1.625rem;
font-weight: 800;
color: var(--sidebar-title);
letter-spacing: -0.015em;
}
/* Main title styling - bold, no bot emoji */
.main-title {
font-size: 2rem;
font-weight: 800;
color: var(--main-text);
margin-bottom: 0.25rem;
letter-spacing: -0.02em;
}
/* Subtitle - italic and submissive */
.main-subtitle {
font-size: 0.9375rem;
font-weight: 400;
font-style: italic;
color: var(--main-text);
opacity: 0.7;
margin-bottom: 2rem;
line-height: 1.5;
}
/* Remove default streamlit title */
h1 {
font-weight: 700 !important;
letter-spacing: -0.02em !important;
}
/* Chat button styling with active indicator */
.stButton button[kind="secondary"] {
background-color: var(--secondary-btn-bg);
color: var(--secondary-btn-text);
text-align: left !important;
justify-content: flex-start !important;
padding-left: 1rem !important;
position: relative;
border: 1px solid var(--border-color);
border-radius: 8px;
transition: all 0.2s ease;
display: flex !important;
align-items: center !important;
}
.stButton button[kind="secondary"]:hover {
background-color: var(--border-color);
border-color: var(--border-color);
}
.stButton button[kind="primary"] {
background: linear-gradient(135deg, rgba(102, 126, 234, 0.12) 0%, rgba(118, 75, 162, 0.12) 100%) !important;
color: #7B6BA8 !important;
border: 1px solid rgba(102, 126, 234, 0.25) !important;
text-align: left !important;
justify-content: flex-start !important;
padding-left: 1.75rem !important;
position: relative;
border-radius: 8px;
font-weight: 500;
transition: all 0.2s ease;
display: flex !important;
align-items: center !important;
}
.stButton button[kind="primary"]:hover {
background: linear-gradient(135deg, rgba(102, 126, 234, 0.18) 0%, rgba(118, 75, 162, 0.18) 100%) !important;
border-color: rgba(102, 126, 234, 0.35) !important;
}
/* Force text alignment in buttons - strictly left aligned */
.stButton button p {
text-align: left !important;
width: 100%;
margin: 0 !important;
padding: 0 !important;
display: block !important;
}
.stButton button div {
text-align: left !important;
width: 100%;
display: flex !important;
justify-content: flex-start !important;
}
.stButton button[kind="primary"] p,
.stButton button[kind="primary"] div {
text-align: left !important;
justify-content: flex-start !important;
}
/* Active chat indicator (green dot) with proper spacing */
.stButton button[kind="primary"]::before {
content: '';
position: absolute;
left: 0.5rem;
top: 50%;
transform: translateY(-50%);
width: 8px;
height: 8px;
background-color: var(--accent-color);
border-radius: 50%;
box-shadow: 0 0 8px rgba(16, 185, 129, 0.5);
margin-right: 0.5rem;
}
/* Section headers in sidebar - left aligned */
.sidebar-section {
font-size: 0.6875rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--main-text);
opacity: 0.6;
margin: 1.5rem 0 0.5rem 0;
text-align: left;
padding-left: 0.25rem;
}
/* Chat bubbles styling - increased width for better text display */
[data-testid="stChatMessage"] {
border-radius: 18px;
padding: 12px 16px;
max-width: 85%;
box-shadow: 0 1px 2px var(--shadow);
word-wrap: break-word;
overflow-wrap: break-word;
}
/* Ensure text doesn't overflow and wraps properly */
[data-testid="stChatMessage"] p {
margin: 0;
line-height: 1.5;
word-wrap: break-word;
overflow-wrap: break-word;
white-space: pre-wrap;
}
/* User message bubble */
[data-testid="stChatMessage"][data-testid*="user"] {
background-color: var(--user-bubble-bg);
color: var(--user-bubble-text);
margin-left: auto;
}
/* Assistant message bubble */
[data-testid="stChatMessage"]:not([data-testid*="user"]) {
background-color: var(--assistant-bubble-bg);
color: var(--assistant-bubble-text);
margin-right: auto;
}
/* Chain of thoughts styling */
.thinking-steps {
background-color: var(--assistant-bubble-bg);
border: 1px solid var(--border-color);
border-radius: 12px;
padding: 1rem;
margin: 1rem 0;
box-shadow: 0 1px 2px var(--shadow);
}
.thinking-step {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.5rem 0;
position: relative;
}
.step-dot {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: var(--border-color);
flex-shrink: 0;
}
.step-dot.active {
background-color: var(--primary-btn-bg);
animation: pulse 1.5s ease-in-out infinite;
box-shadow: 0 0 10px rgba(37, 99, 235, 0.5);
}
.step-dot.completed {
background-color: var(--accent-color);
}
.step-label {
font-size: 0.875rem;
color: var(--main-text);
opacity: 0.7;
}
.step-label.active {
color: var(--primary-btn-bg);
font-weight: 600;
opacity: 1;
}
.step-label.completed {
color: var(--accent-color);
opacity: 0.9;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.7;
transform: scale(1.1);
}
}
/* Welcome card - slightly lighter */
.welcome-card {
background: linear-gradient(135deg, rgba(102, 126, 234, 0.85) 0%, rgba(118, 75, 162, 0.85) 100%);
color: white;
padding: 2rem;
border-radius: 16px;
margin-bottom: 2rem;
box-shadow: 0 4px 12px var(--shadow);
}
.welcome-title {
font-size: 1.5rem;
font-weight: 700;
margin-bottom: 0.5rem;
letter-spacing: -0.01em;
}
.welcome-subtitle {
font-size: 1rem;
opacity: 0.95;
line-height: 1.5;
}
/* Sample queries heading */
.sample-queries-heading {
font-size: 0.9375rem;
font-weight: 500;
color: var(--main-text);
opacity: 0.8;
margin-bottom: 1rem;
margin-top: 0.5rem;
}
/* Primary buttons (Send) */
button[kind="primary"] {
background-color: var(--primary-btn-bg) !important;
color: var(--primary-btn-text) !important;
border: none !important;
border-radius: 8px !important;
font-weight: 500 !important;
}
button[kind="primary"]:hover {
opacity: 0.9;
box-shadow: 0 2px 8px var(--shadow);
}
/* Input field */
[data-testid="stChatInput"] {
border: 1px solid var(--border-color);
border-radius: 12px;
background-color: var(--sidebar-bg);
}
/* Sample query buttons */
.sample-query-btn {
background-color: var(--sidebar-bg);
border: 1px solid var(--border-color);
border-radius: 12px;
padding: 1rem;
transition: all 0.2s ease;
box-shadow: 0 1px 2px var(--shadow);
}
.sample-query-btn:hover {
border-color: var(--primary-btn-bg);
box-shadow: 0 2px 8px var(--shadow);
transform: translateY(-1px);
}
/* Chat tile menu button (3-dot) */
.chat-menu-btn {
opacity: 0;
transition: opacity 0.2s ease;
font-size: 1.2rem;
padding: 0.25rem 0.5rem;
min-width: 32px !important;
}
.stButton:hover .chat-menu-btn {
opacity: 1;
}
/* Menu options styling */
.menu-option-btn {
font-size: 0.875rem;
padding: 0.4rem 0.8rem;
}
/* Rename input styling */
.stTextInput input {
background-color: var(--sidebar-bg);
color: var(--main-text);
border: 1px solid var(--primary-btn-bg);
border-radius: 6px;
font-size: 0.875rem;
}
.stTextInput input:focus {
border-color: var(--primary-btn-bg);
box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.2);
}
</style>
""", unsafe_allow_html=True)
# Helper function to create new chat
def create_new_chat():
import uuid
chat_id = str(uuid.uuid4())
new_chat = {
"id": chat_id,
"messages": [],
"title": "New Chat"
}
st.session_state.chats.append(new_chat)
st.session_state.current_chat_id = chat_id
st.session_state.show_welcome = True
return chat_id
# Helper function to get current chat
def get_current_chat():
if st.session_state.current_chat_id is None:
if not st.session_state.chats:
create_new_chat()
else:
st.session_state.current_chat_id = st.session_state.chats[0]["id"]
for chat in st.session_state.chats:
if chat["id"] == st.session_state.current_chat_id:
return chat
# If current chat not found, create new one
create_new_chat()
return get_current_chat()
# Helper function to update chat title based on first response (3-4 words)
def update_chat_title(chat_id, first_response):
for chat in st.session_state.chats:
if chat["id"] == chat_id:
# Extract first 3-4 words from response
response_text = str(first_response) if not isinstance(first_response, dict) else json.dumps(first_response)
words = response_text.split()[:5]
preview = ' '.join(words)
if len(response_text.split()) > 5:
preview += "..."
chat["title"] = preview
break
# Helper function to get conversation context (last 7 messages)
def get_conversation_context(messages):
"""Get last 7 messages for context without permanent storage"""
if len(messages) <= 1:
return None
# Get last 7 messages (excluding current query)
context_limit = min(7, len(messages) - 1)
recent_messages = messages[-context_limit-1:-1]
if not recent_messages:
return None
context = []
for msg in recent_messages:
context.append({
"role": msg["role"],
"content": str(msg["content"])[:500] # Limit content length
})
return context
# Sidebar - Chat History (like ChatGPT)
with st.sidebar:
# Agent Pulse Logo and Title at top
st.markdown("""
<div class="sidebar-header">
<span style="font-size: 2rem;">⚕️</span>
<div class="sidebar-title">Agent Pulse</div>
</div>
""", unsafe_allow_html=True)
# New Chat button
if st.button("+ New Chat", use_container_width=True, key="new_chat_btn"):
create_new_chat()
st.rerun()
# Recent Conversations section
st.markdown('<div class="sidebar-section">Recent Conversations</div>', unsafe_allow_html=True)
if st.session_state.chats:
for chat in reversed(st.session_state.chats): # Show newest first
is_active = chat["id"] == st.session_state.current_chat_id
# Check if this chat is being renamed
if st.session_state.renaming_chat_id == chat["id"]:
# Show rename input
new_title = st.text_input(
"Rename chat",
value=chat['title'],
key=f"rename_input_{chat['id']}",
label_visibility="collapsed"
)
col1, col2 = st.columns(2)
with col1:
if st.button("Save", key=f"save_{chat['id']}", use_container_width=True):
if new_title.strip():
chat['title'] = new_title.strip()
st.session_state.renaming_chat_id = None
st.rerun()
with col2:
if st.button("Cancel", key=f"cancel_{chat['id']}", use_container_width=True):
st.session_state.renaming_chat_id = None
st.rerun()
# Check if this chat is being deleted
elif st.session_state.deleting_chat_id == chat["id"]:
st.warning(f"Delete '{chat['title']}'?")
col1, col2 = st.columns(2)
with col1:
if st.button("Delete", key=f"confirm_delete_{chat['id']}", use_container_width=True, type="primary"):
# Delete the chat
st.session_state.chats = [c for c in st.session_state.chats if c["id"] != chat["id"]]
# If deleting current chat, switch to another or create new
if st.session_state.current_chat_id == chat["id"]:
if st.session_state.chats:
st.session_state.current_chat_id = st.session_state.chats[-1]["id"]
else:
create_new_chat()
st.session_state.deleting_chat_id = None
st.rerun()
with col2:
if st.button("Cancel", key=f"cancel_delete_{chat['id']}", use_container_width=True):
st.session_state.deleting_chat_id = None
st.rerun()
else:
# Normal chat tile with 3-dot menu
col_chat, col_menu = st.columns([5, 1])
with col_chat:
button_type = "primary" if is_active else "secondary"
if st.button(chat['title'], key=f"chat_{chat['id']}", use_container_width=True, type=button_type):
st.session_state.current_chat_id = chat["id"]
st.session_state.show_welcome = False
st.rerun()
with col_menu:
# 3-dot menu button
if st.button("⋮", key=f"menu_{chat['id']}", help="Options", use_container_width=True):
# Toggle menu
menu_key = f"show_menu_{chat['id']}"
if menu_key not in st.session_state:
st.session_state[menu_key] = True
else:
st.session_state[menu_key] = not st.session_state[menu_key]
st.rerun()
# Show menu options if toggled
if st.session_state.get(f"show_menu_{chat['id']}", False):
col1, col2 = st.columns(2)
with col1:
if st.button("Rename", key=f"rename_{chat['id']}", use_container_width=True):
st.session_state.renaming_chat_id = chat["id"]
st.session_state[f"show_menu_{chat['id']}"] = False
st.rerun()
with col2:
if st.button("Delete", key=f"delete_{chat['id']}", use_container_width=True):
st.session_state.deleting_chat_id = chat["id"]
st.session_state[f"show_menu_{chat['id']}"] = False
st.rerun()
else:
st.info("No conversations yet. Start chatting!")
# Clear All Chats button at bottom
st.markdown('<div style="margin-top: 2rem;"></div>', unsafe_allow_html=True)
if st.button("Clear All Chats", use_container_width=True, key="clear_all_btn"):
st.session_state.chats = []
st.session_state.current_chat_id = None
st.session_state.show_welcome = True
st.rerun()
# Main title
st.markdown('<div class="main-title">Healthcare Data Assistant</div>', unsafe_allow_html=True)
st.markdown('<div class="main-subtitle">Ask questions about healthcare claims, members, providers, and clinical data in natural language.</div>', unsafe_allow_html=True)
# Get current chat
current_chat = get_current_chat()
# Show welcome message with sample queries if it's a new chat
if len(current_chat["messages"]) == 0 and st.session_state.show_welcome:
st.markdown("""
<div class="welcome-card">
<div class="welcome-title">👋 Welcome to Agent Pulse!</div>
<div class="welcome-subtitle">I'm your AI-powered healthcare data assistant. Ask me anything about your healthcare data.</div>
</div>
""", unsafe_allow_html=True)
st.markdown('<div class="sample-queries-heading">💡 Try these sample queries:</div>', unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
with col1:
if st.button("Number of claims in database", use_container_width=True):
query = "Number of claims in database"
st.session_state.sample_query = query
st.session_state.show_welcome = False
st.rerun()
with col2:
if st.button("Show the approved claims", use_container_width=True):
query = "Show the approved claims"
st.session_state.sample_query = query
st.session_state.show_welcome = False
st.rerun()
with col3:
if st.button("Show me the top 5 providers by claim volume", use_container_width=True):
query = "Show me the top 5 providers by claim volume"
st.session_state.sample_query = query
st.session_state.show_welcome = False
st.rerun()
# Chat container
chat_container = st.container()
# Display chat history for current chat
with chat_container:
for message in current_chat["messages"]:
if message["role"] == "user":
with st.chat_message("user"):
st.markdown(message["content"])
else:
with st.chat_message("assistant"):
if isinstance(message["content"], dict):
# If content is JSON/dict, display it nicely
st.json(message["content"])
else:
st.markdown(message["content"])
# Check for sample query
if "sample_query" in st.session_state and st.session_state.sample_query:
query = st.session_state.sample_query
st.session_state.sample_query = None
else:
# Chat input at the bottom
query = st.chat_input("Ask a question...", disabled=st.session_state.processing)
# Process user input
if query and not st.session_state.processing:
st.session_state.show_welcome = False
# Add user message to current chat
current_chat["messages"].append({"role": "user", "content": query})
st.session_state.processing = True
# Display user message immediately
with chat_container:
with st.chat_message("user"):
st.markdown(query)
# Show assistant "thinking" message with chain of thoughts
with chat_container:
with st.chat_message("assistant"):
thinking_placeholder = st.empty()
answer_placeholder = st.empty()
try:
start_time = time.time()
# Print terminal log - WORKFLOW TRIGGER
print("\n" + "_"*40)
print("TRIGGERING WORKFLOW")
print("_"*40)
print(f"Query: {query}")
# Build context query with conversation history
context = get_conversation_context(current_chat["messages"])
if context:
query_payload = {
"current_query": query,
"conversation_history": context
}
context_query = json.dumps(query_payload, indent=2)
print(f"\n[CONTEXT] Including last {len(context)} messages for follow-up context")
else:
context_query = query
# Step 1: Analyzing the query (Planner Agent)
thinking_placeholder.markdown("""
<div class="thinking-steps">
<div class="thinking-step">
<div class="step-dot active"></div>
<div class="step-label active">Analyzing the query</div>
</div>
<div class="thinking-step">
<div class="step-dot"></div>
<div class="step-label">Processing the query</div>
</div>
<div class="thinking-step">
<div class="step-dot"></div>
<div class="step-label">Formatting the result</div>
</div>
</div>
""", unsafe_allow_html=True)
client = CogentiqClient(user_id=USER_ID)
result = client.run_and_wait(context_query, max_wait_seconds=300)
# Print terminal log - WORKFLOW STARTED
print(f"\nWorkflow triggered successfully")
print(f"Trace ID: {result.get('trace_id', 'N/A')}")
print("\n" + "_"*40)
print("WORKFLOW EXECUTION STARTED")
print("_"*40)
print(f"Trace ID: {result.get('trace_id', 'N/A')}\n")
# Step 2: Processing (Data Query Agent)
thinking_placeholder.markdown("""
<div class="thinking-steps">
<div class="thinking-step">
<div class="step-dot completed"></div>
<div class="step-label completed">Analyzing the query</div>
</div>
<div class="thinking-step">
<div class="step-dot active"></div>
<div class="step-label active">Processing the query</div>
</div>
<div class="thinking-step">
<div class="step-dot"></div>
<div class="step-label">Formatting the result</div>
</div>
</div>
""", unsafe_allow_html=True)
time.sleep(0.5) # Small delay for UX
# Print agent execution logs
if result.get("data") and result["data"].get("agents"):
agents = result["data"]["agents"]
for agent in agents:
agent_name = agent.get("name", "Unknown Agent")
agent_output = agent.get("output", {})
output_str = str(agent_output)
# Truncate long outputs
output_preview = output_str[:200] + "..." if len(output_str) > 200 else output_str
print(f"\n[AGENT] {agent_name}")
print(f"[OUTPUT] {output_preview}")
# Step 3: Formatting (Insight Agent)
thinking_placeholder.markdown("""
<div class="thinking-steps">
<div class="thinking-step">
<div class="step-dot completed"></div>
<div class="step-label completed">Analyzing the query</div>
</div>
<div class="thinking-step">
<div class="step-dot completed"></div>
<div class="step-label completed">Processing the query</div>
</div>
<div class="thinking-step">
<div class="step-dot active"></div>
<div class="step-label active">Formatting the result</div>
</div>
</div>
""", unsafe_allow_html=True)
time.sleep(0.3) # Small delay for UX
if result["status"] == "COMPLETED":
# Extract answer using the new exposed API
answer = client.extract_answer(result["data"])
# Clear thinking steps
thinking_placeholder.empty()
elapsed_time = round(time.time() - start_time, 1)
# Print terminal log - COMPLETION
print("\n" + "_"*40)
print(f"WORKFLOW COMPLETED in {elapsed_time}s")
print("_"*40 + "\n")
if answer:
# Display the answer
if isinstance(answer, dict):
answer_placeholder.json(answer)
display_answer = answer
else:
answer_placeholder.markdown(answer)
display_answer = answer
else:
display_answer = "Workflow completed but no output found."
answer_placeholder.warning(display_answer)
# Save to current chat history
current_chat["messages"].append({
"role": "assistant",
"content": display_answer
})
# Update chat title with first response (3-4 words)
if len(current_chat["messages"]) == 2: # First Q&A pair
update_chat_title(current_chat["id"], display_answer)
elif result["status"] == "TIMEOUT":
thinking_placeholder.empty()
timeout_msg = f"⏱️ **Workflow Timeout** - The workflow is still running but hasn't completed within the expected time.\n\n**Run ID:** `{result['run_id']}`\n**Trace ID:** `{result['trace_id']}`"
answer_placeholder.warning(timeout_msg)
current_chat["messages"].append({"role": "assistant", "content": timeout_msg})
elif result["status"] == "FAILED":
thinking_placeholder.empty()
failed_msg = f"❌ **Workflow Failed** - The workflow encountered an error during execution.\n\n**Run ID:** `{result['run_id']}`\n**Trace ID:** `{result['trace_id']}`"
answer_placeholder.error(failed_msg)
current_chat["messages"].append({"role": "assistant", "content": failed_msg})
else:
thinking_placeholder.empty()
error_msg = f"❌ **Workflow Error** - Status: {result.get('status', 'UNKNOWN')}"
answer_placeholder.error(error_msg)
current_chat["messages"].append({"role": "assistant", "content": error_msg})
except Exception as e:
thinking_placeholder.empty()
error_msg = f"**Error:** {str(e)}"
answer_placeholder.error(error_msg)
current_chat["messages"].append({
"role": "assistant",
"content": error_msg
})
st.session_state.processing = False
st.rerun()