shukdevdatta123 commited on
Commit
90b5a30
Β·
verified Β·
1 Parent(s): eafcdfe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +256 -104
app.py CHANGED
@@ -5,6 +5,8 @@ import time
5
  from typing import Dict, List, Tuple, Optional
6
  import threading
7
  from datetime import datetime
 
 
8
 
9
  class ReasoningOrchestra:
10
  def __init__(self):
@@ -30,6 +32,61 @@ class ReasoningOrchestra:
30
  self.is_api_key_set = False
31
  return f"❌ API key validation failed: {str(e)}"
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  def deep_thinker_analyze(self, problem: str, context: str = "") -> Dict:
34
  """DeepSeek R1 - The Deep Thinker"""
35
  if not self.is_api_key_set:
@@ -40,26 +97,26 @@ class ReasoningOrchestra:
40
  Problem: {problem}
41
  {f"Additional Context: {context}" if context else ""}
42
 
43
- Please provide a comprehensive analysis with deep reasoning. Think through all implications, consider multiple angles, and provide detailed step-by-step logic."""
44
 
45
  try:
46
  completion = self.client.chat.completions.create(
47
  model="deepseek-r1-distill-llama-70b",
48
  messages=[{"role": "user", "content": prompt}],
49
  temperature=0.6,
50
- max_completion_tokens=4096,
51
  top_p=0.95,
52
  reasoning_format="raw"
53
  )
54
 
55
- response_content = completion.choices[0].message.content
56
 
57
  return {
58
  "model": "DeepSeek R1 (Deep Thinker)",
59
  "role": "🎭 The Philosopher & Deep Analyzer",
60
  "reasoning": response_content,
61
  "timestamp": datetime.now().strftime("%H:%M:%S"),
62
- "tokens_used": completion.usage.total_tokens if hasattr(completion, 'usage') else "N/A"
63
  }
64
  except Exception as e:
65
  return {"error": f"Deep Thinker error: {str(e)}"}
@@ -81,7 +138,7 @@ Please provide a strategic analysis with:
81
  4. Risk assessment
82
  5. Clear next steps
83
 
84
- Be decisive and solution-focused."""
85
 
86
  try:
