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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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
import gradio as gr
import requests
import json
import os
import asyncio
from datetime import datetime
from typing import Dict, List, Any, Optional, Tuple
from dotenv import load_dotenv
import time
import re
from collections import Counter
import threading
import queue
import uuid
from gradio_consilium_roundtable import consilium_roundtable
from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, VisitWebpageTool, Tool

# Load environment variables
load_dotenv()

# API Configuration - These will be updated by UI if needed
MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY") 
SAMBANOVA_API_KEY = os.getenv("SAMBANOVA_API_KEY")
MODERATOR_MODEL = os.getenv("MODERATOR_MODEL", "mistral")

# Session-based storage for isolated discussions
user_sessions: Dict[str, Dict] = {}

class WikipediaTool(Tool):
    name = "wikipedia_search"
    description = "Search Wikipedia for comprehensive information on any topic"
    inputs = {"query": {"type": "string", "description": "The topic to search for on Wikipedia"}}
    output_type = "string"
    
    def forward(self, query: str) -> str:
        try:
            import wikipedia
            # Search for the topic
            search_results = wikipedia.search(query, results=3)
            if not search_results:
                return f"No Wikipedia articles found for: {query}"
            
            # Get the first article
            page = wikipedia.page(search_results[0])
            summary = page.summary[:1000] + "..." if len(page.summary) > 1000 else page.summary
            
            return f"**Wikipedia: {page.title}**\n\n{summary}\n\nSource: {page.url}"
        except Exception as e:
            return f"Wikipedia search error: {str(e)}"

class WebSearchAgent:
    def __init__(self):
        try:
            # Use TinyLlama for faster inference
            self.agent = CodeAgent(
                tools=[
                    DuckDuckGoSearchTool(), 
                    VisitWebpageTool(),
                    WikipediaTool(),
                    FinalAnswerTool()
                ], 
                model=InferenceClientModel(),
                max_steps=3,
                verbosity_level=0
            )
        except Exception as e:
            print(f"Warning: Could not initialize search agent: {e}")
            self.agent = None
    
    def search(self, query: str, max_results: int = 5) -> str:
        """Use the CodeAgent to perform comprehensive web search and analysis"""
        if not self.agent:
            return f"๐Ÿ” **Web Search for:** {query}\n\nSearch agent not available. Please check dependencies."
        
        try:
            # Simplified prompt for TinyLlama
            agent_prompt = f"Search for information about: {query}"
            
            # Run the agent
            result = self.agent.run(agent_prompt)
            
            # Format the result nicely
            if result:
                return f"๐Ÿ” **Web Research Results for:** {query}\n\n{result}"
            else:
                return f"๐Ÿ” **Web Search for:** {query}\n\nNo results found."
            
        except Exception as e:
            # Fallback to simple error message
            return f"๐Ÿ” **Web Search Error for:** {query}\n\nError: {str(e)}\n\nPlease try again or rephrase your query."

def get_session_id(request: gr.Request = None) -> str:
    """Generate or retrieve session ID"""
    if request and hasattr(request, 'session_hash'):
        return request.session_hash
    return str(uuid.uuid4())

def get_or_create_session_state(session_id: str) -> Dict:
    """Get or create isolated session state"""
    if session_id not in user_sessions:
        user_sessions[session_id] = {
            "roundtable_state": {
                "participants": [],
                "messages": [],
                "currentSpeaker": None,
                "thinking": [],
                "showBubbles": []
            },
            "discussion_log": [],
            "final_answer": "",
            "step_by_step_active": False,
            "step_continue_event": threading.Event(),
            "api_keys": {
                "mistral": None,
                "sambanova": None
            }
        }
    return user_sessions[session_id]

def update_session_api_keys(mistral_key, sambanova_key, session_id_state, request: gr.Request = None):
    """Update API keys for THIS SESSION ONLY"""
    session_id = get_session_id(request) if not session_id_state else session_id_state
    session = get_or_create_session_state(session_id)
    
    status_messages = []
    
    # Update keys for THIS SESSION
    if mistral_key.strip():
        session["api_keys"]["mistral"] = mistral_key.strip()
        status_messages.append("โœ… Mistral API key saved for this session")
    elif MISTRAL_API_KEY:  # Fall back to env var
        session["api_keys"]["mistral"] = MISTRAL_API_KEY
        status_messages.append("โœ… Using Mistral API key from environment")
    else:
        status_messages.append("โŒ No Mistral API key available")
        
    if sambanova_key.strip():
        session["api_keys"]["sambanova"] = sambanova_key.strip()
        status_messages.append("โœ… SambaNova API key saved for this session")
    elif SAMBANOVA_API_KEY:
        session["api_keys"]["sambanova"] = SAMBANOVA_API_KEY
        status_messages.append("โœ… Using SambaNova API key from environment")
    else:
        status_messages.append("โŒ No SambaNova API key available")
    
    return " | ".join(status_messages), session_id

