shukdevdatta123 commited on
Commit
58b3683
Β·
verified Β·
1 Parent(s): 0fc2023

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -77
app.py CHANGED
@@ -33,18 +33,18 @@ class ReasoningOrchestra:
33
  return f"❌ API key validation failed: {str(e)}"
34
 
35
  def format_text_to_html(self, text: str) -> str:
36
- """Convert text to HTML with proper formatting"""
37
  if not text or text.strip() == "" or text == "No response generated":
38
- return "<p style='color: #666; font-style: italic;'>No content was generated. This might be due to API limitations or model availability issues.</p>"
39
 
40
  # Escape HTML characters first
41
  text = html.escape(text)
42
 
43
- # Convert markdown-style formatting to HTML
44
  # Headers
45
- text = re.sub(r'^### (.*$)', r'<h3>\1</h3>', text, flags=re.MULTILINE)
46
- text = re.sub(r'^## (.*$)', r'<h2>\1</h2>', text, flags=re.MULTILINE)
47
- text = re.sub(r'^# (.*$)', r'<h1>\1</h1>', text, flags=re.MULTILINE)
48
 
49
  # Bold text
50
  text = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', text)
@@ -53,8 +53,8 @@ class ReasoningOrchestra:
53
  text = re.sub(r'\*(.*?)\*', r'<em>\1</em>', text)
54
 
55
  # Code blocks
56
- text = re.sub(r'```(.*?)```', r'<pre><code>\1</code></pre>', text, flags=re.DOTALL)
57
- text = re.sub(r'`(.*?)`', r'<code>\1</code>', text)
58
 
59
  # Lists
60
  lines = text.split('\n')
@@ -65,12 +65,12 @@ class ReasoningOrchestra:
65
  stripped = line.strip()
66
  if stripped.startswith('- ') or stripped.startswith('* '):
67
  if not in_list:
68
- formatted_lines.append('<ul>')
69
  in_list = True
70
  formatted_lines.append(f'<li>{stripped[2:]}</li>')
71
  elif stripped.startswith(('1. ', '2. ', '3. ', '4. ', '5. ', '6. ', '7. ', '8. ', '9. ')):
72
  if not in_list:
73
- formatted_lines.append('<ol>')
74
  in_list = True
75
  formatted_lines.append(f'<li>{stripped[3:]}</li>')
76
  else:
@@ -78,7 +78,7 @@ class ReasoningOrchestra:
78
  formatted_lines.append('</ul>' if any('<li>' in line for line in formatted_lines[-5:]) else '</ol>')
79
  in_list = False
80
  if stripped:
81
- formatted_lines.append(f'<p>{line}</p>')
82
  else:
83
  formatted_lines.append('<br>')
84
 
@@ -93,8 +93,11 @@ class ReasoningOrchestra:
93
  return {"error": "API key not set"}
94
 
95
  prompt = f"""You are the Deep Thinker in a collaborative reasoning system. Your role is to provide thorough, methodical analysis with extensive step-by-step reasoning.
 
96
  Problem: {problem}
 
97
  {f"Additional Context: {context}" if context else ""}
 
98
  Please provide a comprehensive analysis with deep reasoning. Think through all implications, consider multiple angles, and provide detailed step-by-step logic. Be thorough and methodical in your approach."""
99
 
100
  try:
@@ -127,14 +130,18 @@ Please provide a comprehensive analysis with deep reasoning. Think through all i
127
  return {"error": "API key not set"}
128
 
129
  prompt = f"""You are the Quick Strategist in a collaborative reasoning system. Your role is to provide fast, efficient strategic analysis with clear action plans.
 
130
  Problem: {problem}
 
131
  {f"Additional Context: {context}" if context else ""}
 
132
  Please provide a strategic analysis with:
133
  1. Key insights and patterns
134
  2. Practical solutions
135
  3. Implementation priorities
136
  4. Risk assessment
137
  5. Clear next steps
 
138
  Be decisive and solution-focused. Provide concrete, actionable recommendations."""
139
 
140
  try:
@@ -166,8 +173,11 @@ Be decisive and solution-focused. Provide concrete, actionable recommendations."
166
  return {"error": "API key not set"}
167
 
168
  prompt = f"""You are the Detail Detective in a collaborative reasoning system. Your role is to provide meticulous investigation and comprehensive fact-checking.
 
169
  Problem: {problem}
 
170
  {f"Additional Context: {context}" if context else ""}
 
171
  Please conduct a thorough investigation including:
172
  1. Detailed analysis of all aspects
173
  2. Potential edge cases and considerations
@@ -175,10 +185,10 @@ Please conduct a thorough investigation including:
175
  4. Historical context or precedents
176
  5. Comprehensive pros and cons
177
  6. Hidden connections or implications
 
178
  Be extremely thorough and leave no stone unturned. Provide detailed evidence and reasoning for your conclusions."""
179
 
180
  try:
181
- # Try with different parameters for QwQ model
182
  completion = self.client.chat.completions.create(
183
  model="qwen-qwq-32b",
184
  messages=[{"role": "user", "content": prompt}],
@@ -189,7 +199,6 @@ Be extremely thorough and leave no stone unturned. Provide detailed evidence and
189
 
190
  response_content = completion.choices[0].message.content
191
  if not response_content or response_content.strip() == "":
192
- # Fallback: try with a simpler prompt
193
  fallback_prompt = f"Analyze this problem in detail: {problem}"
194
  fallback_completion = self.client.chat.completions.create(
195
  model="qwen-qwq-32b",
@@ -210,7 +219,6 @@ Be extremely thorough and leave no stone unturned. Provide detailed evidence and
210
  "tokens_used": getattr(completion.usage, 'total_tokens', 'N/A') if hasattr(completion, 'usage') and completion.usage else "N/A"
211
  }
212
  except Exception as e:
213
- # If QwQ fails, provide a helpful error message
214
  error_msg = f"Detail Detective error: {str(e)}"
215
  if "model" in str(e).lower() or "not found" in str(e).lower():
216
  error_msg += "\n\nNote: The QwQ model may not be available in your region or may have usage restrictions. You can still use the other models in the orchestra."
@@ -221,7 +229,6 @@ Be extremely thorough and leave no stone unturned. Provide detailed evidence and
221
  if not self.is_api_key_set:
222
  return "API key not set"
223
 
224
- # Extract reasoning content safely with better error handling
225
  def extract_reasoning(result: Dict, model_name: str) -> str:
226
  if result.get('error'):
227
  return f"**{model_name} encountered an issue:** {result['error']}"
@@ -235,13 +242,18 @@ Be extremely thorough and leave no stone unturned. Provide detailed evidence and
235
  detective_reasoning = extract_reasoning(detective_result, "Detail Detective")
236
 
237
  synthesis_prompt = f"""You are the Orchestra Conductor using Llama 3.3 70B Versatile model. You have received analytical perspectives from three different AI reasoning specialists on the same problem. Your job is to synthesize these into a comprehensive, unified solution.
 
238
  ORIGINAL PROBLEM: {original_problem}
 
239
  DEEP THINKER ANALYSIS (🎭 DeepSeek R1):
240
  {deep_reasoning}
 
241
  STRATEGIC ANALYSIS (πŸš€ Qwen3 32B):
242
  {strategic_reasoning}
 
243
  DETECTIVE INVESTIGATION (πŸ” QwQ 32B):
244
  {detective_reasoning}
 
245
  As the Orchestra Conductor, please create a unified synthesis that:
246
  1. Combines the best insights from all available analyses
247
  2. Addresses any gaps where models didn't provide input
@@ -249,7 +261,9 @@ As the Orchestra Conductor, please create a unified synthesis that:
249
  4. Provides a comprehensive final recommendation
250
  5. Highlights where the different reasoning styles complement each other
251
  6. Gives a clear, actionable conclusion
 
252
  If some models didn't provide analysis, work with what's available and note any limitations.
 
253
  Format your response as a well-structured final solution that leverages all available reasoning approaches. Use clear sections and bullet points where appropriate for maximum clarity."""
254
 
255
  try:
@@ -279,15 +293,15 @@ def validate_api_key(api_key: str) -> str:
279
  def run_single_model(problem: str, model_choice: str, context: str = "") -> str:
280
  """Run a single model analysis"""
281
  if not orchestra.is_api_key_set:
282
- return """<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6;">
283
- <h3>❌ API Key Required</h3>
284
- <p>Please set your Groq API key first in the API Configuration section above.</p>
285
  </div>"""
286
 
287
  if not problem.strip():
288
- return """<div style="color: orange; padding: 20px; border: 2px solid orange; border-radius: 10px; background-color: #fff3e6;">
289
- <h3>⚠️ Problem Required</h3>
290
- <p>Please enter a problem to analyze.</p>
291
  </div>"""
292
 
293
  start_time = time.time()
@@ -299,17 +313,17 @@ def run_single_model(problem: str, model_choice: str, context: str = "") -> str:
299
  elif model_choice == "Detail Detective (QwQ 32B)":
300
  result = orchestra.detail_detective_analyze(problem, context)
301
  else:
302
- return """<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6;">
303
- <h3>❌ Invalid Model Selection</h3>
304
- <p>Please select a valid model from the dropdown.</p>
305
  </div>"""
306
 
307
  elapsed_time = time.time() - start_time
308
 
309
  if "error" in result:
310
- return f"""<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6;">
311
- <h3>❌ Error</h3>
312
- <p>{result['error']}</p>
313
  </div>"""
314
 
315
  # Format the response as HTML
@@ -318,11 +332,11 @@ def run_single_model(problem: str, model_choice: str, context: str = "") -> str:
318
  formatted_output = f"""
319
  <div style="border: 2px solid #28a745; border-radius: 15px; padding: 25px; margin: 15px 0; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);">
320
  <div style="display: flex; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid #28a745;">
321
- <h2 style="margin: 0; color: #28a745;">{result['role']}</h2>
322
  </div>
323
 
324
  <div style="background-color: white; padding: 15px; border-radius: 10px; margin-bottom: 20px;">
325
- <div style="display: flex; gap: 20px; font-size: 14px; color: #666;">
326
  <span><strong>Model:</strong> {result['model']}</span>
327
  <span><strong>Analysis Time:</strong> {elapsed_time:.2f} seconds</span>
328
  <span><strong>Timestamp:</strong> {result['timestamp']}</span>
@@ -330,7 +344,7 @@ def run_single_model(problem: str, model_choice: str, context: str = "") -> str:
330
  </div>
331
  </div>
332
 
333
- <div style="background-color: white; padding: 20px; border-radius: 10px; line-height: 1.6;">
334
  {reasoning_html}
335
  </div>
336
  </div>
@@ -341,16 +355,16 @@ def run_single_model(problem: str, model_choice: str, context: str = "") -> str:
341
  def run_full_orchestra(problem: str, context: str = "") -> Tuple[str, str, str, str]:
342
  """Run the full collaborative reasoning orchestra"""
343
  if not orchestra.is_api_key_set:
344
- error_msg = """<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6;">
345
- <h3>❌ API Key Required</h3>
346
- <p>Please set your Groq API key first in the API Configuration section above.</p>
347
  </div>"""
348
  return error_msg, error_msg, error_msg, error_msg
349
 
350
  if not problem.strip():
351
- error_msg = """<div style="color: orange; padding: 20px; border: 2px solid orange; border-radius: 10px; background-color: #fff3e6;">
352
- <h3>⚠️ Problem Required</h3>
353
- <p>Please enter a problem to analyze.</p>
354
  </div>"""
355
  return error_msg, error_msg, error_msg, error_msg
356
 
@@ -368,10 +382,10 @@ def run_full_orchestra(problem: str, context: str = "") -> Tuple[str, str, str,
368
 
369
  def format_result_html(result: Dict, color: str, icon: str) -> str:
370
  if "error" in result:
371
- return f"""<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6;">
372
- <h3>❌ Model Error</h3>
373
- <p>{result['error']}</p>
374
- <p style="font-size: 12px; color: #666; margin-top: 10px;"><em>This model may have restrictions or temporary availability issues. The other models can still provide analysis.</em></p>
375
  </div>"""
376
 
377
  reasoning_html = orchestra.format_text_to_html(result['reasoning'])
@@ -380,17 +394,17 @@ def run_full_orchestra(problem: str, context: str = "") -> Tuple[str, str, str,
380
  <div style="border: 2px solid {color}; border-radius: 15px; padding: 25px; margin: 15px 0; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);">
381
  <div style="display: flex; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid {color};">
382
  <span style="font-size: 24px; margin-right: 10px;">{icon}</span>
383
- <h2 style="margin: 0; color: {color};">{result['model']}</h2>
384
  </div>
385
 
386
  <div style="background-color: white; padding: 15px; border-radius: 10px; margin-bottom: 20px;">
387
- <div style="display: flex; gap: 20px; font-size: 14px; color: #666;">
388
  <span><strong>Timestamp:</strong> {result['timestamp']}</span>
389
  <span><strong>Tokens:</strong> {result['tokens_used']}</span>
390
  </div>
391
  </div>
392
 
393
- <div style="background-color: white; padding: 20px; border-radius: 10px; line-height: 1.6;">
394
  {reasoning_html}
395
  </div>
396
  </div>
@@ -405,10 +419,10 @@ def run_full_orchestra(problem: str, context: str = "") -> Tuple[str, str, str,
405
  <div style="border: 2px solid #dc3545; border-radius: 15px; padding: 25px; margin: 15px 0; background: linear-gradient(135deg, #fff5f5 0%, #fee);">
406
  <div style="display: flex; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid #dc3545;">
407
  <span style="font-size: 24px; margin-right: 10px;">🎼</span>
408
- <h2 style="margin: 0; color: #dc3545;">Orchestra Conductor - Final Synthesis (Llama 3.3 70B Versatile)</h2>
409
  </div>
410
 
411
- <div style="background-color: white; padding: 20px; border-radius: 10px; line-height: 1.6;">
412
  {synthesis_html}
413
  </div>
414
  </div>
@@ -416,38 +430,46 @@ def run_full_orchestra(problem: str, context: str = "") -> Tuple[str, str, str,
416
 
417
  return deep_output, strategic_output, detective_output, synthesis_output
418
 
419
- # Custom CSS for better styling
420
  custom_css = """
421
  .gradio-container {
422
  max-width: 1400px !important;
423
  margin: 0 auto !important;
 
424
  }
 
425
  .api-key-section {
426
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
427
  padding: 20px;
428
  border-radius: 10px;
429
  margin-bottom: 20px;
430
  }
 
431
  .model-section {
432
  border: 2px solid #e1e5e9;
433
  border-radius: 10px;
434
  padding: 15px;
435
  margin: 10px 0;
436
  }
 
437
  .orchestra-header {
438
  text-align: center;
439
  background: linear-gradient(45deg, #f093fb 0%, #f5576c 100%);
440
  padding: 20px;
441
  border-radius: 15px;
442
  margin-bottom: 20px;
 
443
  }
 
444
  .status-box {
445
  background-color: #f8f9fa;
446
  border-left: 4px solid #28a745;
447
  padding: 15px;
448
  margin: 10px 0;
449
  border-radius: 5px;
 
450
  }
 
451
  /* Custom styling for HTML outputs */
452
  .html-content {
453
  max-height: 600px;
@@ -456,6 +478,33 @@ custom_css = """
456
  border-radius: 8px;
457
  padding: 10px;
458
  background-color: #fafafa;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  }
460
  """
461
 
@@ -464,29 +513,31 @@ with gr.Blocks(css=custom_css, title="Reasoning Orchestra") as app:
464
  # Header
465
  gr.HTML("""
466
  <div class="orchestra-header">
467
- <h1>🎼 The Collaborative Reasoning Orchestra</h1>
468
- <p><em>Where AI models collaborate like musicians in an orchestra to solve complex problems</em></p>
469
- <p><strong>Now with Llama 3.3 70B Versatile as Orchestra Conductor & Enhanced HTML-Formatted Responses!</strong></p>
470
  </div>
471
  """)
472
 
473
  # API Key Section
474
  with gr.Group():
475
- gr.HTML('<div class="api-key-section"><h3 style="color: white; margin-top: 0;">πŸ”‘ API Configuration</h3></div>')
476
  with gr.Row():
477
  api_key_input = gr.Textbox(
478
  label="Enter your Groq API Key",
479
  type="password",
480
  placeholder="gsk_...",
481
- info="Get your free API key from https://console.groq.com/keys"
 
482
  )
483
  api_status = gr.Textbox(
484
  label="API Status",
485
  interactive=False,
486
- placeholder="Enter API key to validate..."
 
487
  )
488
 
489
- validate_btn = gr.Button("πŸ” Validate API Key", variant="primary")
490
  validate_btn.click(
491
  fn=validate_api_key,
492
  inputs=[api_key_input],
@@ -505,12 +556,14 @@ with gr.Blocks(css=custom_css, title="Reasoning Orchestra") as app:
505
  single_problem = gr.Textbox(
506
  label="Problem Statement",
507
  placeholder="Enter the problem you want to analyze...",
508
- lines=4
 
509
  )
510
  single_context = gr.Textbox(
511
  label="Additional Context (Optional)",
512
  placeholder="Any additional context or constraints...",
513
- lines=2
 
514
  )
515
  model_choice = gr.Dropdown(
516
  label="Choose Model",
@@ -519,12 +572,13 @@ with gr.Blocks(css=custom_css, title="Reasoning Orchestra") as app:
519
  "Quick Strategist (Qwen3 32B)",
520
  "Detail Detective (QwQ 32B)"
521
  ],
522
- value="Deep Thinker (DeepSeek R1)"
 
523
  )
524
- single_analyze_btn = gr.Button("πŸš€ Analyze with HTML Output", variant="primary", size="lg")
525
 
526
  with gr.Column(scale=2):
527
- single_output = gr.HTML(label="Analysis Result", elem_classes=["html-content"])
528
 
529
  single_analyze_btn.click(
530
  fn=run_single_model,
@@ -542,21 +596,23 @@ with gr.Blocks(css=custom_css, title="Reasoning Orchestra") as app:
542
  orchestra_problem = gr.Textbox(
543
  label="Problem Statement",
544
  placeholder="Enter a complex problem that benefits from multiple reasoning perspectives...",
545
- lines=6
 
546
  )
547
  orchestra_context = gr.Textbox(
548
  label="Additional Context (Optional)",
549
  placeholder="Background information, constraints, or specific requirements...",
550
- lines=3
 
551
  )
552
- orchestra_analyze_btn = gr.Button("🎼 Start Orchestra Analysis", variant="primary", size="lg")
553
 
554
  # Orchestra Results
555
  with gr.Column():
556
- deep_output = gr.HTML(label="🎭 Deep Thinker Analysis", elem_classes=["html-content"])
557
- strategic_output = gr.HTML(label="πŸš€ Quick Strategist Analysis", elem_classes=["html-content"])
558
- detective_output = gr.HTML(label="πŸ” Detail Detective Analysis", elem_classes=["html-content"])
559
- synthesis_output = gr.HTML(label="🎼 Final Orchestrated Solution (Llama 3.3 70B)", elem_classes=["html-content"])
560
 
561
  orchestra_analyze_btn.click(
562
  fn=run_full_orchestra,
@@ -593,30 +649,30 @@ with gr.Blocks(css=custom_css, title="Reasoning Orchestra") as app:
593
 
594
  # Footer
595
  gr.HTML("""
596
- <div style="text-align: center; margin-top: 30px; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white;">
597
- <h3>🎼 How the Orchestra Works</h3>
598
  <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin: 20px 0;">
599
  <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
600
- <h4>🎭 Deep Thinker (DeepSeek R1)</h4>
601
- <p>Provides thorough philosophical and theoretical analysis with comprehensive reasoning chains</p>
602
  </div>
603
  <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
604
- <h4>πŸš€ Quick Strategist (Qwen3 32B)</h4>
605
- <p>Delivers practical strategies, action plans, and rapid decision-making frameworks</p>
606
  </div>
607
  <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
608
- <h4>πŸ” Detail Detective (QwQ 32B)</h4>
609
- <p>Conducts comprehensive investigation, fact-checking, and finds hidden connections</p>
610
  </div>
611
  <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
612
- <h4>🎼 Orchestra Conductor</h4>
613
- <p>Synthesizes all perspectives into unified, comprehensive solutions</p>
614
  </div>
615
  </div>
616
- <p style="margin-top: 20px;"><em>Built with ❀️ using Groq's lightning-fast inference, Gradio, and beautiful HTML formatting</em></p>
617
  </div>
618
  """)
619
 
620
  # Launch the app
621
  if __name__ == "__main__":
622
- app.launch(share=False) # Set share=False for local running; use share=True for public sharing
 
33
  return f"❌ API key validation failed: {str(e)}"
34
 
35
  def format_text_to_html(self, text: str) -> str:
36
+ """Convert text to HTML with proper formatting and consistent font size"""
37
  if not text or text.strip() == "" or text == "No response generated":
38
+ return "<p style='color: #666; font-style: italic; font-size: 16px;'>No content was generated. This might be due to API limitations or model availability issues.</p>"
39
 
40
  # Escape HTML characters first
41
  text = html.escape(text)
42
 
43
+ # Convert markdown-style formatting to HTML with consistent font sizes
44
  # Headers
45
+ text = re.sub(r'^### (.*$)', r'<h3 style="font-size: 18px;">\1</h3>', text, flags=re.MULTILINE)
46
+ text = re.sub(r'^## (.*$)', r'<h2 style="font-size: 20px;">\1</h2>', text, flags=re.MULTILINE)
47
+ text = re.sub(r'^# (.*$)', r'<h1 style="font-size: 22px;">\1</h1>', text, flags=re.MULTILINE)
48
 
49
  # Bold text
50
  text = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', text)
 
53
  text = re.sub(r'\*(.*?)\*', r'<em>\1</em>', text)
54
 
55
  # Code blocks
56
+ text = re.sub(r'```(.*?)```', r'<pre style="font-size: 15px; background: #f5f5f5; padding: 10px; border-radius: 5px;"><code>\1</code></pre>', text, flags=re.DOTALL)
57
+ text = re.sub(r'`(.*?)`', r'<code style="font-size: 15px; background: #f5f5f5; padding: 2px 4px; border-radius: 3px;">\1</code>', text)
58
 
59
  # Lists
60
  lines = text.split('\n')
 
65
  stripped = line.strip()
66
  if stripped.startswith('- ') or stripped.startswith('* '):
67
  if not in_list:
68
+ formatted_lines.append('<ul style="font-size: 16px;">')
69
  in_list = True
70
  formatted_lines.append(f'<li>{stripped[2:]}</li>')
71
  elif stripped.startswith(('1. ', '2. ', '3. ', '4. ', '5. ', '6. ', '7. ', '8. ', '9. ')):
72
  if not in_list:
73
+ formatted_lines.append('<ol style="font-size: 16px;">')
74
  in_list = True
75
  formatted_lines.append(f'<li>{stripped[3:]}</li>')
76
  else:
 
78
  formatted_lines.append('</ul>' if any('<li>' in line for line in formatted_lines[-5:]) else '</ol>')
79
  in_list = False
80
  if stripped:
81
+ formatted_lines.append(f'<p style="font-size: 16px; margin: 8px 0;">{line}</p>')
82
  else:
83
  formatted_lines.append('<br>')
84
 
 
93
  return {"error": "API key not set"}
94
 
95
  prompt = f"""You are the Deep Thinker in a collaborative reasoning system. Your role is to provide thorough, methodical analysis with extensive step-by-step reasoning.
96
+
97
  Problem: {problem}
98
+
99
  {f"Additional Context: {context}" if context else ""}
100
+
101
  Please provide a comprehensive analysis with deep reasoning. Think through all implications, consider multiple angles, and provide detailed step-by-step logic. Be thorough and methodical in your approach."""
102
 
103
  try:
 
130
  return {"error": "API key not set"}
131
 
132
  prompt = f"""You are the Quick Strategist in a collaborative reasoning system. Your role is to provide fast, efficient strategic analysis with clear action plans.
133
+
134
  Problem: {problem}
135
+
136
  {f"Additional Context: {context}" if context else ""}
137
+
138
  Please provide a strategic analysis with:
139
  1. Key insights and patterns
140
  2. Practical solutions
141
  3. Implementation priorities
142
  4. Risk assessment
143
  5. Clear next steps
144
+
145
  Be decisive and solution-focused. Provide concrete, actionable recommendations."""
146
 
147
  try:
 
173
  return {"error": "API key not set"}
174
 
175
  prompt = f"""You are the Detail Detective in a collaborative reasoning system. Your role is to provide meticulous investigation and comprehensive fact-checking.
176
+
177
  Problem: {problem}
178
+
179
  {f"Additional Context: {context}" if context else ""}
180
+
181
  Please conduct a thorough investigation including:
182
  1. Detailed analysis of all aspects
183
  2. Potential edge cases and considerations
 
185
  4. Historical context or precedents
186
  5. Comprehensive pros and cons
187
  6. Hidden connections or implications
188
+
189
  Be extremely thorough and leave no stone unturned. Provide detailed evidence and reasoning for your conclusions."""
190
 
191
  try:
 
192
  completion = self.client.chat.completions.create(
193
  model="qwen-qwq-32b",
194
  messages=[{"role": "user", "content": prompt}],
 
199
 
200
  response_content = completion.choices[0].message.content
201
  if not response_content or response_content.strip() == "":
 
202
  fallback_prompt = f"Analyze this problem in detail: {problem}"
203
  fallback_completion = self.client.chat.completions.create(
204
  model="qwen-qwq-32b",
 
219
  "tokens_used": getattr(completion.usage, 'total_tokens', 'N/A') if hasattr(completion, 'usage') and completion.usage else "N/A"
220
  }
221
  except Exception as e:
 
222
  error_msg = f"Detail Detective error: {str(e)}"
223
  if "model" in str(e).lower() or "not found" in str(e).lower():
224
  error_msg += "\n\nNote: The QwQ model may not be available in your region or may have usage restrictions. You can still use the other models in the orchestra."
 
229
  if not self.is_api_key_set:
230
  return "API key not set"
231
 
 
232
  def extract_reasoning(result: Dict, model_name: str) -> str:
233
  if result.get('error'):
234
  return f"**{model_name} encountered an issue:** {result['error']}"
 
242
  detective_reasoning = extract_reasoning(detective_result, "Detail Detective")
243
 
244
  synthesis_prompt = f"""You are the Orchestra Conductor using Llama 3.3 70B Versatile model. You have received analytical perspectives from three different AI reasoning specialists on the same problem. Your job is to synthesize these into a comprehensive, unified solution.
245
+
246
  ORIGINAL PROBLEM: {original_problem}
247
+
248
  DEEP THINKER ANALYSIS (🎭 DeepSeek R1):
249
  {deep_reasoning}
250
+
251
  STRATEGIC ANALYSIS (πŸš€ Qwen3 32B):
252
  {strategic_reasoning}
253
+
254
  DETECTIVE INVESTIGATION (πŸ” QwQ 32B):
255
  {detective_reasoning}
256
+
257
  As the Orchestra Conductor, please create a unified synthesis that:
258
  1. Combines the best insights from all available analyses
259
  2. Addresses any gaps where models didn't provide input
 
261
  4. Provides a comprehensive final recommendation
262
  5. Highlights where the different reasoning styles complement each other
263
  6. Gives a clear, actionable conclusion
264
+
265
  If some models didn't provide analysis, work with what's available and note any limitations.
266
+
267
  Format your response as a well-structured final solution that leverages all available reasoning approaches. Use clear sections and bullet points where appropriate for maximum clarity."""
268
 
269
  try:
 
293
  def run_single_model(problem: str, model_choice: str, context: str = "") -> str:
294
  """Run a single model analysis"""
295
  if not orchestra.is_api_key_set:
296
+ return """<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6; font-size: 16px;">
297
+ <h3 style="font-size: 18px;">❌ API Key Required</h3>
298
+ <p style="font-size: 16px;">Please set your Groq API key first in the API Configuration section above.</p>
299
  </div>"""
300
 
301
  if not problem.strip():
302
+ return """<div style="color: orange; padding: 20px; border: 2px solid orange; border-radius: 10px; background-color: #fff3e6; font-size: 16px;">
303
+ <h3 style="font-size: 18px;">⚠️ Problem Required</h3>
304
+ <p style="font-size: 16px;">Please enter a problem to analyze.</p>
305
  </div>"""
306
 
307
  start_time = time.time()
 
313
  elif model_choice == "Detail Detective (QwQ 32B)":
314
  result = orchestra.detail_detective_analyze(problem, context)
315
  else:
316
+ return """<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6; font-size: 16px;">
317
+ <h3 style="font-size: 18px;">❌ Invalid Model Selection</h3>
318
+ <p style="font-size: 16px;">Please select a valid model from the dropdown.</p>
319
  </div>"""
320
 
321
  elapsed_time = time.time() - start_time
322
 
323
  if "error" in result:
324
+ return f"""<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6; font-size: 16px;">
325
+ <h3 style="font-size: 18px;">❌ Error</h3>
326
+ <p style="font-size: 16px;">{result['error']}</p>
327
  </div>"""
328
 
329
  # Format the response as HTML
 
332
  formatted_output = f"""
333
  <div style="border: 2px solid #28a745; border-radius: 15px; padding: 25px; margin: 15px 0; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);">
334
  <div style="display: flex; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid #28a745;">
335
+ <h2 style="margin: 0; color: #28a745; font-size: 22px;">{result['role']}</h2>
336
  </div>
337
 
338
  <div style="background-color: white; padding: 15px; border-radius: 10px; margin-bottom: 20px;">
339
+ <div style="display: flex; gap: 20px; font-size: 16px; color: #666;">
340
  <span><strong>Model:</strong> {result['model']}</span>
341
  <span><strong>Analysis Time:</strong> {elapsed_time:.2f} seconds</span>
342
  <span><strong>Timestamp:</strong> {result['timestamp']}</span>
 
344
  </div>
345
  </div>
346
 
347
+ <div style="background-color: white; padding: 20px; border-radius: 10px; line-height: 1.6; font-size: 16px;">
348
  {reasoning_html}
349
  </div>
350
  </div>
 
355
  def run_full_orchestra(problem: str, context: str = "") -> Tuple[str, str, str, str]:
356
  """Run the full collaborative reasoning orchestra"""
357
  if not orchestra.is_api_key_set:
358
+ error_msg = """<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6; font-size: 16px;">
359
+ <h3 style="font-size: 18px;">❌ API Key Required</h3>
360
+ <p style="font-size: 16px;">Please set your Groq API key first in the API Configuration section above.</p>
361
  </div>"""
362
  return error_msg, error_msg, error_msg, error_msg
363
 
364
  if not problem.strip():
365
+ error_msg = """<div style="color: orange; padding: 20px; border: 2px solid orange; border-radius: 10px; background-color: #fff3e6; font-size: 16px;">
366
+ <h3 style="font-size: 18px;">⚠️ Problem Required</h3>
367
+ <p style="font-size: 16px;">Please enter a problem to analyze.</p>
368
  </div>"""
369
  return error_msg, error_msg, error_msg, error_msg
370
 
 
382
 
383
  def format_result_html(result: Dict, color: str, icon: str) -> str:
384
  if "error" in result:
385
+ return f"""<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6; font-size: 16px;">
386
+ <h3 style="font-size: 18px;">❌ Model Error</h3>
387
+ <p style="font-size: 16px;">{result['error']}</p>
388
+ <p style="font-size: 14px; color: #666; margin-top: 10px;"><em>This model may have restrictions or temporary availability issues. The other models can still provide analysis.</em></p>
389
  </div>"""
390
 
391
  reasoning_html = orchestra.format_text_to_html(result['reasoning'])
 
394
  <div style="border: 2px solid {color}; border-radius: 15px; padding: 25px; margin: 15px 0; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);">
395
  <div style="display: flex; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid {color};">
396
  <span style="font-size: 24px; margin-right: 10px;">{icon}</span>
397
+ <h2 style="margin: 0; color: {color}; font-size: 22px;">{result['model']}</h2>
398
  </div>
399
 
400
  <div style="background-color: white; padding: 15px; border-radius: 10px; margin-bottom: 20px;">
401
+ <div style="display: flex; gap: 20px; font-size: 16px; color: #666;">
402
  <span><strong>Timestamp:</strong> {result['timestamp']}</span>
403
  <span><strong>Tokens:</strong> {result['tokens_used']}</span>
404
  </div>
405
  </div>
406
 
407
+ <div style="background-color: white; padding: 20px; border-radius: 10px; line-height: 1.6; font-size: 16px;">
408
  {reasoning_html}
409
  </div>
410
  </div>
 
419
  <div style="border: 2px solid #dc3545; border-radius: 15px; padding: 25px; margin: 15px 0; background: linear-gradient(135deg, #fff5f5 0%, #fee);">
420
  <div style="display: flex; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid #dc3545;">
421
  <span style="font-size: 24px; margin-right: 10px;">🎼</span>
422
+ <h2 style="margin: 0; color: #dc3545; font-size: 22px;">Orchestra Conductor - Final Synthesis (Llama 3.3 70B Versatile)</h2>
423
  </div>
424
 
425
+ <div style="background-color: white; padding: 20px; border-radius: 10px; line-height: 1.6; font-size: 16px;">
426
  {synthesis_html}
427
  </div>
428
  </div>
 
430
 
431
  return deep_output, strategic_output, detective_output, synthesis_output
432
 
433
+ # Custom CSS for better styling with consistent font sizes
434
  custom_css = """
435
  .gradio-container {
436
  max-width: 1400px !important;
437
  margin: 0 auto !important;
438
+ font-size: 16px !important;
439
  }
440
+
441
  .api-key-section {
442
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
443
  padding: 20px;
444
  border-radius: 10px;
445
  margin-bottom: 20px;
446
  }
447
+
448
  .model-section {
449
  border: 2px solid #e1e5e9;
450
  border-radius: 10px;
451
  padding: 15px;
452
  margin: 10px 0;
453
  }
454
+
455
  .orchestra-header {
456
  text-align: center;
457
  background: linear-gradient(45deg, #f093fb 0%, #f5576c 100%);
458
  padding: 20px;
459
  border-radius: 15px;
460
  margin-bottom: 20px;
461
+ font-size: 16px;
462
  }
463
+
464
  .status-box {
465
  background-color: #f8f9fa;
466
  border-left: 4px solid #28a745;
467
  padding: 15px;
468
  margin: 10px 0;
469
  border-radius: 5px;
470
+ font-size: 16px;
471
  }
472
+
473
  /* Custom styling for HTML outputs */
474
  .html-content {
475
  max-height: 600px;
 
478
  border-radius: 8px;
479
  padding: 10px;
480
  background-color: #fafafa;
481
+ font-size: 16px !important;
482
+ }
483
+
484
+ /* Ensure all text has consistent font size */
485
+ p, li, span, div, textarea, input, select, button {
486
+ font-size: 16px !important;
487
+ }
488
+
489
+ h1 {
490
+ font-size: 24px !important;
491
+ }
492
+
493
+ h2 {
494
+ font-size: 22px !important;
495
+ }
496
+
497
+ h3 {
498
+ font-size: 20px !important;
499
+ }
500
+
501
+ h4 {
502
+ font-size: 18px !important;
503
+ }
504
+
505
+ /* Make sure code blocks are readable */
506
+ pre, code {
507
+ font-size: 15px !important;
508
  }
509
  """
510
 
 
513
  # Header
514
  gr.HTML("""
515
  <div class="orchestra-header">
516
+ <h1 style="font-size: 28px;">🎼 The Collaborative Reasoning Orchestra</h1>
517
+ <p style="font-size: 18px;"><em>Where AI models collaborate like musicians in an orchestra to solve complex problems</em></p>
518
+ <p style="font-size: 18px;"><strong>Now with Llama 3.3 70B Versatile as Orchestra Conductor & Enhanced HTML-Formatted Responses!</strong></p>
519
  </div>
520
  """)
521
 
522
  # API Key Section
523
  with gr.Group():
524
+ gr.HTML('<div class="api-key-section"><h3 style="color: white; margin-top: 0; font-size: 20px;">πŸ”‘ API Configuration</h3></div>')
525
  with gr.Row():
526
  api_key_input = gr.Textbox(
527
  label="Enter your Groq API Key",
528
  type="password",
529
  placeholder="gsk_...",
530
+ info="Get your free API key from https://console.groq.com/keys",
531
+ elem_id="api_key_input"
532
  )
533
  api_status = gr.Textbox(
534
  label="API Status",
535
  interactive=False,
536
+ placeholder="Enter API key to validate...",
537
+ elem_id="api_status"
538
  )
539
 
540
+ validate_btn = gr.Button("πŸ” Validate API Key", variant="primary", elem_id="validate_btn")
541
  validate_btn.click(
542
  fn=validate_api_key,
543
  inputs=[api_key_input],
 
556
  single_problem = gr.Textbox(
557
  label="Problem Statement",
558
  placeholder="Enter the problem you want to analyze...",
559
+ lines=4,
560
+ elem_id="single_problem"
561
  )
562
  single_context = gr.Textbox(
563
  label="Additional Context (Optional)",
564
  placeholder="Any additional context or constraints...",
565
+ lines=2,
566
+ elem_id="single_context"
567
  )
568
  model_choice = gr.Dropdown(
569
  label="Choose Model",
 
572
  "Quick Strategist (Qwen3 32B)",
573
  "Detail Detective (QwQ 32B)"
574
  ],
575
+ value="Deep Thinker (DeepSeek R1)",
576
+ elem_id="model_choice"
577
  )
578
+ single_analyze_btn = gr.Button("πŸš€ Analyze with HTML Output", variant="primary", size="lg", elem_id="single_analyze_btn")
579
 
580
  with gr.Column(scale=2):
581
+ single_output = gr.HTML(label="Analysis Result", elem_classes=["html-content"], elem_id="single_output")
582
 
583
  single_analyze_btn.click(
584
  fn=run_single_model,
 
596
  orchestra_problem = gr.Textbox(
597
  label="Problem Statement",
598
  placeholder="Enter a complex problem that benefits from multiple reasoning perspectives...",
599
+ lines=6,
600
+ elem_id="orchestra_problem"
601
  )
602
  orchestra_context = gr.Textbox(
603
  label="Additional Context (Optional)",
604
  placeholder="Background information, constraints, or specific requirements...",
605
+ lines=3,
606
+ elem_id="orchestra_context"
607
  )
608
+ orchestra_analyze_btn = gr.Button("🎼 Start Orchestra Analysis", variant="primary", size="lg", elem_id="orchestra_analyze_btn")
609
 
610
  # Orchestra Results
611
  with gr.Column():
612
+ deep_output = gr.HTML(label="🎭 Deep Thinker Analysis", elem_classes=["html-content"], elem_id="deep_output")
613
+ strategic_output = gr.HTML(label="πŸš€ Quick Strategist Analysis", elem_classes=["html-content"], elem_id="strategic_output")
614
+ detective_output = gr.HTML(label="πŸ” Detail Detective Analysis", elem_classes=["html-content"], elem_id="detective_output")
615
+ synthesis_output = gr.HTML(label="🎼 Final Orchestrated Solution (Llama 3.3 70B)", elem_classes=["html-content"], elem_id="synthesis_output")
616
 
617
  orchestra_analyze_btn.click(
618
  fn=run_full_orchestra,
 
649
 
650
  # Footer
651
  gr.HTML("""
652
+ <div style="text-align: center; margin-top: 30px; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white; font-size: 16px;">
653
+ <h3 style="font-size: 22px;">🎼 How the Orchestra Works</h3>
654
  <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin: 20px 0;">
655
  <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
656
+ <h4 style="font-size: 18px;">🎭 Deep Thinker (DeepSeek R1)</h4>
657
+ <p style="font-size: 16px;">Provides thorough philosophical and theoretical analysis with comprehensive reasoning chains</p>
658
  </div>
659
  <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
660
+ <h4 style="font-size: 18px;">πŸš€ Quick Strategist (Qwen3 32B)</h4>
661
+ <p style="font-size: 16px;">Delivers practical strategies, action plans, and rapid decision-making frameworks</p>
662
  </div>
663
  <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
664
+ <h4 style="font-size: 18px;">πŸ” Detail Detective (QwQ 32B)</h4>
665
+ <p style="font-size: 16px;">Conducts comprehensive investigation, fact-checking, and finds hidden connections</p>
666
  </div>
667
  <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
668
+ <h4 style="font-size: 18px;">🎼 Orchestra Conductor</h4>
669
+ <p style="font-size: 16px;">Synthesizes all perspectives into unified, comprehensive solutions</p>
670
  </div>
671
  </div>
672
+ <p style="margin-top: 20px; font-size: 16px;"><em>Built with ❀️ using Groq's lightning-fast inference, Gradio, and beautiful HTML formatting</em></p>
673
  </div>
674
  """)
675
 
676
  # Launch the app
677
  if __name__ == "__main__":
678
+ app.launch(share=False)