87
  completion = self.client.chat.completions.create(
@@ -89,16 +146,18 @@ Be decisive and solution-focused."""
89
  messages=[{"role": "user", "content": prompt}],
90
  temperature=0.6,
91
  top_p=0.95,
92
- max_completion_tokens=4096,
93
  reasoning_effort="default"
94
  )
95
 
 
 
96
  return {
97
  "model": "Qwen3 32B (Quick Strategist)",
98
  "role": "πŸš€ The Strategic Decision Maker",
99
- "reasoning": completion.choices[0].message.content,
100
  "timestamp": datetime.now().strftime("%H:%M:%S"),
101
- "tokens_used": completion.usage.total_tokens if hasattr(completion, 'usage') else "N/A"
102
  }
103
  except Exception as e:
104
  return {"error": f"Quick Strategist error: {str(e)}"}
@@ -121,7 +180,7 @@ Please conduct a thorough investigation including:
121
  5. Comprehensive pros and cons
122
  6. Hidden connections or implications
123
 
124
- Be extremely thorough and leave no stone unturned."""
125
 
126
  try:
127
  completion = self.client.chat.completions.create(
@@ -129,16 +188,18 @@ Be extremely thorough and leave no stone unturned."""
129
  messages=[{"role": "user", "content": prompt}],
130
  temperature=0.6,
131
  top_p=0.95,
132
- max_completion_tokens=4096,
133
  reasoning_format="parsed"
134
  )
135
 
 
 
136
  return {
137
  "model": "QwQ 32B (Detail Detective)",
138
  "role": "πŸ” The Meticulous Investigator",
139
- "reasoning": completion.choices[0].message.content,
140
  "timestamp": datetime.now().strftime("%H:%M:%S"),
141
- "tokens_used": completion.usage.total_tokens if hasattr(completion, 'usage') else "N/A"
142
  }
143
  except Exception as e:
144
  return {"error": f"Detail Detective error: {str(e)}"}
@@ -148,18 +209,23 @@ Be extremely thorough and leave no stone unturned."""
148
  if not self.is_api_key_set:
149
  return "API key not set"
150
 
 
 
 
 
 
151
  synthesis_prompt = f"""You are the Orchestra Conductor. You have received three different analytical perspectives on the same problem. Your job is to synthesize these into a comprehensive, unified solution.
152
 
153
  ORIGINAL PROBLEM: {original_problem}
154
 
155
  DEEP THINKER ANALYSIS:
156
- {deep_result.get('reasoning', 'No analysis available')}
157
 
158
  STRATEGIC ANALYSIS:
159
- {strategic_result.get('reasoning', 'No analysis available')}
160
 
161
  DETECTIVE INVESTIGATION:
162
- {detective_result.get('reasoning', 'No analysis available')}
163
 
164
  Please create a unified synthesis that:
165
  1. Combines the best insights from all three perspectives
@@ -175,11 +241,11 @@ Format your response as a well-structured final solution that leverages all thre
175
  model="qwen/qwen3-32b",
176
  messages=[{"role": "user", "content": synthesis_prompt}],
177
  temperature=0.7,
178
- max_completion_tokens=4096,
179
  top_p=0.9
180
  )
181
 
182
- return completion.choices[0].message.content
183
  except Exception as e:
184
  return f"Synthesis error: {str(e)}"
185
 
@@ -190,16 +256,28 @@ def validate_api_key(api_key: str) -> str:
190
  """Validate the API key and return status"""
191
  return orchestra.set_api_key(api_key)
192
 
193
- def run_single_model(problem: str, model_choice: str, context: str = "") -> Tuple[str, str]:
194
  """Run a single model analysis"""
195
  if not orchestra.is_api_key_set:
196
- return "❌ Please set your API key first", ""
 
 
 
197
 
198
  if not problem.strip():
199
- return "❌ Please enter a problem to analyze", ""
 
 
 
200
 
201
  start_time = time.time()
202
 
 
 
 
 
 
 
203
  if model_choice == "Deep Thinker (DeepSeek R1)":
204
  result = orchestra.deep_thinker_analyze(problem, context)
205
  elif model_choice == "Quick Strategist (Qwen3 32B)":
@@ -207,81 +285,127 @@ def run_single_model(problem: str, model_choice: str, context: str = "") -> Tupl
207
  elif model_choice == "Detail Detective (QwQ 32B)":
208
  result = orchestra.detail_detective_analyze(problem, context)
209
  else:
210
- return "❌ Invalid model selection", ""
 
 
 
211
 
212
  elapsed_time = time.time() - start_time
213
 
214
  if "error" in result:
215
- return f"❌ {result['error']}", ""
 
 
 
216
 
217
- formatted_output = f"""## {result['role']} - {result['model']}
218
- **Analysis Time:** {elapsed_time:.2f} seconds | **Timestamp:** {result['timestamp']} | **Tokens:** {result['tokens_used']}
219
-
220
- ---
221
-
222
- {result['reasoning']}
223
- """
224
 
225
- return formatted_output, ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
 
227
  def run_full_orchestra(problem: str, context: str = "") -> Tuple[str, str, str, str]:
228
  """Run the full collaborative reasoning orchestra"""
229
  if not orchestra.is_api_key_set:
230
- error_msg = "❌ Please set your API key first"
 
 
 
231
  return error_msg, error_msg, error_msg, error_msg
232
 
233
  if not problem.strip():
234
- error_msg = "❌ Please enter a problem to analyze"
 
 
 
235
  return error_msg, error_msg, error_msg, error_msg
236
 
237
- status_updates = []
238
-
239
  # Phase 1: Deep Thinker
240
- status_updates.append("🎭 Deep Thinker is analyzing the problem...")
241
  deep_result = orchestra.deep_thinker_analyze(problem, context)
242
 
243
  # Phase 2: Quick Strategist
244
- status_updates.append("πŸš€ Quick Strategist is developing strategies...")
245
  strategic_result = orchestra.quick_strategist_analyze(problem, context)
246
 
247
  # Phase 3: Detail Detective
248
- status_updates.append("πŸ” Detail Detective is investigating thoroughly...")
249
  detective_result = orchestra.detail_detective_analyze(problem, context)
250
 
251
  # Phase 4: Synthesis
252
- status_updates.append("🎼 Orchestra Conductor is synthesizing all perspectives...")
253
  synthesis = orchestra.synthesize_orchestra(deep_result, strategic_result, detective_result, problem)
254
 
255
- # Format outputs
256
- def format_result(result: Dict) -> str:
257
  if "error" in result:
258
- return f"❌ {result['error']}"
 
 
 
259
 
260
- return f"""## {result['role']} - {result['model']}
261
- **Timestamp:** {result['timestamp']} | **Tokens:** {result['tokens_used']}
262
-
263
- ---
264
-
265
- {result['reasoning']}
266
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
 
268
- deep_output = format_result(deep_result)
269
- strategic_output = format_result(strategic_result)
270
- detective_output = format_result(detective_result)
271
 
272
- synthesis_output = f"""## 🎼 Orchestra Conductor - Final Synthesis
273
-
274
- ---
275
-
276
- {synthesis}
277
- """
 
 
 
 
 
 
 
278
 
279
  return deep_output, strategic_output, detective_output, synthesis_output
280
 
281
  # Custom CSS for better styling
282
  custom_css = """
283
  .gradio-container {
284
- max-width: 1200px !important;
 
285
  }
286
  .api-key-section {
287
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
@@ -309,6 +433,15 @@ custom_css = """
309
  margin: 10px 0;
310
  border-radius: 5px;
311
  }
 
 
 
 
 
 
 
 
 
312
  """
313
 
314
  # Build the Gradio interface
@@ -318,6 +451,7 @@ with gr.Blocks(css=custom_css, title="Reasoning Orchestra") as app:
318
  <div class="orchestra-header">
319
  <h1>🎼 The Collaborative Reasoning Orchestra</h1>
320
  <p><em>Where AI models collaborate like musicians in an orchestra to solve complex problems</em></p>
 
321
  </div>
322
  """)