class VisualConsensusEngine:
    def __init__(self, moderator_model: str = None, update_callback=None, session_id: str = None):
        self.moderator_model = moderator_model or MODERATOR_MODEL
        self.search_agent = WebSearchAgent()
        self.update_callback = update_callback
        self.session_id = session_id
        
        # Get session-specific keys or fall back to global
        session = get_or_create_session_state(session_id) if session_id else {"api_keys": {}}
        session_keys = session.get("api_keys", {})
        
        mistral_key = session_keys.get("mistral") or MISTRAL_API_KEY
        sambanova_key = session_keys.get("sambanova") or SAMBANOVA_API_KEY
        
        self.models = {
            'mistral': {
                'name': 'Mistral Large',
                'api_key': mistral_key,
                'available': bool(mistral_key)
            },
            'sambanova_deepseek': {
                'name': 'DeepSeek-R1',
                'api_key': sambanova_key,
                'available': bool(sambanova_key)
            },
            'sambanova_llama': {
                'name': 'Meta-Llama-3.1-8B',
                'api_key': sambanova_key,
                'available': bool(sambanova_key)
            },
            'sambanova_qwq': {
                'name': 'QwQ-32B',
                'api_key': sambanova_key,
                'available': bool(sambanova_key)
            },
            'search': {
                'name': 'Web Search Agent',
                'api_key': True,
                'available': True
            }
        }
        
        # Store session keys for API calls
        self.session_keys = {
            'mistral': mistral_key,
            'sambanova': sambanova_key
        }
        
        # Role definitions
        self.roles = {
            'standard': "You are participating in a collaborative AI discussion. Provide thoughtful, balanced analysis.",
            'devils_advocate': "You are the devil's advocate. Challenge assumptions, point out weaknesses, and argue alternative perspectives even if unpopular.",
            'fact_checker': "You are the fact checker. Focus on verifying claims, checking accuracy, and identifying potential misinformation.",
            'synthesizer': "You are the synthesizer. Focus on finding common ground, combining different perspectives, and building bridges between opposing views.",
            'domain_expert': "You are a domain expert. Provide specialized knowledge, technical insights, and authoritative perspective on the topic.",
            'creative_thinker': "You are the creative thinker. Approach problems from unusual angles, suggest innovative solutions, and think outside conventional boundaries."
        }
    
    def update_visual_state(self, state_update: Dict[str, Any]):
        """Update the visual roundtable state for this session"""
        if self.update_callback:
            self.update_callback(state_update)
    
    def call_model(self, model: str, prompt: str, context: str = "") -> Optional[str]:
        """Generic model calling function using session-specific keys"""
        if model == 'search':
            search_query = self._extract_search_query(prompt)
            return self.search_agent.search(search_query)
        
        if not self.models[model]['available']:
            return None
            
        full_prompt = f"{context}\n\n{prompt}" if context else prompt
        
        try:
            if model == 'mistral':
                return self._call_mistral(full_prompt)
            elif model.startswith('sambanova_'):
                return self._call_sambanova(model, full_prompt)
        except Exception as e:
            print(f"Error calling {model}: {str(e)}")
            return None
    
    def _extract_search_query(self, prompt: str) -> str:
        """Extract search query from prompt or generate one"""
        lines = prompt.split('\n')
        for line in lines:
            if 'QUESTION:' in line:
                return line.replace('QUESTION:', '').strip()
        
        for line in lines:
            if len(line.strip()) > 10:
                return line.strip()[:100]
        
        return prompt[:100]
    
    def _call_sambanova(self, model: str, prompt: str) -> Optional[str]:
        api_key = self.session_keys.get('sambanova')
        if not api_key:
            return None
            
        try:
            from openai import OpenAI
            
            client = OpenAI(
                base_url="https://api.sambanova.ai/v1", 
                api_key=api_key
            )
            
            model_mapping = {
                'sambanova_deepseek': 'DeepSeek-R1',
                'sambanova_llama': 'Meta-Llama-3.1-8B-Instruct', 
                'sambanova_qwq': 'QwQ-32B'
            }
            
            sambanova_model = model_mapping.get(model, 'Meta-Llama-3.1-8B-Instruct')
            
            completion = client.chat.completions.create(
                model=sambanova_model,
                messages=[
                    {"role": "user", "content": prompt}
                ],
                max_tokens=2000,
                temperature=0.7
            )
            
            return completion.choices[0].message.content
            
        except Exception as e:
            print(f"Error calling Sambanova {model}: {str(e)}")
            return None
    
    def _call_mistral(self, prompt: str) -> Optional[str]:
        api_key = self.session_keys.get('mistral')
        if not api_key:
            return None
            
        try:
            from openai import OpenAI
            
            client = OpenAI(
                base_url="https://api.mistral.ai/v1", 
                api_key=api_key
            )
            
            completion = client.chat.completions.create(
                model='mistral-large-latest',
                messages=[
                    {"role": "user", "content": prompt}
                ],
                max_tokens=2000,
                temperature=0.7
            )
            
            return completion.choices[0].message.content
            
        except Exception as e:
            print(f"Error calling Mistral API mistral-large-latest: {str(e)}")
            return None
    
    def assign_roles(self, models: List[str], role_assignment: str) -> Dict[str, str]:
        """Assign roles to models"""
        if role_assignment == "none":
            return {model: "standard" for model in models}
        
        roles_to_assign = []
        if role_assignment == "balanced":
            roles_to_assign = ["devils_advocate", "fact_checker", "synthesizer", "standard"]
        elif role_assignment == "specialized":
            roles_to_assign = ["domain_expert", "fact_checker", "creative_thinker", "synthesizer"]
        elif role_assignment == "adversarial":
            roles_to_assign = ["devils_advocate", "devils_advocate", "standard", "standard"]
        
        while len(roles_to_assign) < len(models):
            roles_to_assign.append("standard")
        
        model_roles = {}
        for i, model in enumerate(models):
            model_roles[model] = roles_to_assign[i % len(roles_to_assign)]
        
        return model_roles
    
    def _extract_confidence(self, response: str) -> float:
        """Extract confidence score from response"""
        confidence_match = re.search(r'Confidence:\s*(\d+(?:\.\d+)?)', response)
        if confidence_match:
            try:
                return float(confidence_match.group(1))
            except ValueError:
                pass
        return 5.0
    
    def run_visual_consensus_session(self, question: str, discussion_rounds: int = 3, 
                                   decision_protocol: str = "consensus", role_assignment: str = "balanced",
                                   topology: str = "full_mesh", moderator_model: str = "mistral",
                                   enable_step_by_step: bool = False, log_function=None):
        """Run consensus with session-isolated visual updates"""
        
        available_models = [model for model, info in self.models.items() if info['available']]
        if not available_models:
            return "โŒ No AI models available"
        
        model_roles = self.assign_roles(available_models, role_assignment)
        participant_names = [self.models[model]['name'] for model in available_models]
        
        # Use session-specific logging
        def log_event(event_type: str, speaker: str = "", content: str = "", **kwargs):
            if log_function:
                log_function(event_type, speaker, content, **kwargs)
        
        # Log the start
        log_event('phase', content=f"๐Ÿš€ Starting Discussion: {question}")
        log_event('phase', content=f"๐Ÿ“Š Configuration: {len(available_models)} models, {decision_protocol} protocol, {role_assignment} roles")
        
        # Initialize visual state
        self.update_visual_state({
            "participants": participant_names,
            "messages": [],
            "currentSpeaker": None,
            "thinking": [],
            "showBubbles": []
        })
        
        all_messages = []
        
        # Phase 1: Initial responses
        log_event('phase', content="๐Ÿ“ Phase 1: Initial Responses")
        
        for model in available_models:
            # Log and set thinking state
            log_event('thinking', speaker=self.models[model]['name'])
            self.update_visual_state({
                "participants": participant_names,
                "messages": all_messages,
                "currentSpeaker": None,
                "thinking": [self.models[model]['name']]
            })
            
            if not enable_step_by_step:
                time.sleep(1)
            
            role = model_roles[model]
            role_context = self.roles[role]
            
            prompt = f"""{role_context}

QUESTION: {question}

Please provide your initial analysis and answer. Be thoughtful, detailed, and explain your reasoning.

Your response should include:
1. Your direct answer to the question
2. Your reasoning and evidence  
3. Any important considerations or nuances
4. END YOUR RESPONSE WITH: "Confidence: X/10" where X is your confidence level"""

            # Log and set speaking state
            log_event('speaking', speaker=self.models[model]['name'])
            self.update_visual_state({
                "participants": participant_names,
                "messages": all_messages,
                "currentSpeaker": self.models[model]['name'],
                "thinking": []
            })
            
            if not enable_step_by_step:
                time.sleep(2)
            
            response = self.call_model(model, prompt)
            
            if response:
                confidence = self._extract_confidence(response)
                message = {
                    "speaker": self.models[model]['name'],
                    "text": response,
                    "confidence": confidence,
                    "role": role
                }
                all_messages.append(message)
                
                # Log the full response
                log_event('message', 
                         speaker=self.models[model]['name'], 
                         content=response,
                         role=role,
                         confidence=confidence)
                
                # Update with new message
                responded_speakers = list(set(msg["speaker"] for msg in all_messages if msg.get("speaker")))
                
                self.update_visual_state({
                    "participants": participant_names,
                    "messages": all_messages,
                    "currentSpeaker": None,
                    "thinking": [],
                    "showBubbles": responded_speakers
                })
                
                if enable_step_by_step:
                    session = get_or_create_session_state(self.session_id)
                    session["step_continue_event"].clear()
                    session["step_continue_event"].wait()
                else:
                    time.sleep(0.5)
        
        # Phase 2: Discussion rounds
        if discussion_rounds > 0:
            log_event('phase', content=f"๐Ÿ’ฌ Phase 2: Discussion Rounds ({discussion_rounds} rounds)")
            
            for round_num in range(discussion_rounds):
                log_event('phase', content=f"๐Ÿ”„ Discussion Round {round_num + 1}")
                
                for model in available_models:
                    log_event('thinking', speaker=self.models[model]['name'])
                    self.update_visual_state({
                        "participants": participant_names,
                        "messages": all_messages,
                        "currentSpeaker": None,
                        "thinking": [self.models[model]['name']]
                    })
                    
                    if not enable_step_by_step:
                        time.sleep(1)
                    
                    # Create context of other responses
                    other_responses = ""
                    for other_model in available_models:
                        if other_model != model:
                            other_responses += f"\n**{self.models[other_model]['name']}**: [Previous response]\n"
                    
                    discussion_prompt = f"""CONTINUING DISCUSSION FOR: {question}

Round {round_num + 1} of {discussion_rounds}

Other models' current responses:
{other_responses}

Please provide your updated analysis considering the discussion so far.
END WITH: "Confidence: X/10" """

                    log_event('speaking', speaker=self.models[model]['name'])
                    self.update_visual_state({
                        "participants": participant_names,
                        "messages": all_messages,
                        "currentSpeaker": self.models[model]['name'],
                        "thinking": []
                    })
                    
                    if not enable_step_by_step:
                        time.sleep(2)
                    
                    response = self.call_model(model, discussion_prompt)
                    
                    if response:
                        confidence = self._extract_confidence(response)
                        message = {
                            "speaker": self.models[model]['name'],
                            "text": f"Round {round_num + 1}: {response}",
                            "confidence": confidence,
                            "role": model_roles[model]
                        }
                        all_messages.append(message)
                        
                        log_event('message', 
                                 speaker=self.models[model]['name'], 
                                 content=f"Round {round_num + 1}: {response}",
                                 role=model_roles[model],
                                 confidence=confidence)
                        
                        responded_speakers = list(set(msg["speaker"] for msg in all_messages if msg.get("speaker")))
                        
                        self.update_visual_state({
                            "participants": participant_names,
                            "messages": all_messages,
                            "currentSpeaker": None,
                            "thinking": [],
                            "showBubbles": responded_speakers
                        })
                        
                        if enable_step_by_step:
                            session = get_or_create_session_state(self.session_id)
                            session["step_continue_event"].clear()
                            session["step_continue_event"].wait()
                        else:
                            time.sleep(1)
        
        # Phase 3: Final consensus
        log_event('phase', content=f"๐ŸŽฏ Phase 3: Final Consensus ({decision_protocol})")
        log_event('thinking', speaker="All participants", content="Building consensus...")
        
        self.update_visual_state({
            "participants": participant_names,
            "messages": all_messages,
            "currentSpeaker": None,
            "thinking": participant_names
        })
        
        if not enable_step_by_step:
            time.sleep(2)
        
        # Generate consensus
        moderator = self.moderator_model if self.models[self.moderator_model]['available'] else available_models[0]
        
        # Collect responses from session log
        session = get_or_create_session_state(self.session_id)
        all_responses = ""
        confidence_scores = []
        for entry in session["discussion_log"]:
            if entry['type'] == 'message' and entry['speaker'] != 'Consilium':
                all_responses += f"\n**{entry['speaker']}**: {entry['content']}\n"
                if 'confidence' in entry:
                    confidence_scores.append(entry['confidence'])
        
        avg_confidence = sum(confidence_scores) / len(confidence_scores) if confidence_scores else 5.0
        consensus_threshold = 7.0
        
        consensus_prompt = f"""You are synthesizing the final result from this AI discussion.

ORIGINAL QUESTION: {question}

ALL PARTICIPANT RESPONSES:
{all_responses}

AVERAGE CONFIDENCE LEVEL: {avg_confidence:.1f}/10

Your task:
1. Analyze if the participants reached genuine consensus or if there are significant disagreements
2. If there IS consensus: Provide a comprehensive final answer incorporating all insights
3. If there is NO consensus: Clearly state the disagreements and present the main conflicting positions
4. If partially aligned: Identify areas of agreement and areas of disagreement

Be honest about the level of consensus achieved. Do not force agreement where none exists.

Format your response as:
**CONSENSUS STATUS:** [Reached/Partial/Not Reached]

**FINAL ANSWER:** [Your synthesis]

**AREAS OF DISAGREEMENT:** [If any - explain the key points of contention]"""

        log_event('speaking', speaker="Consilium", content="Analyzing consensus and synthesizing final answer...")
        self.update_visual_state({
            "participants": participant_names,
            "messages": all_messages,
            "currentSpeaker": "Consilium",
            "thinking": []
        })
        
        consensus_result = self.call_model(moderator, consensus_prompt)
        
        if not consensus_result:
            consensus_result = f"""**CONSENSUS STATUS:** Analysis Failed

**FINAL ANSWER:** Unable to generate consensus analysis. Please review individual participant responses in the discussion log.

**AREAS OF DISAGREEMENT:** Analysis could not be completed due to technical issues."""
        
        consensus_reached = "CONSENSUS STATUS: Reached" in consensus_result or avg_confidence >= consensus_threshold
        
        if consensus_reached:
            visual_summary = "โœ… Consensus reached!"
        elif "Partial" in consensus_result:
            visual_summary = "โš ๏ธ Partial consensus - some disagreements remain"
        else:
            visual_summary = "โŒ No consensus - significant disagreements identified"
        
        final_message = {
            "speaker": "Consilium",
            "text": f"{visual_summary} {consensus_result}",
            "confidence": avg_confidence,
            "role": "consensus"
        }
        all_messages.append(final_message)
        
        log_event('message', 
                 speaker="Consilium", 
                 content=consensus_result,
                 confidence=avg_confidence)
        
        responded_speakers = list(set(msg["speaker"] for msg in all_messages if msg.get("speaker")))
        
        self.update_visual_state({
            "participants": participant_names,
            "messages": all_messages,
            "currentSpeaker": None,
            "thinking": [],
            "showBubbles": responded_speakers
        })
        
        log_event('phase', content="โœ… Discussion Complete")
        
        return consensus_result

