GhufranAI commited on
Commit
feed86d
Β·
verified Β·
1 Parent(s): 0c76b4f

Upload app_multiagent.py

Browse files
Files changed (1) hide show
  1. app_multiagent.py +427 -0
app_multiagent.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Streamlit App for Multi-Agent Research Assistant
3
+ ================================================
4
+ Beautiful UI with real-time progress tracking and interactive results
5
+ """
6
+
7
+ import streamlit as st
8
+ import sys
9
+ import os
10
+ from datetime import datetime
11
+ import json
12
+
13
+ # Add the project directory to path
14
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
15
+
16
+ # Import the multi-agent system
17
+ from multi_agent_system import MultiAgentSystem
18
+
19
+ # Page configuration
20
+ st.set_page_config(
21
+ page_title="Multi-Agent Research Assistant",
22
+ page_icon="πŸ€–",
23
+ layout="wide",
24
+ initial_sidebar_state="expanded"
25
+ )
26
+
27
+ # Custom CSS
28
+ st.markdown("""
29
+ <style>
30
+ .main-header {
31
+ font-size: 3rem;
32
+ font-weight: bold;
33
+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
34
+ -webkit-background-clip: text;
35
+ -webkit-text-fill-color: transparent;
36
+ text-align: center;
37
+ margin-bottom: 1rem;
38
+ }
39
+ .sub-header {
40
+ text-align: center;
41
+ color: #666;
42
+ margin-bottom: 2rem;
43
+ }
44
+ .agent-box {
45
+ padding: 1rem;
46
+ border-radius: 10px;
47
+ margin: 1rem 0;
48
+ border-left: 4px solid;
49
+ }
50
+ .researcher-box {
51
+ background-color: #e3f2fd;
52
+ border-color: #2196f3;
53
+ }
54
+ .analyst-box {
55
+ background-color: #f3e5f5;
56
+ border-color: #9c27b0;
57
+ }
58
+ .writer-box {
59
+ background-color: #e8f5e9;
60
+ border-color: #4caf50;
61
+ }
62
+ .critic-box {
63
+ background-color: #fff3e0;
64
+ border-color: #ff9800;
65
+ }
66
+ .metric-card {
67
+ background: white;
68
+ padding: 1.5rem;
69
+ border-radius: 10px;
70
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
71
+ text-align: center;
72
+ }
73
+ .stButton>button {
74
+ width: 100%;
75
+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
76
+ color: white;
77
+ border: none;
78
+ padding: 0.75rem;
79
+ font-size: 1.1rem;
80
+ font-weight: bold;
81
+ border-radius: 8px;
82
+ transition: transform 0.2s;
83
+ }
84
+ .stButton>button:hover {
85
+ transform: translateY(-2px);
86
+ box-shadow: 0 4px 8px rgba(0,0,0,0.2);
87
+ }
88
+ </style>
89
+ """, unsafe_allow_html=True)
90
+
91
+
92
+ # Initialize session state
93
+ if 'system' not in st.session_state:
94
+ st.session_state.system = None
95
+ if 'research_history' not in st.session_state:
96
+ st.session_state.research_history = []
97
+ if 'current_result' not in st.session_state:
98
+ st.session_state.current_result = None
99
+
100
+
101
+ def initialize_system(token):
102
+ """Initialize the multi-agent system"""
103
+ try:
104
+ with st.spinner("πŸ€– Initializing AI agents..."):
105
+ system = MultiAgentSystem(token=token, max_iterations=2)
106
+ st.success("βœ… System initialized successfully!")
107
+ return system
108
+ except Exception as e:
109
+ st.error(f"❌ Initialization failed: {str(e)}")
110
+ return None
111
+
112
+
113
+ def display_progress(step):
114
+ """Display progress bar based on current step"""
115
+ steps = {
116
+ "researcher": (25, "πŸ” Researching..."),
117
+ "analyst": (50, "πŸ“Š Analyzing..."),
118
+ "writer": (75, "✍️ Writing report..."),
119
+ "critic": (90, "🎯 Quality check..."),
120
+ "complete": (100, "βœ… Complete!")
121
+ }
122
+
123
+ if step in steps:
124
+ progress, text = steps[step]
125
+ st.progress(progress)
126
+ st.info(text)
127
+
128
+
129
+ def display_agent_output(agent_name, content, box_class):
130
+ """Display agent output in a styled box"""
131
+ st.markdown(f'<div class="agent-box {box_class}">', unsafe_allow_html=True)
132
+ st.markdown(f"### {agent_name}")
133
+ st.markdown(content)
134
+ st.markdown('</div>', unsafe_allow_html=True)
135
+
136
+
137
+ def main():
138
+ # Header
139
+ st.markdown('<h1 class="main-header">πŸ€– Multi-Agent Research Assistant</h1>', unsafe_allow_html=True)
140
+ st.markdown('<p class="sub-header">Powered by LangGraph & Advanced AI Agents</p>', unsafe_allow_html=True)
141
+
142
+ # Sidebar
143
+ with st.sidebar:
144
+ st.header("βš™οΈ Configuration")
145
+
146
+ # Token input
147
+ token = st.text_input(
148
+ "HuggingFace API Token",
149
+ type="password",
150
+ help="Enter your HuggingFace API token"
151
+ )
152
+
153
+ # Initialize button
154
+ if st.button("πŸš€ Initialize System"):
155
+ if token:
156
+ st.session_state.system = initialize_system(token)
157
+ else:
158
+ st.error("Please enter your HuggingFace token")
159
+
160
+ st.divider()
161
+
162
+ # System status
163
+ st.header("πŸ“Š System Status")
164
+ if st.session_state.system:
165
+ st.success("🟒 System Active")
166
+ st.metric("Research Queries", len(st.session_state.research_history))
167
+ else:
168
+ st.warning("πŸ”΄ System Inactive")
169
+
170
+ st.divider()
171
+
172
+ # Example questions
173
+ st.header("πŸ’‘ Example Questions")
174
+ examples = [
175
+ "what is 2+2",
176
+ "calculate (15*3)+7",
177
+ "what is artificial intelligence",
178
+ "what is machine learning",
179
+ "what is python programming"
180
+ ]
181
+
182
+ for example in examples:
183
+ if st.button(f"πŸ“ {example}", key=f"ex_{example}"):
184
+ st.session_state.example_question = example
185
+
186
+ st.divider()
187
+
188
+ # History
189
+ st.header("πŸ“š Research History")
190
+ if st.session_state.research_history:
191
+ for i, item in enumerate(reversed(st.session_state.research_history[-5:])):
192
+ with st.expander(f"πŸ” {item['question'][:30]}..."):
193
+ st.write(f"**Time:** {item['timestamp']}")
194
+ st.write(f"**Score:** {item['score']}/10")
195
+ else:
196
+ st.info("No research history yet")
197
+
198
+ st.divider()
199
+
200
+ # Clear history
201
+ if st.button("πŸ—‘οΈ Clear History"):
202
+ st.session_state.research_history = []
203
+ st.session_state.current_result = None
204
+ st.rerun()
205
+
206
+ # Main content
207
+ if not st.session_state.system:
208
+ # Welcome screen
209
+ col1, col2, col3 = st.columns([1, 2, 1])
210
+ with col2:
211
+ st.info("πŸ‘ˆ Please initialize the system using the sidebar")
212
+
213
+ st.markdown("### 🌟 Features")
214
+ features = [
215
+ "πŸ” **Smart Research**: Automatic tool selection and execution",
216
+ "πŸ“Š **Deep Analysis**: AI-powered insight extraction",
217
+ "✍️ **Professional Reports**: Well-structured documentation",
218
+ "🎯 **Quality Assurance**: Automated review and refinement",
219
+ "πŸ”„ **Iterative Improvement**: Multiple revision cycles"
220
+ ]
221
+ for feature in features:
222
+ st.markdown(feature)
223
+
224
+ st.markdown("### πŸ› οΈ Technology Stack")
225
+ tech = [
226
+ "LangGraph for agent orchestration",
227
+ "Meta Llama 3.1 8B Instruct",
228
+ "Pydantic for structured outputs",
229
+ "NumExpr for safe calculations"
230
+ ]
231
+ for item in tech:
232
+ st.markdown(f"- {item}")
233
+
234
+ else:
235
+ # Research interface
236
+ st.markdown("## πŸ” Ask Your Question")
237
+
238
+ # Check if example was clicked
239
+ default_question = st.session_state.get('example_question', '')
240
+ if default_question:
241
+ st.session_state.example_question = ''
242
+
243
+ question = st.text_input(
244
+ "Enter your research question:",
245
+ value=default_question,
246
+ placeholder="e.g., what is 2+2, what is artificial intelligence...",
247
+ key="question_input"
248
+ )
249
+
250
+ col1, col2 = st.columns([3, 1])
251
+ with col1:
252
+ research_button = st.button("πŸš€ Start Research", type="primary")
253
+ with col2:
254
+ clear_button = st.button("πŸ”„ Clear Results")
255
+
256
+ if clear_button:
257
+ st.session_state.current_result = None
258
+ st.rerun()
259
+
260
+ if research_button and question:
261
+ # Create progress container
262
+ progress_container = st.container()
263
+ result_container = st.container()
264
+
265
+ with progress_container:
266
+ st.markdown("### πŸ”„ Research in Progress")
267
+ progress_bar = st.progress(0)
268
+ status_text = st.empty()
269
+
270
+ # Capture output
271
+ import io
272
+ from contextlib import redirect_stdout
273
+
274
+ output_capture = io.StringIO()
275
+
276
+ try:
277
+ with redirect_stdout(output_capture):
278
+ # Run research
279
+ final_state = st.session_state.system.research(question)
280
+
281
+ # Update progress
282
+ progress_bar.progress(100)
283
+ status_text.success("βœ… Research Complete!")
284
+
285
+ if final_state:
286
+ # Store result
287
+ st.session_state.current_result = final_state
288
+
289
+ # Add to history
290
+ st.session_state.research_history.append({
291
+ 'question': question,
292
+ 'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
293
+ 'score': final_state['critique_output'].score
294
+ })
295
+
296
+ st.rerun()
297
+
298
+ except Exception as e:
299
+ progress_bar.progress(100)
300
+ status_text.error(f"❌ Error: {str(e)}")
301
+
302
+ # Display results
303
+ if st.session_state.current_result:
304
+ st.markdown("---")
305
+ result = st.session_state.current_result
306
+
307
+ # Metrics row
308
+ st.markdown("## πŸ“Š Research Metrics")
309
+ col1, col2, col3, col4 = st.columns(4)
310
+
311
+ with col1:
312
+ st.markdown('<div class="metric-card">', unsafe_allow_html=True)
313
+ st.metric("Quality Score", f"{result['critique_output'].score}/10")
314
+ st.markdown('</div>', unsafe_allow_html=True)
315
+
316
+ with col2:
317
+ st.markdown('<div class="metric-card">', unsafe_allow_html=True)
318
+ st.metric("Iterations", result['report_iterations'])
319
+ st.markdown('</div>', unsafe_allow_html=True)
320
+
321
+ with col3:
322
+ st.markdown('<div class="metric-card">', unsafe_allow_html=True)
323
+ st.metric("Confidence", f"{result['research_output'].confidence*100:.0f}%")
324
+ st.markdown('</div>', unsafe_allow_html=True)
325
+
326
+ with col4:
327
+ st.markdown('<div class="metric-card">', unsafe_allow_html=True)
328
+ sources = ", ".join(result['research_output'].sources_used)
329
+ st.metric("Sources", len(result['research_output'].sources_used))
330
+ st.caption(sources)
331
+ st.markdown('</div>', unsafe_allow_html=True)
332
+
333
+ st.markdown("---")
334
+
335
+ # Tabbed interface for results
336
+ tab1, tab2, tab3, tab4 = st.tabs(["πŸ“„ Final Report", "πŸ” Research", "πŸ“Š Analysis", "🎯 Quality Review"])
337
+
338
+ with tab1:
339
+ report = result['report_output']
340
+ st.markdown(f"# {report.title}")
341
+ st.markdown(report.content)
342
+
343
+ # Download button
344
+ st.download_button(
345
+ label="πŸ“₯ Download Report",
346
+ data=report.content,
347
+ file_name=f"research_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
348
+ mime="text/plain"
349
+ )
350
+
351
+ with tab2:
352
+ research = result['research_output']
353
+ display_agent_output(
354
+ "πŸ” Research Agent",
355
+ f"""
356
+ **Answer:** {research.answer}
357
+
358
+ **Sources Used:** {', '.join(research.sources_used)}
359
+
360
+ **Confidence:** {research.confidence*100:.1f}%
361
+ """,
362
+ "researcher-box"
363
+ )
364
+
365
+ with tab3:
366
+ analysis = result['analysis_output']
367
+ display_agent_output(
368
+ "πŸ“Š Analysis Agent",
369
+ f"""
370
+ **Key Points:**
371
+ {chr(10).join(f'β€’ {point}' for point in analysis.key_points)}
372
+
373
+ **Implications:**
374
+ {analysis.implications}
375
+ """,
376
+ "analyst-box"
377
+ )
378
+
379
+ with tab4:
380
+ critique = result['critique_output']
381
+
382
+ # Score gauge
383
+ score = critique.score
384
+ color = "🟒" if score >= 8 else "🟑" if score >= 6 else "πŸ”΄"
385
+
386
+ st.markdown(f"### {color} Quality Score: {score}/10")
387
+ st.progress(score / 10)
388
+
389
+ st.markdown(f"""
390
+ **Status:** {"βœ… Approved" if not critique.needs_revision else "πŸ”„ Needs Revision"}
391
+ """)
392
+
393
+ # Export all data
394
+ st.markdown("---")
395
+ if st.button("πŸ“¦ Export Full Research Data (JSON)"):
396
+ export_data = {
397
+ 'question': result['question'],
398
+ 'timestamp': datetime.now().isoformat(),
399
+ 'research': {
400
+ 'answer': result['research_output'].answer,
401
+ 'sources': result['research_output'].sources_used,
402
+ 'confidence': result['research_output'].confidence
403
+ },
404
+ 'analysis': {
405
+ 'key_points': result['analysis_output'].key_points,
406
+ 'implications': result['analysis_output'].implications
407
+ },
408
+ 'report': {
409
+ 'title': result['report_output'].title,
410
+ 'content': result['report_output'].content
411
+ },
412
+ 'quality': {
413
+ 'score': result['critique_output'].score,
414
+ 'needs_revision': result['critique_output'].needs_revision
415
+ }
416
+ }
417
+
418
+ st.download_button(
419
+ label="πŸ“₯ Download JSON",
420
+ data=json.dumps(export_data, indent=2),
421
+ file_name=f"research_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
422
+ mime="application/json"
423
+ )
424
+
425
+
426
+ if __name__ == "__main__":
427
+ main()