File size: 14,472 Bytes
e5a20e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import os
import gradio as gr
from crewai import Agent, Task, Crew, Process, LLM
from crewai_tools import SerperDevTool
import tempfile
from datetime import datetime

# Initialize LLM
llm = LLM(model="gemini/gemini-2.5-flash")

class PersonalResearchAssistant:
    def __init__(self):
        self.search_tool = SerperDevTool()

    def create_agents(self):
        # Research Coordinator - orchestrates the research process
        coordinator = Agent(
            role="Research Coordinator",
            goal="Orchestrate comprehensive research by coordinating multiple specialized agents",
            backstory="""You are a senior research coordinator with expertise in managing 
            complex research projects. You excel at breaking down research queries into 
            specific tasks and coordinating multiple specialists to deliver comprehensive results.""",
            llm=llm,
            verbose=True,
            allow_delegation=True
        )

        # Primary Researcher - conducts initial research
        primary_researcher = Agent(
            role="Primary Research Specialist",
            goal="Conduct comprehensive initial research on the given topic",
            backstory="""You are a senior research specialist with 15+ years of experience 
            in conducting thorough research across multiple domains. You excel at finding 
            relevant, current, and authoritative sources.""",
            tools=[self.search_tool],
            llm=llm,
            verbose=True,
            allow_delegation=False
        )

        # Domain Expert - provides specialized knowledge
        domain_expert = Agent(
            role="Domain Expert Analyst",
            goal="Provide specialized domain expertise and deep analysis",
            backstory="""You are a domain expert with deep knowledge across multiple fields. 
            You can quickly identify key concepts, trends, and implications within any subject area.""",
            tools=[self.search_tool],
            llm=llm,
            verbose=True,
            allow_delegation=False
        )

        # Fact Checker - verifies information accuracy
        fact_checker = Agent(
            role="Fact Verification Specialist",
            goal="Verify facts and cross-reference information for accuracy",
            backstory="""You are a meticulous fact-checker with expertise in verifying 
            information across multiple sources. You excel at identifying inconsistencies 
            and ensuring information accuracy.""",
            tools=[self.search_tool],
            llm=llm,
            verbose=True,
            allow_delegation=False
        )

        # Trend Analyst - identifies patterns and trends
        trend_analyst = Agent(
            role="Trend Analysis Expert",
            goal="Identify trends, patterns, and future implications",
            backstory="""You are a trend analysis expert who specializes in identifying 
            patterns, emerging trends, and predicting future developments based on current data.""",
            tools=[self.search_tool],
            llm=llm,
            verbose=True,
            allow_delegation=False
        )

        # Report Writer - synthesizes findings
        report_writer = Agent(
            role="Senior Report Writer",
            goal="Synthesize research findings into comprehensive, well-structured reports",
            backstory="""You are an expert technical writer with a talent for synthesizing 
            complex research into clear, engaging, and well-structured reports that are 
            accessible to various audiences.""",
            llm=llm,
            verbose=True,
            allow_delegation=False
        )

        return coordinator, primary_researcher, domain_expert, fact_checker, trend_analyst, report_writer

    def create_tasks(self, query, coordinator, primary_researcher, domain_expert, fact_checker, trend_analyst, report_writer):
        # Task 1: Research Coordination
        coordination_task = Task(
            description=f"""Analyze the research query: "{query}"
            
            Break down this query into specific research areas and coordinate the research process:
            1. Identify key research areas and subtopics
            2. Determine the scope and depth needed
            3. Plan the research strategy
            4. Coordinate with other agents for comprehensive coverage
            
            Provide a research plan and coordinate the overall process.""",
            expected_output="""A comprehensive research coordination plan including:
            - Key research areas identified
            - Research strategy and approach
            - Coordination guidelines for other agents""",
            agent=coordinator
        )

        # Task 2: Primary Research
        primary_research_task = Task(
            description=f"""Conduct comprehensive primary research on: "{query}"
            
            Focus on:
            1. Current state and recent developments
            2. Key players and organizations involved
            3. Recent news and updates
            4. Statistical data and metrics
            5. Expert opinions and analysis
            
            Use multiple search queries to gather comprehensive information.""",
            expected_output="""Detailed primary research findings including:
            - Current state analysis
            - Key developments and news
            - Statistical data and metrics
            - Expert opinions and sources""",
            agent=primary_researcher,
            context=[coordination_task]
        )

        # Task 3: Domain Expert Analysis
        domain_analysis_task = Task(
            description=f"""Provide expert domain analysis for: "{query}"
            
            Focus on:
            1. Technical aspects and complexities
            2. Industry-specific implications
            3. Regulatory and compliance considerations
            4. Best practices and standards
            5. Challenges and opportunities
            
            Provide deep domain expertise and specialized insights.""",
            expected_output="""Expert domain analysis including:
            - Technical analysis and implications
            - Industry-specific insights
            - Regulatory considerations
            - Challenges and opportunities identified""",
            agent=domain_expert,
            context=[coordination_task, primary_research_task]
        )

        # Task 4: Fact Verification
        fact_check_task = Task(
            description=f"""Verify and cross-reference key facts about: "{query}"
            
            Focus on:
            1. Verify statistical claims and data
            2. Cross-reference information across sources
            3. Identify any conflicting information
            4. Validate expert claims and quotes
            5. Ensure information currency and accuracy
            
            Provide fact-checked and verified information.""",
            expected_output="""Fact verification report including:
            - Verified facts and statistics
            - Source credibility assessment
            - Any conflicting information identified
            - Accuracy validation results""",
            agent=fact_checker,
            context=[primary_research_task, domain_analysis_task]
        )

        # Task 5: Trend Analysis
        trend_analysis_task = Task(
            description=f"""Analyze trends and patterns related to: "{query}"
            
            Focus on:
            1. Historical trends and evolution
            2. Current market/industry trends
            3. Emerging patterns and developments
            4. Future predictions and implications
            5. Comparative analysis with related areas
            
            Identify significant trends and their implications.""",
            expected_output="""Comprehensive trend analysis including:
            - Historical trend analysis
            - Current market trends
            - Emerging patterns identified
            - Future predictions and implications""",
            agent=trend_analyst,
            context=[primary_research_task, domain_analysis_task, fact_check_task]
        )

        # Task 6: Final Report Generation
        report_task = Task(
            description=f"""Create a comprehensive research report on: "{query}"
            
            Synthesize all research findings into a well-structured report including:
            1. Executive Summary
            2. Current State Analysis
            3. Key Findings and Insights
            4. Domain Expert Analysis
            5. Trend Analysis and Future Outlook
            6. Verified Facts and Statistics
            7. Conclusions and Recommendations
            8. Sources and References
            
            Ensure the report is comprehensive, well-organized, and actionable.""",
            expected_output="""A comprehensive research report in markdown format with:
            - Executive summary
            - Detailed analysis sections
            - Key findings and insights
            - Trend analysis and predictions
            - Actionable recommendations
            - Properly cited sources""",
            agent=report_writer,
            context=[coordination_task, primary_research_task, domain_analysis_task, fact_check_task, trend_analysis_task],
            output_file="research_report.md"
        )

        return [
            coordination_task,
            primary_research_task,
            domain_analysis_task,
            fact_check_task,
            trend_analysis_task,
            report_task,
        ]

    def conduct_research(self, query, progress=gr.Progress()):
        try:
            progress(0.1, desc="Initializing research agents...")

            # Create agents
            coordinator, primary_researcher, domain_expert, fact_checker, trend_analyst, report_writer = self.create_agents()

            progress(0.2, desc="Creating research tasks...")

            # Create tasks
            tasks = self.create_tasks(query, coordinator, primary_researcher, domain_expert, fact_checker, trend_analyst, report_writer)

            progress(0.3, desc="Starting research crew...")

            # Create and run crew
            crew = Crew(
                agents=[coordinator, primary_researcher, domain_expert, fact_checker, trend_analyst, report_writer],
                tasks=tasks,
                process=Process.sequential,
                verbose=True
            )

            progress(0.4, desc="Conducting comprehensive research...")

            # Execute research
            result = crew.kickoff()

            progress(0.9, desc="Generating final report...")

            # Create downloadable file
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"research_report_{timestamp}.md"

            with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
                f.write(str(result.raw))
                temp_file_path = f.name

            progress(1.0, desc="Research completed!")

            return str(result.raw), temp_file_path

        except Exception as e:
            return f"Error during research: {str(e)}", None

