jindalgoldy commited on
Commit
9f7e1a9
·
verified ·
1 Parent(s): 2a10ae4

Upload 7 files

Browse files
Files changed (7) hide show
  1. LICENSE +23 -0
  2. README.md +90 -13
  3. agents.py +95 -0
  4. app.py +92 -0
  5. requirements.txt +7 -0
  6. tasks.py +32 -0
  7. tools.py +12 -0
LICENSE ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Ayush Jindal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ For more information or inquiries, please contact Ayush Jindal
README.md CHANGED
@@ -1,13 +1,90 @@
1
- ---
2
- title: Precaution
3
- emoji: 🔥
4
- colorFrom: red
5
- colorTo: blue
6
- sdk: streamlit
7
- sdk_version: 1.39.0
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Precaution Recommendation System
2
+
3
+ ## Description
4
+
5
+ The Precaution Recommendation System is an AI-driven tool designed to provide users with real-time news updates and relevant precautionary recommendations. This system is powered by multiple agents, including a News Research Agent, a Precaution Recommendation Agent, and a Report Generation Agent. The agents collaborate to research trending news topics, summarize key insights, generate actionable precautions, and deliver the compiled report via email. The application uses technologies like CrewAI, LangChain, Streamlit, Python, and Google Gemini Flash 1.5 LLM.
6
+
7
+ This tool is ideal for users who want to stay informed about global events and receive practical steps to mitigate associated risks in real-time.
8
+
9
+ ## Demo of the app
10
+ A demo showcasing the MPrecaution Recommendation System in action can be viewed at the link below:
11
+ https://precaution-recommendation-system.onrender.com/
12
+
13
+ <img src="https://github.com/jindalayush326/Precaution_Recommendation_System/blob/main/image/Screenshot%20(6072).png"/>
14
+ <img src="https://github.com/jindalayush326/Precaution_Recommendation_System/blob/main/image/Screenshot%20(6073).png"/>
15
+ <img src="https://github.com/jindalayush326/Precaution_Recommendation_System/blob/main/image/Screenshot%20(6074).png"/>
16
+ <img src="https://github.com/jindalayush326/Precaution_Recommendation_System/blob/main/image/Screenshot%20(6075).png"/>
17
+
18
+ ## Installation
19
+
20
+ To run this project, follow these steps:
21
+
22
+ 1. Clone this repository to your local machine.
23
+ ```bash
24
+ git clone [https://github.com/jindalayush326/Precaution_Recommendation_System.git]
25
+ ```
26
+
27
+ 2. Navigate to the project directory.
28
+ ```bash
29
+ cd Precaution_Recommendation_System
30
+ ```
31
+
32
+ 3. Install the required dependencies.
33
+ ```bash
34
+ pip install -r requirements.txt
35
+ ```
36
+
37
+ Set up API keys:
38
+
39
+ 4. Create a .env file in the root directory and add your API keys for Google Gemini Flash 1.5 and SerperAPI as follows:
40
+ GOOGLE_API_KEY=<your-google-api-key>
41
+ EMAIL_HOST=<your-email-host>
42
+ EMAIL_PORT=<your-email-port>
43
+ FROM_EMAIL=<your-email-address>
44
+ EMAIL_PASSWORD=<your-email-password>
45
+
46
+ ## Usage
47
+
48
+ 1. Ensure you have installed all dependencies as instructed above.
49
+
50
+ 2. Run the Streamlit app.
51
+ ```bash
52
+ streamlit run app.py
53
+ ```
54
+
55
+ 3. Access the app through your browser at http://localhost:8501
56
+
57
+ 4. Interact with the app:
58
+
59
+ Enter a topic or keyword for news research.
60
+ Provide your email address to receive the generated report.
61
+ Submit to get a comprehensive report containing the news summary and precautionary steps.
62
+
63
+ ## Key Features
64
+ 1. News Research: The News Research Agent fetches top news articles based on the provided keyword and delivers a summary.
65
+ 2. Precautionary Recommendations: The Precaution Agent generates actionable steps to mitigate potential risks from the summarized news.
66
+ 3. Report Generation and Emailing: The system compiles the summary and precautions into a report and sends it directly to the user's email.
67
+ 4. Streamlit Interface: A user-friendly web interface built with Streamlit that enables easy interaction with the system.
68
+
69
+ ## Technologies Used
70
+ 1. CrewAI: A framework for building and managing AI agents.
71
+ 2. LangChain: An API that allows agents to interact with language models for deeper insights.
72
+ 3. Google Gemini Flash 1.5 LLM: A powerful large language model used to gather and analyze data.
73
+ 4. Streamlit: A framework to build and run the web-based front-end of the app.
74
+ 5. SerperAPI: Used for advanced web search and data extraction.
75
+ 6. Python: The programming language used to build the core logic.
76
+ 7. SMTP: For sending email reports securely to the user.
77
+
78
+ ## Credits
79
+
80
+ - [CrewAI](https://www.crewai.com/)
81
+ - [Langchain](https://www.langchain.com/)
82
+ - [Google Gemini Flash 1.5](https://deepmind.google/technologies/gemini/flash/)
83
+ - [Streamlit](https://streamlit.io/)
84
+ - [SerperAPI](https://serper.dev/)
85
+ - [Python](https://www.python.org/)
86
+
87
+ ## License
88
+
89
+ This project is licensed under the [MIT License](LICENSE).
90
+ ```
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()