-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
2070 lines (1753 loc) · 99.9 KB
/
Copy pathstreamlit_app.py
File metadata and controls
2070 lines (1753 loc) · 99.9 KB
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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import time
import pandas as pd
from agent_activation_viz import visualize_agent_activation
from config.loader import config
from llm.providers import LLMFactory
from agents.sub_agents.ethics_agent import EthicsAgent
from agents.sub_agents.social_agent import SocialAgent
from agents.sub_agents.sentiment_agent import SentimentAgent
from agents.sub_agents.past_experience_agent import PastExperienceAgent
from langgraph_workflow import app as workflow_app
from controller.adaptive_controller import AdaptiveController
from domains.config import get_active_domains, get_domain
from agents.rag_helper import get_rag_helper
from agents.real_executor_agent import RealExecutorAgent
# Page config
st.set_page_config(
page_title="P-CABA: Pluggable Cognitive Adaptive Brain Agent",
page_icon="🧠",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for compact, professional UI
st.markdown("""
<style>
/* Reduce top padding */
.block-container {
padding-top: 2rem !important;
padding-bottom: 1rem !important;
}
/* Agent analysis boxes */
.agent-box {
padding: 1rem;
border-radius: 0.5rem;
margin: 0.5rem 0;
}
.cognitive-agent {
background-color: #e3f2fd;
border-left: 4px solid #2196f3;
}
.emotional-agent {
background-color: #fce4ec;
border-left: 4px solid #e91e63;
}
.sub-agent {
background-color: #f5f5f5;
border-left: 4px solid #9e9e9e;
margin-left: 1rem;
}
/* Full-width buttons */
.stButton>button {
width: 100%;
}
/* Compact headings */
h2 {
margin-top: 0rem;
margin-bottom: 0.5rem;
}
/* Tab content padding */
.stTabs [data-baseweb="tab-panel"] {
padding-top: 1rem;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
</style>
""", unsafe_allow_html=True)
# --- ChatGPT-like session management ---
if 'all_sessions' not in st.session_state:
st.session_state.all_sessions = {'Session 1': []}
if 'current_session' not in st.session_state:
st.session_state.current_session = 'Session 1'
if 'session_counter' not in st.session_state:
st.session_state.session_counter = 1
# Helper to generate a smart session name from a prompt
def generate_session_name(prompt):
"""Generate a concise session name (max 50 chars) from the first prompt"""
try:
# Remove extra whitespace
prompt = ' '.join(prompt.split())
# If it's a question, extract the key question words
if '?' in prompt:
# Take everything before the question mark
prompt = prompt.split('?')[0]
# Remove common filler words
filler_words = ['i', 'a', 'an', 'the', 'is', 'are', 'was', 'were', 'be', 'been', 'being',
'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'should', 'could',
'can', 'may', 'might', 'must', 'shall', 'me', 'my', 'we', 'our', 'you', 'your']
words = prompt.lower().split()
meaningful_words = [w for w in words if w not in filler_words]
# Reconstruct with meaningful words (capitalize first letter of each word)
if meaningful_words:
name = ' '.join(meaningful_words[:6]) # Max 6 words
name = ' '.join(word.capitalize() for word in name.split())
else:
# Fallback if all words were filtered
name = ' '.join(words[:5])
name = ' '.join(word.capitalize() for word in name.split())
# Truncate to 50 chars with ellipsis
if len(name) > 50:
name = name[:47] + "..."
return name if name else "Untitled Chat"
except:
return "Untitled Chat"
# Helper to rename current session based on first query
def rename_session_from_query(query):
"""Rename the current session if it's still using default Session X name"""
current_name = st.session_state.current_session
# Only rename if it's still the default "Session X" format
if current_name.startswith("Session ") and current_name.split()[-1].isdigit():
new_name = generate_session_name(query)
# Ensure unique name by adding number if needed
base_name = new_name
counter = 1
while new_name in st.session_state.all_sessions:
new_name = f"{base_name} ({counter})"
counter += 1
# Rename the session
st.session_state.all_sessions[new_name] = st.session_state.all_sessions.pop(current_name)
st.session_state.current_session = new_name
# Helper to start a new session
def start_new_session():
st.session_state.session_counter += 1
session_name = f"Session {st.session_state.session_counter}"
st.session_state.all_sessions[session_name] = []
st.session_state.current_session = session_name
# Helper to select a session
def select_session(session_name):
st.session_state.current_session = session_name
# --- Left sidebar: Chat session list ---
st.sidebar.title("💬 Chat Sessions")
for session_name in st.session_state.all_sessions:
if st.sidebar.button(session_name, key=session_name):
select_session(session_name)
st.sidebar.button("➕ New Chat", on_click=start_new_session)
st.sidebar.markdown("---")
# Email Notifications (Optional) - MOVED TO TOP
st.sidebar.markdown("### 📧 Email Notifications")
st.sidebar.caption("Get notified when reports are generated (optional)")
# Initialize email settings in session state
if 'email_enabled' not in st.session_state:
st.session_state.email_enabled = False
if 'user_email' not in st.session_state:
st.session_state.user_email = ""
email_enabled = st.sidebar.checkbox(
"Enable email alerts for reports",
value=st.session_state.email_enabled,
key="email_checkbox",
help="Receive email when FDA reports, market analysis, or legal documents are generated"
)
user_email = ""
if email_enabled:
user_email = st.sidebar.text_input(
"Your email address",
value=st.session_state.user_email,
key="email_input",
placeholder="your.email@example.com",
help="We'll notify you when long-running actions complete"
)
st.sidebar.caption("🔒 Email stored in session only (not saved)")
st.sidebar.caption("📧 Emails sent only for: FDA reports, market analysis, legal documents")
# Update session state
if user_email:
st.session_state.user_email = user_email
st.session_state.email_enabled = email_enabled
st.sidebar.markdown("---")
# PDF Upload for RAG
st.sidebar.markdown("### 📄 Upload Knowledge (RAG)")
st.sidebar.caption("Add PDF documents to knowledge base")
from agents.pdf_rag_ingestion import get_pdf_ingestion
pdf_ingestion = get_pdf_ingestion()
# Domain selector for PDF upload
upload_domain = st.sidebar.selectbox(
"Target Domain",
["healthcare", "business", "legal"],
key="upload_domain",
format_func=lambda x: {
'healthcare': '🏥 Healthcare',
'business': '💼 Business',
'legal': '⚖️ Legal'
}.get(x, x)
)
# File uploader
uploaded_file = st.sidebar.file_uploader(
"Choose PDF file",
type=['pdf'],
key="pdf_upload",
help="Upload a PDF to add to the knowledge base"
)
if uploaded_file is not None:
if st.sidebar.button("🚀 Process & Add to Knowledge Base", use_container_width=True):
with st.sidebar:
with st.spinner("Processing PDF..."):
result = pdf_ingestion.process_uploaded_pdf(uploaded_file, upload_domain)
if result['success']:
st.success(f"✅ Processed **{result['filename']}**!")
st.info(f"📊 Created {result['chunks_created']} knowledge chunks in {result['processing_time']:.2f}s")
st.caption(f"💾 Size: {result['size_bytes']/1024:.1f} KB | ID: {result['doc_id']}")
else:
st.error(f"❌ Error: {result['error']}")
# Show upload summary if documents exist
upload_summary = pdf_ingestion.get_upload_summary()
if upload_summary['total_documents'] > 0:
with st.sidebar.expander(f"📚 {upload_summary['total_documents']} Documents Uploaded"):
st.caption(f"Total Chunks: {upload_summary['total_chunks']}")
st.caption(f"Domains: {', '.join(upload_summary['domains'])}")
st.markdown("**Recent Uploads:**")
for doc in upload_summary['recent_uploads']:
st.markdown(f"- **{doc['filename']}** ({doc['domain']})")
st.caption(f" {doc['chunks']} chunks | {doc['size_kb']:.1f} KB")
st.sidebar.markdown("---")
# Smart Domain Detection (Auto-detects from query!)
st.sidebar.markdown("### 🧠 Smart Domain Detection")
st.sidebar.caption("Domain is automatically detected from your query context")
# Initialize domain in session state (will be overridden by button clicks)
if 'selected_domain' not in st.session_state:
st.session_state.selected_domain = 'healthcare'
st.sidebar.markdown("---")
# Quick Example Prompts
st.sidebar.markdown("### 💡 Quick Test Prompts")
st.sidebar.caption("One-click testing for demo & judges")
# Healthcare Examples
with st.sidebar.expander("🏥 Healthcare", expanded=False):
if st.sidebar.button("H1: Drug Approval Ethics", key="h1", use_container_width=True):
st.session_state.input_text = "Should I approve an experimental drug for a terminal patient with no other treatment options?"
st.session_state.selected_domain = "healthcare"
st.rerun()
if st.sidebar.button("H2: AI Triage System", key="h2", use_container_width=True):
st.session_state.input_text = "Should we implement AI-assisted triage in our emergency room?"
st.session_state.selected_domain = "healthcare"
st.rerun()
# Business Examples
with st.sidebar.expander("💼 Business", expanded=False):
if st.sidebar.button("B1: Layoff vs Salary Cut", key="b1", use_container_width=True):
st.session_state.input_text = "Should I lay off 100 employees or cut everyone's salary by 20%? Our SaaS startup has 8 months of runway left."
st.session_state.selected_domain = "business"
st.rerun()
if st.sidebar.button("B2: M&A Decision", key="b2", use_container_width=True):
st.session_state.input_text = "Should we acquire our main competitor for $50M?"
st.session_state.selected_domain = "business"
st.rerun()
# Legal Examples
with st.sidebar.expander("⚖️ Legal", expanded=False):
if st.sidebar.button("L1: Settlement vs Trial", key="l1", use_container_width=True):
st.session_state.input_text = "Should we accept the $2M settlement offer or proceed to trial?"
st.session_state.selected_domain = "legal"
st.rerun()
if st.sidebar.button("L2: Whistleblower Dilemma", key="l2", use_container_width=True):
st.session_state.input_text = "Should I report suspected financial fraud internally or to regulators?"
st.session_state.selected_domain = "legal"
st.rerun()
st.sidebar.markdown("---")
st.sidebar.title("⚙️ P-CABA Controls")
st.sidebar.markdown("---")
st.sidebar.markdown("### 🎚️ Adaptive Weights")
cognitive_weight = st.sidebar.slider(
"Cognitive Weight",
0.0, 1.0, 0.5, 0.1
)
emotional_weight = 1.0 - cognitive_weight
st.sidebar.info(f"Emotional Weight: {emotional_weight:.1f}")
thinking_time = st.sidebar.slider(
"⏱️ Max Thinking Time (seconds)",
1, 30, 10, 1
)
resource_limit = st.sidebar.slider(
"💻 Resource Limit",
1, 100, 50, 5
)
st.sidebar.markdown("---")
st.sidebar.markdown("### 📊 Statistics")
current_history = st.session_state.all_sessions[st.session_state.current_session]
if current_history:
st.sidebar.metric("Total Queries", len(current_history))
avg_confidence = sum(h['final_confidence'] for h in current_history if 'final_confidence' in h) / len(current_history)
st.sidebar.metric("Avg Confidence", f"{avg_confidence:.2f}")
# Confidence Evolution Chart
st.sidebar.markdown("#### 📈 Confidence Over Time")
confidence_data = []
for idx, turn in enumerate(current_history, 1):
if 'final_confidence' in turn:
confidence_data.append({
'query': idx,
'cognitive': turn.get('cognitive', {}).get('confidence', 0),
'emotional': turn.get('emotional', {}).get('confidence', 0),
'final': turn.get('final_confidence', 0)
})
if confidence_data:
import plotly.graph_objects as go
fig = go.Figure()
queries = [d['query'] for d in confidence_data]
# Cognitive confidence line
fig.add_trace(go.Scatter(
x=queries,
y=[d['cognitive'] for d in confidence_data],
mode='lines+markers',
name='Cognitive',
line=dict(color='#2196f3', width=2),
marker=dict(size=6)
))
# Emotional confidence line
fig.add_trace(go.Scatter(
x=queries,
y=[d['emotional'] for d in confidence_data],
mode='lines+markers',
name='Emotional',
line=dict(color='#e91e63', width=2),
marker=dict(size=6)
))
# Final confidence line
fig.add_trace(go.Scatter(
x=queries,
y=[d['final'] for d in confidence_data],
mode='lines+markers',
name='Final',
line=dict(color='#4caf50', width=3, dash='dot'),
marker=dict(size=8, symbol='diamond')
))
fig.update_layout(
height=250,
margin=dict(l=10, r=10, t=10, b=10),
xaxis_title="Query #",
yaxis_title="Confidence",
yaxis=dict(range=[0, 1]),
legend=dict(orientation="h", yanchor="top", y=-0.1, xanchor="center", x=0.5),
hovermode='x unified',
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)'
)
st.sidebar.plotly_chart(fig, use_container_width=True)
# Export functions
def export_json(history):
"""Export conversation as JSON"""
import json
from datetime import datetime
export_data = {
"session": st.session_state.current_session,
"exported_at": datetime.now().isoformat(),
"conversation": [h for h in history if not h.get('thinking')]
}
return json.dumps(export_data, indent=2)
def export_markdown(history, session_name):
"""Export conversation as Markdown"""
from datetime import datetime
md_content = f"# P-CABA Conversation Export\n\n"
md_content += f"**Session:** {session_name}\n"
md_content += f"**Exported:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
md_content += "---\n\n"
for idx, turn in enumerate([h for h in history if not h.get('thinking')], 1):
query = turn.get('query', 'N/A')
md_content += f"## Query {idx}\n\n"
md_content += f"**User:** {query}\n\n"
if 'synthesis' in turn and turn['synthesis']:
md_content += f"**Final Answer:**\n{turn['synthesis'].get('final_answer', 'N/A')}\n\n"
if 'cognitive' in turn and turn['cognitive']:
md_content += f"**Cognitive Analysis:**\n{turn['cognitive'].get('analysis', 'N/A')[:300]}...\n\n"
if 'emotional' in turn and turn['emotional']:
md_content += f"**Emotional Analysis:**\n{turn['emotional'].get('analysis', 'N/A')[:300]}...\n\n"
md_content += "---\n\n"
return md_content
def export_text(history):
"""Export conversation as plain text"""
from datetime import datetime
text_content = f"P-CABA Conversation - {st.session_state.current_session}\n"
text_content += f"Exported: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
text_content += "="*60 + "\n\n"
for idx, turn in enumerate([h for h in history if not h.get('thinking')], 1):
query = turn.get('query', 'N/A')
text_content += f"[Q{idx}] {query}\n\n"
if 'synthesis' in turn and turn['synthesis']:
text_content += f"[A{idx}] {turn['synthesis'].get('final_answer', 'N/A')}\n\n"
text_content += "-"*60 + "\n\n"
return text_content
# Use config-driven LLM provider selection
llm_config = config.get_llm_config()
llm_provider = LLMFactory.create_provider(llm_config)
# Instantiate agents (for direct calls if needed)
ethics_agent_obj = EthicsAgent(llm_provider)
social_agent_obj = SocialAgent(llm_provider)
sentiment_agent_obj = SentimentAgent(llm_provider)
past_experience_agent_obj = PastExperienceAgent(llm_provider)
# Use workflow from langgraph_workflow.py
app = workflow_app
# --- Main area: Clean interface ---
st.markdown("## 🧠 P-CABA")
st.caption("Pluggable Cognitive Adaptive Brain | Multi-Agent Decision System")
# Create tabs - 6 tabs for better organization
tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs([
"💬 Chat",
"🔍 Agent Analysis",
"⚖️ Adaptive Weights",
"🤖 Executor Actions",
"🧠 Memory & Context",
"🏗️ Architecture"
])
# TAB 1: Chat Interface (CLEAN - conversation only!)
with tab1:
current_history = st.session_state.all_sessions[st.session_state.current_session]
# === REMOVED DUPLICATE EXPORT SECTION (already in main chat area) ===
_dummy_export_removed = True # Placeholder to maintain structure
if False: # Disabled - export buttons are in main chat area
if st.button("📥 Download", use_container_width=True, key="export_btn_disabled"):
import json
from datetime import datetime
if export_format == "JSON":
# Full data export
export_data = {
"session": st.session_state.current_session,
"exported_at": datetime.now().isoformat(),
"conversation": [h for h in current_history if not h.get('thinking')]
}
json_str = json.dumps(export_data, indent=2)
st.download_button(
label="💾 Download JSON",
data=json_str,
file_name=f"pcaba_conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
mime="application/json",
key="download_json"
)
elif export_format == "Markdown":
# Human-readable markdown
md_content = f"# P-CABA Conversation Export\n\n"
md_content += f"**Session:** {st.session_state.current_session}\n"
md_content += f"**Exported:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
md_content += "---\n\n"
for idx, turn in enumerate([h for h in current_history if not h.get('thinking')], 1):
query = turn.get('query', 'N/A')
md_content += f"## Query {idx}\n\n"
md_content += f"**User:** {query}\n\n"
if turn.get('synthesis', {}).get('final_answer'):
md_content += f"**Final Answer:**\n{turn['synthesis']['final_answer']}\n\n"
if turn.get('cognitive', {}).get('analysis'):
md_content += f"### 🧠 Cognitive Analysis\n{turn['cognitive']['analysis']}\n\n"
if turn.get('emotional', {}).get('analysis'):
md_content += f"### ❤️ Emotional Analysis\n{turn['emotional']['analysis']}\n\n"
if turn.get('debate_log'):
md_content += f"### 💬 Debate\n```\n{turn['debate_log']}\n```\n\n"
md_content += "---\n\n"
st.download_button(
label="💾 Download Markdown",
data=md_content,
file_name=f"pcaba_conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md",
mime="text/markdown",
key="download_md"
)
else: # Text Summary
# Concise summary
summary = f"P-CABA Conversation Summary\n"
summary += f"Session: {st.session_state.current_session}\n"
summary += f"Exported: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
summary += f"Total Queries: {len([h for h in current_history if not h.get('thinking')])}\n\n"
summary += "=" * 60 + "\n\n"
for idx, turn in enumerate([h for h in current_history if not h.get('thinking')], 1):
query = turn.get('query', 'N/A')
answer = turn.get('synthesis', {}).get('final_answer', 'N/A')[:200]
confidence = turn.get('final_confidence', 0)
summary += f"Q{idx}: {query}\n"
summary += f"A{idx}: {answer}...\n"
summary += f"Confidence: {confidence:.2%}\n\n"
st.download_button(
label="💾 Download Summary",
data=summary,
file_name=f"pcaba_summary_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
mime="text/plain",
key="download_txt"
)
st.markdown("---")
# ===== TAB 1 CONTENT: CHAT with LIVE AGENT ANALYSIS =====
# Create 2-column layout: Main chat (left 66%) + Live Analysis (right 33%)
col_main_chat, col_live_analysis = st.columns([2, 1])
# ===== LEFT COLUMN: Main Chat Conversation =====
with col_main_chat:
# Export button at top of chat (if conversation exists)
if current_history and len([t for t in current_history if not t.get("thinking")]) > 0:
st.markdown("### 💬 Conversation")
export_col1, export_col2, export_col3, export_col4 = st.columns([1, 1, 1, 2])
with export_col1:
# JSON export
json_data = export_json(current_history)
st.download_button(
label="📥 JSON",
data=json_data,
file_name=f"{st.session_state.current_session.replace(' ', '_')}.json",
mime="application/json",
use_container_width=True
)
with export_col2:
# Markdown export
markdown_data = export_markdown(current_history, st.session_state.current_session)
st.download_button(
label="📝 Markdown",
data=markdown_data,
file_name=f"{st.session_state.current_session.replace(' ', '_')}.md",
mime="text/markdown",
use_container_width=True
)
with export_col3:
# Text export
text_data = export_text(current_history)
st.download_button(
label="📄 Text",
data=text_data,
file_name=f"{st.session_state.current_session.replace(' ', '_')}.txt",
mime="text/plain",
use_container_width=True
)
st.markdown("---")
# --- Chat bubbles above input box, scrollable only inside bubbles ---
chat_bubble_height = "50vh"
# Only show chat area if there is at least one valid user prompt or a thinking bubble
valid_turns = []
for turn in current_history:
if turn.get("query"):
valid_turns.append(turn)
elif turn.get("thinking") and (not valid_turns or valid_turns[-1].get("thinking") is not True):
# Only add a thinking bubble if not already present for this user turn
valid_turns.append(turn)
if valid_turns:
st.markdown(f"<div style='max-height:{chat_bubble_height};overflow-y:auto;padding:1rem;background:#181a20;border-radius:0.5rem;'>", unsafe_allow_html=True)
for chat in valid_turns:
# Get user query from either the query field or session_history
user_query = chat.get("query", "")
if not user_query:
user_query = chat.get("session_history", [{}])[-1].get("query") if chat.get("session_history") and isinstance(chat.get("session_history")[-1], dict) else "N/A"
# Get domain info for this query
domain_id = chat.get("domain_id", "healthcare")
domain_info = get_domain(domain_id)
domain_badge = ""
if domain_info:
domain_badge = f"<span style='background:#1976d2;color:white;padding:0.2rem 0.5rem;border-radius:0.8rem;font-size:0.75rem;margin-left:0.5rem;'>{domain_info.icon} {domain_info.name}</span>"
st.markdown(f"<div style='background:#23272f;padding:0.5rem 1rem;border-radius:0.5rem;margin-bottom:0.2rem;color:#fff;max-width:80%;'><b>User:</b> {user_query}{domain_badge}</div>", unsafe_allow_html=True)
# Show only one agent bubble: either thinking or response
if chat.get("thinking"):
st.markdown(f"<div style='background:#e3f2fd;padding:0.6rem 1rem;border-radius:0.5rem;margin-bottom:0.5rem;color:#1976d2;max-width:80%;border-left:4px solid #1976d2;'><b>🤖 Multi-Agent System:</b> <span style='animation:pulse 1.5s infinite;'>Processing...</span><br/><small style='opacity:0.8;'>🧠 Cognitive & Emotional Analysis → 💬 Agent Debate → 🎯 Synthesis</small></div>", unsafe_allow_html=True)
else:
# Show final synthesized answer if available, otherwise fall back to cognitive/emotional
agent_summary = ""
if 'synthesis' in chat and chat['synthesis'] and chat['synthesis'].get('final_answer'):
agent_summary = chat['synthesis']['final_answer']
elif 'cognitive' in chat and chat['cognitive'] and chat['cognitive'].get('analysis'):
agent_summary = chat['cognitive']['analysis']
elif 'emotional' in chat and chat['emotional'] and chat['emotional'].get('analysis'):
agent_summary = chat['emotional']['analysis']
if agent_summary:
# Don't truncate - show full synthesized answer
# Escape HTML to prevent rendering issues
agent_summary_escaped = agent_summary.replace('<', '<').replace('>', '>')
st.markdown(f"<div style='background:#fffbe6;padding:0.5rem 1rem;border-radius:0.5rem;margin-bottom:0.5rem;color:#222;max-width:80%;max-height:400px;overflow-y:auto;'><b>Agent:</b> {agent_summary_escaped}</div>", unsafe_allow_html=True)
# Show RAG Knowledge Base badges FIRST (most important!)
rag_badges = []
if 'cognitive' in chat and chat['cognitive'].get('rag_result'):
cog_rag = chat['cognitive']['rag_result']
if cog_rag.get('source_count', 0) > 0:
domain_icon = cog_rag.get('domain_icon', '📚')
source_count = cog_rag.get('source_count', 0)
rag_badges.append(f"<span style='background:#4caf50;color:white;padding:0.3rem 0.6rem;border-radius:1rem;font-size:0.85rem;'>{domain_icon} Knowledge Base: {source_count} sources</span>")
if 'emotional' in chat and chat['emotional'].get('rag_result'):
emo_rag = chat['emotional']['rag_result']
if emo_rag.get('source_count', 0) > 0 and not rag_badges: # Only show if cognitive didn't already
domain_icon = emo_rag.get('domain_icon', '📚')
source_count = emo_rag.get('source_count', 0)
rag_badges.append(f"<span style='background:#4caf50;color:white;padding:0.3rem 0.6rem;border-radius:1rem;font-size:0.85rem;'>{domain_icon} Knowledge Base: {source_count} sources</span>")
if rag_badges:
badges_html = "<div style='display:flex;gap:0.5rem;flex-wrap:wrap;margin-bottom:0.5rem;max-width:80%;'>"
badges_html += "".join(rag_badges)
badges_html += "</div>"
st.markdown(badges_html, unsafe_allow_html=True)
# Show tool usage badges if external tools were used
if 'cognitive' in chat and chat['cognitive'].get('tool_results'):
tool_results = chat['cognitive']['tool_results']
badges_html = "<div style='display:flex;gap:0.5rem;flex-wrap:wrap;margin-bottom:0.5rem;max-width:80%;'>"
for tool_name, result in tool_results.items():
if result.get('success'):
tool_icon = {
'web_search': '🔍',
'weather': '🌤️',
'calculator': '🧮'
}.get(tool_name, '🔧')
tool_display = {
'web_search': 'Web Search',
'weather': 'Weather Data',
'calculator': 'Calculator'
}.get(tool_name, tool_name.title())
badges_html += f"<span style='background:#e3f2fd;color:#1976d2;padding:0.3rem 0.6rem;border-radius:1rem;font-size:0.85em;border:1px solid #1976d2;'>{tool_icon} {tool_display}</span>"
badges_html += "</div>"
st.markdown(badges_html, unsafe_allow_html=True)
st.markdown("</div>", unsafe_allow_html=True)
# ===== BALANCED QUERY QUICK BUTTONS (Organized by Domain!) =====
st.markdown("---")
st.markdown("### 💡 Quick Test: Balanced Queries")
st.caption("Click to auto-fill prompts that showcase P-CABA's balanced reasoning across domains")
# Create 3 columns for domains
col_health, col_business, col_legal = st.columns(3)
with col_health:
st.markdown("**🏥 Healthcare**")
if st.button("Drug Approval Ethics", key="health_1", use_container_width=True):
st.session_state.input_text = "Should I approve experimental aspirin-based drug for a terminal patient with no other treatment options? Check FDA database for similar drugs and safety data."
st.session_state.selected_domain = "healthcare"
st.rerun()
if st.button("AI Triage System", key="health_2", use_container_width=True):
st.session_state.input_text = "Should we implement AI-assisted triage in our emergency room to prioritize patients?"
st.session_state.selected_domain = "healthcare"
st.rerun()
with col_business:
st.markdown("**💼 Business**")
if st.button("Layoff vs Salary Cut", key="business_1", use_container_width=True):
st.session_state.input_text = "Should I lay off 100 employees or cut everyone's salary by 20%? Our SaaS startup has 8 months of runway left. Get current market data for WCLD (SaaS cloud computing ETF) to understand industry conditions."
st.session_state.selected_domain = "business"
st.rerun()
if st.button("Acquire Competitor", key="business_2", use_container_width=True):
st.session_state.input_text = "Should we acquire our main competitor for $50M? Analyze market conditions and strategic implications."
st.session_state.selected_domain = "business"
st.rerun()
with col_legal:
st.markdown("**⚖️ Legal**")
if st.button("Settlement Decision", key="legal_1", use_container_width=True):
st.session_state.input_text = "Should we accept the $2M settlement offer or proceed to trial? Case involves product liability."
st.session_state.selected_domain = "legal"
st.rerun()
if st.button("Whistleblower Dilemma", key="legal_2", use_container_width=True):
st.session_state.input_text = "Should I report suspected financial fraud internally or to regulators?"
st.session_state.selected_domain = "legal"
st.rerun()
st.markdown("---")
# ===== INPUT AREA (Clean, no clutter above it) =====
# Initialize domain in session state
if 'selected_domain' not in st.session_state:
st.session_state.selected_domain = 'healthcare'
# Initialize input text in session state
if 'input_text' not in st.session_state:
st.session_state.input_text = ''
# Input area - using text_area for better visibility
# Use on_change to avoid the rerun issue
def update_input():
pass # Just needed for the callback
user_input = st.text_area(
"Type your message...",
value=st.session_state.input_text,
height=100,
placeholder="💡 Ask a question or use sidebar prompts...",
on_change=update_input
)
# Sync the session state with what user types
if user_input != st.session_state.input_text:
st.session_state.input_text = user_input
col1, col2, col3 = st.columns([1, 1, 4])
with col1:
submit_button = st.button("📤 Send", type="primary", use_container_width=True)
with col2:
if st.button("🗑️ Clear", use_container_width=True):
st.session_state.input_text = ''
st.rerun()
if submit_button and user_input.strip():
# Clear the input text for next time
st.session_state.input_text = ''
# Rename session based on first query (if still default name)
if len(current_history) == 0: # This will be the first query
rename_session_from_query(user_input.strip())
# If last entry is a thinking bubble, replace it; else append new
if current_history and current_history[-1].get("thinking"):
st.session_state.all_sessions[st.session_state.current_session][-1] = {
"query": user_input.strip(),
"domain_id": st.session_state.selected_domain, # Store selected domain
"cognitive": {},
"thinking": True
}
else:
st.session_state.all_sessions[st.session_state.current_session].append({
"query": user_input.strip(),
"domain_id": st.session_state.selected_domain, # Store selected domain
"cognitive": {},
"thinking": True
})
st.rerun()
# ===== RIGHT COLUMN: Live Agent Analysis (Always visible) =====
with col_live_analysis:
st.markdown("### 🧠 Live Analysis")
st.markdown("---")
# Get latest completed query
latest_completed = None
for turn in reversed(current_history):
if not turn.get("thinking") and turn.get("query"):
latest_completed = turn
break
if latest_completed:
# Agent Activation Graph - Full Visualization
st.markdown("#### 🔗 Agent Activation")
if 'cognitive' in latest_completed and 'emotional' in latest_completed:
# Build agent timings from latest result (including executor)
agent_timings = {
'controller': latest_completed.get('controller_time', 0.5),
'cognitive': latest_completed.get('cognitive', {}).get('time_taken', 0),
'emotional': latest_completed.get('emotional', {}).get('time_taken', 0),
'synthesizer': latest_completed.get('synthesis', {}).get('time_taken', 0),
'executor': latest_completed.get('executor_time', 0), # Fixed: use executor_time
'ethics': 0,
'social': 0,
'sentiment': 0,
'past_experience': 0
}
# Extract sub-agent times from outputs
cog_outputs = latest_completed.get('cognitive', {}).get('outputs', [])
emo_outputs = latest_completed.get('emotional', {}).get('outputs', [])
for output in cog_outputs:
if 'Ethics' in output.get('agent', ''):
agent_timings['ethics'] = latest_completed.get('cognitive', {}).get('action_time', 2.0) / 2
elif 'Social' in output.get('agent', ''):
agent_timings['social'] = latest_completed.get('cognitive', {}).get('action_time', 2.0) / 2
for output in emo_outputs:
if 'Sentiment' in output.get('agent', ''):
agent_timings['sentiment'] = latest_completed.get('emotional', {}).get('time_taken', 0) / 2
elif 'Past' in output.get('agent', ''):
agent_timings['past_experience'] = latest_completed.get('emotional', {}).get('time_taken', 0) / 2
# Build agent thoughts (increased char limit for better visibility)
agent_thoughts = {
'controller': 'Orchestrates multi-agent workflow',
'cognitive': latest_completed.get('cognitive', {}).get('analysis', 'Cognitive reasoning')[:150],
'emotional': latest_completed.get('emotional', {}).get('analysis', 'Emotional reasoning')[:150],
'synthesizer': latest_completed.get('synthesis', {}).get('final_answer', 'Synthesis')[:150],
'executor': latest_completed.get('executor', {}).get('summary', 'Executing actions')[:150],
'ethics': cog_outputs[0].get('analysis', 'Ethics analysis')[:120] if len(cog_outputs) > 0 else 'Ethics analysis',
'social': cog_outputs[1].get('analysis', 'Social analysis')[:120] if len(cog_outputs) > 1 else 'Social impact',
'sentiment': emo_outputs[0].get('analysis', 'Sentiment analysis')[:120] if len(emo_outputs) > 0 else 'Sentiment',
'past_experience': emo_outputs[1].get('analysis', 'Past experience')[:120] if len(emo_outputs) > 1 else 'Experience'
}
# Get debate time
debate_time = latest_completed.get('debate_time', 0)
# Create Agent Activation Graph
try:
from agent_activation_viz import visualize_agent_activation
fig = visualize_agent_activation(
agent_timings,
agent_thoughts,
debate_time=debate_time,
show_architecture_labels=False # Compact for right pane
)
st.plotly_chart(fig, use_container_width=True)
except Exception as e:
st.caption("⏳ Graph loading...")
else:
st.info("⏳ Processing...")
st.markdown("---")
# Performance Metrics
st.markdown("#### 📊 Performance")
if 'cognitive' in latest_completed and 'emotional' in latest_completed:
cog_score = latest_completed['cognitive'].get('confidence', 0)
emo_score = latest_completed['emotional'].get('confidence', 0)
cog_time = latest_completed['cognitive'].get('time_taken', 0)
emo_time = latest_completed['emotional'].get('time_taken', 0)
# Show confidence scores
col_a, col_b = st.columns(2)
with col_a:
st.metric("🧠 Cognitive", f"{cog_score:.0%}")
st.caption(f"⏱️ {cog_time:.2f}s")
with col_b:
st.metric("❤️ Emotional", f"{emo_score:.0%}")
st.caption(f"⏱️ {emo_time:.2f}s")
# Total time
total_time = cog_time + emo_time
if 'synthesis' in latest_completed:
synth_time = latest_completed['synthesis'].get('time_taken', 0)
total_time += synth_time
st.caption(f"🎯 Total: {total_time:.2f}s")
# Show debate if available
debate_log = latest_completed.get('debate_log', '')
debate_time_val = latest_completed.get('debate_time', 0)
with st.expander("💬 Debate", expanded=False):
if debate_log:
st.caption(f"⏱️ Duration: {debate_time_val:.3f}s")
st.markdown("---")
# Parse and display debate exchanges with full formatting
lines = debate_log.split('\n')
formatted_debate = []
for line in lines:
if 'Turn' in line and ('Cognitive:' in line or 'Emotional:' in line):
if 'Cognitive:' in line:
# Cognitive debate turns - blue background
formatted_debate.append(f"<div style='background:#1976d2;padding:0.5rem;border-left:3px solid #0d47a1;margin:0.2rem 0;border-radius:0.2rem;color:#ffffff;font-weight:500;font-size:0.85em;'>{line}</div>")
else:
# Emotional debate turns - pink background
formatted_debate.append(f"<div style='background:#c2185b;padding:0.5rem;border-left:3px solid #880e4f;margin:0.2rem 0;border-radius:0.2rem;color:#ffffff;font-weight:500;font-size:0.85em;'>{line}</div>")
elif 'COMMON GROUND' in line or '🤝' in line:
# Common ground - green background
formatted_debate.append(f"<div style='background:#388e3c;padding:0.5rem;border-left:3px solid #1b5e20;margin:0.2rem 0;border-radius:0.2rem;color:#ffffff;font-weight:600;font-size:0.85em;'>{line}</div>")
elif 'RESOLUTION' in line or '⚖️' in line:
# Resolution - gold background
formatted_debate.append(f"<div style='background:#ffc107;padding:0.5rem;border-left:3px solid #f57f17;margin:0.2rem 0;border-radius:0.2rem;color:#1a1a1a;font-weight:600;font-size:0.85em;'>{line}</div>")
elif 'Confidence:' in line:
formatted_debate.append(f"<div style='padding:0.2rem 0.3rem;color:#bbbbbb;font-size:0.75em;'>{line}</div>")
elif line.strip() and not line.startswith('==='):
formatted_debate.append(f"<div style='padding:0.2rem 0.3rem;color:#e0e0e0;font-size:0.8em;'>{line}</div>")
st.markdown('\n'.join(formatted_debate), unsafe_allow_html=True)
else:
st.info("No debate available for this query.")
else:
st.info("⏳ Processing...")
# Adaptive Weights
st.markdown("---")
st.markdown("#### ⚖️ Adaptive Weights")
# Check multiple possible locations for weights
weights = None
# First check top-level weights from controller
if 'weights' in latest_completed:
weights = latest_completed['weights']
# Then check synthesis for backward compatibility
elif 'synthesis' in latest_completed:
if 'adaptive_weights' in latest_completed['synthesis']:
weights = latest_completed['synthesis']['adaptive_weights']
elif 'final_weights' in latest_completed['synthesis']:
weights = latest_completed['synthesis']['final_weights']
if weights:
cog_weight = weights.get('cognitive', 0.5)
emo_weight = weights.get('emotional', 0.5)
st.progress(cog_weight, text=f"🧠 Cognitive: {cog_weight:.2%}")
st.progress(emo_weight, text=f"❤️ Emotional: {emo_weight:.2%}")
# Show weight interpretation
if cog_weight > 0.6:
st.caption("📊 Logic-heavy query")
elif emo_weight > 0.6:
st.caption("💝 Empathy-focused query")
else:
st.caption("⚖️ Balanced reasoning")
else:
# Show default weights if synthesis hasn't completed
st.progress(0.5, text="🧠 Cognitive: 50%")
st.progress(0.5, text="❤️ Emotional: 50%")
st.caption("⏳ Using balanced defaults")
# Knowledge Base (RAG)
st.markdown("---")
st.markdown("#### 📚 Knowledge Base")
if 'cognitive' in latest_completed and 'rag_result' in latest_completed['cognitive']:
rag_result = latest_completed['cognitive']['rag_result']
source_count = rag_result.get('source_count', 0)
if source_count > 0:
domain_icon = rag_result.get('domain_icon', '📚')
domain_name = rag_result.get('domain_name', 'Domain')