shukdevdatta123 commited on
Commit
f14baa8
Β·
verified Β·
1 Parent(s): 4f6dfc4

Create v1.txt

Browse files
Files changed (1) hide show
  1. v1.txt +622 -0
v1.txt ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from groq import Groq
3
+ import json
4
+ import time
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):
13
+ self.client = None
14
+ self.is_api_key_set = False
15
+
16
+ def set_api_key(self, api_key: str) -> str:
17
+ """Set the Groq API key and test connection"""
18
+ if not api_key.strip():
19
+ return "❌ Please enter a valid API key"
20
+
21
+ try:
22
+ self.client = Groq(api_key=api_key.strip())
23
+ # Test the connection with a simple request
24
+ test_completion = self.client.chat.completions.create(
25
+ model="qwen/qwen3-32b",
26
+ messages=[{"role": "user", "content": "Hello"}],
27
+ max_completion_tokens=10
28
+ )
29
+ self.is_api_key_set = True
30
+ return "βœ… API key validated successfully! You can now use the Reasoning Orchestra."
31
+ except Exception as e:
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 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)
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 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
+
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:
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:
101
+ completion = self.client.chat.completions.create(
102
+ model="deepseek-r1-distill-llama-70b",
103
+ messages=[{"role": "user", "content": prompt}],
104
+ temperature=0.6,
105
+ max_completion_tokens=8192,
106
+ top_p=0.95,
107
+ reasoning_format="raw"
108
+ )
109
+
110
+ response_content = completion.choices[0].message.content
111
+ if not response_content or response_content.strip() == "":
112
+ response_content = "The model did not generate a response. This could be due to content filtering, model limitations, or API issues."
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)}"}
123
+
124
+ def quick_strategist_analyze(self, problem: str, context: str = "") -> Dict:
125
+ """Qwen3 32B - The Quick Strategist"""
126
+ if not self.is_api_key_set:
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:
141
+ completion = self.client.chat.completions.create(
142
+ model="qwen/qwen3-32b",
143
+ messages=[{"role": "user", "content": prompt}],
144
+ temperature=0.6,
145
+ top_p=0.95,
146
+ max_completion_tokens=8192
147
+ )
148
+
149
+ response_content = completion.choices[0].message.content
150
+ if not response_content or response_content.strip() == "":
151
+ response_content = "The model did not generate a response. This could be due to content filtering, model limitations, or API issues."
152
+
153
+ return {
154
+ "model": "Qwen3 32B (Quick Strategist)",
155
+ "role": "πŸš€ The Strategic Decision Maker",
156
+ "reasoning": response_content,
157
+ "timestamp": datetime.now().strftime("%H:%M:%S"),
158
+ "tokens_used": getattr(completion.usage, 'total_tokens', 'N/A') if hasattr(completion, 'usage') and completion.usage else "N/A"
159
+ }
160
+ except Exception as e:
161
+ return {"error": f"Quick Strategist error: {str(e)}"}
162
+
163
+ def detail_detective_analyze(self, problem: str, context: str = "") -> Dict:
164
+ """QwQ 32B - The Detail Detective"""
165
+ if not self.is_api_key_set:
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
174
+ 3. Verification of assumptions
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}],
185
+ temperature=0.7,
186
+ top_p=0.9,
187
+ max_completion_tokens=8192
188
+ )
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",
196
+ messages=[{"role": "user", "content": fallback_prompt}],
197
+ temperature=0.5,
198
+ max_completion_tokens=8192
199
+ )
200
+ response_content = fallback_completion.choices[0].message.content
201
+
202
+ if not response_content or response_content.strip() == "":
203
+ response_content = "The QwQ model encountered an issue generating content. This could be due to the complexity of the prompt, content filtering, or temporary model availability issues. The model may work better with simpler, more direct questions."
204
+
205
+ return {
206
+ "model": "QwQ 32B (Detail Detective)",
207
+ "role": "πŸ” The Meticulous Investigator",
208
+ "reasoning": response_content,
209
+ "timestamp": datetime.now().strftime("%H:%M:%S"),
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."
217
+ return {"error": error_msg}
218
+
219
+ def synthesize_orchestra(self, deep_result: Dict, strategic_result: Dict, detective_result: Dict, original_problem: str) -> str:
220
+ """Synthesize all three perspectives into a final orchestrated solution using Llama 3.3 70B"""
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']}"
228
+ reasoning = result.get('reasoning', '')
229
+ if not reasoning or reasoning.strip() == "" or reasoning == "No response generated":
230
+ return f"**{model_name}** did not provide analysis (this may be due to model limitations or API issues)."
231
+ return reasoning
232
+
233
+ deep_reasoning = extract_reasoning(deep_result, "Deep Thinker")
234
+ strategic_reasoning = extract_reasoning(strategic_result, "Quick Strategist")
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
248
+ 3. Resolves any contradictions between the analyses
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:
256
+ completion = self.client.chat.completions.create(
257
+ model="llama-3.3-70b-versatile",
258
+ messages=[{"role": "user", "content": synthesis_prompt}],
259
+ temperature=0.7,
260
+ max_completion_tokens=8192,
261
+ top_p=0.9
262
+ )
263
+
264
+ synthesis_content = completion.choices[0].message.content
265
+ if not synthesis_content or synthesis_content.strip() == "":
266
+ return "The synthesis could not be generated. This may be due to API limitations or the complexity of combining the different analyses."
267
+
268
+ return synthesis_content
269
+ except Exception as e:
270
+ return f"Synthesis error: {str(e)}"
271
+
272
+ # Initialize the orchestra
273
+ orchestra = ReasoningOrchestra()
274
+
275
+ def validate_api_key(api_key: str) -> str:
276
+ """Validate the API key and return status"""
277
+ return orchestra.set_api_key(api_key)
278
+
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()
294
+
295
+ if model_choice == "Deep Thinker (DeepSeek R1)":
296
+ result = orchestra.deep_thinker_analyze(problem, context)
297
+ elif model_choice == "Quick Strategist (Qwen3 32B)":
298
+ result = orchestra.quick_strategist_analyze(problem, context)
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
316
+ reasoning_html = orchestra.format_text_to_html(result['reasoning'])
317
+
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>
329
+ <span><strong>Tokens:</strong> {result['tokens_used']}</span>
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>
337
+ """
338
+
339
+ return formatted_output
340
+
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
+
357
+ # Phase 1: Deep Thinker
358
+ deep_result = orchestra.deep_thinker_analyze(problem, context)
359
+
360
+ # Phase 2: Quick Strategist
361
+ strategic_result = orchestra.quick_strategist_analyze(problem, context)
362
+
363
+ # Phase 3: Detail Detective
364
+ detective_result = orchestra.detail_detective_analyze(problem, context)
365
+
366
+ # Phase 4: Synthesis using Llama 3.3 70B
367
+ synthesis = orchestra.synthesize_orchestra(deep_result, strategic_result, detective_result, problem)
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'])
378
+
379
+ return f"""
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>
397
+ """
398
+
399
+ deep_output = format_result_html(deep_result, "#6f42c1", "🎭")
400
+ strategic_output = format_result_html(strategic_result, "#fd7e14", "πŸš€")
401
+ detective_output = format_result_html(detective_result, "#20c997", "πŸ”")
402
+
403
+ synthesis_html = orchestra.format_text_to_html(synthesis)
404
+ synthesis_output = f"""
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>
415
+ """
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;
454
+ overflow-y: auto;
455
+ border: 1px solid #ddd;
456
+ border-radius: 8px;
457
+ padding: 10px;
458
+ background-color: #fafafa;
459
+ }
460
+ """
461
+
462
+ # Build the Gradio interface
463
+ 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],
493
+ outputs=[api_status]
494
+ )
495
+
496
+ # Main Interface Tabs
497
+ with gr.Tabs() as tabs:
498
+
499
+ # Single Model Tab
500
+ with gr.TabItem("🎯 Single Model Analysis"):
501
+ gr.Markdown("### Test individual reasoning models with beautiful HTML output")
502
+
503
+ with gr.Row():
504
+ with gr.Column(scale=1):
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",
517
+ choices=[
518
+ "Deep Thinker (DeepSeek R1)",
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,
531
+ inputs=[single_problem, model_choice, single_context],
532
+ outputs=[single_output]
533
+ )
534
+
535
+ # Full Orchestra Tab
536
+ with gr.TabItem("🎼 Full Orchestra Collaboration"):
537
+ gr.Markdown("### Run all three models collaboratively with Llama 3.3 70B as Orchestra Conductor and stunning HTML-formatted output")
538
+
539
+ with gr.Column():
540
+ with gr.Row():
541
+ with gr.Column(scale=1):
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,
563
+ inputs=[orchestra_problem, orchestra_context],
564
+ outputs=[deep_output, strategic_output, detective_output, synthesis_output]
565
+ )
566
+
567
+ # Examples Tab
568
+ with gr.TabItem("πŸ’‘ Example Problems"):
569
+ gr.Markdown("""
570
+ ### Try these example problems to see the Orchestra in action:
571
+
572
+ **🏒 Business Strategy:**
573
+ "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."
574
+
575
+ **πŸ€– Ethical AI:**
576
+ "Should autonomous vehicles prioritize passenger safety over pedestrian safety in unavoidable accident scenarios? Consider the ethical, legal, and practical implications for mass adoption."
577
+
578
+ **🌍 Environmental Policy:**
579
+ "Design a policy framework to reduce carbon emissions in urban areas by 40% within 10 years while maintaining economic growth and social equity."
580
+
581
+ **🧬 Scientific Research:**
582
+ "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?"
583
+
584
+ **πŸŽ“ Educational Innovation:**
585
+ "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?"
586
+
587
+ **🏠 Urban Planning:**
588
+ "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."
589
+
590
+ **πŸš— Transportation Future:**
591
+ "Design a comprehensive transportation system for a smart city of 1 million people in 2035, integrating autonomous vehicles, public transit, and sustainable mobility."
592
+ """)
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