-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui.py
More file actions
2350 lines (1969 loc) · 84.1 KB
/
Copy pathui.py
File metadata and controls
2350 lines (1969 loc) · 84.1 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
"""
UI for Deliberate AI using PyQt6
Migrated from CustomTkinter to PyQt6 for better threading and responsiveness
"""
import sys
import json
import yaml
import os
import re
import traceback
from datetime import datetime
from typing import Optional, Callable
# Import torch BEFORE PyQt6 to avoid DLL conflicts on Windows
import torch
import numpy as np
from PyQt6.QtWidgets import (
QApplication,
QMainWindow,
QWidget,
QVBoxLayout,
QHBoxLayout,
QPushButton,
QLabel,
QTextEdit,
QTextBrowser,
QLineEdit,
QComboBox,
QCheckBox,
QSplitter,
QTabWidget,
QScrollArea,
QFrame,
QStatusBar,
QMessageBox,
QFileDialog,
QGroupBox,
QDialog,
QSlider,
)
from PyQt6.QtCore import (
Qt,
QRunnable,
QThreadPool,
pyqtSignal,
QObject,
QTimer,
pyqtSlot,
)
from PyQt6.QtGui import QFont
from pipeline import Pipeline
from tts_client import get_tts_client, TTSClient
from error_tracker import error_tracker, log_pipeline_error, log_ui_error
from search import search_searxng, check_searxng_reachable
# TTS client will be initialized lazily when first needed
tts_client = None
# Set application style
QApplication.setStyle("Fusion")
class WorkerSignals(QObject):
"""Signals for worker thread communication"""
finished = pyqtSignal()
error = pyqtSignal(tuple)
result = pyqtSignal(object)
progress = pyqtSignal(str)
log_message = pyqtSignal(str)
persona_added = pyqtSignal(dict)
round_complete = pyqtSignal(dict)
class TTSGenerationWorker(QRunnable):
"""Worker for generating TTS audio in background thread"""
def __init__(self, text: str, voice_index: int = 0, save_to_file: bool = True):
super().__init__()
self.signals = WorkerSignals()
self.text = text
self.voice_index = voice_index
self.save_to_file = save_to_file
@pyqtSlot()
def run(self):
"""Generate and play audio in background thread"""
try:
self.signals.progress.emit("Initializing TTS...")
# Get TTS client instance
client = get_tts_client()
voice = (
client.available_voices[self.voice_index]
if self.voice_index < len(client.available_voices)
else "alba"
)
# Generate and play (this blocks until playback is complete)
# Save to file if requested
client.generate_and_play(
self.text,
voice=voice,
save_to_file=self.save_to_file,
progress_callback=lambda msg: self.signals.progress.emit(msg),
complete_callback=lambda error=None: self.signals.finished.emit(),
)
except Exception as e:
self.signals.error.emit((str(e), "TTS Generation Failed"))
class PersonaResponseWorker(QRunnable):
"""Worker for generating persona responses in background thread"""
def __init__(
self,
persona,
user_message,
pipeline,
current_question,
predicted_outcome,
chat_history=None,
search_enabled=False,
):
super().__init__()
self.signals = WorkerSignals()
self.persona = persona
self.user_message = user_message
self.pipeline = pipeline
self.current_question = current_question
self.predicted_outcome = predicted_outcome
self.chat_history = chat_history or []
self.search_enabled = search_enabled
@pyqtSlot()
def run(self):
"""Generate response in background thread"""
try:
search_context = None
# Smart web search if enabled
if self.search_enabled:
# Check if search is needed using hybrid approach
needs_search, queries = self._analyze_for_search_needed(
self.user_message
)
if needs_search and queries:
# Show searching status
self.signals.progress.emit(f"Searching: {queries[0]}...")
# Perform web search
search_context = self._perform_web_search(queries)
# Build prompt (with or without search context)
prompt = self._build_prompt(search_context)
# Call LLM with conversation history if available
messages = [{"role": "user", "content": prompt}]
# Add conversation history if it exists
if self.chat_history:
# Insert history before the current message
for msg in self.chat_history[-5:]: # Last 5 messages for context
role = (
"assistant"
if msg["role"] == self.persona.get("name")
else "user"
)
messages.insert(0, {"role": role, "content": msg["text"]})
# Call LLM with raw response for conversational chat
# Use minimal stop sequences to avoid cutting off detailed responses
stop_sequences = ["\n\n\n", "\n---", "END OF RESPONSE"]
response = self.pipeline.call_llm(
messages,
thinking=False,
temperature=0.7,
max_tokens=1200, # Increased to allow more detailed responses
raw_response=True,
stop_sequences=stop_sequences,
)
# Response should be a string now
result = (
response.strip() if isinstance(response, str) else str(response).strip()
)
# Emit result
self.signals.result.emit(result)
self.signals.finished.emit()
except Exception as e:
error_msg = str(e).lower()
if "json" in error_msg and "parse" in error_msg:
error = "Error: The AI response format was invalid. Please try again."
elif "timeout" in error_msg:
error = "Error: The request timed out. Please try again."
else:
error = f"Error generating response: {str(e)[:100]}"
self.signals.error.emit((type(e), Exception(error), traceback.format_exc()))
def _build_prompt(self, search_context: Optional[str] = None):
"""Build the prompt for the persona - detailed, direct answers with full context"""
persona = self.persona
predicted_outcome = self.predicted_outcome
current_question = self.current_question
# Build complete conversation history context
conversation_context = ""
if self.chat_history:
conversation_context = "COMPLETE CONVERSATION HISTORY:\n"
for i, msg in enumerate(self.chat_history, 1):
conversation_context += f"{i}. {msg['role']}: {msg['text']}\n"
conversation_context += "\n"
prompt = f"""You are {persona.get("name", "")}, a {persona.get("role_title", "")} at {persona.get("organization", "")}.
YOUR EXPERTISE:
- Approach: {persona.get("approach", "")}
- Background: {persona.get("background", "")}
- Your assessment from the analysis: {persona.get("initial_position", "")}
ORIGINAL QUESTION BEING ANALYZED:
{current_question if current_question else "Unknown"}
FINAL CONCLUSION FROM ANALYSIS:
{predicted_outcome}
{conversation_context}
CURRENT MESSAGE FROM USER:
{self.user_message}
CRITICAL RESPONSE REQUIREMENTS:
1. **ANSWER THE EXACT QUESTION ASKED** - Don't deflect, don't change the subject, don't talk around it. If they ask about X, answer about X. Give them what they're asking for.
2. **BE EXTREMELY DETAILED** - Don't give short, vague answers. Provide thorough, comprehensive explanations with specific examples, reasoning, and insights. Minimum 300-500 words.
3. **NO AVOIDANCE** - If the user asks for clarification on a specific point, give it. Don't pivot to a different topic. Don't say "that's complex" without actually explaining the complexity.
4. **INCORPORATE CONVERSATION HISTORY** - Reference what the user has already told you. Build on their insights. Show you're listening to the full conversation, not just the last message.
5. **BE SPECIFIC** - Use concrete examples, specific mechanisms, detailed reasoning. Don't be vague or academic.
6. **NO REPETITION** - Don't repeat the same points from earlier in the conversation. Add new insights, build on what's been discussed.
7. **BE DIRECT** - No hedging, no "it depends" without explanation, no vague generalizations. Give a substantive answer.
8. **VALIDATE USER INSIGHTS** - If the user makes an astute observation, acknowledge it and explain why it's clinically significant.
"""
# Add search context if available
if search_context:
prompt += f"""
CURRENT INFORMATION (from web search):
{search_context}
INSTRUCTIONS: Use this current information to provide accurate, up-to-date responses. Integrate this information naturally into your response without mentioning that you searched for it. Just provide the information seamlessly.
"""
prompt += f"""
Respond as {persona.get("name", "")} would - give a DIRECT, COMPREHENSIVE, detailed answer that actually addresses what the user is asking. No deflection, no vagueness, no evasion. Answer the question fully with your full expertise."""
return prompt
def _analyze_for_search_needed(self, user_message: str) -> tuple:
"""
Hybrid approach: heuristic first, then LLM if needed.
Returns (needs_search: bool, queries: list)
"""
# Step 1: Heuristic detection (fast)
current_indicators = [
"recently",
"currently",
"now",
"latest",
"new",
"just",
"what's happening",
"what happened",
"update",
"trends",
"2024",
"2025",
"2026",
"this year",
"recent developments",
"look up",
"search for",
"check current",
"what's the latest",
]
message_lower = user_message.lower()
has_clear_indicator = any(ind in message_lower for ind in current_indicators)
# If clear indicator, proceed to search
if has_clear_indicator:
queries = self._extract_search_topics(user_message)
return True, queries
# Step 2: For unclear cases, use LLM to decide
# Check for ambiguous cases that might need search
ambiguous_patterns = [
"is it true",
"verify",
"confirm",
"facts about",
"statistics",
]
has_ambiguous = any(pat in message_lower for pat in ambiguous_patterns)
if has_ambiguous:
# Use LLM for final decision
try:
analysis_prompt = f"""Analyze if web search would help answer this: "{user_message[:150]}"
Respond with JSON: {{"needs_search": true/false, "queries": ["query1", "query2"]}}"""
response = self.pipeline.call_llm(
[{"role": "user", "content": analysis_prompt}],
max_tokens=100,
temperature=0.3,
raw_response=True,
)
import json
analysis = json.loads(response)
if analysis.get("needs_search"):
return True, analysis.get("queries", [])[:3]
except:
pass
return False, []
def _extract_search_topics(self, message: str) -> list:
"""Extract key topics from message for search queries"""
# Simple keyword extraction
stop_words = {
"what",
"is",
"the",
"a",
"an",
"in",
"on",
"at",
"to",
"for",
"about",
"with",
}
words = message.lower().replace("?", "").replace(".", "").split()
keywords = [w for w in words if w not in stop_words and len(w) > 3]
# Create 2-3 search queries
queries = []
if len(keywords) >= 2:
queries.append(" ".join(keywords[:3]))
if len(keywords) > 3:
queries.append(" ".join(keywords[1:5]))
elif keywords:
queries.append(
keywords[0] + " " + keywords[1] if len(keywords) > 1 else keywords[0]
)
return queries[:3]
def _perform_web_search(self, queries: list) -> str:
"""Execute web searches and format results"""
from search import search_searxng
all_results = []
# Search each query
for query in queries[:5]: # Max 5 queries
results = search_searxng(query, num_results=5)
all_results.extend(results[:2]) # Take top 2 from each query
if not all_results:
return "No search results found."
# Format results (max 7 total)
formatted = "CURRENT INFORMATION FROM WEB SEARCH:\n\n"
for i, result in enumerate(all_results[:7], 1):
title = result.get("title", "No title")
snippet = result.get("snippet", "No content")
formatted += f"{i}. {title}\n {snippet[:250]}...\n\n"
return formatted
def _build_prompt_with_search(self, search_context: str) -> str:
"""Build prompt with search context included - deprecated, use _build_prompt instead"""
return self._build_prompt(search_context)
class SimulationWorker(QRunnable):
"""Worker for running the complete simulation"""
def __init__(
self,
situation,
pipeline,
settings,
search_reachable,
debate_mode="simultaneous",
num_rounds=5,
):
super().__init__()
self.signals = WorkerSignals()
self.situation = situation
self.pipeline = pipeline
self.settings = settings
self.search_reachable = search_reachable
self.debate_mode = debate_mode
self.num_rounds = num_rounds
def _format_search_results(self, results: list) -> str:
"""Format search results into a readable context string."""
if not results:
return "No search results found."
formatted = "SEARCH RESULTS:\n\n"
for i, result in enumerate(results, 1):
title = result.get("title", "No title")
snippet = result.get("snippet", "No content")
formatted += f"{i}. {title}\n {snippet[:300]}...\n\n"
return formatted
@pyqtSlot()
def run(self):
"""Run simulation in background thread"""
try:
self.signals.progress.emit("Starting simulation...")
# The situation is already a dict with "question" key
original_input = self.situation.get("question", "")
self.signals.log_message.emit(f"Input: {original_input[:100]}...")
# Check web search availability
search_available = self.search_reachable
search_context = None
if search_available:
try:
self.signals.progress.emit("Checking web search availability...")
search_available = check_searxng_reachable()
if search_available:
self.signals.log_message.emit("Web search is available")
else:
self.signals.log_message.emit("Web search unavailable")
except Exception as e:
self.signals.log_message.emit(
f"Web search check failed: {str(e)[:100]}"
)
search_available = False
# Initialize round_history
round_history = []
# Stage 1: Extract situation with web search context if available
self.signals.progress.emit("Stage 1: Situation Extraction")
if search_available:
self.signals.progress.emit("Searching for current information...")
try:
# Generate search queries from the input
search_queries = [
original_input[:100],
f"current status {original_input[:80]}",
f"latest news {original_input[:70]}",
]
all_results = []
for query in search_queries:
results = search_searxng(query, num_results=5)
all_results.extend(results)
# Format search results
search_context = self._format_search_results(all_results)
self.signals.log_message.emit(
f"Web search found {len(all_results)} relevant results"
)
except Exception as e:
self.signals.log_message.emit(f"Web search failed: {str(e)[:100]}")
search_context = None
situation = self.pipeline.stage1_situation_extraction(original_input)
self.signals.log_message.emit(
f"Situation: {situation.get('title', 'Unknown')}"
)
# Stage 2: Generate personas with web search context if available
self.signals.progress.emit("Stage 2: Persona Generation")
personas = self.pipeline.stage2_persona_generation(
situation, original_input, search_context=search_context
)
for persona in personas:
self.signals.persona_added.emit(persona)
self.signals.progress.emit(
f"Generated: {persona.get('name', 'Unknown')}"
)
self.signals.progress.emit(
f"Generated: {persona.get('name', 'Unknown')}"
)
# Stage 3: Run debate rounds based on mode
self.signals.progress.emit("Stage 3: Debate Rounds")
try:
round_history = []
initial_positions = None
if self.debate_mode == "sequential":
self.signals.progress.emit(
f"Sequential Debate Mode ({self.num_rounds} rounds)"
)
for round_num in range(1, self.num_rounds + 1):
self.signals.progress.emit(
f"Running Sequential Round {round_num}/{self.num_rounds}"
)
# Run sequential round
round_data, converged = self.pipeline.stage3_sequential_round(
personas=personas,
situation=situation,
round_history=round_history,
current_round=round_num,
total_rounds=self.num_rounds,
include_initial_positions=(round_num == 1),
initial_positions=initial_positions,
search_context=search_context,
)
# Compress round data for history
compressed_round = self.pipeline.stage4_round_compression(
round_data=round_data, round_num=round_num
)
round_history.append(compressed_round)
if converged:
self.signals.progress.emit(
f"Debate converged at round {round_num}"
)
break
else:
# Simultaneous mode - use a default of 3 rounds (typical for simultaneous)
num_simultaneous_rounds = 3
self.signals.progress.emit(
f"Simultaneous Debate Mode ({num_simultaneous_rounds} rounds)"
)
for round_num in range(1, num_simultaneous_rounds + 1):
self.signals.progress.emit(
f"Running Simultaneous Round {round_num}/{num_simultaneous_rounds}"
)
round_data = self.pipeline.stage3_simulation_round(
personas=personas,
situation=situation,
round_history=round_history,
current_round=round_num,
total_rounds=num_simultaneous_rounds,
include_initial_positions=(round_num == 1),
initial_positions=initial_positions,
search_context=search_context,
)
# Compress round data for history
compressed_round = self.pipeline.stage4_round_compression(
round_data=round_data, round_num=round_num
)
round_history.append(compressed_round)
# Generate report from compressed round history
self.signals.progress.emit("Stage 4: Report Generation")
report = self.pipeline.stage5_report_generation(
situation=situation,
personas=personas,
round_history=round_history,
initial_positions=initial_positions,
original_input=original_input,
)
executive_summary = report.get("executive_summary", "")
except Exception as e:
error_msg = f"Stage 3/4 failed: {str(e)}"
log_pipeline_error(
"Stage3_4",
e,
{
"mode": self.debate_mode,
"num_rounds": self.num_rounds
if self.debate_mode == "sequential"
else 5,
"num_personas": len(personas),
"round_history_sample": str(round_history[:2])
if round_history
else "empty",
},
)
self.signals.error.emit(
(type(e), Exception(error_msg), traceback.format_exc())
)
return
self.signals.result.emit(
{
"situation": situation,
"personas": personas,
"round_history": round_history,
"report": report,
"executive_summary": executive_summary,
}
)
self.signals.finished.emit()
except Exception as e:
log_pipeline_error("Worker", e, {"situation": self.situation})
self.signals.error.emit((type(e), e, traceback.format_exc()))
class DeliberateAI(QMainWindow):
"""Main application window for Deliberate AI"""
def __init__(self):
super().__init__()
# Window setup
self.setWindowTitle("Deliberate AI: Multi-Perspective Decision Analysis")
self.setGeometry(100, 100, 1400, 900)
# Initialize state
self.settings = self.load_settings()
self.current_mode = "question"
self.context_data = None
self.selected_scenario = None
# Initialize pipeline with settings
self.pipeline = Pipeline(
endpoint_url=self.settings.get(
"vllm_endpoint_url", "http://localhost:8000/v1"
),
model_name=self.settings.get("model_name", "default"),
api_key=self.settings.get("api_key", "empty"),
)
self.is_running = False
self.search_reachable = True # Assume web search is reachable
self.search_enabled = self.settings.get(
"search_enabled", False
) # Default from settings
self.debate_mode = "simultaneous" # sequential or simultaneous
self.num_rounds = 5 # Number of rounds for sequential mode
self.chat_history = {}
self.current_persona = None
self.current_session_name = None
self.current_question = None
self.current_report = None
self.current_personas = []
self.current_executive_summary = ""
self.is_generating_response = False
# TTS state
self.current_tts_playback = None
self.is_playing_tts = False
self.tts_audio_buffer = None
self.tts_sample_rate = None
# Window resize tracking
self._original_geometry = None
self._is_expanded = False
# Thread pool for background tasks
self.threadpool = QThreadPool()
thread_count = self.threadpool.maxThreadCount()
print(f"Multithreading with maximum {thread_count} threads")
# Setup UI
self.init_ui()
# Setup status bar timer
self.status_timer = QTimer()
self.status_timer.setInterval(1000)
self.status_timer.timeout.connect(self.update_status_bar)
self.status_timer.start()
def closeEvent(self, event):
"""Handle application close - clean up TTS audio files"""
try:
# Stop any currently playing TTS
tts_client = get_tts_client()
if tts_client and tts_client.is_playing:
tts_client.stop()
# Clean up old TTS audio files (older than 24 hours)
TTSClient.cleanup_tts_folder()
print("[UI] TTS audio folder cleaned up", file=sys.stderr)
except Exception as e:
print(f"[UI] Error during cleanup: {e}", file=sys.stderr)
# Accept the close event
event.accept()
def init_ui(self):
"""Initialize the main UI layout"""
# Central widget
central_widget = QWidget()
self.setCentralWidget(central_widget)
# Main layout with splitter for resizable panels
main_layout = QHBoxLayout(central_widget)
# Create splitter for resizable panels
splitter = QSplitter(Qt.Orientation.Horizontal)
# Left Sidebar
left_panel = self.create_left_panel()
splitter.addWidget(left_panel)
# Center Panel
center_panel = self.create_center_panel()
splitter.addWidget(center_panel)
# Right Panel with tabs
right_panel = self.create_right_panel()
splitter.addWidget(right_panel)
# Set initial sizes
splitter.setSizes([300, 600, 500])
main_layout.addWidget(splitter)
# Setup status bar
self.status_bar = QStatusBar()
self.setStatusBar(self.status_bar)
self.status_bar.showMessage("Ready")
def create_left_panel(self):
"""Create the left sidebar panel"""
panel = QFrame()
panel.setFixedWidth(320)
panel.setStyleSheet("""
QFrame {
background-color: #2a2a2a;
border-right: 1px solid #444;
}
""")
layout = QVBoxLayout(panel)
layout.setSpacing(12)
layout.setContentsMargins(15, 15, 15, 15)
# Title
title = QLabel("Deliberate AI")
title.setFont(QFont("Arial", 18, QFont.Weight.Bold))
title.setStyleSheet("color: #3B8ED0; padding: 10px;")
layout.addWidget(title)
# Input mode selector (simplified to just Question mode)
mode_group = QGroupBox("Input Mode")
mode_layout = QVBoxLayout(mode_group)
mode_layout.setSpacing(5)
self.mode_combo = QComboBox()
self.mode_combo.addItems(["Question"]) # Only question mode
self.mode_combo.setEnabled(False) # Disabled since only one option
mode_layout.addWidget(self.mode_combo)
layout.addWidget(mode_group)
# Debate mode selector
debate_group = QGroupBox("Debate Mode")
debate_scroll = QScrollArea()
debate_scroll.setWidgetResizable(True)
debate_scroll.setFrameShape(QScrollArea.Shape.NoFrame)
debate_scroll.setMaximumHeight(130)
debate_scroll.setStyleSheet("""
QScrollArea {
background-color: transparent;
border: none;
}
""")
debate_widget = QWidget()
debate_layout = QVBoxLayout(debate_widget)
debate_layout.setSpacing(6)
debate_layout.setContentsMargins(0, 0, 0, 0)
self.debate_mode_combo = QComboBox()
self.debate_mode_combo.addItems(["Simultaneous", "Sequential (3-10 rounds)"])
self.debate_mode_combo.setMinimumHeight(28)
self.debate_mode_combo.currentTextChanged.connect(self.on_debate_mode_change)
debate_layout.addWidget(self.debate_mode_combo)
# Rounds slider (only relevant for sequential mode)
self.rounds_label = QLabel("5 rounds")
self.rounds_label.setStyleSheet("color: #888888; font-size: 10px;")
self.rounds_label.setAlignment(Qt.AlignmentFlag.AlignLeft)
self.rounds_slider = QSlider(Qt.Orientation.Horizontal)
self.rounds_slider.setMinimum(3)
self.rounds_slider.setMaximum(10)
self.rounds_slider.setValue(5)
self.rounds_slider.setTickPosition(QSlider.TickPosition.TicksBelow)
self.rounds_slider.setTickInterval(1)
self.rounds_slider.setStyleSheet("""
QSlider::groove:horizontal {
border: 1px solid #444;
height: 8px;
background: #2a2a2a;
border-radius: 4px;
}
QSlider::handle:horizontal {
background: #3B8ED0;
border: 1px solid #1E6FA9;
width: 16px;
height: 16px;
margin: -4px 0;
border-radius: 8px;
}
QSlider::handle:horizontal:hover {
background: #1E6FA9;
}
""")
self.rounds_slider.valueChanged.connect(self.update_rounds_label)
debate_layout.addWidget(self.rounds_label)
debate_layout.addWidget(self.rounds_slider)
debate_layout.addStretch()
debate_scroll.setWidget(debate_widget)
layout.addWidget(debate_scroll)
# Web search option
search_group = QGroupBox("Web Search / Fact-Check")
search_layout = QVBoxLayout(search_group)
search_layout.setSpacing(5)
self.search_checkbox = QCheckBox("Enable web search between debate rounds")
self.search_checkbox.setChecked(False)
self.search_checkbox.stateChanged.connect(self.on_search_toggle)
search_layout.addWidget(self.search_checkbox)
search_info = QLabel(
"When enabled, the system will search for facts and validate claims between debate rounds"
)
search_info.setWordWrap(True)
search_info.setStyleSheet("color: #888888; font-size: 10px;")
search_info.setContentsMargins(10, 0, 0, 0)
search_layout.addWidget(search_info)
layout.addWidget(search_group)
# Input text area
input_group = QGroupBox("Scenario")
input_layout = QVBoxLayout(input_group)
input_layout.setContentsMargins(0, 0, 0, 0)
input_layout.setSpacing(0)
# Create a scroll area wrapper
scroll_wrapper = QScrollArea()
scroll_wrapper.setWidgetResizable(True)
scroll_wrapper.setFrameShape(QScrollArea.Shape.NoFrame)
scroll_wrapper.setHorizontalScrollBarPolicy(
Qt.ScrollBarPolicy.ScrollBarAlwaysOff
)
scroll_wrapper.setStyleSheet("""
QScrollArea {
background-color: transparent;
border: none;
}
""")
# Container widget for the text edit
text_container = QWidget()
text_layout = QVBoxLayout(text_container)
text_layout.setContentsMargins(0, 0, 0, 0)
text_layout.setSpacing(0)
self.input_text = QTextEdit()
self.input_text.setPlaceholderText(
"Enter your decision question or scenario here...\n\nExample: 'Should I invest in this new AI startup given the current market conditions?'"
)
self.input_text.setMinimumHeight(180)
self.input_text.setMaximumHeight(250)
self.input_text.setAcceptRichText(False)
self.input_text.setLineWrapMode(QTextEdit.LineWrapMode.WidgetWidth)
self.input_text.setStyleSheet("""
QTextEdit {
background-color: #1a1a1a;
color: #e0e0e0;
border: 1px solid #444;
border-radius: 4px;
padding: 10px;
padding-bottom: 20px;
}
""")
text_layout.addWidget(self.input_text)
scroll_wrapper.setWidget(text_container)
input_layout.addWidget(scroll_wrapper)
layout.addWidget(input_group)
# Buttons
self.run_btn = QPushButton("Run Simulation")
self.run_btn.setMinimumHeight(40)
self.run_btn.setStyleSheet("""
QPushButton {
background-color: #3B8ED0;
color: white;
font-weight: bold;
font-size: 14px;
border-radius: 4px;
padding: 10px;
}
QPushButton:hover {
background-color: #1E6FA9;
}
QPushButton:disabled {
background-color: #555555;
}
""")
self.run_btn.clicked.connect(self.run_simulation)
layout.addWidget(self.run_btn)
self.new_sim_btn = QPushButton("New Simulation")
self.new_sim_btn.setMinimumHeight(35)
self.new_sim_btn.setStyleSheet("""
QPushButton {
background-color: #555555;
color: white;
border-radius: 4px;
padding: 8px;
}
QPushButton:hover {
background-color: #666666;
}
""")
self.new_sim_btn.clicked.connect(self.new_simulation)
layout.addWidget(self.new_sim_btn)
self.settings_btn = QPushButton("Settings")
self.settings_btn.setMinimumHeight(35)
self.settings_btn.setStyleSheet("""
QPushButton {
background-color: #555555;
color: white;
border-radius: 4px;
padding: 8px;
}
QPushButton:hover {
background-color: #666666;
}
""")
self.settings_btn.clicked.connect(self.open_settings)
layout.addWidget(self.settings_btn)
layout.addStretch()
return panel
def create_center_panel(self):
"""Create the center panel for input and progress"""
panel = QFrame()
panel.setStyleSheet("""
QFrame {
background-color: #1a1a1a;
}
""")
layout = QVBoxLayout(panel)
layout.setSpacing(10)
layout.setContentsMargins(10, 10, 10, 10)
# Progress log
progress_group = QGroupBox("Simulation Progress")
progress_layout = QVBoxLayout(progress_group)
self.progress_log = QTextEdit()
self.progress_log.setReadOnly(True)
self.progress_log.setMinimumHeight(400)
self.progress_log.setStyleSheet("""
QTextEdit {
background-color: #0a0a0a;
color: #00ff00;
font-family: 'Consolas', 'Monospace';
font-size: 11px;
border: 1px solid #444;
border-radius: 4px;
padding: 8px;
}