323
 
@@ -349,10 +483,10 @@ with gr.Blocks(css=custom_css, title="Reasoning Orchestra") as app:
349
 
350
  # Single Model Tab
351
  with gr.TabItem("🎯 Single Model Analysis"):
352
- gr.Markdown("### Test individual reasoning models")
353
 
354
  with gr.Row():
355
- with gr.Column():
356
  single_problem = gr.Textbox(
357
  label="Problem Statement",
358
  placeholder="Enter the problem you want to analyze...",
@@ -372,47 +506,42 @@ with gr.Blocks(css=custom_css, title="Reasoning Orchestra") as app:
372
  ],
373
  value="Deep Thinker (DeepSeek R1)"
374
  )
375
- single_analyze_btn = gr.Button("πŸš€ Analyze", variant="primary")
376
 
377
- with gr.Column():
378
- single_output = gr.Markdown(label="Analysis Result")
379
 
380
  single_analyze_btn.click(
381
  fn=run_single_model,
382
  inputs=[single_problem, model_choice, single_context],
383
- outputs=[single_output, gr.Textbox(visible=False)]
384
  )
385
 
386
  # Full Orchestra Tab
387
  with gr.TabItem("🎼 Full Orchestra Collaboration"):
388
- gr.Markdown("### Run all three models collaboratively for comprehensive analysis")
389
 
390
- with gr.Row():
391
- with gr.Column(scale=1):
392
- orchestra_problem = gr.Textbox(
393
- label="Problem Statement",
394
- placeholder="Enter a complex problem that benefits from multiple reasoning perspectives...",
395
- lines=6
396
- )
397
- orchestra_context = gr.Textbox(
398
- label="Additional Context (Optional)",
399
- placeholder="Background information, constraints, or specific requirements...",
400
- lines=3
401
- )
402
- orchestra_analyze_btn = gr.Button("🎼 Start Orchestra Analysis", variant="primary", size="lg")
 
403
 
404
- with gr.Column(scale=2):
405
- gr.Markdown("### 🎭 Deep Thinker Analysis")
406
- deep_output = gr.Markdown()
407
-
408
- gr.Markdown("### πŸš€ Quick Strategist Analysis")
409
- strategic_output = gr.Markdown()
410
-
411
- gr.Markdown("### πŸ” Detail Detective Analysis")
412
- detective_output = gr.Markdown()
413
-
414
- gr.Markdown("### 🎼 Final Orchestrated Solution")
415
- synthesis_output = gr.Markdown()
416
 
