cryogenic22 commited on
Commit
03bc604
·
verified ·
1 Parent(s): 01471bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +192 -114
app.py CHANGED
@@ -1,5 +1,6 @@
1
  # app.py
2
  import os
 
3
  import streamlit as st
4
  from dotenv import load_dotenv
5
  from crewai import Agent, Crew, Process, Task
@@ -15,7 +16,7 @@ st.set_page_config(
15
  layout="wide"
16
  )
17
 
18
- # Add custom CSS
19
  st.markdown("""
20
  <style>
21
  .stButton>button {
@@ -28,143 +29,220 @@ st.markdown("""
28
  border-radius: 10px;
29
  margin-top: 20px;
30
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  </style>
32
  """, unsafe_allow_html=True)
33
 
34
- def run_market_research(topic: str):
35
- with st.status("🤖 AI Crew working on your report...", expanded=True) as status:
36
- try:
37
- status.update(label="🔍 Creating AI agents...")
38
-
39
- # Initialize tools
40
- search_tool = SerperDevTool()
41
- scrape_tool = ScrapeWebsiteTool()
42
-
43
- # Create agents
44
- researcher = Agent(
45
- role='Research Analyst',
46
- goal=f'Conduct thorough market research about {topic}',
47
- backstory='You are an experienced market research analyst with expertise in data analysis and trend identification.',
48
- tools=[search_tool, scrape_tool],
49
- verbose=True
50
- )
51
-
52
- analyst = Agent(
53
- role='Data Analyst',
54
- goal='Analyze research findings and identify key insights',
55
- backstory='You are a skilled data analyst with expertise in interpreting market research and creating actionable insights.',
56
- tools=[search_tool],
57
- verbose=True
58
- )
59
-
60
- writer = Agent(
61
- role='Report Writer',
62
- goal='Create comprehensive and engaging market research reports',
63
- backstory='You are a professional writer specializing in creating clear and compelling business reports.',
64
- verbose=True
65
- )
66
-
67
- status.update(label="📋 Defining research tasks...")
68
-
69
- # Define tasks with expected outputs
70
- research_task = Task(
71
- description=f"""
72
- Conduct comprehensive market research on {topic}.
73
- Focus on:
74
- 1. Current market size and growth projections
75
- 2. Key players and their market share
76
- 3. Consumer adoption trends
77
- 4. Regulatory environment
78
-
79
- Output should be a detailed research findings document with data and sources.
80
- """,
81
- agent=researcher,
82
- expected_output="A comprehensive research document containing market data, trends, and competitor analysis with clear citations and sources."
83
- )
84
-
85
- analysis_task = Task(
86
- description=f"""
87
- Analyze the research findings for {topic} and identify:
88
- 1. Key market opportunities
89
- 2. Potential challenges
90
- 3. Growth drivers
91
- 4. Competitive dynamics
92
-
93
- Use the research provided by the Research Analyst to create an analytical report.
94
- """,
95
- agent=analyst,
96
- expected_output="An analytical report with key insights, opportunities, challenges, and strategic implications based on the research data.",
97
- context=[research_task]
98
- )
99
-
100
- report_task = Task(
101
- description=f"""
102
- Create a detailed market research report that includes:
103
- 1. Executive summary
104
- 2. Market overview
105
- 3. Key findings
106
- 4. Strategic recommendations
107
-
108
- Base the report on the research and analysis provided by the other agents.
109
- The report should be well-structured, professional, and actionable.
110
- """,
111
- agent=writer,
112
- expected_output="A complete market research report in markdown format with executive summary, findings, and recommendations.",
113
- context=[research_task, analysis_task]
114
- )
115
 
116
- status.update(label="🚀 Assembling the crew and starting research...")
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
- # Create and run the crew with boolean verbose flag
119
- crew = Crew(
120
- agents=[researcher, analyst, writer],
121
- tasks=[research_task, analysis_task, report_task],
122
- verbose=True, # Changed from 2 to True
123
- process=Process.sequential
124
- )
 
 
 
 
 
 
 
125
 
126
- result = crew.kickoff()
127
- status.update(label="✅ Report generated successfully!", state="complete")
128
- return result
 
 
 
 
129
 
130
- except Exception as e:
131
- status.update(label=f"❌ Error: {str(e)}", state="error")
132
- st.error(f"Error details: {str(e)}")
133
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
  def main():
136
  st.title("🤖 AI Market Research Generator")
137
  st.markdown("""
138
  This tool uses a crew of AI agents to generate comprehensive market research reports.
139
- Each report is created through a collaborative process involving:
140
- - 🔍 A Research Analyst who gathers market data
141
- - 📊 A Data Analyst who processes the findings
142
- - ✍️ A Report Writer who creates the final document
143
  """)
144
 
145
- # Input section
146
- st.subheader("Research Topic")
147
- topic = st.text_input(
148
- "Enter the market or product you want to research",
149
- placeholder="e.g., Electric Vehicles Market",
150
- key="research_topic"
151
- )
 
 
 
 
 
152
 
153
- if st.button("Generate Report", type="primary"):
 
 
 
 
 
 
 
 
154
  if not topic:
155
  st.error("Please enter a research topic")
156
  return
157
-
158
- report = run_market_research(topic)
 
 
 
 
 
 
159
 
160
  if report:
161
- st.subheader("📑 Generated Report")
162
- with st.container():
163
  st.markdown('<div class="report-container">', unsafe_allow_html=True)
164
  st.markdown(report)
165
  st.markdown('</div>', unsafe_allow_html=True)
166
 
167
- # Add download button
168
  st.download_button(
169
  label="Download Report",
170
  data=report,
 
1
  # app.py
2
  import os
3
+ import time
4
  import streamlit as st
5
  from dotenv import load_dotenv
6
  from crewai import Agent, Crew, Process, Task
 
16
  layout="wide"
17
  )
18
 
19
+ # Add custom CSS for agent chat bubbles and animations
20
  st.markdown("""
21
  <style>
22
  .stButton>button {
 
29
  border-radius: 10px;
30
  margin-top: 20px;
31
  }
32
+ .agent-bubble {
33
+ padding: 10px 15px;
34
+ border-radius: 15px;
35
+ margin: 5px 0;
36
+ max-width: 80%;
37
+ animation: fadeIn 0.5s ease-in;
38
+ }
39
+ .researcher {
40
+ background-color: #E3F2FD;
41
+ margin-right: 20%;
42
+ }
43
+ .analyst {
44
+ background-color: #F3E5F5;
45
+ margin-right: 20%;
46
+ }
47
+ .writer {
48
+ background-color: #E8F5E9;
49
+ margin-right: 20%;
50
+ }
51
+ @keyframes fadeIn {
52
+ from { opacity: 0; transform: translateY(10px); }
53
+ to { opacity: 1; transform: translateY(0); }
54
+ }
55
+ .agent-name {
56
+ font-weight: bold;
57
+ margin-bottom: 5px;
58
+ }
59
+ .agent-thinking {
60
+ color: #666;
61
+ font-style: italic;
62
+ }
63
  </style>
64
  """, unsafe_allow_html=True)
65
 
66
+ def create_agent_message(agent_role: str, message: str, container):
67
+ """Create a styled message bubble for an agent"""
68
+ class_name = agent_role.lower().replace(" ", "-")
69
+ agent_icons = {
70
+ "Research Analyst": "🔍",
71
+ "Data Analyst": "📊",
72
+ "Report Writer": "✍️"
73
+ }
74
+
75
+ container.markdown(
76
+ f"""
77
+ <div class="agent-bubble {class_name}">
78
+ <div class="agent-name">{agent_icons.get(agent_role, '')} {agent_role}</div>
79
+ {message}
80
+ </div>
81
+ """,
82
+ unsafe_allow_html=True
83
+ )
84
+
85
+ def run_market_research(topic: str, chat_container):
86
+ try:
87
+ # Initialize tools
88
+ search_tool = SerperDevTool()
89
+ scrape_tool = ScrapeWebsiteTool()
90
+
91
+ # Create custom callback for agent interactions
92
+ class AgentCallback:
93
+ def on_agent_start(self, agent):
94
+ create_agent_message(
95
+ agent.role,
96
+ f"<div class='agent-thinking'>Starting my task to {agent.goal.lower()}...</div>",
97
+ chat_container
98
+ )
99
+ time.sleep(1) # Add slight delay for visual effect
100
+
101
+ def on_agent_end(self, agent, result):
102
+ create_agent_message(
103
+ agent.role,
104
+ f"I've completed my analysis. Here are the key points:\n\n{result[:200]}...",
105
+ chat_container
106
+ )
107
+ time.sleep(1)
108
+
109
+ # Create agents
110
+ researcher = Agent(
111
+ role='Research Analyst',
112
+ goal=f'Conduct thorough market research about {topic}',
113
+ backstory='You are an experienced market research analyst with expertise in data analysis and trend identification.',
114
+ tools=[search_tool, scrape_tool],
115
+ verbose=True
116
+ )
117
+
118
+ analyst = Agent(
119
+ role='Data Analyst',
120
+ goal='Analyze research findings and identify key insights',
121
+ backstory='You are a skilled data analyst with expertise in interpreting market research and creating actionable insights.',
122
+ tools=[search_tool],
123
+ verbose=True
124
+ )
125
+
126
+ writer = Agent(
127
+ role='Report Writer',
128
+ goal='Create comprehensive and engaging market research reports',
129
+ backstory='You are a professional writer specializing in creating clear and compelling business reports.',
130
+ verbose=True
131
+ )
132
+
133
+ # Define tasks with expected outputs
134
+ research_task = Task(
135
+ description=f"""
136
+ Conduct comprehensive market research on {topic}.
137
+ Focus on:
138
+ 1. Current market size and growth projections
139
+ 2. Key players and their market share
140
+ 3. Consumer adoption trends
141
+ 4. Regulatory environment
 
 
 
 
 
142
 
143
+ Output should be a detailed research findings document with data and sources.
144
+ """,
145
+ agent=researcher,
146
+ expected_output="A comprehensive research document containing market data, trends, and competitor analysis with clear citations and sources."
147
+ )
148
+
149
+ analysis_task = Task(
150
+ description=f"""
151
+ Analyze the research findings for {topic} and identify:
152
+ 1. Key market opportunities
153
+ 2. Potential challenges
154
+ 3. Growth drivers
155
+ 4. Competitive dynamics
156
 
157
+ Use the research provided by the Research Analyst to create an analytical report.
158
+ """,
159
+ agent=analyst,
160
+ expected_output="An analytical report with key insights, opportunities, challenges, and strategic implications based on the research data.",
161
+ context=[research_task]
162
+ )
163
+
164
+ report_task = Task(
165
+ description=f"""
166
+ Create a detailed market research report that includes:
167
+ 1. Executive summary
168
+ 2. Market overview
169
+ 3. Key findings
170
+ 4. Strategic recommendations
171
 
172
+ Base the report on the research and analysis provided by the other agents.
173
+ The report should be well-structured, professional, and actionable.
174
+ """,
175
+ agent=writer,
176
+ expected_output="A complete market research report in markdown format with executive summary, findings, and recommendations.",
177
+ context=[research_task, analysis_task]
178
+ )
179
 
180
+ # Create and run the crew
181
+ crew = Crew(
182
+ agents=[researcher, analyst, writer],
183
+ tasks=[research_task, analysis_task, report_task],
184
+ verbose=True,
185
+ process=Process.sequential
186
+ )
187
+
188
+ # Add callback to crew
189
+ crew.callback = AgentCallback()
190
+
191
+ result = crew.kickoff()
192
+ return result
193
+
194
+ except Exception as e:
195
+ st.error(f"Error details: {str(e)}")
196
+ return None
197
 
198
  def main():
199
  st.title("🤖 AI Market Research Generator")
200
  st.markdown("""
201
  This tool uses a crew of AI agents to generate comprehensive market research reports.
202
+ Watch the agents collaborate in real-time below!
 
 
 
203
  """)
204
 
205
+ # Create two columns
206
+ col1, col2 = st.columns([2, 3])
207
+
208
+ with col1:
209
+ st.subheader("Research Topic")
210
+ topic = st.text_input(
211
+ "Enter the market or product you want to research",
212
+ placeholder="e.g., Electric Vehicles Market",
213
+ key="research_topic"
214
+ )
215
+
216
+ start_button = st.button("Generate Report", type="primary")
217
 
218
+ # Initialize or get the chat container from session state
219
+ if "chat_container" not in st.session_state:
220
+ st.session_state.chat_container = col2.container()
221
+
222
+ # Initialize or get the report container from session state
223
+ if "report_container" not in st.session_state:
224
+ st.session_state.report_container = st.container()
225
+
226
+ if start_button:
227
  if not topic:
228
  st.error("Please enter a research topic")
229
  return
230
+
231
+ # Clear previous chat messages
232
+ st.session_state.chat_container.empty()
233
+
234
+ # Show the agent conversation
235
+ with st.session_state.chat_container:
236
+ st.subheader("🤖 Agents at Work")
237
+ report = run_market_research(topic, st.session_state.chat_container)
238
 
239
  if report:
240
+ with st.session_state.report_container:
241
+ st.subheader("📑 Generated Report")
242
  st.markdown('<div class="report-container">', unsafe_allow_html=True)
243
  st.markdown(report)
244
  st.markdown('</div>', unsafe_allow_html=True)
245
 
 
246
  st.download_button(
247
  label="Download Report",
248
  data=report,