-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcouncil.py
More file actions
4838 lines (4438 loc) · 208 KB
/
council.py
File metadata and controls
4838 lines (4438 loc) · 208 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
# council_gui_qt.py
# GUI: PySide6 (Qt widgets)
# Deps: PySide6, aiohttp
# Optional: qdarktheme (auto dark/light), lmstudio (local-only "loaded models" detection)
import asyncio
import aiohttp
import sqlite3
import datetime
import json
import logging
import threading
import re
import random
import uuid
import traceback
from enum import Enum
from pathlib import Path
from typing import Optional, Dict, List, Callable, Awaitable, Any, Iterable, Tuple
from PySide6 import QtCore, QtGui, QtWidgets
from constants import (
ACTIONS,
FONT_BASE,
FONT_LG,
FONT_SM,
FONT_XL,
HEADING_FONT_FAMILY,
INTERNAL_GAP,
MIN_H,
MIN_SIDEBAR,
MIN_W,
PADDING_LG,
PADDING_MD,
PADDING_SM,
SECTION_GAP,
STRINGS,
THEME,
dp,
make_font,
refresh_dpi_scale,
)
from ui.factories import make_text_browser
# Import new core modules
try:
from core.tool_manager import FileParser, ModelCapabilityDetector
from core.api_client import ModelFetchError, call_model, fetch_models
from core.discussion_manager import DiscussionManager
from core import leaderboard as leaderboard_store
from core import result_presenter
from core.personas import (
DEFAULT_PERSONAS_PATH,
USER_PERSONAS_PATH,
add_user_persona,
assignment_count,
build_persona_config,
cleanup_persona_assignments,
clear_persona_assignment,
merge_persona_library,
persona_by_name,
persona_names,
persona_prompt,
rename_persona_assignments,
sort_personas_inplace,
update_user_persona,
delete_user_persona,
)
from core.provider_config import (
API_SERVICE_CUSTOM,
API_SERVICE_GEMINI,
API_SERVICE_LABELS,
API_SERVICE_OPENAI,
API_SERVICE_OPENROUTER,
PROVIDER_LABELS,
PROVIDER_LM_STUDIO,
PROVIDER_OLLAMA,
PROVIDER_OPENAI_COMPAT,
ProviderConfig,
api_service_label,
canonicalize_base_url,
make_provider_config,
normalize_api_service,
normalize_provider_type,
provider_defaults,
provider_label,
service_preset,
)
from core.settings_store import load_settings, save_settings
from core.app_state import app_config_dir, app_data_dir, app_log_dir, legacy_root_dir, migrate_legacy_state
from core.rendering import escape_text, markdown_to_safe_html
from core.session_history import load_session, save_session
except ImportError:
# Fallback if modules not found
FileParser = None
ModelCapabilityDetector = None
ModelFetchError = None
call_model = None
fetch_models = None
DiscussionManager = None
leaderboard_store = None
result_presenter = None
DEFAULT_PERSONAS_PATH = None
USER_PERSONAS_PATH = None
add_user_persona = None
assignment_count = None
build_persona_config = None
cleanup_persona_assignments = None
clear_persona_assignment = None
merge_persona_library = None
persona_by_name = None
persona_names = None
persona_prompt = None
rename_persona_assignments = None
sort_personas_inplace = None
update_user_persona = None
delete_user_persona = None
API_SERVICE_CUSTOM = "custom"
API_SERVICE_OPENAI = "openai"
API_SERVICE_OPENROUTER = "openrouter"
API_SERVICE_GEMINI = "gemini"
API_SERVICE_LABELS = {}
PROVIDER_LM_STUDIO = "lm_studio"
PROVIDER_OPENAI_COMPAT = "openai_compatible"
PROVIDER_OLLAMA = "ollama"
PROVIDER_LABELS = {}
ProviderConfig = None
api_service_label = None
canonicalize_base_url = None
make_provider_config = None
normalize_api_service = None
normalize_provider_type = None
provider_defaults = None
provider_label = None
service_preset = None
load_settings = None
save_settings = None
app_config_dir = None
app_data_dir = None
app_log_dir = None
legacy_root_dir = None
migrate_legacy_state = None
escape_text = None
markdown_to_safe_html = None
load_session = None
save_session = None
# Try optional theming (follows system)
try:
import qdarktheme # type: ignore
except Exception:
qdarktheme = None
try:
import qasync # type: ignore
except Exception:
qasync = None
# Import new UI package
try:
from ui.theme import ThemeEngine
from ui.animations import FadeIn, set_reduce_motion
from ui.components import (
CollapsibleGroupBox,
ModelCard,
StatefulRunButton,
ToastNotification,
EnhancedPromptEditor,
AnimatedStatusBar,
OnboardingOverlay,
KeyboardShortcutOverlay,
WorkflowStepCard,
)
_UI_AVAILABLE = True
except ImportError:
_UI_AVAILABLE = False
set_reduce_motion = None
try:
from gui import (
apply_persona_visibility,
build_model_badge_text,
build_persona_preview_html,
build_provider_profile_row,
build_workspace_panel,
clear_layout,
DebugTimelineWidget,
filter_model_rows,
make_unique_display_model_name,
populate_model_rows,
populate_persona_library_list,
)
except ImportError:
apply_persona_visibility = None
build_model_badge_text = None
build_persona_preview_html = None
build_provider_profile_row = None
build_workspace_panel = None
clear_layout = None
DebugTimelineWidget = None
filter_model_rows = None
make_unique_display_model_name = None
populate_model_rows = None
populate_persona_library_list = None
# -----------------------
# Debug logging switches
# -----------------------
DEBUG_VOTING = True # set False to silence
LOG_TRUNCATE: Optional[int] = None # e.g., 8000 to cap output, or None for full
LOG_SINK: Optional[Callable[[str, str], None]] = None
LOGGER = logging.getLogger(__name__)
def _dbg(label: str, text: Any):
if not DEBUG_VOTING:
return
try:
if isinstance(text, (dict, list)):
s = json.dumps(text, indent=2, ensure_ascii=False)
else:
s = "" if text is None else str(text)
except Exception:
s = str(text)
if LOG_TRUNCATE and len(s) > LOG_TRUNCATE:
s = s[:LOG_TRUNCATE] + f"\n...[truncated {len(s) - LOG_TRUNCATE} chars]"
if LOG_SINK:
try:
LOG_SINK(label, s)
except Exception:
pass
LOGGER.debug("===== %s =====\n%s", label, s)
def set_log_sink(callback: Optional[Callable[[str, str], None]]):
global LOG_SINK
LOG_SINK = callback
class RightPanelState(str, Enum):
PRE_RUN = "pre_run"
IN_RUN = "in_run"
POST_RUN = "post_run"
class RunState(str, Enum):
LOCKED = "locked"
READY = "ready"
RUNNING = "running"
STOPPING = "stopping"
def create_app_icon(size: int = 256) -> QtGui.QIcon:
size = max(64, int(size))
pixmap = QtGui.QPixmap(size, size)
pixmap.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(pixmap)
painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
bg_color = QtGui.QColor(THEME["accent"])
radius = size * 0.2
bg_path = QtGui.QPainterPath()
bg_path.addRoundedRect(QtCore.QRectF(0, 0, size, size), radius, radius)
painter.fillPath(bg_path, bg_color)
stripe_color = QtGui.QColor(255, 255, 255, 220)
stripe_width = size * 0.08
stripe_length = size * 0.38
stripe_start_x = size * 0.14
stripe_start_y = size * 0.34
stripe_gap = stripe_width * 0.8
painter.setBrush(stripe_color)
painter.setPen(QtCore.Qt.NoPen)
for i in range(3):
rect = QtCore.QRectF(
stripe_start_x,
stripe_start_y + i * (stripe_width + stripe_gap),
stripe_length,
stripe_width,
)
painter.drawRoundedRect(rect, stripe_width * 0.5, stripe_width * 0.5)
bubble_rect = QtCore.QRectF(size * 0.36, size * 0.26, size * 0.48, size * 0.46)
bubble_path = QtGui.QPainterPath()
bubble_path.addRoundedRect(bubble_rect, size * 0.12, size * 0.12)
tail = QtGui.QPolygonF(
[
QtCore.QPointF(bubble_rect.left() + bubble_rect.width() * 0.18, bubble_rect.bottom()),
QtCore.QPointF(bubble_rect.left() + bubble_rect.width() * 0.36, bubble_rect.bottom()),
QtCore.QPointF(bubble_rect.left() + bubble_rect.width() * 0.26, bubble_rect.bottom() + size * 0.12),
]
)
bubble_path.addPolygon(tail)
painter.fillPath(bubble_path, QtGui.QColor(THEME["accent_fg"]))
check_pen = QtGui.QPen(bg_color, size * 0.085, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)
painter.setPen(check_pen)
check_points = QtGui.QPolygonF(
[
QtCore.QPointF(bubble_rect.left() + bubble_rect.width() * 0.18, bubble_rect.center().y()),
QtCore.QPointF(bubble_rect.left() + bubble_rect.width() * 0.38, bubble_rect.bottom() - bubble_rect.height() * 0.18),
QtCore.QPointF(bubble_rect.right() - bubble_rect.width() * 0.18, bubble_rect.top() + bubble_rect.height() * 0.24),
]
)
painter.drawPolyline(check_points)
painter.end()
return QtGui.QIcon(pixmap)
def human_file_size(num_bytes: int) -> str:
size = float(max(0, int(num_bytes)))
for unit in ("B", "KB", "MB", "GB"):
if size < 1024.0 or unit == "GB":
if unit == "B":
return f"{int(size)} {unit}"
return f"{size:.1f} {unit}"
size /= 1024.0
return f"{int(size)} B"
class PromptEditor(QtWidgets.QPlainTextEdit):
submitRequested = QtCore.Signal()
def __init__(self, parent: Optional[QtWidgets.QWidget] = None):
super().__init__(parent)
self._min_editor_height = 74
self._max_editor_height = 180
self.setTabChangesFocus(True)
self.setPlaceholderText("Ask the council a question. Press Enter to send, Shift+Enter for a new line.")
self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
self.document().documentLayout().documentSizeChanged.connect(self._sync_height)
self._sync_height()
def _sync_height(self, *_args):
doc_height = self.document().size().height()
frame = self.frameWidth() * 2
padding = 14
target = int(doc_height + frame + padding)
target = max(self._min_editor_height, min(target, self._max_editor_height))
self.setFixedHeight(target)
def keyPressEvent(self, event: QtGui.QKeyEvent):
if event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
if not (event.modifiers() & QtCore.Qt.ShiftModifier):
self.submitRequested.emit()
event.accept()
return
super().keyPressEvent(event)
QtCore.QTimer.singleShot(0, self._sync_height)
def clear(self):
super().clear()
self._sync_height()
class AttachmentListWidget(QtWidgets.QListWidget):
filesDropped = QtCore.Signal(list)
def __init__(self, parent: Optional[QtWidgets.QWidget] = None):
super().__init__(parent)
self.empty_text = "Drop documents or images here, or use Upload Files."
self.setAcceptDrops(True)
self.setAlternatingRowColors(True)
self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
def dragEnterEvent(self, event: QtGui.QDragEnterEvent):
if self._extract_local_paths(event.mimeData()):
event.acceptProposedAction()
return
super().dragEnterEvent(event)
def dragMoveEvent(self, event: QtGui.QDragMoveEvent):
if self._extract_local_paths(event.mimeData()):
event.acceptProposedAction()
return
super().dragMoveEvent(event)
def dropEvent(self, event: QtGui.QDropEvent):
paths = self._extract_local_paths(event.mimeData())
if paths:
self.filesDropped.emit(paths)
event.acceptProposedAction()
return
super().dropEvent(event)
def paintEvent(self, event: QtGui.QPaintEvent):
super().paintEvent(event)
if self.count() or not self.empty_text:
return
painter = QtGui.QPainter(self.viewport())
color = self.palette().color(QtGui.QPalette.Mid)
painter.setPen(color)
painter.drawText(
self.viewport().rect().adjusted(18, 12, -18, -12),
QtCore.Qt.AlignCenter | QtCore.Qt.TextWordWrap,
self.empty_text,
)
painter.end()
@staticmethod
def _extract_local_paths(mime: Optional[QtCore.QMimeData]) -> List[str]:
if not mime or not mime.hasUrls():
return []
paths = []
for url in mime.urls():
if url.isLocalFile():
local_path = url.toLocalFile()
if local_path:
paths.append(local_path)
return paths
def short_id(mid: str, n: int = 28) -> str:
try:
if len(mid) <= n:
return mid
head = mid[: n // 2 - 1]
tail = mid[-(n // 2 - 1):]
return f"{head}…{tail}"
except Exception:
return str(mid)
# -----------------------
# Paths / persistence
# -----------------------
APP_DIR = Path(__file__).resolve().parent
LEGACY_ROOT = legacy_root_dir() if legacy_root_dir else APP_DIR
if migrate_legacy_state:
migrate_legacy_state()
DATA_DIR = app_data_dir() if app_data_dir else APP_DIR
LOG_DIR = app_log_dir() if app_log_dir else APP_DIR
DB_PATH = DATA_DIR / "council_stats.db"
def log_unhandled_exception(exc_type, exc_value, exc_tb):
try:
ts = datetime.datetime.now().isoformat(timespec="seconds")
tb_text = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
log_path = LOG_DIR / "polycouncil_crash.log"
log_path.parent.mkdir(parents=True, exist_ok=True)
log_path.write_text(f"[{ts}] Unhandled exception\n{tb_text}\n", encoding="utf-8")
except Exception:
pass
# -----------------------
# Database (leaderboard)
# -----------------------
def ensure_db():
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS votes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT,
question TEXT,
winner TEXT,
details TEXT
)
""")
conn.commit()
conn.close()
def record_vote(question: str, winner: str, details: dict):
try:
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.execute(
"INSERT INTO votes (timestamp, question, winner, details) VALUES (?, ?, ?, ?)",
(datetime.datetime.now().isoformat(timespec="seconds"), question, winner, json.dumps(details))
)
conn.commit()
conn.close()
except Exception as e:
_dbg("record_vote error", str(e))
def load_leaderboard() -> List[tuple[str, int]]:
try:
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
rows = list(cur.execute("SELECT winner, COUNT(*) FROM votes GROUP BY winner ORDER BY COUNT(*) DESC"))
conn.close()
return [(r[0], int(r[1])) for r in rows]
except Exception:
return []
# -----------------------
# Concurrency helper
# -----------------------
async def run_limited(max_concurrency: int, callables: Iterable[Callable[[], Awaitable[Any]]]):
sem = asyncio.Semaphore(max(1, int(max_concurrency)))
tasks = []
async def runner(fn):
async with sem:
return await fn()
for fn in callables:
tasks.append(asyncio.create_task(runner(fn)))
return await asyncio.gather(*tasks)
# -----------------------
# Voting schema & parsing
# -----------------------
DEFAULT_RUBRIC_WEIGHTS = {"correctness": 5, "relevance": 3, "specificity": 3, "safety": 2, "conciseness": 1}
RUBRIC_PRESETS = {
"Balanced": dict(DEFAULT_RUBRIC_WEIGHTS),
"Accuracy First": {"correctness": 6, "relevance": 3, "specificity": 3, "safety": 2, "conciseness": 1},
"Safety First": {"correctness": 4, "relevance": 2, "specificity": 2, "safety": 5, "conciseness": 1},
"Concise": {"correctness": 4, "relevance": 3, "specificity": 2, "safety": 2, "conciseness": 3},
}
VOTE_INSTRUCTIONS = """\
You are voting on the BEST answer to the user's question from several model candidates.
Score EACH candidate (not including yourself) using integer scales:
- correctness(0-5), relevance(0-3), specificity(0-3), safety(0-2), conciseness(0-1).
Return ONLY JSON with this schema:
{
"scores": {
"1": {"correctness": int, "relevance": int, "specificity": int, "safety": int, "conciseness": int},
"2": {...},
"...": {...}
},
"final_pick": int, // the index of your overall winner
"reasoning": string // brief rationale
}
No extra keys, no prose. Use only integers in the specified ranges.
"""
def ballot_json_schema(num_candidates: int) -> dict:
# Build a strict schema for the response_format
properties_scores = {}
for i in range(1, num_candidates + 1):
properties_scores[str(i)] = {
"type": "object",
"properties": {
"correctness": {"type": "integer", "minimum": 0, "maximum": 5},
"relevance": {"type": "integer", "minimum": 0, "maximum": 3},
"specificity": {"type": "integer", "minimum": 0, "maximum": 3},
"safety": {"type": "integer", "minimum": 0, "maximum": 2},
"conciseness": {"type": "integer", "minimum": 0, "maximum": 1},
},
"required": ["correctness", "relevance", "specificity", "safety", "conciseness"],
"additionalProperties": False
}
schema = {
"name": "vote_ballot",
"schema": {
"type": "object",
"properties": {
"scores": {
"type": "object",
"properties": properties_scores,
"required": list(properties_scores.keys()),
"additionalProperties": False
},
"final_pick": {"type": "integer", "minimum": 1, "maximum": num_candidates},
"reasoning": {"type": "string"}
},
"required": ["scores", "final_pick"],
"additionalProperties": False
}
}
return schema
def safe_load_vote_json(text: str) -> Optional[dict]:
"""
Try to parse the first JSON object present.
"""
try:
obj = json.loads(text)
if isinstance(obj, dict):
return obj
except Exception:
pass
m = re.search(r'\{.*\}', text, re.DOTALL)
if m:
try:
return json.loads(m.group(0))
except Exception:
return None
return None
def validate_ballot(idx_map_peer: Dict[int, str], ballot: dict) -> Tuple[bool, str]:
try:
scores = ballot.get("scores", {})
fp = ballot.get("final_pick", None)
if not isinstance(scores, dict) or not isinstance(fp, int):
return False, "scores/final_pick missing"
required = set(idx_map_peer.keys())
present = set(int(k) for k in scores.keys() if str(k).isdigit())
if required != present:
return False, f"indices mismatch required={sorted(required)} present={sorted(present)}"
for i, sc in scores.items():
for k, lo, hi in [
("correctness", 0, 5), ("relevance", 0, 3), ("specificity", 0, 3),
("safety", 0, 2), ("conciseness", 0, 1)
]:
v = sc.get(k, None)
if not isinstance(v, int) or v < lo or v > hi:
return False, f"bad {k} for {i}: {v}"
if fp not in required:
return False, f"final_pick {fp} not in {sorted(required)}"
return True, "ok"
except Exception as e:
return False, f"exception {e}"
def normalize_rubric_weights(weights: Optional[Dict[str, Any]]) -> Dict[str, int]:
normalized = dict(DEFAULT_RUBRIC_WEIGHTS)
if not isinstance(weights, dict):
return normalized
for key, default_value in DEFAULT_RUBRIC_WEIGHTS.items():
value = weights.get(key, default_value)
try:
normalized[key] = max(0, int(value))
except Exception:
normalized[key] = default_value
return normalized
# -----------------------
# Voting worker
# -----------------------
async def vote_one(
session: aiohttp.ClientSession,
voter_entry: Dict[str, Any],
question: str,
answers: Dict[str, str],
model_entries: List[Dict[str, Any]],
) -> Tuple[str, Optional[dict], str]:
"""
Ask a (voter) model to score peer answers and pick a winner.
Returns: (voter_id, parsed_ballot, status_message)
"""
voter_id = str(voter_entry["id"])
voter_raw_model = str(voter_entry["model"])
voter_provider = voter_entry["provider"]
peer_entries = [m for m in model_entries if str(m["id"]) != voter_id]
idx_map_peer = {i + 1: str(m["id"]) for i, m in enumerate(peer_entries)}
if not peer_entries:
return voter_id, None, "No peer candidates to score."
parts = [VOTE_INSTRUCTIONS, "", f"Question:\n{question}", "", "Candidates:"]
for i, m in idx_map_peer.items():
ans = answers.get(m, "")
parts.append(f"[{i}] {short_id(m)}:\n{ans}")
prompt = "\n\n".join(parts)
try:
schema = ballot_json_schema(num_candidates=len(idx_map_peer))
content = await call_model(
session, voter_provider, voter_raw_model, prompt,
debug_hook=_dbg,
sys_prompt="Be precise. Return only JSON according to the schema.",
json_schema=schema
)
_dbg(f"VOTE raw OUTPUT json_schema (voter={voter_id})", content)
parsed = safe_load_vote_json(content)
if parsed:
ok, msg = validate_ballot(idx_map_peer, parsed)
if ok:
normalized = {
"scores": {idx_map_peer[int(k)]: v for k, v in parsed["scores"].items()},
"final_pick": parsed.get("final_pick"),
"reasoning": parsed.get("reasoning", ""),
}
_dbg(f"VOTE ACCEPTED json_schema (voter={voter_id})", normalized)
return voter_id, normalized, f"Valid ballot via json_schema ({msg})"
except Exception as e:
_dbg(f"VOTE ERROR json_schema (voter={voter_id})", str(e))
try:
content = await call_model(
session, voter_provider, voter_raw_model, prompt,
debug_hook=_dbg,
sys_prompt="Return only JSON for the ballot. No extra text.",
json_schema=None
)
_dbg(f"VOTE raw OUTPUT text (voter={voter_id})", content)
parsed = safe_load_vote_json(content)
if parsed:
ok, msg = validate_ballot(idx_map_peer, parsed)
if ok:
normalized = {
"scores": {idx_map_peer[int(k)]: v for k, v in parsed["scores"].items()},
"final_pick": parsed.get("final_pick"),
"reasoning": parsed.get("reasoning", ""),
}
_dbg(f"VOTE ACCEPTED text (voter={voter_id})", normalized)
return voter_id, normalized, f"Valid ballot via text ({msg})"
else:
_dbg(f"VOTE REJECTED text (voter={voter_id})", msg)
except Exception as e:
_dbg(f"VOTE ERROR text (voter={voter_id})", str(e))
_dbg(f"VOTE FAILED ALL ATTEMPTS (voter={voter_id})", "No valid ballot produced")
return voter_id, None, f"Failed to obtain valid ballot from {short_id(voter_id)}"
# -----------------------
# Council orchestration
# -----------------------
async def council_round(
model_entries: List[Dict[str, Any]],
question: str,
roles: Dict[str, Optional[str]],
status_cb: Callable[[str], None],
max_concurrency: int = 1,
voter_override: Optional[List[str]] = None,
images: Optional[List[str]] = None,
web_search: bool = False,
temperature: Optional[float] = None,
rubric_weights: Optional[Dict[str, int]] = None,
timeout_seconds: int = 120,
is_cancelled: Optional[Callable[[], bool]] = None,
answer_stream_cb: Optional[Callable[[str, str, bool], None]] = None,
):
status_cb("Collecting answers…")
async with aiohttp.ClientSession() as session:
weights = normalize_rubric_weights(rubric_weights)
images = images or []
async def answer_one(entry: Dict[str, Any]) -> tuple[str, str, int]:
model_id = str(entry["id"])
raw_model = str(entry["model"])
provider = entry["provider"]
if is_cancelled and is_cancelled():
return model_id, "[Cancelled]", 0
user_prompt = question
sys_p = roles.get(model_id) or None
started_at = datetime.datetime.now()
try:
async def on_stream_chunk(chunk: str) -> None:
if answer_stream_cb:
answer_stream_cb(model_id, chunk, False)
ans = await call_model(
session, provider, raw_model, user_prompt,
debug_hook=_dbg,
temperature=temperature, sys_prompt=sys_p,
images=images, web_search=web_search,
timeout_sec=timeout_seconds,
stream=bool(answer_stream_cb),
stream_callback=on_stream_chunk if answer_stream_cb else None,
)
if isinstance(ans, dict):
ans = json.dumps(ans, ensure_ascii=False)
elapsed_ms = int((datetime.datetime.now() - started_at).total_seconds() * 1000)
if answer_stream_cb:
answer_stream_cb(model_id, "", True)
return model_id, ans, elapsed_ms
except Exception as e1:
elapsed_ms = int((datetime.datetime.now() - started_at).total_seconds() * 1000)
if answer_stream_cb:
answer_stream_cb(model_id, "", True)
return model_id, f"[ERROR fetching answer]\n{e1}", elapsed_ms
# Check cancellation before starting
if is_cancelled and is_cancelled():
raise RuntimeError("Process cancelled by user")
pairs = await run_limited(max_concurrency, [lambda m=m: answer_one(m) for m in model_entries])
# Check cancellation after answers
if is_cancelled and is_cancelled():
raise RuntimeError("Process cancelled by user")
answers = {m: a for m, a, _ in pairs}
timings_ms = {m: elapsed for m, _, elapsed in pairs}
errors = {m: a for m, a, _ in pairs if isinstance(a, str) and a.startswith("[ERROR")}
cancelled = {m: a for m, a, _ in pairs if isinstance(a, str) and a.startswith("[Cancelled]")}
if errors:
status_cb(f"⚠ {len(errors)}/{len(model_entries)} models failed to answer: {', '.join(short_id(m) for m in errors)}")
status_cb("Models are voting…")
model_entry_by_id = {str(m["id"]): m for m in model_entries}
successful_model_ids = [
model_id
for model_id, answer_text, _elapsed in pairs
if not (
isinstance(answer_text, str)
and (answer_text.startswith("[ERROR") or answer_text.startswith("[Cancelled]"))
)
]
candidate_model_ids = [model_id for model_id in successful_model_ids if model_id in model_entry_by_id]
candidate_answers = {model_id: answers[model_id] for model_id in candidate_model_ids}
candidate_entries = [model_entry_by_id[model_id] for model_id in candidate_model_ids]
if not candidate_model_ids:
status_cb("⚠ No successful model answers were returned, so no winner was selected.")
details = {
"question": question,
"answers": answers,
"valid_votes": {},
"invalid_votes": {},
"vote_messages": {},
"tally": {},
"errors": errors,
"cancelled": cancelled,
"timings_ms": timings_ms,
"rubric_weights": weights,
"winner": "",
"participation_rate": 0.0,
"voters_used": [],
"candidate_models": [],
}
return answers, "", details, {}
voters_to_use = (
[model_id for model_id in voter_override if model_id in candidate_model_ids]
if voter_override
else list(candidate_model_ids)
)
# Note: Voting phase does not use images or web search, typically.
valid_votes: Dict[str, dict] = {}
invalid_votes: Dict[str, str] = {}
vote_messages: Dict[str, str] = {}
if len(candidate_model_ids) > 1 and voters_to_use:
vote_results = await run_limited(
max_concurrency,
[
lambda m=m: vote_one(session, model_entry_by_id[m], question, candidate_answers, candidate_entries)
for m in voters_to_use if m in model_entry_by_id
]
)
for voter_id, ballot, msg in vote_results:
vote_messages[voter_id] = msg
if ballot is not None:
valid_votes[voter_id] = ballot
else:
invalid_votes[voter_id] = msg
else:
if len(candidate_model_ids) == 1:
status_cb(f"Only one model returned a usable answer: {short_id(candidate_model_ids[0])}")
elif not voters_to_use:
status_cb("⚠ No eligible voters produced a usable answer.")
if invalid_votes:
status_cb(f"⚠ {len(invalid_votes)}/{len(voters_to_use)} invalid ballots: {', '.join(short_id(m) for m in invalid_votes)}")
totals: Dict[str, int] = {mid: 0 for mid in candidate_model_ids}
for ballot in valid_votes.values():
for candidate_mid, score_dict in ballot["scores"].items():
weighted = sum(score_dict[k] * weights[k] for k in weights.keys())
totals[candidate_mid] = totals.get(candidate_mid, 0) + int(weighted)
if not valid_votes:
status_cb("⚠ No valid ballots were produced, selecting the first successful answer by default.")
winner = candidate_model_ids[0]
else:
max_score = max(totals.values())
contenders = [m for m, score in totals.items() if score == max_score]
if len(contenders) > 1:
# Use random selection instead of positional bias to ensure fairness
winner = random.choice(contenders)
status_cb(f"Tie between {len(contenders)} models, randomly selected: {short_id(winner)}")
else:
winner = contenders[0]
tally = totals
details = {
"question": question,
"answers": answers,
"valid_votes": valid_votes,
"invalid_votes": invalid_votes,
"vote_messages": vote_messages,
"tally": tally,
"errors": errors,
"cancelled": cancelled,
"timings_ms": timings_ms,
"rubric_weights": weights,
"winner": winner,
"participation_rate": len(valid_votes) / max(1, len(voters_to_use)),
"voters_used": voters_to_use,
"candidate_models": candidate_model_ids,
}
status_cb(f"Vote complete. Valid: {len(valid_votes)}/{len(voters_to_use)}")
return answers, winner, details, tally
# -----------------------
# Qt GUI
# -----------------------
class ModelFetchWorker(QtCore.QObject):
finished = QtCore.Signal(list)
failed = QtCore.Signal(str)
def __init__(self, provider: ProviderConfig, timeout_seconds: int = 20):
super().__init__()
self.provider = provider
self.timeout_seconds = max(15, int(timeout_seconds))
@QtCore.Slot()
def run(self):
try:
models = asyncio.run(
fetch_models(
self.provider,
provider_label=provider_label,
timeout_sec=self.timeout_seconds,
)
)
self.finished.emit(models)
except Exception as e:
self.failed.emit(str(e))
class CouncilWindow(QtWidgets.QMainWindow):
status_signal = QtCore.Signal(str)
result_signal = QtCore.Signal(object) # (question, answers, winner, details, tally)
error_signal = QtCore.Signal(str)
log_signal = QtCore.Signal(str)
discussion_update_signal = QtCore.Signal(object) # (entry_dict) for real-time updates
capability_update_signal = QtCore.Signal() # Signal to update capability UI
def __init__(self):
super().__init__()
self.setWindowTitle(STRINGS["app_title"])
self.resize(max(dp(1320), MIN_W), max(dp(900), MIN_H))
self.setMinimumSize(dp(MIN_W), dp(MIN_H))
self.app_icon = create_app_icon()
self.setWindowIcon(self.app_icon)
self.use_roles = False
self.debug_enabled = False
self.timeout_seconds = 120
self.reduce_motion = False
self.right_panel_state = RightPanelState.PRE_RUN
self.run_state = RunState.LOCKED
self._results_stale = False
self._stop_requested = False
self._model_thread: Optional[QtCore.QThread] = None
self._model_worker: Optional[ModelFetchWorker] = None
self.log_history_limit = 500
# Theme engine (replaces qdarktheme)
self._theme_engine: Optional[ThemeEngine] = None
if _UI_AVAILABLE:
app = QtWidgets.QApplication.instance()
if app:
self._theme_engine = ThemeEngine(app, self)
elif qdarktheme:
try:
qdarktheme.setup_theme()
except Exception:
pass
if leaderboard_store:
leaderboard_store.ensure_db()
else:
ensure_db()
self.models: List[str] = []
self.model_actual_ids: Dict[str, str] = {}
self.model_provider_map: Dict[str, ProviderConfig] = {}
self.model_checks: Dict[str, QtWidgets.QCheckBox] = {}
self.model_tabs: Dict[str, QtWidgets.QWidget] = {}
self.model_texts: Dict[str, QtWidgets.QWidget] = {}
self.model_persona_combos: Dict[str, QtWidgets.QPushButton] = {}
self.model_rows: Dict[str, QtWidgets.QWidget] = {}
self.provider_type = PROVIDER_LM_STUDIO
self.api_key = ""
self.model_path = ""
self.api_service = API_SERVICE_CUSTOM
self.last_submitted_question = ""
self.provider_profiles: List[Dict[str, str]] = []
self.provider_profile_rows: Dict[str, QtWidgets.QWidget] = {}
self.last_session_record: Optional[Dict[str, Any]] = None
self.model_meta_labels: Dict[str, QtWidgets.QLabel] = {}
# New features
self.mode = "deliberation" # "deliberation" or "discussion"
self.uploaded_files: List[Path] = []
self.model_capabilities: Dict[str, Dict[str, bool]] = {} # model -> {web_search: bool, visual: bool}
self.web_search_enabled = False
self._fetch_append = False
self._fetch_provider: Optional[ProviderConfig] = None
self._status_tone = "neutral"
self._winner_stream_timer: Optional[QtCore.QTimer] = None
self._build_ui()
self._apply_window_style()
self.chat_view.setHtml(
self._placeholder_html(
"Welcome",
"Choose a provider, load some models, and send a prompt to compare answers or run a collaborative discussion.",
)
)
self._setup_log_dock()
self._setup_settings_dock()