417
  orchestra_analyze_btn.click(
418
  fn=run_full_orchestra,
@@ -426,34 +555,57 @@ with gr.Blocks(css=custom_css, title="Reasoning Orchestra") as app:
426
  ### Try these example problems to see the Orchestra in action:
427
 
428
  **🏒 Business Strategy:**
429
- "Our tech startup has limited funding and needs to decide between focusing on product development or marketing. We have a working MVP but low user adoption."
430
 
431
  **πŸ€– Ethical AI:**
432
- "Should autonomous vehicles prioritize passenger safety over pedestrian safety in unavoidable accident scenarios? Consider the ethical, legal, and practical implications."
433
 
434
  **🌍 Environmental Policy:**
435
- "Design a policy framework to reduce carbon emissions in urban areas while maintaining economic growth and social equity."
436
 
437
  **🧬 Scientific Research:**
438
- "We've discovered a potential breakthrough in gene therapy, but it requires human trials. How should we proceed given the risks, benefits, and regulatory requirements?"
439
 
440
  **πŸŽ“ Educational Innovation:**
441
- "How can we redesign traditional university education to better prepare students for the rapidly changing job market of the 2030s?"
442
 
443
  **🏠 Urban Planning:**
444
- "A city wants to build affordable housing but faces opposition from current residents, environmental concerns, and budget constraints. Develop a comprehensive solution."
 
 
 
445
  """)
 
 
 
 
 
 
 
446
 
447
  # Footer
448
  gr.HTML("""
449
- <div style="text-align: center; margin-top: 30px; padding: 20px; background-color: #f8f9fa; border-radius: 10px;">
450
- <h4>🎼 How the Orchestra Works</h4>
451
- <p><strong>Deep Thinker (DeepSeek R1):</strong> Provides thorough philosophical and theoretical analysis</p>
452
- <p><strong>Quick Strategist (Qwen3 32B):</strong> Delivers practical strategies and action plans</p>
453
- <p><strong>Detail Detective (QwQ 32B):</strong> Conducts comprehensive investigation and fact-checking</p>
454
- <p><strong>Orchestra Conductor:</strong> Synthesizes all perspectives into a unified solution</p>
455
- <br>
456
- <p><em>Built with ❀️ using Groq's lightning-fast inference and Gradio</em></p>
 
 
 
 
 
 
 
 
 
 
 
 
 
457
  </div>
458
  """)
459
 
 
5
  from typing import Dict, List, Tuple, Optional
6
  import threading
7
  from datetime import datetime
8
+ import html
9
+ import re
10
 
11
  class ReasoningOrchestra:
12
  def __init__(self):
 
32
  self.is_api_key_set = False
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:
38
+ return "<p>No content available</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)
51
+
52
+ # Italic text
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')
61
+ in_list = False
62
+ formatted_lines = []
63
+
64
+ for line in lines:
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:
77
+ if in_list:
78
+ formatted_lines.append('</ul>' if formatted_lines[-2].startswith('<li>') 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
+
85
+ if in_list:
86
+ formatted_lines.append('</ul>')
87
+
88
+ return '\n'.join(formatted_lines)
89
+
90
  def deep_thinker_analyze(self, problem: str, context: str = "") -> Dict:
91
  """DeepSeek R1 - The Deep Thinker"""
92
  if not self.is_api_key_set:
 
97
  Problem: {problem}
98
  {f"Additional Context: {context}" if context else ""}
99
 
100
+ 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."""
101
 
102
  try:
103
  completion = self.client.chat.completions.create(
104
  model="deepseek-r1-distill-llama-70b",
105
  messages=[{"role": "user", "content": prompt}],
106
  temperature=0.6,
107
+ max_completion_tokens=2048,
108
  top_p=0.95,
109
  reasoning_format="raw"
110
  )
111
 
112
+ response_content = completion.choices[0].message.content or "No response generated"
113
 
114
  return {
115
  "model": "DeepSeek R1 (Deep Thinker)",
116
  "role": "🎭 The Philosopher & Deep Analyzer",
117
  "reasoning": response_content,
118
  "timestamp": datetime.now().strftime("%H:%M:%S"),
119
+ "tokens_used": getattr(completion.usage, 'total_tokens', 'N/A') if hasattr(completion, 'usage') and completion.usage else "N/A"
120
  }
121
  except Exception as e:
122
  return {"error": f"Deep Thinker error: {str(e)}"}
 
138
  4. Risk assessment
139
  5. Clear next steps
140
 
141
+ Be decisive and solution-focused. Provide concrete, actionable recommendations."""
142
 
143
  try:
144
  completion = self.client.chat.completions.create(
 
146
  messages=[{"role": "user", "content": prompt}],
147
  temperature=0.6,
148
  top_p=0.95,
149
+ max_completion_tokens=1536,
150
  reasoning_effort="default"
151
  )
152
 
153
+ response_content = completion.choices[0].message.content or "No response generated"
154
+
155
  return {
156
  "model": "Qwen3 32B (Quick Strategist)",
157
  "role": "πŸš€ The Strategic Decision Maker",
158
+ "reasoning": response_content,
159
  "timestamp": datetime.now().strftime("%H:%M:%S"),
160
+ "tokens_used": getattr(completion.usage, 'total_tokens', 'N/A') if hasattr(completion, 'usage') and completion.usage else "N/A"
161
  }
162
  except Exception as e:
163
  return {"error": f"Quick Strategist error: {str(e)}"}
 
180
  5. Comprehensive pros and cons
181
  6. Hidden connections or implications
182
 
183
+ Be extremely thorough and leave no stone unturned. Provide detailed evidence and reasoning for your conclusions."""
184
 
185
  try:
186
  completion = self.client.chat.completions.create(
 
188
  messages=[{"role": "user", "content": prompt}],
189
  temperature=0.6,
190
  top_p=0.95,
191
+ max_completion_tokens=2048,
192
  reasoning_format="parsed"
193
  )
194
 
195
+ response_content = completion.choices[0].message.content or "No response generated"
196
+
197
  return {
198
  "model": "QwQ 32B (Detail Detective)",
199
  "role": "πŸ” The Meticulous Investigator",
200
+ "reasoning": response_content,
201
  "timestamp": datetime.now().strftime("%H:%M:%S"),
202
+ "tokens_used": getattr(completion.usage, 'total_tokens', 'N/A') if hasattr(completion, 'usage') and completion.usage else "N/A"
203
  }
204
  except Exception as e:
205
  return {"error": f"Detail Detective error: {str(e)}"}
 
209
  if not self.is_api_key_set:
210
  return "API key not set"
211
 
212
+ # Extract reasoning content safely
213
+ deep_reasoning = deep_result.get('reasoning', 'Analysis not available') if not deep_result.get('error') else f"Error: {deep_result['error']}"
214
+ strategic_reasoning = strategic_result.get('reasoning', 'Analysis not available') if not strategic_result.get('error') else f"Error: {strategic_result['error']}"
215
+ detective_reasoning = detective_result.get('reasoning', 'Analysis not available') if not detective_result.get('error') else f"Error: {detective_result['error']}"
216
+
217
  synthesis_prompt = f"""You are the Orchestra Conductor. You have received three different analytical perspectives on the same problem. Your job is to synthesize these into a comprehensive, unified solution.
218
 
219
  ORIGINAL PROBLEM: {original_problem}
220
 
221
  DEEP THINKER ANALYSIS:
222
+ {deep_reasoning}
223
 
224
  STRATEGIC ANALYSIS:
225
+ {strategic_reasoning}
226
 
227
  DETECTIVE INVESTIGATION:
228
+ {detective_reasoning}
229
 
230
  Please create a unified synthesis that:
231
  1. Combines the best insights from all three perspectives
 
241
  model="qwen/qwen3-32b",
242
  messages=[{"role": "user", "content": synthesis_prompt}],
243
  temperature=0.7,
244
+ max_completion_tokens=2048,
245
  top_p=0.9
246
  )
247
 
248
+ return completion.choices[0].message.content or "No synthesis generated"
249
  except Exception as e:
250
  return f"Synthesis error: {str(e)}"
251
 
 
256
  """Validate the API key and return status"""
257
  return orchestra.set_api_key(api_key)
258
 
259
+ def run_single_model(problem: str, model_choice: str, context: str = "") -> str:
260
  """Run a single model analysis"""
261
  if not orchestra.is_api_key_set:
262
+ return """<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6;">
263
+ <h3>❌ API Key Required</h3>
264
+ <p>Please set your Groq API key first in the API Configuration section above.</p>
265
+ </div>"""
266
 
267
  if not problem.strip():
268
+ return """<div style="color: orange; padding: 20px; border: 2px solid orange; border-radius: 10px; background-color: #fff3e6;">
269
+ <h3>⚠️ Problem Required</h3>
270
+ <p>Please enter a problem to analyze.</p>
271
+ </div>"""
272
 
273
  start_time = time.time()
274
 
275
+ # Show loading state
276
+ loading_html = f"""<div style="padding: 20px; border: 2px solid #007bff; border-radius: 10px; background-color: #e6f3ff;">
277
+ <h3>πŸ”„ Processing...</h3>
278
+ <p>The {model_choice} is analyzing your problem. Please wait...</p>
279
+ </div>"""
280
+
281
  if model_choice == "Deep Thinker (DeepSeek R1)":
282
  result = orchestra.deep_thinker_analyze(problem, context)
283
  elif model_choice == "Quick Strategist (Qwen3 32B)":
 
285
  elif model_choice == "Detail Detective (QwQ 32B)":
286
  result = orchestra.detail_detective_analyze(problem, context)
287
  else:
288
+ return """<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6;">
289
+ <h3>❌ Invalid Model Selection</h3>
290
+ <p>Please select a valid model from the dropdown.</p>
291
+ </div>"""
292
 
293
  elapsed_time = time.time() - start_time
294
 
295
  if "error" in result:
296
+ return f"""<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6;">
297
+ <h3>❌ Error</h3>
298
+ <p>{result['error']}</p>
299
+ </div>"""
300
 
301
+ # Format the response as HTML
302
+ reasoning_html = orchestra.format_text_to_html(result['reasoning'])
 
 
 
 
 
303
 
304
+ formatted_output = f"""
305
+ <div style="border: 2px solid #28a745; border-radius: 15px; padding: 25px; margin: 15px 0; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);">
306
+ <div style="display: flex; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid #28a745;">
307
+ <h2 style="margin: 0; color: #28a745;">{result['role']}</h2>
308
+ </div>
309
+
310
+ <div style="background-color: white; padding: 15px; border-radius: 10px; margin-bottom: 20px;">
311
+ <div style="display: flex; gap: 20px; font-size: 14px; color: #666;">
312
+ <span><strong>Model:</strong> {result['model']}</span>
313
+ <span><strong>Analysis Time:</strong> {elapsed_time:.2f} seconds</span>
314
+ <span><strong>Timestamp:</strong> {result['timestamp']}</span>
315
+ <span><strong>Tokens:</strong> {result['tokens_used']}</span>
316
+ </div>
317
+ </div>
318
+
319
+ <div style="background-color: white; padding: 20px; border-radius: 10px; line-height: 1.6;">
320
+ {reasoning_html}
321
+ </div>
322
+ </div>
323
+ """
324
+
325
+ return formatted_output
326
 
327
  def run_full_orchestra(problem: str, context: str = "") -> Tuple[str, str, str, str]:
328
  """Run the full collaborative reasoning orchestra"""
329
  if not orchestra.is_api_key_set:
330
+ error_msg = """<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6;">
331
+ <h3>❌ API Key Required</h3>
332
+ <p>Please set your Groq API key first in the API Configuration section above.</p>
333
+ </div>"""
334
  return error_msg, error_msg, error_msg, error_msg
335
 
336
  if not problem.strip():
337
+ error_msg = """<div style="color: orange; padding: 20px; border: 2px solid orange; border-radius: 10px; background-color: #fff3e6;">
338
+ <h3>⚠️ Problem Required</h3>
339
+ <p>Please enter a problem to analyze.</p>
340
+ </div>"""
341
  return error_msg, error_msg, error_msg, error_msg
342
 
 
 
343
  # Phase 1: Deep Thinker
 
344
  deep_result = orchestra.deep_thinker_analyze(problem, context)
345
 
346
  # Phase 2: Quick Strategist
 
347
  strategic_result = orchestra.quick_strategist_analyze(problem, context)
348
 
349
  # Phase 3: Detail Detective
 
350
  detective_result = orchestra.detail_detective_analyze(problem, context)
351
 
352
  # Phase 4: Synthesis
 
353
  synthesis = orchestra.synthesize_orchestra(deep_result, strategic_result, detective_result, problem)
354
 
355
+ def format_result_html(result: Dict, color: str, icon: str) -> str:
 
356
  if "error" in result:
357
+ return f"""<div style="color: red; padding: 20px; border: 2px solid red; border-radius: 10px; background-color: #ffe6e6;">
358
+ <h3>❌ Error</h3>
359
+ <p>{result['error']}</p>
360
+ </div>"""
361
 
362
+ reasoning_html = orchestra.format_text_to_html(result['reasoning'])
363
+
364
+ return f"""
365
+ <div style="border: 2px solid {color}; border-radius: 15px; padding: 25px; margin: 15px 0; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);">
366
+ <div style="display: flex; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid {color};">
367
+ <span style="font-size: 24px; margin-right: 10px;">{icon}</span>
368
+ <h2 style="margin: 0; color: {color};">{result['model']}</h2>
369
+ </div>
370
+
371
+ <div style="background-color: white; padding: 15px; border-radius: 10px; margin-bottom: 20px;">
372
+ <div style="display: flex; gap: 20px; font-size: 14px; color: #666;">
373
+ <span><strong>Timestamp:</strong> {result['timestamp']}</span>
374
+ <span><strong>Tokens:</strong> {result['tokens_used']}</span>
375
+ </div>
376
+ </div>
377
+
378
+ <div style="background-color: white; padding: 20px; border-radius: 10px; line-height: 1.6;">
379
+ {reasoning_html}
380
+ </div>
381
+ </div>
382
+ """
383
 
384
+ deep_output = format_result_html(deep_result, "#6f42c1", "🎭")
385
+ strategic_output = format_result_html(strategic_result, "#fd7e14", "πŸš€")
386
+ detective_output = format_result_html(detective_result, "#20c997", "πŸ”")
387
 
388
+ synthesis_html = orchestra.format_text_to_html(synthesis)
389
+ synthesis_output = f"""
390
+ <div style="border: 2px solid #dc3545; border-radius: 15px; padding: 25px; margin: 15px 0; background: linear-gradient(135deg, #fff5f5 0%, #fee);">
391
+ <div style="display: flex; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid #dc3545;">
392
+ <span style="font-size: 24px; margin-right: 10px;">🎼</span>
393
+ <h2 style="margin: 0; color: #dc3545;">Orchestra Conductor - Final Synthesis</h2>
394
+ </div>
395
+
396
+ <div style="background-color: white; padding: 20px; border-radius: 10px; line-height: 1.6;">
397
+ {synthesis_html}
398
+ </div>
399
+ </div>
400
+ """
401
 
402
  return deep_output, strategic_output, detective_output, synthesis_output
403
 
404
  # Custom CSS for better styling
405
  custom_css = """
406
  .gradio-container {
407
+ max-width: 1400px !important;
408
+ margin: 0 auto !important;
409
  }
410
  .api-key-section {
411
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
 
433
  margin: 10px 0;
434
  border-radius: 5px;
435
  }
436
+ /* Custom styling for HTML outputs */
437
+ .html-content {
438
+ max-height: 600px;
439
+ overflow-y: auto;
440
+ border: 1px solid #ddd;
441
+ border-radius: 8px;
442
+ padding: 10px;
443
+ background-color: #fafafa;
444
+ }
445
  """
446
 
447
  # Build the Gradio interface
 
451
  <div class="orchestra-header">
452
  <h1>🎼 The Collaborative Reasoning Orchestra</h1>
453
  <p><em>Where AI models collaborate like musicians in an orchestra to solve complex problems</em></p>
454
+ <p><strong>Now with Beautiful HTML-Formatted Responses!</strong></p>
455
  </div>
456
  """)
