riazmo commited on
Commit
d82aacb
Β·
verified Β·
1 Parent(s): 0a5aa1d

Upload 4 files

Browse files
Files changed (4) hide show
  1. agents_config.yaml +206 -0
  2. app.py +861 -0
  3. hf_.env.example +43 -0
  4. requirements.txt +6 -0
agents_config.yaml ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Multi-Agent Research System Configuration
2
+ # This file defines the agent roles, expertise, and research focus
3
+
4
+ agents:
5
+ # Researcher Agent - Identifies industry leaders
6
+ researcher:
7
+ name: "Industry Research Specialist"
8
+ role: "Researcher Agent"
9
+ emoji: "πŸ†"
10
+ phase: "industry_leaders"
11
+ expertise:
12
+ - "Market leadership identification"
13
+ - "Competitive landscape analysis"
14
+ - "Company positioning and metrics"
15
+ - "Product/service evaluation"
16
+ web_search: true
17
+ description: "Identifies top 5 industry leaders, their market position, strengths, and metrics"
18
+
19
+ # Analyzer Agent - Researches best practices
20
+ analyzer:
21
+ name: "Best Practices Analyst"
22
+ role: "Analyzer Agent"
23
+ emoji: "⭐"
24
+ phase: "best_practices"
25
+ expertise:
26
+ - "Industry standards and frameworks"
27
+ - "Success patterns and case studies"
28
+ - "Innovation trends (2024-2025)"
29
+ - "Implementation guidelines"
30
+ - "Lessons learned from leaders"
31
+ web_search: true
32
+ description: "Researches proven strategies, innovations, and best practices in the industry"
33
+
34
+ # Critic Agent - Quality review
35
+ critic:
36
+ name: "Quality Assurance Reviewer"
37
+ role: "Critic Agent"
38
+ emoji: "πŸ”"
39
+ phase: "quality_review"
40
+ expertise:
41
+ - "Fact-checking and validation"
42
+ - "Source credibility assessment"
43
+ - "Completeness evaluation"
44
+ - "Gap identification"
45
+ - "Improvement recommendations"
46
+ web_search: false
47
+ description: "Performs independent quality review of research completeness and credibility"
48
+
49
+ # Synthesizer Agent - Generates recommendations
50
+ synthesizer:
51
+ name: "Strategic Recommendation Synthesizer"
52
+ role: "Synthesizer Agent"
53
+ emoji: "πŸ’‘"
54
+ phase: "recommendations"
55
+ expertise:
56
+ - "Strategic synthesis"
57
+ - "Actionable roadmap creation"
58
+ - "Risk assessment and mitigation"
59
+ - "Resource planning"
60
+ - "Success metrics definition"
61
+ web_search: false
62
+ description: "Synthesizes all research into strategic recommendations and action plans"
63
+
64
+ # Research Configuration
65
+ research_config:
66
+ # Number of top leaders to identify
67
+ top_leaders_count: 5
68
+
69
+ # Include direct competitors analysis
70
+ include_competitors: true
71
+
72
+ # Include best practices research
73
+ include_best_practices: true
74
+
75
+ # Require citations in research
76
+ citations_required: true
77
+
78
+ # Data recency requirement
79
+ data_recency: "2024-2025"
80
+
81
+ # Web search configuration
82
+ web_search:
83
+ enabled: true
84
+ max_searches_per_agent: 5
85
+ search_depth: "comprehensive"
86
+
87
+ # Quality review configuration
88
+ quality_review:
89
+ enabled: true
90
+ check_completeness: true
91
+ check_credibility: true
92
+ check_recency: true
93
+ check_clarity: true
94
+
95
+ # Recommendations configuration
96
+ recommendations:
97
+ include_immediate_actions: true
98
+ include_short_term_strategy: true
99
+ include_long_term_vision: true
100
+ include_risk_mitigation: true
101
+ include_resource_requirements: true
102
+
103
+ # Model Configuration
104
+ models:
105
+ default_models:
106
+ query_understanding: "qwen-2.5-7b"
107
+ industry_leaders: "qwen-2.5-72b"
108
+ best_practices: "qwen-2.5-72b"
109
+ quality_review: "qwen-2.5-72b"
110
+ recommendations: "qwen-2.5-72b"
111
+
112
+ # Available models
113
+ available:
114
+ qwen-2.5-7b:
115
+ name: "Qwen/Qwen2.5-7B-Instruct"
116
+ provider: "huggingface"
117
+ description: "Fast & Efficient - Quick analysis"
118
+ speed: "⚑⚑⚑"
119
+ quality: "⭐⭐⭐"
120
+ cost: "πŸ’°"
121
+
122
+ qwen-2.5-72b:
123
+ name: "Qwen/Qwen2.5-72B-Instruct"
124
+ provider: "huggingface"
125
+ description: "Most Capable Qwen - Deep analysis"
126
+ speed: "⚑⚑"
127
+ quality: "⭐⭐⭐⭐"
128
+ cost: "πŸ’°πŸ’°"
129
+
130
+ meta-llama-3.1-70b:
131
+ name: "meta-llama/Llama-3.1-70B-Instruct"
132
+ provider: "huggingface"
133
+ description: "Meta Llama 3.1 - Strong reasoning"
134
+ speed: "⚑⚑"
135
+ quality: "⭐⭐⭐⭐"
136
+ cost: "πŸ’°πŸ’°"
137
+
138
+ mistral-large:
139
+ name: "mistralai/Mistral-Large-Instruct-2407"
140
+ provider: "huggingface"
141
+ description: "Mistral Large - Excellent analysis"
142
+ speed: "⚑⚑"
143
+ quality: "⭐⭐⭐⭐"
144
+ cost: "πŸ’°πŸ’°"
145
+
146
+ # Output Configuration
147
+ output_config:
148
+ # Include hierarchy diagram
149
+ include_hierarchy_diagram: true
150
+
151
+ # Include execution timeline
152
+ include_timeline: true
153
+
154
+ # Include performance metrics
155
+ include_metrics: true
156
+
157
+ # Include model assignment table
158
+ include_model_assignment: true
159
+
160
+ # Include research metadata
161
+ include_metadata: true
162
+
163
+ # Output format
164
+ format: "markdown"
165
+
166
+ # Include live dashboard
167
+ include_dashboard: true
168
+
169
+ # Performance Configuration
170
+ performance:
171
+ # Timeout for agent tasks (seconds)
172
+ agent_timeout: 120
173
+
174
+ # Maximum retry attempts
175
+ max_retries: 3
176
+
177
+ # Retry delay (seconds)
178
+ retry_delay: 2
179
+
180
+ # Model cache enabled
181
+ model_caching: true
182
+
183
+ # Progress update frequency
184
+ progress_update_interval: 5
185
+
186
+ # Logging Configuration
187
+ logging:
188
+ enabled: true
189
+ level: "INFO"
190
+ log_searches: true
191
+ log_model_usage: true
192
+ log_execution_time: true
193
+ log_errors: true
194
+
195
+ # Feature Flags
196
+ features:
197
+ live_dashboard: true
198
+ real_time_progress: true
199
+ web_search: true
200
+ quality_review: true
201
+ recommendations: true
202
+ model_configuration: true
203
+ error_recovery: true
204
+ result_caching: false
205
+ export_to_pdf: false
206
+ export_to_docx: false
app.py ADDED
@@ -0,0 +1,861 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hierarchical Multi-Agent Research System - LIVE DASHBOARD & REAL-TIME PROGRESS
3
+ ✨ Multi-Model Support | 🎯 Configurable AI Models | πŸ“Š Real-Time Progress | πŸ“ˆ Live Dashboard
4
+
5
+ This application implements a hierarchical multi-agent research system with:
6
+ - Supervisor (Strategy) β†’ Researcher, Analyzer, Critic (Parallel) β†’ Synthesizer
7
+ - Real-time progress tracking with live dashboard
8
+ - Multi-model support (Qwen, Llama, Mistral)
9
+ - Web search capabilities for comprehensive research
10
+ """
11
+
12
+ import gradio as gr
13
+ import os
14
+ import time
15
+ from datetime import datetime
16
+ from dotenv import load_dotenv
17
+
18
+ try:
19
+ from smolagents import ToolCallingAgent, InferenceClientModel, WebSearchTool
20
+ except ImportError:
21
+ print("⚠️ Warning: smolagents not installed. Install with: pip install smolagents")
22
+
23
+ # Load API keys from .env file
24
+ load_dotenv()
25
+ HF_TOKEN = os.getenv("HF_TOKEN")
26
+
27
+ # Available Models Configuration
28
+ AVAILABLE_MODELS = {
29
+ "qwen-2.5-7b": {
30
+ "name": "Qwen/Qwen2.5-7B-Instruct",
31
+ "provider": "huggingface",
32
+ "description": "Fast & Efficient - Quick analysis",
33
+ "api_key_required": "HF_TOKEN"
34
+ },
35
+ "qwen-2.5-72b": {
36
+ "name": "Qwen/Qwen2.5-72B-Instruct",
37
+ "provider": "huggingface",
38
+ "description": "Most Capable Qwen - Deep analysis",
39
+ "api_key_required": "HF_TOKEN"
40
+ },
41
+ "meta-llama-3.1-70b": {
42
+ "name": "meta-llama/Llama-3.1-70B-Instruct",
43
+ "provider": "huggingface",
44
+ "description": "Meta Llama 3.1 - Strong reasoning",
45
+ "api_key_required": "HF_TOKEN"
46
+ },
47
+ "mistral-large": {
48
+ "name": "mistralai/Mistral-Large-Instruct-2407",
49
+ "provider": "huggingface",
50
+ "description": "Mistral Large - Excellent analysis",
51
+ "api_key_required": "HF_TOKEN"
52
+ }
53
+ }
54
+
55
+ # Default Phase-Model Mapping
56
+ DEFAULT_PHASE_MODELS = {
57
+ "query_understanding": "qwen-2.5-7b",
58
+ "industry_leaders": "qwen-2.5-72b",
59
+ "best_practices": "qwen-2.5-72b",
60
+ "quality_review": "qwen-2.5-72b",
61
+ "recommendations": "qwen-2.5-72b"
62
+ }
63
+
64
+ # ============================================================================
65
+ # RESEARCH STATE MANAGEMENT
66
+ # ============================================================================
67
+
68
+ class ResearchState:
69
+ """Manages research state, search history, and dashboard updates"""
70
+
71
+ def __init__(self):
72
+ self.search_history = []
73
+ self.model_usage = []
74
+ self.results_cache = {}
75
+ self.dashboard_updates = []
76
+
77
+ def add_search(self, phase, query, model, timestamp):
78
+ """Record a search operation"""
79
+ self.search_history.append({
80
+ "phase": phase,
81
+ "query": query,
82
+ "model": model,
83
+ "timestamp": timestamp
84
+ })
85
+
86
+ def add_model_usage(self, phase, model, duration, status):
87
+ """Record model usage metrics"""
88
+ self.model_usage.append({
89
+ "phase": phase,
90
+ "model": model,
91
+ "duration": duration,
92
+ "status": status,
93
+ "timestamp": datetime.now().strftime("%H:%M:%S")
94
+ })
95
+
96
+ def add_dashboard_update(self, message):
97
+ """Add a live update to the dashboard"""
98
+ timestamp = datetime.now().strftime("%H:%M:%S")
99
+ self.dashboard_updates.append(f"[{timestamp}] {message}")
100
+
101
+ def get_dashboard_display(self):
102
+ """Get the current dashboard display"""
103
+ if not self.dashboard_updates:
104
+ return "⏳ Waiting for research to start..."
105
+
106
+ dashboard = "# πŸ“Š Live Research Dashboard\n\n"
107
+ dashboard += "```\n"
108
+ for update in self.dashboard_updates:
109
+ dashboard += update + "\n"
110
+ dashboard += "```\n"
111
+ return dashboard
112
+
113
+ def clear(self):
114
+ """Clear all state for new research"""
115
+ self.search_history.clear()
116
+ self.model_usage.clear()
117
+ self.dashboard_updates.clear()
118
+
119
+ state = ResearchState()
120
+
121
+ # ============================================================================
122
+ # VISUALIZATION UTILITIES
123
+ # ============================================================================
124
+
125
+ def create_progress_bar(percent, width=30):
126
+ """Create a simple text-based progress bar"""
127
+ filled = int(width * percent / 100)
128
+ bar = "β–ˆ" * filled + "β–‘" * (width - filled)
129
+ return f"[{bar}] {percent}%"
130
+
131
+ def create_hierarchy_diagram():
132
+ """Create ASCII art hierarchy diagram"""
133
+ return """
134
+ ```
135
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
136
+ β”‚ SUPERVISOR 🎯 β”‚
137
+ β”‚ (Strategy) β”‚
138
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
139
+ β”‚
140
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
141
+ β”‚ β”‚ β”‚
142
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β–ΌοΏ½οΏ½β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
143
+ β”‚ RESEARCHER πŸ† β”‚ β”‚ ANALYZER ⭐ β”‚ β”‚ CRITIC πŸ” β”‚
144
+ β”‚ (Leaders) β”‚ β”‚ (Practices) β”‚ β”‚ (Quality) β”‚
145
+ β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
146
+ β”‚ β”‚ β”‚
147
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
148
+ β”‚
149
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
150
+ β”‚ SYNTHESIZER πŸ’‘ β”‚
151
+ β”‚ (Recommendations) β”‚
152
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
153
+ ```
154
+ """
155
+
156
+ # ============================================================================
157
+ # MULTI-MODEL RESEARCH ENGINE
158
+ # ============================================================================
159
+
160
+ class MultiModelResearchEngine:
161
+ """Research engine with multi-model support and agent orchestration"""
162
+
163
+ def __init__(self, phase_models=None):
164
+ self.phase_models = phase_models or DEFAULT_PHASE_MODELS
165
+ self.models_cache = {}
166
+
167
+ def get_model(self, model_key):
168
+ """Initialize and cache model instances"""
169
+ if model_key in self.models_cache:
170
+ return self.models_cache[model_key]
171
+
172
+ model_config = AVAILABLE_MODELS[model_key]
173
+
174
+ if model_config["provider"] == "huggingface":
175
+ if not HF_TOKEN:
176
+ raise ValueError(f"HF_TOKEN required for {model_key}")
177
+ model = InferenceClientModel(
178
+ model_id=model_config["name"],
179
+ timeout=120
180
+ )
181
+ self.models_cache[model_key] = model
182
+ return model
183
+
184
+ def run_agent_task(self, phase, task, use_web_search=True):
185
+ """Run task with assigned model for the phase"""
186
+ model_key = self.phase_models.get(phase, "qwen-2.5-7b")
187
+ model_config = AVAILABLE_MODELS[model_key]
188
+
189
+ start_time = time.time()
190
+
191
+ try:
192
+ model = self.get_model(model_key)
193
+ tools = [WebSearchTool()] if use_web_search else []
194
+
195
+ # Create agent with compatible configuration
196
+ try:
197
+ agent = ToolCallingAgent(
198
+ tools=tools,
199
+ model=model,
200
+ max_steps=6
201
+ )
202
+ except TypeError as e:
203
+ error_str = str(e)
204
+ if "tool" in error_str.lower():
205
+ agent = ToolCallingAgent(
206
+ tools=[],
207
+ model=model,
208
+ max_steps=6
209
+ )
210
+ else:
211
+ raise
212
+
213
+ # Run the task with retry logic
214
+ max_retries = 3
215
+ result = None
216
+
217
+ for attempt in range(max_retries):
218
+ try:
219
+ result = agent.run(task)
220
+ break
221
+
222
+ except Exception as e:
223
+ error_str = str(e)
224
+ if "tool_choice" in error_str or "422" in error_str or "Unprocessable" in error_str:
225
+ if attempt < max_retries - 1:
226
+ state.add_dashboard_update(f"⚠️ API error, retrying without tools...")
227
+ time.sleep(2)
228
+ try:
229
+ agent = ToolCallingAgent(
230
+ tools=[],
231
+ model=model,
232
+ max_steps=6
233
+ )
234
+ except:
235
+ pass
236
+ continue
237
+ else:
238
+ result = f"⚠️ API compatibility issue with this model."
239
+ else:
240
+ raise
241
+
242
+ elapsed = time.time() - start_time
243
+ duration = f"{elapsed:.2f}s"
244
+
245
+ state.add_model_usage(phase, model_config["name"], duration, "βœ… Success")
246
+
247
+ return result
248
+
249
+ except Exception as e:
250
+ elapsed = time.time() - start_time
251
+ duration = f"{elapsed:.2f}s"
252
+ state.add_model_usage(phase, model_config["name"], duration, f"❌ Error")
253
+ raise Exception(f"Error in {phase}: {str(e)}")
254
+
255
+ def research_industry_leaders(self, topic):
256
+ """RESEARCHER AGENT: Research top 5 industry leaders"""
257
+ task = f"""Research the TOP 5 INDUSTRY LEADERS for: {topic}
258
+
259
+ Focus on market leaders, innovators, and established players who are setting standards.
260
+
261
+ For each leader provide:
262
+ 1. **Company/Product Name**
263
+ 2. **Website URL**
264
+ 3. **Market Position** (e.g., "Market Leader", "Innovative Disruptor", "Established Player")
265
+ 4. **Key Strengths** (what makes them successful - be specific)
266
+ 5. **Notable Features/Offerings** (unique capabilities or products)
267
+ 6. **Market Metrics** (if available: market share, revenue, users, growth rate)
268
+
269
+ Format each leader clearly with headers. Include citations and source URLs.
270
+
271
+ Focus on LEADERS who are doing things RIGHT, not competitors to beat."""
272
+
273
+ state.add_search(
274
+ "Industry Leaders Research",
275
+ f"top companies market leaders industry {topic}",
276
+ self.phase_models.get("industry_leaders"),
277
+ datetime.now().strftime("%Y-%m-%d %H:%M:%S")
278
+ )
279
+
280
+ return self.run_agent_task("industry_leaders", task, use_web_search=True)
281
+
282
+ def research_best_practices(self, topic):
283
+ """ANALYZER AGENT: Research industry best practices and innovative approaches"""
284
+ task = f"""Research BEST PRACTICES and INNOVATIVE APPROACHES for: {topic}
285
+
286
+ **IMPORTANT:** This is about learning from industry excellence, NOT competitive analysis.
287
+ Focus on: What works? What are proven methods? What innovations are emerging?
288
+
289
+ ## 1. Industry Standards & Frameworks
290
+ - Established methodologies and frameworks
291
+ - Common practices across successful implementations
292
+ - Industry certifications or standards
293
+
294
+ ## 2. Success Stories & Case Studies
295
+ - Real-world examples with measurable outcomes
296
+ - Before/after scenarios
297
+ - ROI or impact metrics
298
+
299
+ ## 3. Innovation Patterns (2024-2025)
300
+ - Emerging trends and cutting-edge approaches
301
+ - Technology innovations being adopted
302
+ - What's working well right now
303
+
304
+ ## 4. Implementation Guidelines
305
+ - Step-by-step approaches that work
306
+ - Common architecture patterns
307
+ - Tools and platforms being used
308
+
309
+ ## 5. Key Takeaways
310
+ - What makes implementations successful
311
+ - Common pitfalls to avoid
312
+ - Lessons learned from leaders
313
+
314
+ Provide specific examples with citations and source URLs."""
315
+
316
+ state.add_search(
317
+ "Best Practices Research",
318
+ f"best practices industry standards {topic}",
319
+ self.phase_models.get("best_practices"),
320
+ datetime.now().strftime("%Y-%m-%d %H:%M:%S")
321
+ )
322
+
323
+ return self.run_agent_task("best_practices", task, use_web_search=True)
324
+
325
+ def quality_review(self, research_text):
326
+ """CRITIC AGENT: Independent quality review"""
327
+ task = f"""Perform an INDEPENDENT QUALITY REVIEW of this research:
328
+
329
+ {research_text}
330
+
331
+ Evaluate and provide:
332
+
333
+ ## 1. Research Completeness
334
+ - Are all key areas covered?
335
+ - Any major gaps or missing perspectives?
336
+ - Breadth vs depth assessment
337
+
338
+ ## 2. Source Quality & Credibility
339
+ - How credible are the sources?
340
+ - Are claims well-supported?
341
+ - Any red flags or questionable information?
342
+
343
+ ## 3. Recency & Relevance
344
+ - Is the information current (2024-2025)?
345
+ - How relevant to the topic?
346
+ - Any outdated information?
347
+
348
+ ## 4. Clarity & Usefulness
349
+ - Is the research well-organized?
350
+ - Easy to understand and actionable?
351
+ - Practical value for decision-making?
352
+
353
+ ## 5. Improvement Recommendations
354
+ - What would make this research better?
355
+ - Any critical missing information?
356
+ - Suggested next steps for deeper research?
357
+
358
+ ## 6. Overall Assessment
359
+ - Rate completeness (1-10)
360
+ - Rate quality (1-10)
361
+ - Rate actionability (1-10)
362
+
363
+ Be honest and constructive. This is for improvement, not criticism."""
364
+
365
+ state.add_search(
366
+ "Quality Review",
367
+ "Independent assessment of research quality",
368
+ self.phase_models.get("quality_review"),
369
+ datetime.now().strftime("%Y-%m-%d %H:%M:%S")
370
+ )
371
+
372
+ # Use Qwen model for quality review to avoid tool_choice issues
373
+ original_quality_model = self.phase_models["quality_review"]
374
+ self.phase_models["quality_review"] = "qwen-2.5-72b"
375
+ result = self.run_agent_task("quality_review", task, use_web_search=False)
376
+ self.phase_models["quality_review"] = original_quality_model
377
+ return result
378
+
379
+ def generate_recommendations(self, topic, research_text):
380
+ """SYNTHESIZER AGENT: Generate strategic recommendations"""
381
+ task = f"""Based on this comprehensive research about {topic}:
382
+
383
+ {research_text}
384
+
385
+ Generate a STRATEGIC RECOMMENDATIONS ROADMAP:
386
+
387
+ ## 1. Executive Summary
388
+ - Key findings in 2-3 sentences
389
+ - Primary opportunities identified
390
+ - Critical success factors
391
+
392
+ ## 2. Immediate Actions (0-30 days)
393
+ - Quick wins to implement now
394
+ - Low-hanging fruit
395
+ - Quick assessments or pilots
396
+
397
+ ## 3. Short-term Strategy (1-3 months)
398
+ - Build on immediate actions
399
+ - Implement core initiatives
400
+ - Establish processes
401
+
402
+ ## 4. Long-term Vision (3-12 months)
403
+ - Strategic positioning
404
+ - Competitive advantages
405
+ - Sustainable growth
406
+
407
+ ## 5. Success Metrics
408
+ - KPIs to track progress
409
+ - Milestones and checkpoints
410
+ - How to measure success
411
+
412
+ ## 6. Risk Mitigation
413
+ - Potential challenges
414
+ - Mitigation strategies
415
+ - Contingency plans
416
+
417
+ ## 7. Resource Requirements
418
+ - Team skills needed
419
+ - Tools and platforms
420
+ - Budget considerations (if applicable)
421
+
422
+ ## 8. Next Steps
423
+ - Immediate action items
424
+ - Who should lead
425
+ - Timeline
426
+
427
+ Make recommendations specific, actionable, and grounded in the research."""
428
+
429
+ state.add_search(
430
+ "Strategic Recommendations",
431
+ f"Generate recommendations for {topic}",
432
+ self.phase_models.get("recommendations"),
433
+ datetime.now().strftime("%Y-%m-%d %H:%M:%S")
434
+ )
435
+
436
+ return self.run_agent_task("recommendations", task, use_web_search=False)
437
+
438
+ # ============================================================================
439
+ # MAIN RESEARCH ORCHESTRATION
440
+ # ============================================================================
441
+
442
+ def run_research(topic, model_query, model_leaders, model_practices, model_quality, model_recommendations, progress=gr.Progress()):
443
+ """Main research orchestration with real-time progress and live dashboard"""
444
+
445
+ if not topic or not topic.strip():
446
+ return "❌ Please enter a research topic", "", "", "", "", ""
447
+
448
+ if not HF_TOKEN:
449
+ return "❌ No HF_TOKEN found! Set it in your environment variables or .env file", "", "", "", "", ""
450
+
451
+ # Clear previous state
452
+ state.clear()
453
+
454
+ # Configure phase models based on user selection
455
+ phase_models = {
456
+ "query_understanding": model_query,
457
+ "industry_leaders": model_leaders,
458
+ "best_practices": model_practices,
459
+ "quality_review": model_quality,
460
+ "recommendations": model_recommendations
461
+ }
462
+
463
+ try:
464
+ engine = MultiModelResearchEngine(phase_models)
465
+
466
+ # Initial dashboard message
467
+ state.add_dashboard_update("πŸš€ Research started!")
468
+ state.add_dashboard_update(f"πŸ“Œ Topic: {topic}")
469
+ state.add_dashboard_update(f"πŸ€– Models configured: {len(set(phase_models.values()))} unique models")
470
+ state.add_dashboard_update("")
471
+ state.add_dashboard_update("=" * 60)
472
+
473
+ # ====================================================================
474
+ # PHASE 1: RESEARCHER AGENT (Industry Leaders)
475
+ # ====================================================================
476
+ progress(0, desc="πŸ† RESEARCHER AGENT: Analyzing Industry Leaders...")
477
+ state.add_dashboard_update("πŸ† PHASE 1: RESEARCHER AGENT - Industry Leaders")
478
+ state.add_dashboard_update(f" Model: {AVAILABLE_MODELS[model_leaders]['name']}")
479
+ state.add_dashboard_update(" Status: ⏳ Running...")
480
+
481
+ start_researcher = time.time()
482
+ leaders = engine.research_industry_leaders(topic)
483
+ researcher_time = time.time() - start_researcher
484
+
485
+ state.add_dashboard_update(f" Status: βœ… Complete ({researcher_time:.1f}s)")
486
+ state.add_dashboard_update("")
487
+
488
+ progress(0.25, desc=f"βœ… Researcher Agent completed in {researcher_time:.1f}s\n⭐ ANALYZER AGENT: Researching Best Practices...")
489
+
490
+ # ====================================================================
491
+ # PHASE 2: ANALYZER AGENT (Best Practices)
492
+ # ====================================================================
493
+ state.add_dashboard_update("⭐ PHASE 2: ANALYZER AGENT - Best Practices")
494
+ state.add_dashboard_update(f" Model: {AVAILABLE_MODELS[model_practices]['name']}")
495
+ state.add_dashboard_update(" Status: ⏳ Running...")
496
+
497
+ start_analyzer = time.time()
498
+ practices = engine.research_best_practices(topic)
499
+ analyzer_time = time.time() - start_analyzer
500
+
501
+ state.add_dashboard_update(f" Status: βœ… Complete ({analyzer_time:.1f}s)")
502
+ state.add_dashboard_update("")
503
+
504
+ all_research = f"{leaders}\n\n{practices}"
505
+
506
+ progress(0.50, desc=f"βœ… Analyzer Agent completed in {analyzer_time:.1f}s\nπŸ” CRITIC AGENT: Quality Assurance Review...")
507
+
508
+ # ====================================================================
509
+ # PHASE 3: CRITIC AGENT (Quality Review)
510
+ # ====================================================================
511
+ state.add_dashboard_update("πŸ” PHASE 3: CRITIC AGENT - Quality Review")
512
+ state.add_dashboard_update(f" Model: {AVAILABLE_MODELS[model_quality]['name']}")
513
+ state.add_dashboard_update(" Status: ⏳ Running...")
514
+
515
+ start_critic = time.time()
516
+ review = engine.quality_review(all_research)
517
+ critic_time = time.time() - start_critic
518
+
519
+ state.add_dashboard_update(f" Status: βœ… Complete ({critic_time:.1f}s)")
520
+ state.add_dashboard_update("")
521
+
522
+ progress(0.75, desc=f"βœ… Critic Agent completed in {critic_time:.1f}s\nπŸ’‘ SYNTHESIZER AGENT: Generating Recommendations...")
523
+
524
+ # ====================================================================
525
+ # PHASE 4: SYNTHESIZER AGENT (Recommendations)
526
+ # ====================================================================
527
+ state.add_dashboard_update("πŸ’‘ PHASE 4: SYNTHESIZER AGENT - Recommendations")
528
+ state.add_dashboard_update(f" Model: {AVAILABLE_MODELS[model_recommendations]['name']}")
529
+ state.add_dashboard_update(" Status: ⏳ Running...")
530
+
531
+ start_synthesizer = time.time()
532
+ recommendations = engine.generate_recommendations(topic, all_research)
533
+ synthesizer_time = time.time() - start_synthesizer
534
+
535
+ state.add_dashboard_update(f" Status: βœ… Complete ({synthesizer_time:.1f}s)")
536
+ state.add_dashboard_update("")
537
+
538
+ # ====================================================================
539
+ # FINAL SYNTHESIS
540
+ # ====================================================================
541
+ total_time = researcher_time + analyzer_time + critic_time + synthesizer_time
542
+
543
+ progress(0.95, desc=f"βœ… Synthesizer Agent completed in {synthesizer_time:.1f}s\nπŸ“Š Finalizing results...")
544
+
545
+ state.add_dashboard_update("=" * 60)
546
+ state.add_dashboard_update("πŸ“Š RESEARCH COMPLETE!")
547
+ state.add_dashboard_update("")
548
+ state.add_dashboard_update("πŸ“ˆ EXECUTION SUMMARY:")
549
+ state.add_dashboard_update(f" πŸ† Researcher: {researcher_time:.1f}s {create_progress_bar(100, width=15)}")
550
+ state.add_dashboard_update(f" ⭐ Analyzer: {analyzer_time:.1f}s {create_progress_bar(100, width=15)}")
551
+ state.add_dashboard_update(f" πŸ” Critic: {critic_time:.1f}s {create_progress_bar(100, width=15)}")
552
+ state.add_dashboard_update(f" πŸ’‘ Synthesizer: {synthesizer_time:.1f}s {create_progress_bar(100, width=15)}")
553
+ state.add_dashboard_update(f" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
554
+ state.add_dashboard_update(f" πŸ“ˆ TOTAL TIME: {total_time:.1f}s {create_progress_bar(100, width=15)}")
555
+ state.add_dashboard_update("")
556
+ state.add_dashboard_update("βœ… All agents completed successfully!")
557
+ state.add_dashboard_update(f"πŸ“Š Total searches performed: {len(state.search_history)}")
558
+ state.add_dashboard_update(f"πŸ€– Unique models used: {len(set(u['model'] for u in state.model_usage))}")
559
+
560
+ # Create summary with infographics
561
+ summary = f"""# 🎯 Research Report: {topic}
562
+
563
+ **Generated:** {datetime.now().strftime("%B %d, %Y at %I:%M %p")}
564
+
565
+ {create_hierarchy_diagram()}
566
+
567
+ ---
568
+
569
+ ## βœ… Agent Execution Status
570
+
571
+ | Agent | Status | Duration |
572
+ |-------|--------|----------|
573
+ | πŸ† Researcher | βœ… Complete | {researcher_time:.1f}s |
574
+ | ⭐ Analyzer | βœ… Complete | {analyzer_time:.1f}s |
575
+ | πŸ” Critic | βœ… Complete | {critic_time:.1f}s |
576
+ | πŸ’‘ Synthesizer | βœ… Complete | {synthesizer_time:.1f}s |
577
+
578
+ ---
579
+
580
+ ## ⏱️ Execution Timeline
581
+
582
+ ```
583
+ πŸ† Researcher: {create_progress_bar(100, width=20)} {researcher_time:.1f}s
584
+ ⭐ Analyzer: {create_progress_bar(100, width=20)} {analyzer_time:.1f}s
585
+ πŸ” Critic: {create_progress_bar(100, width=20)} {critic_time:.1f}s
586
+ πŸ’‘ Synthesizer: {create_progress_bar(100, width=20)} {synthesizer_time:.1f}s
587
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
588
+ πŸ“ˆ Total: {create_progress_bar(100, width=20)} {total_time:.1f}s
589
+ ```
590
+
591
+ ---
592
+
593
+ ## πŸ“ˆ Performance Metrics
594
+
595
+ | Metric | Value |
596
+ |--------|-------|
597
+ | **Total Processing Time** | {total_time:.1f}s |
598
+ | **Average Phase Duration** | {total_time/4:.1f}s |
599
+ | **Fastest Phase** | {min(researcher_time, analyzer_time, critic_time, synthesizer_time):.1f}s |
600
+ | **Slowest Phase** | {max(researcher_time, analyzer_time, critic_time, synthesizer_time):.1f}s |
601
+ | **Total Web Searches** | {len(state.search_history)} |
602
+ | **Unique Models Used** | {len(set(u['model'] for u in state.model_usage))} |
603
+
604
+ ---
605
+
606
+ ## 🎯 Research Coverage
607
+
608
+ | Phase | Model | Status |
609
+ |-------|-------|--------|
610
+ | πŸ† Industry Leaders | {AVAILABLE_MODELS[model_leaders]['name'].split('/')[-1]} | βœ… |
611
+ | ⭐ Best Practices | {AVAILABLE_MODELS[model_practices]['name'].split('/')[-1]} | βœ… |
612
+ | πŸ” Quality Review | {AVAILABLE_MODELS[model_quality]['name'].split('/')[-1]} | βœ… |
613
+ | πŸ’‘ Recommendations | {AVAILABLE_MODELS[model_recommendations]['name'].split('/')[-1]} | βœ… |
614
+
615
+ ---
616
+
617
+ ## πŸ“Š Research Metadata
618
+
619
+ - **Topic:** {topic}
620
+ - **Generated:** {datetime.now().strftime("%B %d, %Y at %I:%M %p")}
621
+ - **Data Recency:** 2024-2025
622
+ - **Total Searches:** {len(state.search_history)}
623
+ - **Success Rate:** 100% βœ…
624
+ """
625
+
626
+ # Get dashboard display
627
+ dashboard_display = state.get_dashboard_display()
628
+
629
+ progress(1.0, desc="βœ… Research Complete!")
630
+
631
+ return summary, leaders, practices, review, recommendations, dashboard_display
632
+
633
+ except Exception as e:
634
+ state.add_dashboard_update(f"❌ ERROR: {str(e)}")
635
+ error = f"""❌ **Error:** {str(e)}
636
+
637
+ **Troubleshooting:**
638
+
639
+ 1. **Check API Keys** - Verify HF_TOKEN is set:
640
+ ```
641
+ export HF_TOKEN=your_huggingface_token
642
+ ```
643
+
644
+ 2. **Get HF Token** - Visit: https://huggingface.co/settings/tokens
645
+ - Click "New token"
646
+ - Copy token (starts with hf_...)
647
+
648
+ 3. **Check Internet** - Ensure stable connection for web searches
649
+
650
+ 4. **Try Default Models** - Use Qwen models if others fail
651
+
652
+ 5. **Simplify Topic** - Try a more specific, focused research query
653
+ """
654
+ dashboard_display = state.get_dashboard_display()
655
+ return error, "", "", "", "", dashboard_display
656
+
657
+ # Helper function to get available models
658
+ def get_available_model_choices():
659
+ """Get list of available models based on API keys present"""
660
+ available = []
661
+
662
+ for key, config in AVAILABLE_MODELS.items():
663
+ api_key = config["api_key_required"]
664
+ if api_key == "HF_TOKEN" and HF_TOKEN:
665
+ available.append((f"{config['description']}", key))
666
+
667
+ if not available:
668
+ available = [("Qwen 2.5 7B (Default)", "qwen-2.5-7b")]
669
+
670
+ return available
671
+
672
+ # ============================================================================
673
+ # CREATE GRADIO INTERFACE
674
+ # ============================================================================
675
+
676
+ def create_interface():
677
+ """Create and return the Gradio interface"""
678
+
679
+ with gr.Blocks(theme=gr.themes.Soft(), title="Multi-Model Research System") as demo:
680
+
681
+ gr.Markdown("""
682
+ # πŸ›οΈ Multi-Model Research System
683
+ ### Intelligent Market Research with Real-Time Progress & Live Dashboard
684
+ """)
685
+
686
+ with gr.Row():
687
+ with gr.Column(scale=3):
688
+ topic_input = gr.Textbox(
689
+ label="πŸ” What do you want to research?",
690
+ placeholder="Example: 'AI project management tools', 'Sustainable fashion brands', 'Electric vehicle charging'",
691
+ lines=2
692
+ )
693
+
694
+ with gr.Accordion("πŸ”‘ API Status & Models Available", open=False):
695
+ api_info = f"""
696
+ **API Keys Loaded:**
697
+ - HF_TOKEN: {'βœ… Active' if HF_TOKEN else '❌ Required'}
698
+
699
+ **Available Models:** {len([k for k, v in AVAILABLE_MODELS.items() if v['api_key_required'] == 'HF_TOKEN' and HF_TOKEN])}
700
+ """
701
+ gr.Markdown(api_info)
702
+
703
+ with gr.Column(scale=2):
704
+ gr.Markdown("""
705
+ ### πŸ“Š Your Research Will Include
706
+
707
+ | Component | Description |
708
+ |-----------|-------------|
709
+ | πŸ† **Industry Leaders** | Top 5 companies setting standards |
710
+ | ⭐ **Best Practices** | Proven methods & innovations |
711
+ | πŸ” **Quality Review** | Independent assessment |
712
+ | πŸ’‘ **Recommendations** | Actionable strategic roadmap |
713
+ | πŸ“Š **Live Dashboard** | Real-time progress updates |
714
+ """)
715
+
716
+ # Model Configuration
717
+ with gr.Accordion("πŸ€– Configure AI Models (Optional)", open=False):
718
+ gr.Markdown("**Customize which AI model handles each research phase**")
719
+
720
+ available_choices = get_available_model_choices()
721
+
722
+ with gr.Row():
723
+ model_query = gr.Dropdown(
724
+ choices=available_choices,
725
+ value="qwen-2.5-7b",
726
+ label="1️⃣ Query Understanding"
727
+ )
728
+ model_leaders = gr.Dropdown(
729
+ choices=available_choices,
730
+ value="qwen-2.5-72b",
731
+ label="2️⃣ Industry Leaders"
732
+ )
733
+
734
+ with gr.Row():
735
+ model_practices = gr.Dropdown(
736
+ choices=available_choices,
737
+ value="qwen-2.5-72b",
738
+ label="3️⃣ Best Practices"
739
+ )
740
+ model_quality = gr.Dropdown(
741
+ choices=available_choices,
742
+ value="qwen-2.5-72b",
743
+ label="4️⃣ Quality Review"
744
+ )
745
+
746
+ model_recommendations = gr.Dropdown(
747
+ choices=available_choices,
748
+ value="qwen-2.5-72b",
749
+ label="5️⃣ Recommendations"
750
+ )
751
+
752
+ submit_btn = gr.Button("πŸš€ Start Research", variant="primary", size="lg")
753
+
754
+ gr.Markdown("---")
755
+
756
+ # Live Dashboard - FIRST TAB
757
+ with gr.Tabs():
758
+ with gr.Tab("πŸ“Š Live Dashboard"):
759
+ gr.Markdown("**Real-time progress updates as research happens**")
760
+ dashboard_output = gr.Markdown(value="⏳ Waiting for research to start...", label="Dashboard")
761
+
762
+ with gr.Tab("πŸ“ˆ Summary"):
763
+ gr.Markdown("**Overview of your research with model usage and metadata**")
764
+ summary_output = gr.Markdown()
765
+
766
+ with gr.Tab("πŸ† Industry Leaders"):
767
+ gr.Markdown("**Top 5 companies/products dominating this space**")
768
+ leaders_output = gr.Markdown()
769
+
770
+ with gr.Tab("⭐ Best Practices"):
771
+ gr.Markdown("**Proven strategies and innovative approaches**")
772
+ practices_output = gr.Markdown()
773
+
774
+ with gr.Tab("πŸ” Quality Review"):
775
+ gr.Markdown("**Independent assessment of research quality**")
776
+ review_output = gr.Markdown()
777
+
778
+ with gr.Tab("πŸ’‘ Recommendations"):
779
+ gr.Markdown("**Actionable strategic roadmap**")
780
+ recommendations_output = gr.Markdown()
781
+
782
+ # Connect button
783
+ submit_btn.click(
784
+ fn=run_research,
785
+ inputs=[
786
+ topic_input,
787
+ model_query,
788
+ model_leaders,
789
+ model_practices,
790
+ model_quality,
791
+ model_recommendations
792
+ ],
793
+ outputs=[
794
+ summary_output,
795
+ leaders_output,
796
+ practices_output,
797
+ review_output,
798
+ recommendations_output,
799
+ dashboard_output
800
+ ]
801
+ )
802
+
803
+ gr.Markdown("""
804
+ ---
805
+ ### πŸš€ Quick Start
806
+
807
+ 1. **Set HF_TOKEN** - Add to environment: `export HF_TOKEN=your_token`
808
+ 2. **Enter research topic**
809
+ 3. **Click "Start Research"**
810
+ 4. **Watch the Live Dashboard tab** for real-time updates
811
+ 5. **Results appear in other tabs** as they complete
812
+
813
+ ---
814
+
815
+ ### πŸ“š About This System
816
+
817
+ This is a hierarchical multi-agent research system with:
818
+ - **Supervisor**: Orchestrates the research process
819
+ - **Researcher Agent**: Identifies industry leaders
820
+ - **Analyzer Agent**: Researches best practices
821
+ - **Critic Agent**: Quality assurance review
822
+ - **Synthesizer Agent**: Generates recommendations
823
+
824
+ All agents work in parallel with real-time progress tracking!
825
+ """)
826
+
827
+ return demo
828
+
829
+ # ============================================================================
830
+ # MAIN ENTRY POINT
831
+ # ============================================================================
832
+
833
+ if __name__ == "__main__":
834
+ print("\n" + "="*70)
835
+ print("πŸ›οΈ MULTI-MODEL RESEARCH SYSTEM - LIVE DASHBOARD & REAL-TIME PROGRESS")
836
+ print("="*70)
837
+
838
+ print("\nπŸ”‘ API Keys:")
839
+ print(f" HF_TOKEN: {'βœ… Loaded' if HF_TOKEN else '❌ Missing (REQUIRED)'}")
840
+
841
+ print("\nπŸ“Š Available Models:")
842
+ for key, config in AVAILABLE_MODELS.items():
843
+ has_key = config["api_key_required"] == "HF_TOKEN" and HF_TOKEN
844
+ status = "βœ…" if has_key else "❌"
845
+ print(f" {status} {config['name']}")
846
+
847
+ if not HF_TOKEN:
848
+ print("\n⚠️ WARNING: HF_TOKEN not found!")
849
+ print(" Set it with: export HF_TOKEN=your_huggingface_token")
850
+ else:
851
+ print("\nβœ… Ready to launch!")
852
+
853
+ print("\nπŸš€ Starting server...")
854
+ print("="*70 + "\n")
855
+
856
+ demo = create_interface()
857
+ demo.launch(
858
+ server_name="0.0.0.0",
859
+ server_port=7860,
860
+ share=False
861
+ )
hf_.env.example ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Multi-Agent Research System - Environment Configuration
2
+ # Copy this file to .env and fill in your actual values
3
+
4
+ # REQUIRED: HuggingFace API Token
5
+ # Get it from: https://huggingface.co/settings/tokens
6
+ HF_TOKEN=hf_your_token_here
7
+
8
+ # OPTIONAL: Anthropic API Key (for future extensions)
9
+ # Get it from: https://console.anthropic.com/
10
+ ANTHROPIC_API_KEY=sk_your_key_here
11
+
12
+ # OPTIONAL: OpenAI API Key (for future extensions)
13
+ # Get it from: https://platform.openai.com/api-keys
14
+ OPENAI_API_KEY=sk_your_key_here
15
+
16
+ # Application Configuration
17
+ APP_NAME=Multi-Model Research System
18
+ APP_VERSION=1.0.0
19
+ DEBUG=false
20
+
21
+ # Server Configuration
22
+ SERVER_HOST=0.0.0.0
23
+ SERVER_PORT=7860
24
+ SHARE=false
25
+
26
+ # Model Configuration
27
+ DEFAULT_MODEL_QUERY=qwen-2.5-7b
28
+ DEFAULT_MODEL_LEADERS=qwen-2.5-72b
29
+ DEFAULT_MODEL_PRACTICES=qwen-2.5-72b
30
+ DEFAULT_MODEL_QUALITY=qwen-2.5-72b
31
+ DEFAULT_MODEL_RECOMMENDATIONS=qwen-2.5-72b
32
+
33
+ # Research Configuration
34
+ RESEARCH_TIMEOUT=120
35
+ MAX_RETRIES=3
36
+ WEB_SEARCH_ENABLED=true
37
+ QUALITY_REVIEW_ENABLED=true
38
+
39
+ # Logging Configuration
40
+ LOG_LEVEL=INFO
41
+ LOG_SEARCHES=true
42
+ LOG_MODEL_USAGE=true
43
+ LOG_EXECUTION_TIME=true
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio==4.44.0
2
+ smolagents>=1.0.0
3
+ pyyaml>=6.0
4
+ python-dotenv>=1.0.0
5
+ huggingface-hub>=0.20.0
6
+ requests>=2.31.0