-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
445 lines (353 loc) · 15.9 KB
/
main.py
File metadata and controls
445 lines (353 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
from debate.context_mode import ContextMode
from debate.debate_controller import DebateController
from agents.base_agent import DebateAgent
from agents.model_providers import get_available_providers
from agents.template_loader import TemplateLoader
def ask_model_provider():
"""Ask user which model provider to use"""
print("\n🤖 MODEL PROVIDER SELECTION:")
providers = get_available_providers()
if not providers:
print("❌ No model providers available!")
print(" • For Gemini: Set GEMINI_API_KEY environment variable")
print(" • For Ollama: Install Ollama and pull phi3 model")
return None
print("Available model providers:")
provider_list = list(providers.items())
for i, (key, provider) in enumerate(provider_list, 1):
print(f" {i} → {provider.get_name()}")
if key == 'gemini':
print(" • Cloud-based, fast, requires API key")
elif key.startswith('ollama'):
print(" • Local, private, no API key needed")
while True:
try:
choice = input(f"Select provider (1-{len(provider_list)}) ▶ ").strip()
if not choice:
choice = "1"
index = int(choice) - 1
if 0 <= index < len(provider_list):
selected_key, selected_provider = provider_list[index]
print(f"✅ Selected: {selected_provider.get_name()}")
return selected_provider
else:
print(f"Please enter a number between 1 and {len(provider_list)}")
except ValueError:
print("Please enter a valid number")
def choose_agent_creation_method(model_provider):
"""Let user choose how to create agents"""
print("\n👥 AGENT CREATION:")
print("How would you like to create agents?")
print(" 1 → Select from personality templates (recommended)")
print(" 2 → Use default 3-agent setup")
print(" 3 → Create custom agents")
choice = input("Your choice (1-3) [1] ▶ ").strip() or "1"
if choice == "2":
# Default 3 agents
agents = [
DebateAgent(
name="Dr. Sarah Chen",
persona="calm, evidence-based",
role="medical researcher",
expertise="AI in healthcare & ethics",
style="professional",
knowledge_domain="medical"
),
DebateAgent(
name="Marcus Rivera",
persona="optimistic, tech-forward",
role="startup founder",
expertise="AI entrepreneurship",
style="casual",
knowledge_domain="tech"
),
DebateAgent(
name="Prof. Elena Vasquez",
persona="thoughtful, ethical",
role="philosopher",
expertise="AI ethics",
style="academic",
knowledge_domain="ethics"
)
]
# Set model provider for all agents
for agent in agents:
agent.model_provider = model_provider
return agents
elif choice == "3":
# Custom agents
return create_custom_agents(model_provider)
else:
# Templates (default)
return select_agents_from_templates(model_provider)
def select_agents_from_templates(model_provider):
"""Let user pick agents from personality templates"""
loader = TemplateLoader()
print("\n📋 Available Agent Templates:")
print("=" * 60)
templates = loader.get_template_info()
template_list = list(templates.keys())
for i, (template_id, description) in enumerate(templates.items(), 1):
print(f"{i:2d}. {template_id.replace('_', ' ').title()}")
print(f" {description}")
print()
print("Select agents by entering numbers (e.g., '1,3,5' or '1-3'):")
selection = input("Your choice ▶ ").strip()
# Parse selection
selected_indices = []
if not selection:
# Default selection
selected_indices = [1, 2, 3]
print("Using default selection: 1,2,3")
else:
try:
for part in selection.split(','):
part = part.strip()
if '-' in part:
# Range selection (e.g., "1-3")
start, end = map(int, part.split('-'))
selected_indices.extend(range(start, end + 1))
else:
selected_indices.append(int(part))
except ValueError:
print("Invalid selection format. Using default: 1,2,3")
selected_indices = [1, 2, 3]
# Convert to template IDs and create agents
selected_templates = []
for idx in selected_indices:
if 1 <= idx <= len(template_list):
selected_templates.append(template_list[idx - 1])
if not selected_templates:
print("No valid agents selected. Using default selection.")
selected_templates = template_list[:3] # First 3 templates
# Create agents from templates
agents = loader.create_multiple_agents(selected_templates, model_provider=model_provider)
print(f"\n✅ Selected {len(agents)} agents:")
for agent in agents:
print(f" • {agent}")
return agents
def create_custom_agents(model_provider):
"""Create custom agents interactively"""
agents = []
num_agents = int(input("How many custom agents? (2-6): ") or "3")
# Domain mapping for auto-assignment
domain_keywords = {
"medical": ["doctor", "physician", "medical", "healthcare", "clinical"],
"tech": ["engineer", "developer", "programmer", "tech", "startup", "entrepreneur"],
"ethics": ["philosopher", "ethicist", "activist", "moral"],
"legal": ["lawyer", "attorney", "judge", "legal"],
"economics": ["economist", "financial", "business", "market"]
}
for i in range(num_agents):
print(f"\n🛠️ Create Agent {i+1}:")
name = input("Name: ").strip() or f"Agent {i+1}"
persona = input("Personality (e.g., 'calm, logical'): ").strip() or "balanced, thoughtful"
role = input("Role (e.g., 'teacher', 'scientist'): ").strip() or "expert"
expertise = input("Area of expertise: ").strip() or "general knowledge"
style = input("Speaking style: ").strip() or "professional"
# Auto-assign domain based on role
knowledge_domain = None
role_lower = role.lower()
for domain, keywords in domain_keywords.items():
if any(keyword in role_lower for keyword in keywords):
knowledge_domain = domain
break
agent = DebateAgent(
name=name,
persona=persona,
role=role,
expertise=expertise,
style=style,
knowledge_domain=knowledge_domain
)
# Set model provider after creation
agent.model_provider = model_provider
agents.append(agent)
if knowledge_domain:
print(f" → Auto-assigned domain: {knowledge_domain}")
return agents
def ask_context_mode() -> ContextMode:
print(
"\nContext options:\n"
" 1 → FULL (entire chat each turn)\n"
" 2 → SUMMARIZED (rolling summary only)\n"
" 3 → HYBRID (summary + last few messages) [default]"
)
choice = input("Select 1, 2 or 3 ▶ ").strip()
return {
"1": ContextMode.FULL,
"2": ContextMode.SUMMARIZED,
"3": ContextMode.HYBRID,
"": ContextMode.HYBRID
}.get(choice, ContextMode.HYBRID)
def ask_batching_preference():
"""Ask user about batching preference"""
print("\n⚡ BATCHING OPTIMIZATION:")
print(" Batching combines multiple agent responses into 1 API call")
print(" • PRO: ~66% fewer API calls, faster execution, lower costs")
print(" • CON: Less reliable parsing, shared context between agents")
print(" • NOTE: Only works with Gemini (Ollama doesn't support batching)")
print()
choice = input("Enable batching? (y/N): ").strip().lower()
use_batching = choice.startswith('y')
if use_batching:
print("✅ Batching ENABLED - Agents will respond simultaneously")
else:
print("❌ Batching DISABLED - Agents will respond individually")
return use_batching
def ask_length_limits():
"""Ask user about length limits and configure if enabled"""
print("\n📏 LENGTH LIMITS:")
print(" Enforce word limits on agent responses")
print(" • PRO: ~60-70% fewer tokens, faster responses, lower costs")
print(" • CON: Shorter arguments, may cut off detailed explanations")
print()
choice = input("Enable length limits? (y/N): ").strip().lower()
use_length_limits = choice.startswith('y')
if not use_length_limits:
print("❌ Length limits DISABLED - Natural response lengths")
return False, None
print("✅ Length limits ENABLED")
print("\n📏 Configure word limits for each debate stage:")
print("(Press Enter for defaults)")
opening_input = input("Opening statements word limit [100]: ").strip()
opening_words = int(opening_input) if opening_input.isdigit() else 100
rebuttal_input = input("Rebuttal word limit [75]: ").strip()
rebuttal_words = int(rebuttal_input) if rebuttal_input.isdigit() else 75
closing_input = input("Closing arguments word limit [125]: ").strip()
closing_words = int(closing_input) if closing_input.isdigit() else 125
word_limits = {
"opening": {"words": opening_words, "tokens": opening_words * 2},
"rebuttal": {"words": rebuttal_words, "tokens": rebuttal_words * 2},
"closing": {"words": closing_words, "tokens": closing_words * 2}
}
print(f"✅ Word limits set: Opening({opening_words}), Rebuttal({rebuttal_words}), Closing({closing_words})")
return True, word_limits
def ask_rag_preference():
"""Ask user about RAG knowledge retrieval"""
print("\n📚 RAG KNOWLEDGE RETRIEVAL:")
print(" Agents access domain-specific documents during debates")
print(" • PRO: More accurate, source-backed arguments")
print(" • CON: Requires document setup, slightly slower")
print()
choice = input("Enable RAG knowledge retrieval? (y/N): ").strip().lower()
use_rag = choice.startswith('y')
if use_rag:
print("✅ RAG ENABLED - Agents will access domain knowledge")
try:
from rag.retriever import KnowledgeRetriever
retriever = KnowledgeRetriever()
domains = retriever.available_domains()
if domains:
print(f" Available knowledge domains: {', '.join(domains)}")
else:
print(" ⚠️ No knowledge bases found. Run 'python rag/indexer.py' first")
except ImportError:
print(" ⚠️ RAG system not available")
else:
print("❌ RAG DISABLED - Agents use only training knowledge")
return use_rag
def run():
print("\n🗣️ DebAIte – Multi-Agent Debate Simulator")
print("==========================================")
# 1) Model Provider Selection
model_provider = ask_model_provider()
if not model_provider:
print("Cannot proceed without a model provider. Exiting.")
return
# 2) Debate Mode Selection
debate_mode = choose_debate_mode()
# 3) Topic
topic = input("\nDebate topic ▶ ").strip()
if not topic:
topic = "Should governments impose strict regulations on AI research?"
print(f"(Default topic selected → {topic})")
if debate_mode == "2":
# User vs AI mode
result = setup_user_vs_ai_debate(model_provider)
if not result:
return
agents, user_goes_first = result
# Get optimization settings (simpler for user debates)
use_length_limits, word_limits = ask_length_limits()
use_rag = ask_rag_preference()
print(f"\n📋 USER vs AI CONFIGURATION:")
print(f" AI Opponents: {len(agents)} agents")
print(f" Turn Order: {'User first' if user_goes_first else 'AI first'}")
print(f" Length Limits: {'✅ ENABLED' if use_length_limits else '❌ DISABLED'}")
print(f" RAG Knowledge: {'✅ ENABLED' if use_rag else '❌ DISABLED'}")
if word_limits:
print(f" Word Limits: Opening({word_limits['opening']['words']}), "
f"Rebuttal({word_limits['rebuttal']['words']}), "
f"Closing({word_limits['closing']['words']})")
input("\nPress <Enter> to begin your debate against AI...")
# Import and run user vs AI controller
from debate.user_vs_ai_controller import UserVsAIController
UserVsAIController(
ai_agents=agents,
topic=topic,
user_goes_first=user_goes_first,
use_length_limits=use_length_limits,
word_limits=word_limits,
use_rag=use_rag
).run()
else:
# Existing AI vs AI mode
agents = choose_agent_creation_method(model_provider)
if len(agents) < 2:
print("Need at least 2 agents for an AI vs AI debate!")
return
# ... rest of existing AI vs AI logic
mode = ask_context_mode()
use_batching = ask_batching_preference()
if use_batching and 'ollama' in model_provider.get_name().lower():
print("⚠️ Batching not supported with Ollama, disabling batching")
use_batching = False
use_length_limits, word_limits = ask_length_limits()
use_rag = ask_rag_preference()
print(f"\n📋 AI vs AI CONFIGURATION:")
print(f" Model Provider: {model_provider.get_name()}")
print(f" Agents: {len(agents)} selected")
print(f" Context Mode: {mode.value.upper()}")
print(f" Batching: {'✅ ENABLED' if use_batching else '❌ DISABLED'}")
print(f" Length Limits: {'✅ ENABLED' if use_length_limits else '❌ DISABLED'}")
print(f" RAG Knowledge: {'✅ ENABLED' if use_rag else '❌ DISABLED'}")
input("\nPress <Enter> to begin the AI debate...")
DebateController(
agents=agents,
topic=topic,
context_mode=mode,
use_batching=use_batching,
use_length_limits=use_length_limits,
word_limits=word_limits,
use_rag=use_rag
).run()
def choose_debate_mode():
"""Let user choose between AI vs AI or User vs AI debate"""
print("\n🎯 DEBATE MODE SELECTION:")
print(" 1 → AI vs AI debate (agents debate each other)")
print(" 2 → User vs AI debate (you debate against AI agents)")
choice = input("Select mode (1-2) [1] ▶ ").strip() or "1"
return choice
def setup_user_vs_ai_debate(model_provider):
"""Setup user vs AI debate configuration"""
print("\n👤 USER vs AI DEBATE SETUP")
print("=" * 40)
# Select AI opponents
agents = choose_agent_creation_method(model_provider)
if len(agents) == 0:
print("❌ Need at least 1 AI opponent!")
return None
print(f"✅ You will debate against {len(agents)} AI opponent(s):")
for agent in agents:
print(f" • {agent.name} ({agent.role}) - {agent.knowledge_domain or 'general'} expert")
# Ask who goes first
print(f"\n🎲 TURN ORDER:")
print(" 1 → You go first (make opening statement)")
print(" 2 → AI goes first (you respond)")
order_choice = input("Who goes first? (1-2) [1] ▶ ").strip() or "1"
user_goes_first = order_choice == "1"
print(f"✅ Order: {'You' if user_goes_first else 'AI'} will go first")
return agents, user_goes_first
if __name__ == "__main__":
run()