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(""" """, 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(""" """, 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('', 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('
', 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('
Healthcare Data Assistant
', unsafe_allow_html=True) st.markdown('
Ask questions about healthcare claims, members, providers, and clinical data in natural language.
', 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("""
👋 Welcome to Agent Pulse!
I'm your AI-powered healthcare data assistant. Ask me anything about your healthcare data.
""", unsafe_allow_html=True) st.markdown('
💡 Try these sample queries:
', 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("""
Analyzing the query
Processing the query
Formatting the result
""", 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("""
Analyzing the query
Processing the query
Formatting the result
""", 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("""
Analyzing the query
Processing the query
Formatting the result
""", 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()