jindalgoldy commited on
Commit
7f44461
β€’
1 Parent(s): fd6257b

Upload 5 files

Browse files
Files changed (5) hide show
  1. agents.py +95 -0
  2. app.py +92 -0
  3. requirements.txt +7 -0
  4. tasks.py +32 -0
  5. tools.py +12 -0
agents.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from crewai import Agent
2
+ import os
3
+ from dotenv import load_dotenv
4
+ from langchain_google_genai import ChatGoogleGenerativeAI
5
+ from tools import tool
6
+
7
+ import smtplib
8
+ from email.mime.text import MIMEText
9
+ from email.mime.multipart import MIMEMultipart
10
+
11
+ load_dotenv()
12
+ import asyncio
13
+
14
+ try:
15
+ loop = asyncio.get_running_loop()
16
+ except RuntimeError:
17
+ loop = asyncio.new_event_loop()
18
+ asyncio.set_event_loop(loop)
19
+
20
+ # Defining the base llm model
21
+ llm = ChatGoogleGenerativeAI(
22
+ model="gemini-1.5-flash",
23
+ google_api_key=os.environ.get("GOOGLE_API_KEY"),
24
+ temperature=0.5,
25
+ verbose=True
26
+ )
27
+
28
+ def send_email(to_email, subject, body):
29
+ from_email = os.environ.get("FROM_EMAIL")
30
+ password = os.environ.get("EMAIL_PASSWORD")
31
+ smtp_server = os.environ.get("SMTP_SERVER")
32
+ smtp_port = int(os.environ.get("SMTP_PORT"))
33
+
34
+ # Create the email content
35
+ msg = MIMEMultipart()
36
+ msg['From'] = from_email
37
+ msg['To'] = to_email
38
+ msg['Subject'] = subject
39
+
40
+ msg.attach(MIMEText(body, 'plain'))
41
+
42
+ try:
43
+ # Create a secure SSL context and log in to the email server
44
+ with smtplib.SMTP(smtp_server, smtp_port) as server:
45
+ server.starttls() # Upgrade to a secure connection
46
+ server.login(from_email, password)
47
+ server.sendmail(from_email, to_email, msg.as_string())
48
+ print("Email sent successfully.")
49
+ except Exception as e:
50
+ print(f"Failed to send email: {e}")
51
+
52
+ async def generate_report_and_send_email(report, email):
53
+ subject = "Market Research & Precaution Report"
54
+ body = f"Here is your report:\n\n{report}"
55
+ print("Sending email to:", email)
56
+ send_email(email, subject, body)
57
+
58
+ # Define the agents
59
+ news_research_agent = Agent(
60
+ role="News Research and Summarization Agent",
61
+ goal="Research and summarize the top news article related to {input_text}.",
62
+ verbose=True,
63
+ memory=True,
64
+ backstory=("You are a News Research and Summarization Agent responsible for gathering news articles "
65
+ "related to user input. Your goal is to summarize the top article in four sentences."),
66
+ tools=[tool],
67
+ llm=llm,
68
+ allow_delegation=False
69
+ )
70
+
71
+ # 2. Precaution Recommendation Agent
72
+ precaution_agent = Agent(
73
+ role="Precaution Recommendation Agent",
74
+ goal="Provide three precautionary steps based on the summary of the top news article.",
75
+ verbose=True,
76
+ memory=True,
77
+ backstory=("You are a Precaution Recommendation Agent responsible for analyzing the summary of a news article "
78
+ "and generating three precautionary steps to mitigate any potential risks."),
79
+ tools=[tool],
80
+ llm=llm,
81
+ allow_delegation=False
82
+ )
83
+
84
+ # 3. Comprehensive Report Generation Agent
85
+ report_generation_agent = Agent(
86
+ role="Comprehensive Report Generation Agent",
87
+ goal="Create a comprehensive report combining the news summary and precautionary steps, then send it via email.",
88
+ verbose=True,
89
+ memory=True,
90
+ backstory=("You are a Comprehensive Report Generation Agent responsible for compiling the summary from the News Research Agent "
91
+ "and the precautionary steps from the Precaution Recommendation Agent into a detailed report."),
92
+ tools=[tool],
93
+ llm=llm,
94
+ allow_delegation=False
95
+ )
app.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import re
3
+ import sys
4
+ from crewai import Crew, Process
5
+ import os
6
+ import asyncio
7
+ from agents import (
8
+ news_research_agent,
9
+ precaution_agent,
10
+ report_generation_agent,
11
+ generate_report_and_send_email
12
+ )
13
+ from tasks import (
14
+ news_research_task,
15
+ precaution_task,
16
+ report_generation_task,
17
+ )
18
+
19
+ # Used to stream sys output on the Streamlit frontend
20
+ class StreamToContainer:
21
+ def __init__(self, container):
22
+ self.container = container
23
+ self.buffer = []
24
+ self.colors = ['red', 'green', 'blue', 'orange']
25
+ self.color_index = 0
26
+
27
+ def write(self, data):
28
+ # Filter out ANSI escape codes using a regular expression
29
+ cleaned_data = re.sub(r'\x1B\[[0-9;]*[mK]', '', data)
30
+
31
+ # Check if the text contains the specified phrase and apply color
32
+ if "Entering new CrewAgentExecutor chain" in cleaned_data:
33
+ self.color_index = (self.color_index + 1) % len(self.colors)
34
+ cleaned_data = cleaned_data.replace(
35
+ "Entering new CrewAgentExecutor chain",
36
+ f":{self.colors[self.color_index]}[Entering new CrewAgentExecutor chain]",
37
+ )
38
+
39
+ # Apply colors to agent names
40
+ for agent_name in ["News Research and Summarization Agent",
41
+ "Precaution Recommendation Agent",
42
+ "Comprehensive Report Generation Agent"]:
43
+ if agent_name in cleaned_data:
44
+ cleaned_data = cleaned_data.replace(agent_name, f":{self.colors[self.color_index]}[{agent_name}]")
45
+
46
+ if "Finished chain." in cleaned_data:
47
+ cleaned_data = cleaned_data.replace("Finished chain.", f":{self.colors[self.color_index]}[Finished chain.]")
48
+
49
+ self.buffer.append(cleaned_data)
50
+ if "\n" in data:
51
+ self.container.markdown(''.join(self.buffer), unsafe_allow_html=True)
52
+ self.buffer = []
53
+
54
+ # Streamlit UI
55
+ st.header("News Summarization & Precaution Recommendation System")
56
+ st.subheader("Generate a comprehensive report based on news articles!", divider="rainbow", anchor=False)
57
+
58
+ # User input form
59
+ with st.form("form"):
60
+ input_text = st.text_input("Enter a topic or keyword", key="input_text")
61
+ email = st.text_input("Enter your email address", key="email")
62
+ submitted = st.form_submit_button("Submit")
63
+
64
+ # Process the submission
65
+ if submitted:
66
+ with st.status("πŸ€– **Agents at work...**", expanded=True, state="running") as status:
67
+ with st.container(height=300):
68
+ sys.stdout = StreamToContainer(st)
69
+
70
+ # Defining the crew comprising of different agents
71
+ crew = Crew(
72
+ agents=[news_research_agent, precaution_agent, report_generation_agent],
73
+ tasks=[news_research_task, precaution_task, report_generation_task],
74
+ process=Process.sequential,
75
+ verbose=True
76
+ )
77
+ result = crew.kickoff(inputs={"input_text": input_text, "email": email})
78
+
79
+ status.update(label="βœ… Your Report is ready", state="complete", expanded=False)
80
+
81
+ st.subheader("Comprehensive Report is ready!", anchor=False, divider="rainbow")
82
+ asyncio.run(generate_report_and_send_email(result, email))
83
+ st.markdown(result)
84
+
85
+
86
+ # Enable file download
87
+ st.download_button(
88
+ label="Download Report",
89
+ data=result,
90
+ file_name=f"{input_text}_News_Report.txt",
91
+ mime="text/plain",
92
+ )
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ load_dotenv
2
+ streamlit
3
+ crewai
4
+ langchain_google_genai
5
+ langchain_openai
6
+ crewai_tools
7
+ smtplib
tasks.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from crewai import Task
2
+ from tools import tool
3
+ from agents import (
4
+ news_research_agent,
5
+ precaution_agent,
6
+ report_generation_agent,
7
+ )
8
+
9
+ # 1. News Research and Summarization Task
10
+ news_research_task = Task(
11
+ description="Research and summarize the top news article related to {input_text}.",
12
+ expected_output="A four-sentence summary of the top news article.",
13
+ tools=[tool],
14
+ agent=news_research_agent,
15
+ )
16
+
17
+ # 2. Precaution Recommendation Task
18
+ precaution_task = Task(
19
+ description="Generate three precautionary steps based on the summary of the news article.",
20
+ expected_output="Three precautionary steps to mitigate potential risks.",
21
+ tools=[tool],
22
+ agent=precaution_agent,
23
+ )
24
+
25
+ # 3. Comprehensive Report Generation Task
26
+ report_generation_task = Task(
27
+ description="Compile the news summary and precautionary steps into a comprehensive report and send it to {email}.",
28
+ expected_output="A detailed report containing the news summary and precautionary steps, sent to the provided email.",
29
+ tools=[tool],
30
+ agent=report_generation_agent,
31
+ async_execution=False, # This can be adjusted based on your needs
32
+ )
tools.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ from crewai_tools import SerperDevTool
3
+ import os
4
+
5
+ # Load environment variables from .env file
6
+ load_dotenv()
7
+
8
+ # Set the API key for Serper (Google Search Tool)
9
+ os.environ["SERPER_API_KEY"] = os.environ.get("SERPER_API_KEY")
10
+
11
+ # Initialize the SerperDevTool for Google searches
12
+ tool = SerperDevTool()