Spaces:
Running
Running
Update app.py
Browse files
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=
|
| 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
|
| 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=
|
| 93 |
reasoning_effort="default"
|
| 94 |
)
|
| 95 |
|
|
|
|
|
|
|
| 96 |
return {
|
| 97 |
"model": "Qwen3 32B (Quick Strategist)",
|
| 98 |
"role": "π The Strategic Decision Maker",
|
| 99 |
-
"reasoning":
|
| 100 |
"timestamp": datetime.now().strftime("%H:%M:%S"),
|
| 101 |
-
"tokens_used": completion.usage
|
| 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=
|
| 133 |
reasoning_format="parsed"
|
| 134 |
)
|
| 135 |
|
|
|
|
|
|
|
| 136 |
return {
|
| 137 |
"model": "QwQ 32B (Detail Detective)",
|
| 138 |
"role": "π The Meticulous Investigator",
|
| 139 |
-
"reasoning":
|
| 140 |
"timestamp": datetime.now().strftime("%H:%M:%S"),
|
| 141 |
-
"tokens_used": completion.usage
|
| 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 |
-
{
|
| 157 |
|
| 158 |
STRATEGIC ANALYSIS:
|
| 159 |
-
{
|
| 160 |
|
| 161 |
DETECTIVE INVESTIGATION:
|
| 162 |
-
{
|
| 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=
|
| 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 = "") ->
|
| 194 |
"""Run a single model analysis"""
|
| 195 |
if not orchestra.is_api_key_set:
|
| 196 |
-
return "
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
if not problem.strip():
|
| 199 |
-
return "
|
|
|
|
|
|
|
|
|
|
| 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 "
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
elapsed_time = time.time() - start_time
|
| 213 |
|
| 214 |
if "error" in result:
|
| 215 |
-
return f"
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
---
|
| 221 |
-
|
| 222 |
-
{result['reasoning']}
|
| 223 |
-
"""
|
| 224 |
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 = "
|
|
|
|
|
|
|
|
|
|
| 231 |
return error_msg, error_msg, error_msg, error_msg
|
| 232 |
|
| 233 |
if not problem.strip():
|
| 234 |
-
error_msg = "
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 256 |
-
def format_result(result: Dict) -> str:
|
| 257 |
if "error" in result:
|
| 258 |
-
return f"
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
{
|
| 266 |
-
""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
|
| 268 |
-
deep_output =
|
| 269 |
-
strategic_output =
|
| 270 |
-
detective_output =
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 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:
|
|
|
|
| 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.
|
| 379 |
|
| 380 |
single_analyze_btn.click(
|
| 381 |
fn=run_single_model,
|
| 382 |
inputs=[single_problem, model_choice, single_context],
|
| 383 |
-
outputs=[single_output
|
| 384 |
)
|
| 385 |
|
| 386 |
# Full Orchestra Tab
|
| 387 |
with gr.TabItem("πΌ Full Orchestra Collaboration"):
|
| 388 |
-
gr.Markdown("### Run all three models collaboratively
|
| 389 |
|
| 390 |
-
with gr.
|
| 391 |
-
with gr.
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
|
|
|
| 403 |
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
deep_output = gr.
|
| 407 |
-
|
| 408 |
-
gr.
|
| 409 |
-
|
| 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
|
| 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
|
|
|
|
|
|
|
|
|
|
| 445 |
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 446 |
|
| 447 |
# Footer
|
| 448 |
gr.HTML("""
|
| 449 |
-
<div style="text-align: center; margin-top: 30px; padding: 20px; background
|
| 450 |
-
<
|
| 451 |
-
<
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
|