def update_session_roundtable_state(session_id: str, new_state: Dict):
    """Update roundtable state for specific session"""
    session = get_or_create_session_state(session_id)
    session["roundtable_state"].update(new_state)
    return json.dumps(session["roundtable_state"])

def run_consensus_discussion_session(question: str, discussion_rounds: int = 3, 
                                   decision_protocol: str = "consensus", role_assignment: str = "balanced",
                                   topology: str = "full_mesh", moderator_model: str = "mistral",
                                   enable_step_by_step: bool = False, session_id_state: str = None,
                                   request: gr.Request = None):
    """Session-isolated consensus discussion"""
    
    # Get unique session
    session_id = get_session_id(request) if not session_id_state else session_id_state
    session = get_or_create_session_state(session_id)
    
    # Reset session state for new discussion
    session["discussion_log"] = []
    session["final_answer"] = ""
    session["step_by_step_active"] = enable_step_by_step
    session["step_continue_event"].clear()
    
    def session_visual_update_callback(state_update):
        """Session-specific visual update callback"""
        update_session_roundtable_state(session_id, state_update)
    
    def session_log_event(event_type: str, speaker: str = "", content: str = "", **kwargs):
        """Add event to THIS session's log only"""
        session["discussion_log"].append({
            'type': event_type,
            'speaker': speaker,
            'content': content,
            'timestamp': datetime.now().strftime('%H:%M:%S'),
            **kwargs
        })
    
    # Create engine with session-specific callback
    engine = VisualConsensusEngine(moderator_model, session_visual_update_callback, session_id)
    
    # Run consensus with session-specific logging
    result = engine.run_visual_consensus_session(
        question, discussion_rounds, decision_protocol, 
        role_assignment, topology, moderator_model, 
        enable_step_by_step, session_log_event
    )
    
    # Generate session-specific final answer
    available_models = [model for model, info in engine.models.items() if info['available']]
    session["final_answer"] = f"""## ๐ŸŽฏ Final Consensus Answer

{result}

---

### ๐Ÿ“Š Discussion Summary
- **Question:** {question}
- **Protocol:** {decision_protocol.replace('_', ' ').title()}
- **Participants:** {len(available_models)} AI models
- **Roles:** {role_assignment.title()}
- **Session ID:** {session_id[:8]}...

*Generated by Consilium Visual AI Consensus Platform*"""
    
    session["step_by_step_active"] = False
    
    # Format session-specific discussion log
    formatted_log = format_session_discussion_log(session["discussion_log"])
    
    return ("โœ… Discussion Complete - See results below", 
            json.dumps(session["roundtable_state"]), 
            session["final_answer"], 
            formatted_log,
            session_id)