457
 
 
483
 
484
  # Single Model Tab
485
  with gr.TabItem("🎯 Single Model Analysis"):
486
+ gr.Markdown("### Test individual reasoning models with beautiful HTML output")
487
 
488
  with gr.Row():
489
+ with gr.Column(scale=1):
490
  single_problem = gr.Textbox(
491
  label="Problem Statement",
492
  placeholder="Enter the problem you want to analyze...",
 
506
  ],
507
  value="Deep Thinker (DeepSeek R1)"
508
  )
509
+ single_analyze_btn = gr.Button("πŸš€ Analyze with HTML Output", variant="primary", size="lg")
510
 
511
+ with gr.Column(scale=2):
512
+ single_output = gr.HTML(label="Analysis Result", elem_classes=["html-content"])
513
 
514
  single_analyze_btn.click(
515
  fn=run_single_model,
516
  inputs=[single_problem, model_choice, single_context],
517
+ outputs=[single_output]
518
  )
519
 
520
  # Full Orchestra Tab
521
  with gr.TabItem("🎼 Full Orchestra Collaboration"):
522
+ gr.Markdown("### Run all three models collaboratively with stunning HTML-formatted output")
523
 
524
+ with gr.Column():
525
+ with gr.Row():
526
+ with gr.Column(scale=1):
527
+ orchestra_problem = gr.Textbox(
528
+ label="Problem Statement",
529
+ placeholder="Enter a complex problem that benefits from multiple reasoning perspectives...",
530
+ lines=6
531
+ )
532
+ orchestra_context = gr.Textbox(
533
+ label="Additional Context (Optional)",
534
+ placeholder="Background information, constraints, or specific requirements...",
535
+ lines=3
536
+ )
537
+ orchestra_analyze_btn = gr.Button("🎼 Start Orchestra Analysis", variant="primary", size="lg")
538
 
