@ -47,562 +47,304 @@ The Job Finding Swarm consists of three specialized agents, each responsible for
## Step 2: Running the Job Finding Swarm
## Step 2: Running the Job Finding Swarm
```python
```python
from typing import List
from swarms import Agent, SequentialWorkflow
from loguru import logger
import http.client
from swarms.structs.agent import Agent
import json
from swarms.structs.conversation import Conversation
import urllib.parse
from swarms.utils.history_output_formatter import history_output_formatter
from swarms_tools import exa_search
# System prompts for each agent
def get_jobs(query: str, limit: int = 10) -> str:
INTAKE_AGENT_PROMPT = """
"""
You are an M& A Intake Specialist responsible for gathering comprehensive information about a potential transaction.
Fetches real-time jobs using JSearch API based on role, location, and experience.
Uses http.client to match verified working example.
"""
# Prepare query string for URL
encoded_query = urllib.parse.quote(query)
path = f"/search?query={encoded_query}& page=1& num_pages=1& country=us& limit={limit}& date_posted=all"
conn = http.client.HTTPSConnection("jsearch.p.rapidapi.com")
headers = {
"x-rapidapi-key": "", #< ------- Add your RapidAPI key here otherwise it will not work
"x-rapidapi-host": "jsearch.p.rapidapi.com"
}
conn.request("GET", path, headers=headers)
res = conn.getresponse()
data = res.read()
decoded = data.decode("utf-8")
try:
result_dict = json.loads(decoded)
except Exception:
# fallback for unexpected output
return decoded
results = result_dict.get("data", [])
jobs_list = [
{
"title": job.get("job_title"),
"company": job.get("employer_name"),
"location": job.get("job_city") or job.get("job_country"),
"experience": job.get("job_required_experience", {}).get("required_experience_in_months"),
"url": job.get("job_apply_link")
}
for job in results
]
return json.dumps(jobs_list)
REQUIREMENTS_ANALYZER_PROMPT = """
You are the Requirements Analyzer Agent for Job Search.
ROLE:
ROLE:
Engage with the user to understand the full context of the potential M& A deal, extracting critical details that will guide subsequent analyses.
Extract and clarify job search requirements from user input to create optimized search queri es.
RESPONSIBILITIES:
RESPONSIBILITIES:
- Conduct a thorough initial interview to understand:
- Engage with the user to understand:
* Transaction type (acquisition, merger, divestiture)
* Desired job titles and roles
* Industry and sector specifics
* Required skills and qualifications
* Target company profile and size
* Preferred locations (remote, hybrid, on-site)
* Strategic objectives
* Salary expectations
* Buyer/seller perspective
* Company size and culture preferences
* Timeline and urgency
* Industry preferences
* Budget constraints
* Experience level
* Specific concerns or focus areas
* Work authorization status
* Career goals and priorities
- Analyze user responses to identify:
* Key search terms and keywords
* Must-have vs nice-to-have requirements
* Deal-breakers or constraints
* Priority factors in job selection
- Generate optimized search queries:
* Create 3-5 targeted search queries based on user requirements
OUTPUT FORMAT:
OUTPUT FORMAT:
Provide a comprehensive Deal Brief that includes:
Provide a comprehensive requirements analysis:
1. Transaction Overview
1. User Profile Summary:
- Proposed transaction type
- Job titles of interest
- Key parties involved
- Key skills and qualifications
- Initial strategic rationale
- Location preferences
- Salary range
2. Stakeholder Context
- Priority factors
- Buyer's background and motivations
- Target company's current position
2. Search Strategy:
- Key decision-makers
- List of 3-5 optimized search queries, formatted EXACTLY for linkedin.com/jobs/search/?keywords=...
- Rationale for each query
3. Initial Assessment
- Expected result types
- Preliminary strategic fit
- Potential challenges or red flags
3. Clarifications Needed (if any):
- Recommended focus areas for deeper analysis
- Questions to refine search
- Missing information
4. Information Gaps
- Questions that need further clarification
- Additional data points required
IMPORTANT:
IMPORTANT:
- Be thorough and systematic
- Always include ALL user responses verbatim in your analysis
- Ask probing questions to uncover nuanced details
- Format search queries clearly for the next agent and fit directly to LinkedIn search URL s
- Maintain a neutral, professional tone
- Be specific and actionable in your recommendations
- Prepare a foundation for subsequent in-depth analysis
- Ask follow-up questions if requirements are unclear
"""
"""
MARKET_ANALYSIS _PROMPT = """
SEARCH_EXECUTOR _PROMPT = """
You are an M& A Market Intelligence Analyst tasked with conducting comprehensive market res earch.
You are the Search Executor Agent for Job S earch.
ROLE:
ROLE:
Perform an in-depth analysis of market dynamics, competitive landscape, and strategic implications for the potential transaction.
Your job is to execute a job search by querying the tool EXACTLY ONCE using the following required format (FILL IN WHERE IT HAS [ ] WITH THE QUERY INFO OTHERWISE STATED):
TOOLS:
The argument for the query is to be provided as a plain text string in the following format (DO NOT include technical addresses, just the core query string):
You have access to the exa_search tool for gathering real-time market intelligence.
RESPONSIBILITIES:
[jobrole] jobs in [geographiclocation/remoteorinpersonorhybrid]
1. Conduct Market Research
- Use exa_search to gather current market insights
- Analyze industry trends, size, and growth potential
- Identify key players and market share distribution
2. Competitive Landscape Analysis
- Map out competitive ecosystem
- Assess target company's market positioning
- Identify potential competitive advantages or vulnerabilities
3. Strategic Fit Evaluation
- Analyze alignment with buyer's strategic objectives
- Assess potential market entry or expansion opportunities
- Evaluate potential for market disruption
4. External Factor Assessment
- Examine regulatory environment
- Analyze technological disruption potential
- Consider macroeconomic impacts
OUTPUT FORMAT:
For example:
Provide a comprehensive Market Analysis Report:
developer jobs in chicago
1. Market Overview
senior product manager jobs in remote
- Market size and growth trajectory
data engineer jobs in new york hybrid
- Key industry trends
- Competitive landscape summary
2. Strategic Fit Assessment
- Market attractiveness score (1-10)
- Strategic alignment evaluation
- Potential synergies and opportunities
3. Risk and Opportunity Mapping
- Key market opportunities
- Potential competitive threats
- Regulatory and technological risk factors
4. Recommended Next Steps
- Areas requiring deeper investigation
- Initial strategic recommendations
"""
FINANCIAL_VALUATION_PROMPT = """
TOOLS:
You are an M& A Financial Analysis and Risk Expert. Perform comprehensive financial evaluation and risk assessment.
You have access to three tools:
- get_jobs: helps find open job opportunities for your specific job and requirements.
RESPONSIBILITIES:
RESPONSIBILITIES:
1. Financial Health Analysis
- Run ONE single query, in the above format, as the argument to get_jobs.
- Analyze revenue trends and quality
- Analyze search results for:
- Evaluate profitability metrics (EBITDA, margins)
* Job title match
- Conduct cash flow analysis
* Skills alignment
- Assess balance sheet strength
* Location compatibility
- Review working capital requirements
* Salary range fit
* Company reputation
2. Valuation Analysis
* Role responsibilities
- Perform comparable company analysis
* Growth opportunities
- Conduct precedent transaction analysis
- Develop Discounted Cash Flow (DCF) model
- Categorize each result into one of:
- Assess asset-based valuation
* Strong Match (80-100% alignment)
* Good Match (60-79% alignment)
3. Synergy and Risk Assessment
* Moderate Match (40-59% alignment)
- Quantify potential revenue and cost synergies
* Weak Match (< 40 % alignment )
- Identify financial and operational risks
- Evaluate integration complexity
- For each job listing, extract:
- Assess potential deal-breakers
* Job title and company
* Location and work arrangement
* Key requirements
* Salary range (if available)
* Application link or contact
* Match score and reasoning
OUTPUT FORMAT:
OUTPUT FORMAT:
1. Comprehensive Financial Analysis Report
1. Search Execution Summary:
2. Valuation Range (low, mid, high scenarios)
- The query executed (write ONLY the string argument supplied, e.g., "developer jobs in chicago" or "software engineer jobs in new york remote")
3. Synergy Potential Breakdown
- Total results found
4. Detailed Risk Matrix
- Distribution by match category
5. Recommended Pricing Strategy
2. Detailed Job Listings (grouped by match strength):
For each job:
- Company and Job Title
- Location and Work Type
- Key Requirements
- Why it's a match (or not)
- Match Score (percentage)
- Application link
- Source (specify get_jobs)
3. Search Insights:
- Common trends/themes in the results
- Gaps between results and requirements
- Market observations
INSTRUCTIONS:
- Run only the single query in the format described above, with no extra path, no technical addresses, and no full URLs.
- Use all three tools, as applicable, with that exact query argument.
- Clearly cite which results come from which source.
- Be objective in match assessment.
- Provide actionable, structured insights.
"""
"""
DEAL_STRUCTURING_PROMPT = """
RESULTS_CURATOR _PROMPT = """
You are an M& A Deal Structuring Advisor. Recommend the optimal transaction structure.
You are the Results Curator Agent for Job Search .
RESPONSIBILITIES:
ROLE:
1. Transaction Structure Design
Filter, organize, and present job search results to the user for decision-making.
- Evaluate asset vs stock purchase options
- Analyze cash vs stock consideration
- Design earnout provisions
- Develop contingent payment structures
2. Financing Strategy
- Recommend debt/equity mix
- Identify optimal financing sources
- Assess impact on buyer's capital structure
3. Tax and Legal Optimization
- Design tax-efficient structure
- Consider jurisdictional implications
- Minimize tax liabilities
4. Deal Protection Mechanisms
- Develop escrow arrangements
- Design representations and warranties
- Create indemnification provisions
- Recommend non-compete agreements
OUTPUT FORMAT:
1. Recommended Deal Structure
2. Detailed Payment Terms
3. Key Contractual Protections
4. Tax Optimization Strategy
5. Rationale for Proposed Structure
"""
INTEGRATION_PLANNING_PROMPT = """
You are an M& A Integration Planning Expert. Develop a comprehensive post-merger integration roadmap.
RESPONSIBILITIES:
RESPONSIBILITIES:
1. Immediate Integration Priorities
- Review all search results from the Search Executor
- Define critical day-1 actions
- Filter and prioritize based on:
- Develop communication strategy
* Match scores
- Identify quick win opportunities
* User requirements
* Application deadlines
2. 100-Day Integration Plan
* Job quality indicators
- Design organizational structure alignment
- Establish governance framework
- Organize results into:
- Create detailed integration milestones
* Top Recommendations (top 3-5 best matches)
* Strong Alternatives (next 5-10 options)
3. Functional Integration Strategy
* Worth Considering (other relevant matches)
- Plan operations consolidation
- Design systems and technology integration
- For top recommendations, provide:
- Align sales and marketing approaches
* Detailed comparison
- Develop cultural integration plan
* Pros and cons for each
* Application strategy suggestions
4. Synergy Realization
* Next steps
- Create detailed synergy capture timeline
- Establish performance tracking mechanisms
- Engage user for feedback:
- Define accountability framework
* Present curated results clearly
* Ask which jobs interest them
* Identify what's missing
* Determine if new search is needed
OUTPUT FORMAT:
OUTPUT FORMAT:
1. Comprehensive Integration Roadmap
Provide a curated job search report:
2. Detailed 100-Day Plan
3. Functional Integration Strategies
1. Executive Summary:
4. Synergy Realization Timeline
- Total jobs reviewed
5. Risk Mitigation Recommendations
- Number of strong matches
"""
- Key findings
FINAL_RECOMMENDATION_PROMPT = """
2. Top Recommendations (detailed):
You are the Senior M& A Advisory Partner. Synthesize all analyses into a comprehensive recommendation.
For each (max 5):
- Company & Title
RESPONSIBILITIES:
- Why it's a top match
1. Executive Summary
- Key highlights
- Summarize transaction overview
- Potential concerns
- Highlight strategic rationale
- Recommendation strength (1-10)
- Articulate key value drivers
- Application priority (High/Medium/Low)
2. Investment Thesis Validation
3. Strong Alternatives (brief list):
- Assess strategic benefits
- Company & Title
- Evaluate financial attractiveness
- One-line match summary
- Project long-term potential
- Match score
3. Comprehensive Risk Assessment
4. User Decision Point:
- Summarize top risks
Ask the user:
- Provide mitigation strategies
- "Which of these jobs interest you most?"
- Identify potential deal-breakers
- "What's missing from these results?"
- "Should we refine the search or proceed with applications?"
4. Final Recommendation
- "Any requirements you'd like to adjust?"
- Provide clear GO/NO-GO recommendation
- Specify recommended offer range
5. Next Steps:
- Outline key proceeding conditions
Based on user response, either:
- Proceed with selected jobs
- Run new search with adjusted criteria
- Deep dive into specific opportunities
OUTPUT FORMAT:
IMPORTANT:
1. Executive-Level Recommendation Report
- Make it easy for users to make decisions
2. Decision Framework
- Be honest about job fit
3. Risk-Adjusted Strategic Perspective
- Provide clear paths forward
4. Actionable Next Steps
- Always ask for user feedback before concluding
5. Recommendation Confidence Level
"""
"""
class MAAdvisorySwarm:
def __init__ (
self,
name: str = "M& A Advisory Swarm",
description: str = "Comprehensive AI-driven M& A advisory system",
max_loops: int = 1,
user_name: str = "M& A Advisor",
output_type: str = "json",
):
self.max_loops = max_loops
self.name = name
self.description = description
self.user_name = user_name
self.output_type = output_type
self.agents = self._initialize_agents()
self.conversation = Conversation()
self.exa_search_results = []
self.search_queries = []
self.current_iteration = 0
self.max_iterations = 1 # Limiting to 1 iteration for full sequential demo
self.analysis_concluded = False
self.handle_initial_processing()
def handle_initial_processing(self):
self.conversation.add(
role="System",
content=f"Company: {self.name}\n"
f"Description: {self.description}\n"
f"Mission: Provide comprehensive M& A advisory for {self.user_name}"
)
def _initialize_agents(self) -> List[Agent]:
return [
Agent(
agent_name="Emma-Intake-Specialist",
agent_description="Gathers comprehensive initial information about the potential M& A transaction.",
system_prompt=INTAKE_AGENT_PROMPT,
max_loops=self.max_loops,
dynamic_temperature_enabled=True,
output_type="final",
),
Agent(
agent_name="Marcus-Market-Analyst",
agent_description="Conducts in-depth market research and competitive analysis.",
system_prompt=MARKET_ANALYSIS_PROMPT,
max_loops=self.max_loops,
dynamic_temperature_enabled=True,
output_type="final",
),
Agent(
agent_name="Sophia-Financial-Analyst",
agent_description="Performs comprehensive financial valuation and risk assessment.",
system_prompt=FINANCIAL_VALUATION_PROMPT,
max_loops=self.max_loops,
dynamic_temperature_enabled=True,
output_type="final",
),
Agent(
agent_name="David-Deal-Structuring-Advisor",
agent_description="Recommends optimal deal structure and terms.",
system_prompt=DEAL_STRUCTURING_PROMPT,
max_loops=self.max_loops,
dynamic_temperature_enabled=True,
output_type="final",
),
Agent(
agent_name="Nathan-Integration-Planner",
agent_description="Develops comprehensive post-merger integration roadmap.",
system_prompt=INTEGRATION_PLANNING_PROMPT,
max_loops=self.max_loops,
dynamic_temperature_enabled=True,
output_type="final",
),
Agent(
agent_name="Alex-Final-Recommendation-Partner",
agent_description="Synthesizes all analyses into a comprehensive recommendation.",
system_prompt=FINAL_RECOMMENDATION_PROMPT,
max_loops=self.max_loops,
dynamic_temperature_enabled=True,
output_type="final",
)
]
def find_agent_by_name(self, name: str) -> Agent:
for agent in self.agents:
if name in agent.agent_name:
return agent
return None
def intake_and_scoping(self, user_input: str):
"""Phase 1: Intake and initial deal scoping"""
emma_agent = self.find_agent_by_name("Intake-Specialist")
emma_output = emma_agent.run(
f"User Input: {user_input}\n\n"
f"Conversation History: {self.conversation.get_str()}\n\n"
f"Analyze the potential M& A transaction, extract key details, and prepare a comprehensive deal brief. "
f"If information is unclear, ask clarifying questions."
)
self.conversation.add(
role="Intake-Specialist", content=emma_output
)
# Extract potential search queries for market research
self.search_queries = self._extract_search_queries(emma_output)
return emma_output
def _extract_search_queries(self, intake_output: str) -> List[str]:
"""Extract search queries from Intake Specialist output"""
queries = []
lines = intake_output.split('\n')
# Look for lines that could be good search queries
for line in lines:
line = line.strip()
# Simple heuristic: lines with potential research keywords
if any(keyword in line.lower() for keyword in ['market', 'industry', 'trend', 'competitor', 'analysis']):
if len(line) > 20: # Ensure query is substantial
queries.append(line)
# Fallback queries if none found
if not queries:
queries = [
"M& A trends in technology sector",
"Market analysis for potential business acquisition",
"Competitive landscape in enterprise software"
]
return queries[:3] # Limit to 3 queries
def market_research(self):
"""Phase 2: Conduct market research using exa_search"""
# Execute exa_search for each query
self.exa_search_results = []
for query in self.search_queries:
result = exa_search(query)
self.exa_search_results.append({
"query": query,
"exa_result": result
})
# Pass results to Market Analysis agent
marcus_agent = self.find_agent_by_name("Market-Analyst")
# Build exa context
exa_context = "\n\n[Exa Market Research Results]\n"
for item in self.exa_search_results:
exa_context += f"Query: {item['query']}\nResults: {item['exa_result']}\n\n"
marcus_output = marcus_agent.run(
f"Conversation History: {self.conversation.get_str()}\n\n"
f"{exa_context}\n"
f"Analyze these market research results. Provide comprehensive market intelligence and strategic insights."
)
self.conversation.add(
role="Market-Analyst", content=marcus_output
)
return marcus_output
def financial_valuation(self):
"""Phase 3: Perform comprehensive financial valuation and risk assessment"""
sophia_agent = self.find_agent_by_name("Financial-Analyst")
sophia_output = sophia_agent.run(
f"Conversation History: {self.conversation.get_str()}\n\n"
f"Perform comprehensive financial analysis and risk assessment based on previous insights."
)
self.conversation.add(
role="Financial-Analyst", content=sophia_output
)
return sophia_output
def deal_structuring(self):
"""Phase 4: Recommend optimal deal structure"""
david_agent = self.find_agent_by_name("Deal-Structuring-Advisor")
david_output = david_agent.run(
f"Conversation History: {self.conversation.get_str()}\n\n"
f"Recommend the optimal transaction structure and terms based on all prior analyses."
)
self.conversation.add(
role="Deal-Structuring-Advisor", content=david_output
)
return david_output
def integration_planning(self):
"""Phase 5: Develop post-merger integration roadmap"""
nathan_agent = self.find_agent_by_name("Integration-Planner")
nathan_output = nathan_agent.run(
f"Conversation History: {self.conversation.get_str()}\n\n"
f"Create a comprehensive integration plan to realize deal value."
)
self.conversation.add(
role="Integration-Planner", content=nathan_output
)
return nathan_output
def final_recommendation(self):
"""Phase 6: Synthesize all analyses into a comprehensive recommendation"""
alex_agent = self.find_agent_by_name("Final-Recommendation-Partner")
alex_output = alex_agent.run(
f"Conversation History: {self.conversation.get_str()}\n\n"
f"Synthesize all agent analyses into a comprehensive, actionable M& A recommendation."
)
self.conversation.add(
role="Final-Recommendation-Partner", content=alex_output
)
return alex_output
def run(self, initial_user_input: str):
"""
Run the M& A advisory swarm with continuous analysis.
Args:
initial_user_input: User's initial M& A transaction details
"""
self.conversation.add(role=self.user_name, content=initial_user_input)
while not self.analysis_concluded and self.current_iteration < self.max_iterations:
self.current_iteration += 1
logger.info(f"Starting analysis iteration {self.current_iteration}")
# Phase 1: Intake and Scoping
print(f"\n{'='*60}")
print("ITERATION - INTAKE AND SCOPING")
print(f"{'='*60}\n")
self.intake_and_scoping(initial_user_input)
# Phase 2: Market Research (with exa_search)
print(f"\n{'='*60}")
print("ITERATION - MARKET RESEARCH")
print(f"{'='*60}\n")
self.market_research()
# Phase 3: Financial Valuation
print(f"\n{'='*60}")
print("ITERATION - FINANCIAL VALUATION")
print(f"{'='*60}\n")
self.financial_valuation()
# Phase 4: Deal Structuring
print(f"\n{'='*60}")
print("ITERATION - DEAL STRUCTURING")
print(f"{'='*60}\n")
self.deal_structuring()
# Phase 5: Integration Planning
print(f"\n{'='*60}")
print("ITERATION - INTEGRATION PLANNING")
print(f"{'='*60}\n")
self.integration_planning()
# Phase 6: Final Recommendation
print(f"\n{'='*60}")
print("ITERATION - FINAL RECOMMENDATION")
print(f"{'='*60}\n")
self.final_recommendation()
# Conclude analysis after one full sequence for demo purposes
self.analysis_concluded = True
# Return formatted conversation history
return history_output_formatter(
self.conversation, type=self.output_type
)
def main():
def main():
"""Main entry point for M& A advisory swarm"""
# User input for job requirements
user_requirements = """
# Example M& A transaction details
I'm looking for a senior software engineer position with the following requirements:
transaction_details = """
- Job Title: Senior Software Engineer or Staff Engineer
We are exploring a potential acquisition of DataPulse Analytics by TechNova Solutions.
- Skills: Python, distributed systems, cloud architecture (AWS/GCP), Kubernetes
- Location: Remote (US-based) or San Francisco Bay Area
Transaction Context:
- Salary: $180k - $250k
- Buyer: TechNova Solutions (NASDAQ: TNVA) - $500M annual revenue enterprise software company
- Company: Mid-size to large tech companies, prefer companies with strong engineering culture
- Target: DataPulse Analytics - Series B AI-driven analytics startup based in San Francisco
- Experience Level: 7+ years
- Primary Objectives:
- Industry: SaaS, Cloud Infrastructure, or Developer Tools
* Expand predictive analytics capabilities in healthcare and financial services
- Work Authorization: US Citizen
* Accelerate AI-powered business intelligence product roadmap
- Priorities: Technical challenges, work-life balance, remote flexibility, equity upside
* Acquire top-tier machine learning engineering talent
- Deal-breakers: No pure management roles, no strict return-to-office policies
Key Considerations:
- Deep integration of DataPulse's proprietary AI models into TechNova's existing platform
- Retention of key DataPulse leadership and engineering team
- Projected 3-year ROI and synergy potential
- Regulatory and compliance alignment
- Technology stack compatibility
"""
"""
# Initialize the swarm
# Define your agents in a list as in the example format
ma_advisory_swarm = MAAdvisorySwarm(
agents = [
name="AI-Powered M& A Advisory System",
Agent(
description="Comprehensive AI-driven M& A advisory and market intelligence platform",
agent_name="Sarah-Requirements-Analyzer",
user_name="Corporate Development Team",
agent_description="Analyzes user requirements and creates optimized job search queries.",
output_type="json",
system_prompt=REQUIREMENTS_ANALYZER_PROMPT,
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
),
Agent(
agent_name="David-Search-Executor",
agent_description="Executes job searches and analyzes results for relevance.",
system_prompt=SEARCH_EXECUTOR_PROMPT,
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
tools=[get_jobs],
),
Agent(
agent_name="Lisa-Results-Curator",
agent_description="Curates and presents job results for user decision-making.",
system_prompt=RESULTS_CURATOR_PROMPT,
model_name="gpt-4.1",
max_loops=1,
temperature=0.7,
),
]
# Setup the SequentialWorkflow pipeline (following the style of the ETF example)
workflow = SequentialWorkflow(
name="job-search-sequential-workflow",
agents=agents,
max_loops=1,
max_loops=1,
team_awareness=True,
)
)
# Run the swarm
workflow.run(user_requirements)
print("\n" + "="*60)
print("INITIALIZING M& A ADVISORY SWARM")
print("="*60 + "\n")
ma_advisory_swarm.run(initial_user_input=transaction_details)
if __name__ == "__main__":
if __name__ == "__main__":
main()
main()