def format_session_discussion_log(discussion_log: list) -> str:
    """Format discussion log for specific session"""
    if not discussion_log:
        return "No discussion log available yet."
    
    formatted_log = "# ๐ŸŽญ Complete Discussion Log\n\n"
    
    for entry in discussion_log:
        timestamp = entry.get('timestamp', datetime.now().strftime('%H:%M:%S'))
        if entry['type'] == 'thinking':
            formatted_log += f"**{timestamp}** ๐Ÿค” **{entry['speaker']}** is thinking...\n\n"
        elif entry['type'] == 'speaking':
            formatted_log += f"**{timestamp}** ๐Ÿ’ฌ **{entry['speaker']}** is responding...\n\n"
        elif entry['type'] == 'message':
            formatted_log += f"**{timestamp}** โœ… **{entry['speaker']}** ({entry.get('role', 'standard')}):\n"
            formatted_log += f"> {entry['content']}\n"
            if 'confidence' in entry:
                formatted_log += f"*Confidence: {entry['confidence']}/10*\n\n"
            else:
                formatted_log += "\n"
        elif entry['type'] == 'phase':
            formatted_log += f"\n---\n## {entry['content']}\n---\n\n"
    
    return formatted_log

def continue_step_session(session_id_state: str):
    """Function called by the Next Step button for specific session"""
    if session_id_state and session_id_state in user_sessions:
        session = user_sessions[session_id_state]
        session["step_continue_event"].set()
        return "โœ… Continuing... Next AI will respond shortly"
    return "โŒ Session not found"

