cryogenic22 commited on
Commit
d28f2e5
·
verified ·
1 Parent(s): edc0b32

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +71 -76
utils.py CHANGED
@@ -1,84 +1,79 @@
1
- from crewai import Agent, Crew, Process, Task
2
- from crewai_tools import SerperDevTool, ScrapeWebsiteTool
 
 
3
 
4
- def create_research_crew(topic: str, questions: list):
5
- search_tool = SerperDevTool()
6
- scrape_tool = ScrapeWebsiteTool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- researcher = Agent(
9
- role='Senior Market Researcher',
10
- goal=f'Research {topic} market and address: {", ".join(questions)}',
11
- backstory="Expert at gathering and analyzing market data with focus on accuracy and comprehensive coverage.",
12
- tools=[search_tool, scrape_tool],
13
- verbose=True
14
- )
15
 
16
- analyst = Agent(
17
- role='Data Analytics Expert',
18
- goal='Process market data into quantitative insights',
19
- backstory="Data analytics specialist focusing on market metrics, trends, and actionable insights.",
20
- tools=[search_tool],
21
- verbose=True
22
- )
 
 
 
 
23
 
24
- writer = Agent(
25
- role='Research Report Writer',
26
- goal='Create detailed market research report',
27
- backstory="Expert at synthesizing research into clear, structured reports with strategic insights.",
28
- verbose=True
29
- )
30
 
31
- research_task = Task(
32
- description=f"""
33
- Conduct comprehensive market research for {topic}:
34
- Questions to address:
35
- {chr(10).join([f'- {q}' for q in questions])}
36
-
37
- Required sections:
38
- 1. Market Overview (size, segments, growth)
39
- 2. Competitive Landscape
40
- 3. Industry Trends
41
- 4. Key Metrics
42
-
43
- Include specific data points and sources.
44
- """,
45
- agent=researcher,
46
- expected_output="Detailed market research data with verifiable metrics and sources"
47
- )
48
 
49
- analysis_task = Task(
50
- description="""
51
- Analyze research data to provide:
52
- 1. Market size and growth metrics
53
- 2. Competitive market shares
54
- 3. Growth projections
55
- 4. Trend impact analysis
56
- """,
57
- agent=analyst,
58
- expected_output="Quantitative analysis with key metrics and projections",
59
- context=[research_task]
60
- )
61
-
62
- report_task = Task(
63
- description="""
64
- Create structured report with:
65
- 1. Executive Summary
66
- 2. Market Analysis
67
- 3. Competitive Analysis
68
- 4. Future Outlook
69
 
70
- Include all insights from research and analysis.
71
- """,
72
- agent=writer,
73
- expected_output="Complete market research report in markdown format",
74
- context=[research_task, analysis_task]
75
- )
76
-
77
- crew = Crew(
78
- agents=[researcher, analyst, writer],
79
- tasks=[research_task, analysis_task, report_task],
80
- process=Process.sequential,
81
- verbose=True
82
- )
 
 
 
 
83
 
84
- return crew
 
 
1
+ from langchain_openai import ChatOpenAI
2
+ import streamlit as st
3
+ import json
4
+ import re
5
 
6
+ def update_progress(container, percentage, message=""):
7
+ if container:
8
+ progress_bar = container.progress(percentage / 100)
9
+ container.write(message)
10
+
11
+ def extract_section(text, section_name):
12
+ try:
13
+ pattern = f"{section_name}:?\s*(.*?)(?=\n\n|$)"
14
+ match = re.search(pattern, text, re.DOTALL | re.IGNORECASE)
15
+ return match.group(1).strip() if match else ""
16
+ except:
17
+ return ""
18
+
19
+ def extract_data_points(text):
20
+ llm = ChatOpenAI(temperature=0, model="gpt-4")
21
+ prompt = """Extract market metrics from this text as JSON:
22
+ {text}
23
 
24
+ Return format:
25
+ {{"market_size": "value", "cagr": "value", "market_share_leader": "value", "total_players": "value"}}"""
 
 
 
 
 
26
 
27
+ response = llm.invoke(prompt.format(text=text))
28
+ try:
29
+ json_str = re.search(r'\{.*\}', response.content, re.DOTALL).group()
30
+ return json.loads(json_str)
31
+ except:
32
+ return {}
33
+
34
+ def expand_content(base_content, topic):
35
+ llm = ChatOpenAI(temperature=0.7, model="gpt-4")
36
+ prompt = f"""Expand this market research content for {topic}:
37
+ {base_content}
38
 
39
+ Provide detailed analysis covering:
40
+ 1. Current market state
41
+ 2. Growth drivers and barriers
42
+ 3. Competitive dynamics
43
+ 4. Future outlook
 
44
 
45
+ Use markdown formatting."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ return llm.invoke(prompt).content
48
+
49
+ def process_crew_output(crew_result, topic):
50
+ try:
51
+ final_report = crew_result.get('final_report_task', {})
52
+ if isinstance(final_report, str):
53
+ report_text = final_report
54
+ else:
55
+ report_text = str(final_report)
56
+
57
+ metrics = extract_data_points(report_text)
58
+ expanded_content = expand_content(report_text, topic)
 
 
 
 
 
 
 
 
59
 
60
+ return {
61
+ 'metrics': metrics,
62
+ 'content': expanded_content
63
+ }
64
+ except Exception as e:
65
+ st.error(f"Error processing report: {str(e)}")
66
+ return {'metrics': {}, 'content': ''}
67
+
68
+ def display_enhanced_report(report):
69
+ if 'metrics' in report:
70
+ st.subheader("Key Market Metrics")
71
+ cols = st.columns(4)
72
+ metrics = report['metrics']
73
+ cols[0].metric("Market Size", metrics.get('market_size', 'N/A'))
74
+ cols[1].metric("CAGR", metrics.get('cagr', 'N/A'))
75
+ cols[2].metric("Leader Share", metrics.get('market_share_leader', 'N/A'))
76
+ cols[3].metric("Key Players", metrics.get('total_players', 'N/A'))
77
 
78
+ if 'content' in report:
79
+ st.markdown(report['content'])