Sayandip's picture
Create app.py
e5a20e1 verified
Raw
History Blame Contribute Delete
14.5 kB
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
)