Spaces:
Sleeping
Sleeping
File size: 32,534 Bytes
7a00796 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 | 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() |