# Initialize the research assistant
research_assistant = PersonalResearchAssistant()

def research_interface(query):
    if not query.strip():
        return "Please enter a research query.", None

    result, file_path = research_assistant.conduct_research(query)

    if file_path:
        return result, file_path
    else:
        return result, None

# Create Gradio interface
with gr.Blocks(title="Personal Research Assistant", theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        """
    # πŸ” Personal Research Assistant

    **Powered by CrewAI with Multiple Specialized Agents & Gemini 2.5 Flash**

    This advanced research assistant uses 6 specialized AI agents working together:
    - **Research Coordinator**: Orchestrates the entire research process
    - **Primary Researcher**: Conducts comprehensive initial research
    - **Domain Expert**: Provides specialized knowledge and analysis
    - **Fact Checker**: Verifies information accuracy across sources
    - **Trend Analyst**: Identifies patterns and future implications
    - **Report Writer**: Synthesizes findings into comprehensive reports

    Enter your research query below and get a comprehensive, multi-perspective analysis!
    """
    )

    with gr.Row():
        with gr.Column(scale=3):
            query_input = gr.Textbox(
                label="Research Query",
                placeholder="Enter your detailed research question (e.g., 'Latest developments in quantum computing and their impact on cybersecurity')",
                lines=3,
            )

            research_btn = gr.Button("πŸš€ Start Research", variant="primary", size="lg")

        with gr.Column(scale=1):
            gr.Markdown(
                """
            ### πŸ’‘ Tips for Better Results:
            - Be specific and detailed
            - Include context or scope
            - Mention particular aspects you're interested in
            - Ask for comparisons or analysis
            """
            )

    with gr.Row():
        with gr.Column():
            output = gr.Textbox(
                label="Research Report", lines=20, max_lines=50, show_copy_button=True
            )

        with gr.Column(scale=0.3):
            download_file = gr.File(
                label="πŸ“₯ Download Report",
                file_types=[".md"],
            )

    # Example queries
    gr.Examples(
        examples=[
            ["Impact of artificial intelligence on healthcare industry in 2024"],
            ["Sustainable energy solutions and their economic implications"],
            ["Cybersecurity threats in remote work environments"],
            ["Latest developments in electric vehicle technology and market trends"],
            ["Climate change effects on global agriculture and food security"],
        ],
        inputs=query_input,
    )

    research_btn.click(
        fn=research_interface,
        inputs=[query_input],
        outputs=[output, download_file],
        show_progress=True,
    )

# Launch the app
if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True
    )