539
+ # Orchestra Results
540
+ with gr.Column():
541
+ deep_output = gr.HTML(label="🎭 Deep Thinker Analysis", elem_classes=["html-content"])
542
+ strategic_output = gr.HTML(label="πŸš€ Quick Strategist Analysis", elem_classes=["html-content"])
543
+ detective_output = gr.HTML(label="πŸ” Detail Detective Analysis", elem_classes=["html-content"])
544
+ synthesis_output = gr.HTML(label="🎼 Final Orchestrated Solution", elem_classes=["html-content"])
 
 
 
 
 
 
545
 
546
  orchestra_analyze_btn.click(
547
  fn=run_full_orchestra,
 
555
  ### Try these example problems to see the Orchestra in action:
556
 
557
  **🏒 Business Strategy:**
558
+ "Our tech startup has limited funding and needs to decide between focusing on product development or marketing. We have a working MVP but low user adoption. Budget is $50K for the next 6 months."
559
 
560
  **πŸ€– Ethical AI:**
561
+ "Should autonomous vehicles prioritize passenger safety over pedestrian safety in unavoidable accident scenarios? Consider the ethical, legal, and practical implications for mass adoption."
562
 
563
  **🌍 Environmental Policy:**
564
+ "Design a policy framework to reduce carbon emissions in urban areas by 40% within 10 years while maintaining economic growth and social equity."
565
 
566
  **🧬 Scientific Research:**
567
+ "We've discovered a potential breakthrough in gene therapy for treating Alzheimer's, but it requires human trials. How should we proceed given the risks, benefits, regulatory requirements, and ethical considerations?"
568
 
569
  **πŸŽ“ Educational Innovation:**
570
+ "How can we redesign traditional university education to better prepare students for the rapidly changing job market of the 2030s, considering AI, remote work, and emerging technologies?"
571
 
572
  **🏠 Urban Planning:**
573
+ "A city of 500K people wants to build 10,000 affordable housing units but faces opposition from current residents, environmental concerns, and a $2B budget constraint. Develop a comprehensive solution."
574
+
575
+ **πŸš— Transportation Future:**
576
+ "Design a comprehensive transportation system for a smart city of 1 million people in 2035, integrating autonomous vehicles, public transit, and sustainable mobility."
577
  """)
578
+
579
+ # Quick copy buttons for examples
580
+ with gr.Row():
581
+ gr.Button("πŸ“‹ Copy Business Example", variant="secondary").click(
582
+ lambda: "Our tech startup has limited funding and needs to decide between focusing on product development or marketing. We have a working MVP but low user adoption. Budget is $50K for the next 6 months.",
583
+ outputs=[]
584
+ )
585
 
586
  # Footer
587
  gr.HTML("""
588
+ <div style="text-align: center; margin-top: 30px; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white;">
589
+ <h3>🎼 How the Orchestra Works</h3>
590
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin: 20px 0;">
591
+ <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
592
+ <h4>🎭 Deep Thinker (DeepSeek R1)</h4>
593
+ <p>Provides thorough philosophical and theoretical analysis with comprehensive reasoning chains</p>
594
+ </div>
595
+ <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
596
+ <h4>πŸš€ Quick Strategist (Qwen3 32B)</h4>
597
+ <p>Delivers practical strategies, action plans, and rapid decision-making frameworks</p>
598
+ </div>
599
+ <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
600
+ <h4>πŸ” Detail Detective (QwQ 32B)</h4>
601
+ <p>Conducts comprehensive investigation, fact-checking, and finds hidden connections</p>
602
+ </div>
603
+ <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 10px;">
604
+ <h4>🎼 Orchestra Conductor</h4>
605
+ <p>Synthesizes all perspectives into unified, comprehensive solutions</p>
606
+ </div>
607
+ </div>
608
+ <p style="margin-top: 20px;"><em>Built with ❀️ using Groq's lightning-fast inference, Gradio, and beautiful HTML formatting</em></p>
609
  </div>
610
  """)
611