def check_model_status_session(session_id_state: str = None, request: gr.Request = None):
    """Check and display current model availability for specific session"""
    session_id = get_session_id(request) if not session_id_state else session_id_state
    session = get_or_create_session_state(session_id)
    session_keys = session.get("api_keys", {})
    
    # Get session-specific keys or fall back to env vars
    mistral_key = session_keys.get("mistral") or MISTRAL_API_KEY
    sambanova_key = session_keys.get("sambanova") or SAMBANOVA_API_KEY
    
    status_info = "## ๐Ÿ” Model Availability Status\n\n"
    
    models = {
        'Mistral Large': mistral_key,
        'DeepSeek-R1': sambanova_key,
        'Meta-Llama-3.1-8B': sambanova_key,
        'QwQ-32B': sambanova_key,
        'Web Search Agent': True
    }
    
    for model_name, available in models.items():
        if model_name == 'Web Search Agent':
            status = "โœ… Available (Built-in)"
        else:
            if available:
                status = f"โœ… Available (Key: {available[:8]}...)"
            else:
                status = "โŒ Not configured"
        status_info += f"**{model_name}:** {status}\n\n"
    
    return status_info

# Create the hybrid interface
with gr.Blocks(title="๐ŸŽญ Consilium: Visual AI Consensus Platform", theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # ๐ŸŽญ Consilium: Visual AI Consensus Platform
    
    **Watch AI models collaborate in real-time around a visual roundtable!**
    
    This platform combines:
    - ๐ŸŽจ **Visual Roundtable Interface** - See AI avatars thinking and speaking
    - ๐Ÿค– **Multi-Model Consensus** - Mistral, Deepseek, Llama, QwQ  
    - ๐ŸŽญ **Dynamic Role Assignment** - Devil's advocate, fact checker, synthesizer roles
    - ๐ŸŒ **Communication Topologies** - Full mesh, star, ring patterns
    - ๐Ÿ—ณ๏ธ **Decision Protocols** - Consensus, voting, weighted, ranked choice
    - ๐Ÿ” **Web Search Integration** - Real-time information gathering
    - ๐Ÿ”’ **Session Isolation** - Each user gets their own private discussion space
    
    **Perfect for:** Complex decisions, research analysis, creative brainstorming, problem-solving
    """)
    
    # Hidden session state component
    session_state = gr.State()
    
    with gr.Tab("๐ŸŽญ Visual Consensus Discussion"):
        with gr.Row():
            with gr.Column(scale=1):
                question_input = gr.Textbox(
                    label="Discussion Question",
                    placeholder="What would you like the AI council to discuss and decide?",
                    lines=3,
                    value="What are the most effective strategies for combating climate change?"
                )
                
                with gr.Row():
                    decision_protocol = gr.Dropdown(
                        choices=["consensus", "majority_voting", "weighted_voting", "ranked_choice", "unanimity"],
                        value="consensus",
                        label="๐Ÿ—ณ๏ธ Decision Protocol"
                    )
                    
                    role_assignment = gr.Dropdown(
                        choices=["balanced", "specialized", "adversarial", "none"],
                        value="balanced",
                        label="๐ŸŽญ Role Assignment"
                    )
                
                with gr.Row():
                    topology = gr.Dropdown(
                        choices=["full_mesh", "star", "ring"],
                        value="full_mesh",
                        label="๐ŸŒ Communication Pattern"
                    )
                    
                    moderator_model = gr.Dropdown(
                        choices=["mistral", "sambanova_deepseek", "sambanova_llama", "sambanova_qwq"],
                        value="mistral",
                        label="๐Ÿ‘จโ€โš–๏ธ Moderator"
                    )
                
                rounds_input = gr.Slider(
                    minimum=1, maximum=5, value=2, step=1,
                    label="๐Ÿ”„ Discussion Rounds"
                )
                
                enable_clickthrough = gr.Checkbox(
                    label="โฏ๏ธ Enable Step-by-Step Mode",
                    value=False,
                    info="Pause at each step for manual control"
                )
                
                start_btn = gr.Button("๐Ÿš€ Start Visual Consensus Discussion", variant="primary", size="lg")
                
                # Step-by-step control button (only visible when step mode is active)
                next_step_btn = gr.Button("โฏ๏ธ Next Step", variant="secondary", size="lg", visible=False)
                step_status = gr.Textbox(label="Step Control", visible=False, interactive=False)
                
                status_output = gr.Textbox(label="๐Ÿ“Š Discussion Status", interactive=False)
            
            with gr.Column(scale=2):
                # The visual roundtable component
                roundtable = consilium_roundtable(
                    label="๐ŸŽญ AI Consensus Roundtable",
                    value=json.dumps({
                        "participants": [],
                        "messages": [],
                        "currentSpeaker": None,
                        "thinking": [],
                        "showBubbles": []
                    })
                )
        
        # Final answer section
        with gr.Row():
            final_answer_output = gr.Markdown(
                label="๐ŸŽฏ Final Consensus Answer",
                value="*Discussion results will appear here...*"
            )
        
        # Collapsible discussion log
        with gr.Accordion("๐Ÿ“‹ Complete Discussion Log", open=False):
            discussion_log_output = gr.Markdown(
                value="*Complete discussion transcript will appear here...*"
            )
        
        # Event handlers
        def on_start_discussion(question, rounds, protocol, roles, topology, moderator, enable_step, session_id_state, request: gr.Request = None):
            # Start discussion immediately for both modes
            
            if enable_step:
                # Step-by-step mode: Start discussion in background thread
                def run_discussion():
                    run_consensus_discussion_session(question, rounds, protocol, roles, topology, moderator, enable_step, session_id_state, request)
                
                discussion_thread = threading.Thread(target=run_discussion)
                discussion_thread.daemon = True
                discussion_thread.start()
                
                # Get session ID for this user
                session_id = get_session_id(request)
                
                return (
                    "๐ŸŽฌ Step-by-step mode: Discussion started - will pause after each AI response",
                    json.dumps(get_or_create_session_state(session_id)["roundtable_state"]),
                    "*Discussion starting in step-by-step mode...*",
                    "*Discussion log will appear here...*",
                    gr.update(visible=True),  # Show next step button
                    gr.update(visible=True, value="Discussion running - will pause after first AI response"),  # Show step status
                    session_id
                )
            else:
                # Normal mode - start immediately and hide step controls
                result = run_consensus_discussion_session(question, rounds, protocol, roles, topology, moderator, enable_step, session_id_state, request)
                return result + (gr.update(visible=False), gr.update(visible=False))
        
        # Function to toggle step controls visibility
        def toggle_step_controls(enable_step):
            return (
                gr.update(visible=enable_step),  # next_step_btn
                gr.update(visible=enable_step)   # step_status
            )
        
        # Hide/show step controls when checkbox changes
        enable_clickthrough.change(
            toggle_step_controls,
            inputs=[enable_clickthrough],
            outputs=[next_step_btn, step_status]
        )
        
        start_btn.click(
            on_start_discussion,
            inputs=[question_input, rounds_input, decision_protocol, role_assignment, topology, moderator_model, enable_clickthrough, session_state],
            outputs=[status_output, roundtable, final_answer_output, discussion_log_output, next_step_btn, step_status, session_state]
        )
        
        # Next step button handler
        next_step_btn.click(
            continue_step_session,
            inputs=[session_state],
            outputs=[step_status]
        )
        
        # Auto-refresh the roundtable state every 2 seconds during discussion
        def refresh_roundtable(session_id_state, request: gr.Request = None):
            session_id = get_session_id(request) if not session_id_state else session_id_state
            if session_id in user_sessions:
                return json.dumps(user_sessions[session_id]["roundtable_state"])
            return json.dumps({
                "participants": [],
                "messages": [],
                "currentSpeaker": None,
                "thinking": [],
                "showBubbles": []
            })
        
        gr.Timer(0.5).tick(refresh_roundtable, inputs=[session_state], outputs=[roundtable])
    
    with gr.Tab("๐Ÿ”ง Configuration & Setup"):
        gr.Markdown("## ๐Ÿ”‘ API Keys Configuration")
        gr.Markdown("*Enter your API keys below OR set them as environment variables*")
        gr.Markdown("**๐Ÿ”’ Privacy:** Your API keys are stored only for your session and are not shared with other users.")
        
        with gr.Row():
            with gr.Column():
                mistral_key_input = gr.Textbox(
                    label="Mistral API Key",
                    placeholder="Enter your Mistral API key...",
                    type="password",
                    info="Required for Mistral Large model"
                )
                sambanova_key_input = gr.Textbox(
                    label="SambaNova API Key", 
                    placeholder="Enter your SambaNova API key...",
                    type="password",
                    info="Required for DeepSeek, Llama, and QwQ models"
                )
                
            with gr.Column():
                # Add a button to save/update keys
                save_keys_btn = gr.Button("๐Ÿ’พ Save API Keys", variant="secondary")
                keys_status = gr.Textbox(
                    label="Keys Status",
                    value="No API keys configured - using environment variables if available",
                    interactive=False
                )
        
        # Connect the save button
        save_keys_btn.click(
            update_session_api_keys,
            inputs=[mistral_key_input, sambanova_key_input, session_state],
            outputs=[keys_status, session_state]
        )
        
        model_status_display = gr.Markdown(check_model_status_session())
        
        # Add refresh button for model status
        refresh_status_btn = gr.Button("๐Ÿ”„ Refresh Model Status")
        refresh_status_btn.click(
            check_model_status_session,
            inputs=[session_state],
            outputs=[model_status_display]
        )
        
        gr.Markdown("""
        ## ๐Ÿ› ๏ธ Setup Instructions
        
        ### ๐Ÿš€ Quick Start (Recommended)
        1. **Enter API keys above** (they'll be used only for your session)
        2. **Click "Save API Keys"** 
        3. **Start a discussion!**
        
        ### ๐Ÿ”‘ Get API Keys:
        - **Mistral:** [console.mistral.ai](https://console.mistral.ai)
        - **SambaNova:** [cloud.sambanova.ai](https://cloud.sambanova.ai)
        
        ### ๐ŸŒ Alternative: Environment Variables
        ```bash
        export MISTRAL_API_KEY=your_key_here
        export SAMBANOVA_API_KEY=your_key_here
        export MODERATOR_MODEL=mistral
        ```
        
        ### ๐Ÿฆ™ Sambanova Integration
        The platform includes **3 Sambanova models**:
        - **DeepSeek-R1**: Advanced reasoning model
        - **Meta-Llama-3.1-8B**: Fast, efficient discussions  
        - **QwQ-32B**: Large-scale consensus analysis
        
        ### ๐Ÿ” Web Search Agent
        Built-in agent using **smolagents** with:
        - **DuckDuckGoSearchTool**: Web searches
        - **VisitWebpageTool**: Deep content analysis
        - **WikipediaTool**: Comprehensive research
        - **TinyLlama**: Fast inference for search synthesis
        
        ### ๐Ÿ“‹ Dependencies
        ```bash
        pip install gradio requests python-dotenv smolagents gradio-consilium-roundtable wikipedia openai
        ```
        
        ### ๐Ÿ”— MCP Integration
        Add to your Claude Desktop config:
        ```json
        {
          "mcpServers": {
            "consilium": {
              "command": "npx",
              "args": ["mcp-remote", "http://localhost:7860/gradio_api/mcp/sse"]
            }
          }
        }
        ```
        
        ### ๐Ÿ”’ Privacy & Security
        - **Session Isolation**: Each user gets their own private discussion space
        - **API Key Protection**: Keys are stored only in your browser session
        - **No Global State**: Your discussions are not visible to other users
        - **Secure Communication**: All API calls use HTTPS encryption
        """)
    
    with gr.Tab("๐Ÿ“š Usage Examples"):
        gr.Markdown("""
        ## ๐ŸŽฏ Example Discussion Topics
        
        ### ๐Ÿง  Complex Problem Solving
        - "How should we approach the global housing crisis?"
        - "What's the best strategy for reducing plastic pollution?"
        - "How can we make AI development more democratic?"
        
        ### ๐Ÿ’ผ Business Strategy
        - "Should our company invest in quantum computing research?"
        - "What's the optimal remote work policy for productivity?"
        - "How should startups approach AI integration?"
        
        ### ๐Ÿ”ฌ Technical Analysis  
        - "What's the future of web development frameworks?"
        - "How should we handle data privacy in the age of AI?"
        - "What are the best practices for microservices architecture?"
        
        ### ๐ŸŒ Social Issues
        - "How can we bridge political divides in society?"
        - "What's the most effective approach to education reform?"
        - "How should we regulate social media platforms?"
        
        ## ๐ŸŽญ Visual Features
        
        **Watch for these visual cues:**
        - ๐Ÿค” **Orange pulsing avatars** = AI is thinking
        - โœจ **Gold glowing avatars** = AI is responding  
        - ๐Ÿ’ฌ **Speech bubbles** = Click avatars to see messages
        - ๐ŸŽฏ **Center consensus** = Final decision reached
        
        **The roundtable updates in real-time as the discussion progresses!**
        
        ## ๐ŸŽฎ Role Assignments Explained
        
        ### ๐ŸŽญ Balanced (Recommended)
        - **Devil's Advocate**: Challenges assumptions
        - **Fact Checker**: Verifies claims and accuracy
        - **Synthesizer**: Finds common ground
        - **Standard**: Provides balanced analysis
        
        ### ๐ŸŽ“ Specialized
        - **Domain Expert**: Technical expertise
        - **Fact Checker**: Accuracy verification
        - **Creative Thinker**: Innovative solutions
        - **Synthesizer**: Bridge building
        
        ### โš”๏ธ Adversarial
        - **Double Devil's Advocate**: Maximum challenge
        - **Standard**: Balanced counter-perspective
        
        ## ๐Ÿ—ณ๏ธ Decision Protocols
        
        - **Consensus**: Seek agreement among all participants
        - **Majority Voting**: Most popular position wins
        - **Weighted Voting**: Higher confidence scores matter more
        - **Ranked Choice**: Preference-based selection
        - **Unanimity**: All must agree completely
        
        ## ๐Ÿ”’ Session Isolation
        
        **Each user gets their own private space:**
        - โœ… Your discussions are private to you
        - โœ… Your API keys are not shared
        - โœ… Your conversation history is isolated
        - โœ… Multiple users can use the platform simultaneously
        
        **Perfect for teams, research groups, and individual use!**
        """)

# Launch configuration
if __name__ == "__main__":
    demo.queue(default_concurrency_limit=10) 
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        debug=False,
        mcp_server=True
    )