parent
599c7b2431
commit
50e3c050a4
@ -1,39 +1,52 @@
|
||||
agents:
|
||||
- agent_name: "Financial-Analysis-Agent"
|
||||
- agent_name: "Delaware-C-Corp-Tax-Deduction-Agent"
|
||||
model:
|
||||
model_name: "gpt-4o-mini"
|
||||
temperature: 0.1
|
||||
max_tokens: 2000
|
||||
system_prompt: "financial_agent_sys_prompt" # Reference to system prompt file
|
||||
max_tokens: 2500
|
||||
system_prompt: |
|
||||
You are a highly specialized financial analysis agent focused on Delaware C Corps tax deductions. Your task is to provide expert advice on optimizing tax strategies for Delaware C Corps, ensuring compliance with all relevant tax laws and regulations. You should be well-versed in Delaware state tax codes and federal tax laws affecting C Corps. Your responses should include detailed explanations of tax deductions available to Delaware C Corps, including but not limited to:
|
||||
- Research and Development (R&D) tax credits
|
||||
- Depreciation and amortization
|
||||
- Business expense deductions
|
||||
- Charitable contributions
|
||||
- State-specific tax incentives
|
||||
- Federal tax deductions applicable to C Corps
|
||||
max_loops: 1
|
||||
autosave: true
|
||||
dashboard: false
|
||||
verbose: true
|
||||
dynamic_temperature_enabled: true
|
||||
saved_state_path: "finance_agent.json"
|
||||
saved_state_path: "delaware_c_corp_tax_deduction_agent.json"
|
||||
user_name: "swarms_corp"
|
||||
retry_attempts: 1
|
||||
context_length: 200000
|
||||
context_length: 250000
|
||||
return_step_meta: false
|
||||
output_type: "str" # Can be "json" or any other format
|
||||
task: "What are the benefits of working with BlackRock"
|
||||
|
||||
task: "What are the most effective tax deduction strategies for a Delaware C Corp in the technology industry?"
|
||||
|
||||
- agent_name: "Stock-Analysis-Agent"
|
||||
- agent_name: "Delaware-C-Corp-Tax-Optimization-Agent"
|
||||
model:
|
||||
model_name: "gpt-4o-mini"
|
||||
temperature: 0.2
|
||||
max_tokens: 1500
|
||||
system_prompt: "stock_agent_sys_prompt" # Reference to system prompt file
|
||||
max_tokens: 2000
|
||||
system_prompt: |
|
||||
You are a highly specialized financial analysis agent focused on Delaware C Corps tax optimization. Your task is to provide expert advice on optimizing tax strategies for Delaware C Corps, ensuring compliance with all relevant tax laws and regulations. You should be well-versed in Delaware state tax codes and federal tax laws affecting C Corps. Your responses should include detailed explanations of tax optimization strategies available to Delaware C Corps, including but not limited to:
|
||||
- Entity structure optimization
|
||||
- Income shifting strategies
|
||||
- Loss utilization and carryovers
|
||||
- Tax-efficient supply chain management
|
||||
- State-specific tax planning
|
||||
- Federal tax planning applicable to C Corps
|
||||
max_loops: 2
|
||||
autosave: true
|
||||
dashboard: false
|
||||
verbose: true
|
||||
dynamic_temperature_enabled: false
|
||||
saved_state_path: "stock_agent.json"
|
||||
user_name: "stock_user"
|
||||
saved_state_path: "delaware_c_corp_tax_optimization_agent.json"
|
||||
user_name: "tax_optimization_user"
|
||||
retry_attempts: 3
|
||||
context_length: 150000
|
||||
context_length: 200000
|
||||
return_step_meta: true
|
||||
output_type: "str"
|
||||
task: "What is a roth IRA"
|
||||
task: "How can a Delaware C Corp in the finance industry optimize its tax strategy for maximum savings?"
|
||||
|
@ -0,0 +1,340 @@
|
||||
# SwarmRouter Documentation
|
||||
|
||||
## Overview
|
||||
|
||||
The `SwarmRouter` class is a flexible routing system designed to manage different types of swarms for task execution. It provides a unified interface to interact with various swarm types, including `AgentRearrange`, `MixtureOfAgents`, `SpreadSheetSwarm`, `SequentialWorkflow`, and `ConcurrentWorkflow`. We will be continously adding more and more swarm architectures here as we progress with new architectures.
|
||||
|
||||
## Classes
|
||||
|
||||
### SwarmLog
|
||||
|
||||
A Pydantic model for capturing log entries.
|
||||
|
||||
#### Attributes:
|
||||
- `id` (str): Unique identifier for the log entry.
|
||||
- `timestamp` (datetime): Time of log creation.
|
||||
- `level` (str): Log level (e.g., "info", "error").
|
||||
- `message` (str): Log message content.
|
||||
- `swarm_type` (SwarmType): Type of swarm associated with the log.
|
||||
- `task` (str): Task being performed (optional).
|
||||
- `metadata` (Dict[str, Any]): Additional metadata (optional).
|
||||
|
||||
### SwarmRouter
|
||||
|
||||
Main class for routing tasks to different swarm types.
|
||||
|
||||
#### Attributes:
|
||||
- `name` (str): Name of the SwarmRouter instance.
|
||||
- `description` (str): Description of the SwarmRouter instance.
|
||||
- `max_loops` (int): Maximum number of loops to perform.
|
||||
- `agents` (List[Agent]): List of Agent objects to be used in the swarm.
|
||||
- `swarm_type` (SwarmType): Type of swarm to be used.
|
||||
- `swarm` (Union[AgentRearrange, MixtureOfAgents, SpreadSheetSwarm, SequentialWorkflow, ConcurrentWorkflow]): Instantiated swarm object.
|
||||
- `logs` (List[SwarmLog]): List of log entries captured during operations.
|
||||
|
||||
#### Methods:
|
||||
- `__init__(self, name: str, description: str, max_loops: int, agents: List[Agent], swarm_type: SwarmType, *args, **kwargs)`: Initialize the SwarmRouter.
|
||||
- `_create_swarm(self, *args, **kwargs)`: Create and return the specified swarm type.
|
||||
- `_log(self, level: str, message: str, task: str, metadata: Dict[str, Any])`: Create a log entry and add it to the logs list.
|
||||
- `run(self, task: str, *args, **kwargs)`: Run the specified task on the selected swarm.
|
||||
- `get_logs(self)`: Retrieve all logged entries.
|
||||
|
||||
## Installation
|
||||
|
||||
To use the SwarmRouter, first install the required dependencies:
|
||||
|
||||
```bash
|
||||
pip install swarms swarm_models
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
```python
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from swarms import Agent, SwarmRouter
|
||||
from swarm_models import OpenAIChat
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# Get the OpenAI API key from the environment variable
|
||||
api_key = os.getenv("GROQ_API_KEY")
|
||||
|
||||
# Model
|
||||
model = OpenAIChat(
|
||||
openai_api_base="https://api.groq.com/openai/v1",
|
||||
openai_api_key=api_key,
|
||||
model_name="llama-3.1-70b-versatile",
|
||||
temperature=0.1,
|
||||
)
|
||||
# Define specialized system prompts for each agent
|
||||
DATA_EXTRACTOR_PROMPT = """You are a highly specialized private equity agent focused on data extraction from various documents. Your expertise includes:
|
||||
1. Extracting key financial metrics (revenue, EBITDA, growth rates, etc.) from financial statements and reports
|
||||
2. Identifying and extracting important contract terms from legal documents
|
||||
3. Pulling out relevant market data from industry reports and analyses
|
||||
4. Extracting operational KPIs from management presentations and internal reports
|
||||
5. Identifying and extracting key personnel information from organizational charts and bios
|
||||
Provide accurate, structured data extracted from various document types to support investment analysis."""
|
||||
|
||||
SUMMARIZER_PROMPT = """You are an expert private equity agent specializing in summarizing complex documents. Your core competencies include:
|
||||
1. Distilling lengthy financial reports into concise executive summaries
|
||||
2. Summarizing legal documents, highlighting key terms and potential risks
|
||||
3. Condensing industry reports to capture essential market trends and competitive dynamics
|
||||
4. Summarizing management presentations to highlight key strategic initiatives and projections
|
||||
5. Creating brief overviews of technical documents, emphasizing critical points for non-technical stakeholders
|
||||
Deliver clear, concise summaries that capture the essence of various documents while highlighting information crucial for investment decisions."""
|
||||
|
||||
FINANCIAL_ANALYST_PROMPT = """You are a specialized private equity agent focused on financial analysis. Your key responsibilities include:
|
||||
1. Analyzing historical financial statements to identify trends and potential issues
|
||||
2. Evaluating the quality of earnings and potential adjustments to EBITDA
|
||||
3. Assessing working capital requirements and cash flow dynamics
|
||||
4. Analyzing capital structure and debt capacity
|
||||
5. Evaluating financial projections and underlying assumptions
|
||||
Provide thorough, insightful financial analysis to inform investment decisions and valuation."""
|
||||
|
||||
MARKET_ANALYST_PROMPT = """You are a highly skilled private equity agent specializing in market analysis. Your expertise covers:
|
||||
1. Analyzing industry trends, growth drivers, and potential disruptors
|
||||
2. Evaluating competitive landscape and market positioning
|
||||
3. Assessing market size, segmentation, and growth potential
|
||||
4. Analyzing customer dynamics, including concentration and loyalty
|
||||
5. Identifying potential regulatory or macroeconomic impacts on the market
|
||||
Deliver comprehensive market analysis to assess the attractiveness and risks of potential investments."""
|
||||
|
||||
OPERATIONAL_ANALYST_PROMPT = """You are an expert private equity agent focused on operational analysis. Your core competencies include:
|
||||
1. Evaluating operational efficiency and identifying improvement opportunities
|
||||
2. Analyzing supply chain and procurement processes
|
||||
3. Assessing sales and marketing effectiveness
|
||||
4. Evaluating IT systems and digital capabilities
|
||||
5. Identifying potential synergies in merger or add-on acquisition scenarios
|
||||
Provide detailed operational analysis to uncover value creation opportunities and potential risks."""
|
||||
|
||||
# Initialize specialized agents
|
||||
data_extractor_agent = Agent(
|
||||
agent_name="Data-Extractor",
|
||||
system_prompt=DATA_EXTRACTOR_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="data_extractor_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
summarizer_agent = Agent(
|
||||
agent_name="Document-Summarizer",
|
||||
system_prompt=SUMMARIZER_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="summarizer_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
financial_analyst_agent = Agent(
|
||||
agent_name="Financial-Analyst",
|
||||
system_prompt=FINANCIAL_ANALYST_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="financial_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
market_analyst_agent = Agent(
|
||||
agent_name="Market-Analyst",
|
||||
system_prompt=MARKET_ANALYST_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="market_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
operational_analyst_agent = Agent(
|
||||
agent_name="Operational-Analyst",
|
||||
system_prompt=OPERATIONAL_ANALYST_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="operational_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
# Initialize the SwarmRouter
|
||||
router = SwarmRouter(
|
||||
name="pe-document-analysis-swarm",
|
||||
description="Analyze documents for private equity due diligence and investment decision-making",
|
||||
max_loops=1,
|
||||
agents=[
|
||||
data_extractor_agent,
|
||||
summarizer_agent,
|
||||
financial_analyst_agent,
|
||||
market_analyst_agent,
|
||||
operational_analyst_agent,
|
||||
],
|
||||
swarm_type="ConcurrentWorkflow", # or "SequentialWorkflow" or "ConcurrentWorkflow" or
|
||||
)
|
||||
|
||||
# Example usage
|
||||
if __name__ == "__main__":
|
||||
# Run a comprehensive private equity document analysis task
|
||||
result = router.run(
|
||||
"Where is the best place to find template term sheets for series A startups. Provide links and references"
|
||||
)
|
||||
print(result)
|
||||
|
||||
# Retrieve and print logs
|
||||
for log in router.get_logs():
|
||||
print(f"{log.timestamp} - {log.level}: {log.message}")
|
||||
|
||||
|
||||
|
||||
```
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Changing Swarm Types
|
||||
|
||||
You can create multiple SwarmRouter instances with different swarm types:
|
||||
|
||||
```python
|
||||
sequential_router = SwarmRouter(
|
||||
name="SequentialRouter",
|
||||
agents=[agent1, agent2],
|
||||
swarm_type=SwarmType.SequentialWorkflow
|
||||
)
|
||||
|
||||
concurrent_router = SwarmRouter(
|
||||
name="ConcurrentRouter",
|
||||
agents=[agent1, agent2],
|
||||
swarm_type=SwarmType.ConcurrentWorkflow
|
||||
)
|
||||
```
|
||||
|
||||
## Use Cases
|
||||
|
||||
### AgentRearrange
|
||||
|
||||
Use Case: Optimizing agent order for complex multi-step tasks.
|
||||
|
||||
```python
|
||||
rearrange_router = SwarmRouter(
|
||||
name="TaskOptimizer",
|
||||
description="Optimize agent order for multi-step tasks",
|
||||
max_loops=3,
|
||||
agents=[data_extractor, analyzer, summarizer],
|
||||
swarm_type=SwarmType.AgentRearrange,
|
||||
flow = f"{data_extractor.name} -> {analyzer.name} -> {summarizer.name}"
|
||||
)
|
||||
|
||||
result = rearrange_router.run("Analyze and summarize the quarterly financial report")
|
||||
```
|
||||
|
||||
### MixtureOfAgents
|
||||
|
||||
Use Case: Combining diverse expert agents for comprehensive analysis.
|
||||
|
||||
```python
|
||||
mixture_router = SwarmRouter(
|
||||
name="ExpertPanel",
|
||||
description="Combine insights from various expert agents",
|
||||
max_loops=1,
|
||||
agents=[financial_expert, market_analyst, tech_specialist],
|
||||
swarm_type=SwarmType.MixtureOfAgents
|
||||
)
|
||||
|
||||
result = mixture_router.run("Evaluate the potential acquisition of TechStartup Inc.")
|
||||
```
|
||||
|
||||
### SpreadSheetSwarm
|
||||
|
||||
Use Case: Collaborative data processing and analysis.
|
||||
|
||||
```python
|
||||
spreadsheet_router = SwarmRouter(
|
||||
name="DataProcessor",
|
||||
description="Collaborative data processing and analysis",
|
||||
max_loops=1,
|
||||
agents=[data_cleaner, statistical_analyzer, visualizer],
|
||||
swarm_type=SwarmType.SpreadSheetSwarm
|
||||
)
|
||||
|
||||
result = spreadsheet_router.run("Process and visualize customer churn data")
|
||||
```
|
||||
|
||||
### SequentialWorkflow
|
||||
|
||||
Use Case: Step-by-step document analysis and report generation.
|
||||
|
||||
```python
|
||||
sequential_router = SwarmRouter(
|
||||
name="ReportGenerator",
|
||||
description="Generate comprehensive reports sequentially",
|
||||
max_loops=1,
|
||||
agents=[data_extractor, analyzer, writer, reviewer],
|
||||
swarm_type=SwarmType.SequentialWorkflow
|
||||
)
|
||||
|
||||
result = sequential_router.run("Create a due diligence report for Project Alpha")
|
||||
```
|
||||
|
||||
### ConcurrentWorkflow
|
||||
|
||||
Use Case: Parallel processing of multiple data sources.
|
||||
|
||||
```python
|
||||
concurrent_router = SwarmRouter(
|
||||
name="MultiSourceAnalyzer",
|
||||
description="Analyze multiple data sources concurrently",
|
||||
max_loops=1,
|
||||
agents=[financial_analyst, market_researcher, competitor_analyst],
|
||||
swarm_type=SwarmType.ConcurrentWorkflow
|
||||
)
|
||||
|
||||
result = concurrent_router.run("Conduct a comprehensive market analysis for Product X")
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The `SwarmRouter` includes error handling in the `run` method. If an exception occurs during task execution, it will be logged and re-raised for the caller to handle. Always wrap the `run` method in a try-except block:
|
||||
|
||||
```python
|
||||
try:
|
||||
result = router.run("Complex analysis task")
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {str(e)}")
|
||||
# Handle the error appropriately
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. Choose the appropriate swarm type based on your task requirements.
|
||||
2. Provide clear and specific tasks to the swarm for optimal results.
|
||||
3. Regularly review logs to monitor performance and identify potential issues.
|
||||
4. Use descriptive names and descriptions for your SwarmRouter and agents.
|
||||
5. Implement proper error handling in your application code.
|
||||
6. Consider the nature of your tasks when choosing a swarm type (e.g., use ConcurrentWorkflow for tasks that can be parallelized).
|
||||
7. Optimize your agents' prompts and configurations for best performance within the swarm.
|
@ -0,0 +1,156 @@
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from swarms import Agent, circular_swarm
|
||||
|
||||
from swarm_models import OpenAIChat
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# Get the OpenAI API key from the environment variable
|
||||
api_key = os.getenv("GROQ_API_KEY")
|
||||
|
||||
# Model
|
||||
model = OpenAIChat(
|
||||
openai_api_base="https://api.groq.com/openai/v1",
|
||||
openai_api_key=api_key,
|
||||
model_name="llama-3.1-70b-versatile",
|
||||
temperature=0.1,
|
||||
)
|
||||
# Define specialized system prompts for each agent
|
||||
DATA_EXTRACTOR_PROMPT = """You are a highly specialized private equity agent focused on data extraction from various documents. Your expertise includes:
|
||||
1. Extracting key financial metrics (revenue, EBITDA, growth rates, etc.) from financial statements and reports
|
||||
2. Identifying and extracting important contract terms from legal documents
|
||||
3. Pulling out relevant market data from industry reports and analyses
|
||||
4. Extracting operational KPIs from management presentations and internal reports
|
||||
5. Identifying and extracting key personnel information from organizational charts and bios
|
||||
Provide accurate, structured data extracted from various document types to support investment analysis."""
|
||||
|
||||
SUMMARIZER_PROMPT = """You are an expert private equity agent specializing in summarizing complex documents. Your core competencies include:
|
||||
1. Distilling lengthy financial reports into concise executive summaries
|
||||
2. Summarizing legal documents, highlighting key terms and potential risks
|
||||
3. Condensing industry reports to capture essential market trends and competitive dynamics
|
||||
4. Summarizing management presentations to highlight key strategic initiatives and projections
|
||||
5. Creating brief overviews of technical documents, emphasizing critical points for non-technical stakeholders
|
||||
Deliver clear, concise summaries that capture the essence of various documents while highlighting information crucial for investment decisions."""
|
||||
|
||||
FINANCIAL_ANALYST_PROMPT = """You are a specialized private equity agent focused on financial analysis. Your key responsibilities include:
|
||||
1. Analyzing historical financial statements to identify trends and potential issues
|
||||
2. Evaluating the quality of earnings and potential adjustments to EBITDA
|
||||
3. Assessing working capital requirements and cash flow dynamics
|
||||
4. Analyzing capital structure and debt capacity
|
||||
5. Evaluating financial projections and underlying assumptions
|
||||
Provide thorough, insightful financial analysis to inform investment decisions and valuation."""
|
||||
|
||||
MARKET_ANALYST_PROMPT = """You are a highly skilled private equity agent specializing in market analysis. Your expertise covers:
|
||||
1. Analyzing industry trends, growth drivers, and potential disruptors
|
||||
2. Evaluating competitive landscape and market positioning
|
||||
3. Assessing market size, segmentation, and growth potential
|
||||
4. Analyzing customer dynamics, including concentration and loyalty
|
||||
5. Identifying potential regulatory or macroeconomic impacts on the market
|
||||
Deliver comprehensive market analysis to assess the attractiveness and risks of potential investments."""
|
||||
|
||||
OPERATIONAL_ANALYST_PROMPT = """You are an expert private equity agent focused on operational analysis. Your core competencies include:
|
||||
1. Evaluating operational efficiency and identifying improvement opportunities
|
||||
2. Analyzing supply chain and procurement processes
|
||||
3. Assessing sales and marketing effectiveness
|
||||
4. Evaluating IT systems and digital capabilities
|
||||
5. Identifying potential synergies in merger or add-on acquisition scenarios
|
||||
Provide detailed operational analysis to uncover value creation opportunities and potential risks."""
|
||||
|
||||
# Initialize specialized agents
|
||||
data_extractor_agent = Agent(
|
||||
agent_name="Data-Extractor",
|
||||
system_prompt=DATA_EXTRACTOR_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="data_extractor_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
summarizer_agent = Agent(
|
||||
agent_name="Document-Summarizer",
|
||||
system_prompt=SUMMARIZER_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="summarizer_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
financial_analyst_agent = Agent(
|
||||
agent_name="Financial-Analyst",
|
||||
system_prompt=FINANCIAL_ANALYST_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="financial_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
market_analyst_agent = Agent(
|
||||
agent_name="Market-Analyst",
|
||||
system_prompt=MARKET_ANALYST_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="market_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
operational_analyst_agent = Agent(
|
||||
agent_name="Operational-Analyst",
|
||||
system_prompt=OPERATIONAL_ANALYST_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="operational_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
# Initialize the SwarmRouter
|
||||
agents = (
|
||||
[
|
||||
data_extractor_agent,
|
||||
summarizer_agent,
|
||||
financial_analyst_agent,
|
||||
market_analyst_agent,
|
||||
operational_analyst_agent,
|
||||
],
|
||||
)
|
||||
|
||||
task = "Where is the best place to find template term sheets for series A startups. Provide links and references"
|
||||
|
||||
out = circular_swarm(
|
||||
agents,
|
||||
tasks=[
|
||||
task,
|
||||
"Where is the best city where the most deals are taking place rank them",
|
||||
],
|
||||
)
|
||||
print(out)
|
@ -1,45 +0,0 @@
|
||||
from swarms.structs.tree_swarm import TreeAgent, Tree, ForestSwarm
|
||||
|
||||
# Example Usage:
|
||||
|
||||
# Create agents with varying system prompts and dynamically generated distances/keywords
|
||||
agents_tree1 = [
|
||||
TreeAgent(
|
||||
system_prompt="Stock Analysis Agent",
|
||||
agent_name="Stock Analysis Agent",
|
||||
),
|
||||
TreeAgent(
|
||||
system_prompt="Financial Planning Agent",
|
||||
agent_name="Financial Planning Agent",
|
||||
),
|
||||
TreeAgent(
|
||||
agent_name="Retirement Strategy Agent",
|
||||
system_prompt="Retirement Strategy Agent",
|
||||
),
|
||||
]
|
||||
|
||||
agents_tree2 = [
|
||||
TreeAgent(
|
||||
system_prompt="Tax Filing Agent",
|
||||
agent_name="Tax Filing Agent",
|
||||
),
|
||||
TreeAgent(
|
||||
system_prompt="Investment Strategy Agent",
|
||||
agent_name="Investment Strategy Agent",
|
||||
),
|
||||
TreeAgent(
|
||||
system_prompt="ROTH IRA Agent", agent_name="ROTH IRA Agent"
|
||||
),
|
||||
]
|
||||
|
||||
# Create trees
|
||||
tree1 = Tree(tree_name="Financial Tree", agents=agents_tree1)
|
||||
tree2 = Tree(tree_name="Investment Tree", agents=agents_tree2)
|
||||
|
||||
# Create the ForestSwarm
|
||||
multi_agent_structure = ForestSwarm(trees=[tree1, tree2])
|
||||
|
||||
# Run a task
|
||||
task = "Our company is incorporated in delaware, how do we do our taxes for free?"
|
||||
output = multi_agent_structure.run(task)
|
||||
print(output)
|
@ -0,0 +1,109 @@
|
||||
from swarms.structs.tree_swarm import TreeAgent, Tree, ForestSwarm
|
||||
|
||||
# Create agents with varying system prompts and dynamically generated distances/keywords
|
||||
agents_tree1 = [
|
||||
TreeAgent(
|
||||
system_prompt="""You are an expert Stock Analysis Agent with deep knowledge of financial markets, technical analysis, and fundamental analysis. Your primary function is to analyze stock performance, market trends, and provide actionable insights. When analyzing stocks:
|
||||
|
||||
1. Always start with a brief overview of the current market conditions.
|
||||
2. Use a combination of technical indicators (e.g., moving averages, RSI, MACD) and fundamental metrics (e.g., P/E ratio, EPS growth, debt-to-equity).
|
||||
3. Consider both short-term and long-term perspectives in your analysis.
|
||||
4. Provide clear buy, hold, or sell recommendations with supporting rationale.
|
||||
5. Highlight potential risks and opportunities specific to each stock or sector.
|
||||
6. Use bullet points for clarity when listing key points or metrics.
|
||||
7. If relevant, compare the stock to its peers or sector benchmarks.
|
||||
|
||||
Remember to maintain objectivity and base your analysis on factual data. If asked about future performance, always include a disclaimer about market unpredictability. Your goal is to provide comprehensive, accurate, and actionable stock analysis to inform investment decisions.""",
|
||||
agent_name="Stock Analysis Agent",
|
||||
),
|
||||
TreeAgent(
|
||||
system_prompt="""You are a highly skilled Financial Planning Agent, specializing in personal and corporate financial strategies. Your role is to provide comprehensive financial advice tailored to each client's unique situation. When creating financial plans:
|
||||
|
||||
1. Begin by asking key questions about the client's financial goals, current situation, and risk tolerance.
|
||||
2. Develop a holistic view of the client's finances, including income, expenses, assets, and liabilities.
|
||||
3. Create detailed, step-by-step action plans to achieve financial goals.
|
||||
4. Provide specific recommendations for budgeting, saving, and investing.
|
||||
5. Consider tax implications and suggest tax-efficient strategies.
|
||||
6. Incorporate risk management and insurance planning into your recommendations.
|
||||
7. Use charts or tables to illustrate financial projections and scenarios.
|
||||
8. Regularly suggest reviewing and adjusting the plan as circumstances change.
|
||||
|
||||
Always prioritize the client's best interests and adhere to fiduciary standards. Explain complex financial concepts in simple terms, and be prepared to justify your recommendations with data and reasoning.""",
|
||||
agent_name="Financial Planning Agent",
|
||||
),
|
||||
TreeAgent(
|
||||
agent_name="Retirement Strategy Agent",
|
||||
system_prompt="""You are a specialized Retirement Strategy Agent, focused on helping individuals and couples plan for a secure and comfortable retirement. Your expertise covers various aspects of retirement planning, including savings strategies, investment allocation, and income generation during retirement. When developing retirement strategies:
|
||||
|
||||
1. Start by assessing the client's current age, desired retirement age, and expected lifespan.
|
||||
2. Calculate retirement savings goals based on desired lifestyle and projected expenses.
|
||||
3. Analyze current retirement accounts (e.g., 401(k), IRA) and suggest optimization strategies.
|
||||
4. Provide guidance on asset allocation and rebalancing as retirement approaches.
|
||||
5. Explain various retirement income sources (e.g., Social Security, pensions, annuities).
|
||||
6. Discuss healthcare costs and long-term care planning.
|
||||
7. Offer strategies for tax-efficient withdrawals during retirement.
|
||||
8. Consider estate planning and legacy goals in your recommendations.
|
||||
|
||||
Use Monte Carlo simulations or other statistical tools to illustrate the probability of retirement success. Always emphasize the importance of starting early and the power of compound interest. Be prepared to adjust strategies based on changing market conditions or personal circumstances.""",
|
||||
),
|
||||
]
|
||||
|
||||
agents_tree2 = [
|
||||
TreeAgent(
|
||||
system_prompt="""You are a knowledgeable Tax Filing Agent, specializing in personal and business tax preparation and strategy. Your role is to ensure accurate tax filings while maximizing legitimate deductions and credits. When assisting with tax matters:
|
||||
|
||||
1. Start by gathering all necessary financial information and documents.
|
||||
2. Stay up-to-date with the latest tax laws and regulations, including state-specific rules.
|
||||
3. Identify all applicable deductions and credits based on the client's situation.
|
||||
4. Provide step-by-step guidance for completing tax forms accurately.
|
||||
5. Explain tax implications of various financial decisions.
|
||||
6. Offer strategies for tax-efficient investing and income management.
|
||||
7. Assist with estimated tax payments for self-employed individuals or businesses.
|
||||
8. Advise on record-keeping practices for tax purposes.
|
||||
|
||||
Always prioritize compliance with tax laws while ethically minimizing tax liability. Be prepared to explain complex tax concepts in simple terms and provide rationale for your recommendations. If a situation is beyond your expertise, advise consulting a certified tax professional or IRS resources.""",
|
||||
agent_name="Tax Filing Agent",
|
||||
),
|
||||
TreeAgent(
|
||||
system_prompt="""You are a sophisticated Investment Strategy Agent, adept at creating and managing investment portfolios to meet diverse financial goals. Your expertise covers various asset classes, market analysis, and risk management techniques. When developing investment strategies:
|
||||
|
||||
1. Begin by assessing the client's investment goals, time horizon, and risk tolerance.
|
||||
2. Provide a comprehensive overview of different asset classes and their risk-return profiles.
|
||||
3. Create diversified portfolio recommendations based on modern portfolio theory.
|
||||
4. Explain the benefits and risks of various investment vehicles (e.g., stocks, bonds, ETFs, mutual funds).
|
||||
5. Incorporate both passive and active investment strategies as appropriate.
|
||||
6. Discuss the importance of regular portfolio rebalancing and provide a rebalancing strategy.
|
||||
7. Consider tax implications of investment decisions and suggest tax-efficient strategies.
|
||||
8. Provide ongoing market analysis and suggest portfolio adjustments as needed.
|
||||
|
||||
Use historical data and forward-looking projections to illustrate potential outcomes. Always emphasize the importance of long-term investing and the risks of market timing. Be prepared to explain complex investment concepts in clear, accessible language.""",
|
||||
agent_name="Investment Strategy Agent",
|
||||
),
|
||||
TreeAgent(
|
||||
system_prompt="""You are a specialized ROTH IRA Agent, focusing on the intricacies of Roth Individual Retirement Accounts. Your role is to provide expert guidance on Roth IRA rules, benefits, and strategies to maximize their value for retirement planning. When advising on Roth IRAs:
|
||||
|
||||
1. Explain the fundamental differences between traditional and Roth IRAs.
|
||||
2. Clarify Roth IRA contribution limits and income eligibility requirements.
|
||||
3. Discuss the tax advantages of Roth IRAs, including tax-free growth and withdrawals.
|
||||
4. Provide guidance on Roth IRA conversion strategies and their tax implications.
|
||||
5. Explain the five-year rule and how it affects Roth IRA withdrawals.
|
||||
6. Offer strategies for maximizing Roth IRA contributions, such as the backdoor Roth IRA method.
|
||||
7. Discuss how Roth IRAs fit into overall retirement and estate planning strategies.
|
||||
8. Provide insights on investment choices within a Roth IRA to maximize tax-free growth.
|
||||
|
||||
Always stay current with IRS regulations regarding Roth IRAs. Be prepared to provide numerical examples to illustrate the long-term benefits of Roth IRAs. Emphasize the importance of considering individual financial situations when making Roth IRA decisions.""",
|
||||
agent_name="ROTH IRA Agent",
|
||||
),
|
||||
]
|
||||
|
||||
# Create trees
|
||||
tree1 = Tree(tree_name="Financial Tree", agents=agents_tree1)
|
||||
tree2 = Tree(tree_name="Investment Tree", agents=agents_tree2)
|
||||
|
||||
# Create the ForestSwarm
|
||||
multi_agent_structure = ForestSwarm(trees=[tree1, tree2])
|
||||
|
||||
# Run a task
|
||||
task = "What are the best platforms to do our taxes on"
|
||||
output = multi_agent_structure.run(task)
|
||||
print(output)
|
@ -0,0 +1,161 @@
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from swarms import Agent
|
||||
from swarm_models import OpenAIChat
|
||||
from swarms.structs.swarm_router import SwarmRouter
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# Get the OpenAI API key from the environment variable
|
||||
api_key = os.getenv("GROQ_API_KEY")
|
||||
|
||||
# Model
|
||||
model = OpenAIChat(
|
||||
openai_api_base="https://api.groq.com/openai/v1",
|
||||
openai_api_key=api_key,
|
||||
model_name="llama-3.1-70b-versatile",
|
||||
temperature=0.1,
|
||||
)
|
||||
# Define specialized system prompts for each agent
|
||||
DATA_EXTRACTOR_PROMPT = """You are a highly specialized private equity agent focused on data extraction from various documents. Your expertise includes:
|
||||
1. Extracting key financial metrics (revenue, EBITDA, growth rates, etc.) from financial statements and reports
|
||||
2. Identifying and extracting important contract terms from legal documents
|
||||
3. Pulling out relevant market data from industry reports and analyses
|
||||
4. Extracting operational KPIs from management presentations and internal reports
|
||||
5. Identifying and extracting key personnel information from organizational charts and bios
|
||||
Provide accurate, structured data extracted from various document types to support investment analysis."""
|
||||
|
||||
SUMMARIZER_PROMPT = """You are an expert private equity agent specializing in summarizing complex documents. Your core competencies include:
|
||||
1. Distilling lengthy financial reports into concise executive summaries
|
||||
2. Summarizing legal documents, highlighting key terms and potential risks
|
||||
3. Condensing industry reports to capture essential market trends and competitive dynamics
|
||||
4. Summarizing management presentations to highlight key strategic initiatives and projections
|
||||
5. Creating brief overviews of technical documents, emphasizing critical points for non-technical stakeholders
|
||||
Deliver clear, concise summaries that capture the essence of various documents while highlighting information crucial for investment decisions."""
|
||||
|
||||
FINANCIAL_ANALYST_PROMPT = """You are a specialized private equity agent focused on financial analysis. Your key responsibilities include:
|
||||
1. Analyzing historical financial statements to identify trends and potential issues
|
||||
2. Evaluating the quality of earnings and potential adjustments to EBITDA
|
||||
3. Assessing working capital requirements and cash flow dynamics
|
||||
4. Analyzing capital structure and debt capacity
|
||||
5. Evaluating financial projections and underlying assumptions
|
||||
Provide thorough, insightful financial analysis to inform investment decisions and valuation."""
|
||||
|
||||
MARKET_ANALYST_PROMPT = """You are a highly skilled private equity agent specializing in market analysis. Your expertise covers:
|
||||
1. Analyzing industry trends, growth drivers, and potential disruptors
|
||||
2. Evaluating competitive landscape and market positioning
|
||||
3. Assessing market size, segmentation, and growth potential
|
||||
4. Analyzing customer dynamics, including concentration and loyalty
|
||||
5. Identifying potential regulatory or macroeconomic impacts on the market
|
||||
Deliver comprehensive market analysis to assess the attractiveness and risks of potential investments."""
|
||||
|
||||
OPERATIONAL_ANALYST_PROMPT = """You are an expert private equity agent focused on operational analysis. Your core competencies include:
|
||||
1. Evaluating operational efficiency and identifying improvement opportunities
|
||||
2. Analyzing supply chain and procurement processes
|
||||
3. Assessing sales and marketing effectiveness
|
||||
4. Evaluating IT systems and digital capabilities
|
||||
5. Identifying potential synergies in merger or add-on acquisition scenarios
|
||||
Provide detailed operational analysis to uncover value creation opportunities and potential risks."""
|
||||
|
||||
# Initialize specialized agents
|
||||
data_extractor_agent = Agent(
|
||||
agent_name="Data-Extractor",
|
||||
system_prompt=DATA_EXTRACTOR_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="data_extractor_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
summarizer_agent = Agent(
|
||||
agent_name="Document-Summarizer",
|
||||
system_prompt=SUMMARIZER_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="summarizer_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
financial_analyst_agent = Agent(
|
||||
agent_name="Financial-Analyst",
|
||||
system_prompt=FINANCIAL_ANALYST_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="financial_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
market_analyst_agent = Agent(
|
||||
agent_name="Market-Analyst",
|
||||
system_prompt=MARKET_ANALYST_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="market_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
operational_analyst_agent = Agent(
|
||||
agent_name="Operational-Analyst",
|
||||
system_prompt=OPERATIONAL_ANALYST_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="operational_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
# Initialize the SwarmRouter
|
||||
router = SwarmRouter(
|
||||
name="pe-document-analysis-swarm",
|
||||
description="Analyze documents for private equity due diligence and investment decision-making",
|
||||
max_loops=1,
|
||||
agents=[
|
||||
data_extractor_agent,
|
||||
summarizer_agent,
|
||||
financial_analyst_agent,
|
||||
market_analyst_agent,
|
||||
operational_analyst_agent,
|
||||
],
|
||||
swarm_type="ConcurrentWorkflow", # or "SequentialWorkflow" or "ConcurrentWorkflow" or
|
||||
)
|
||||
|
||||
# Example usage
|
||||
if __name__ == "__main__":
|
||||
# Run a comprehensive private equity document analysis task
|
||||
result = router.run(
|
||||
"Where is the best place to find template term sheets for series A startups. Provide links and references"
|
||||
)
|
||||
print(result)
|
||||
|
||||
# Retrieve and print logs
|
||||
for log in router.get_logs():
|
||||
print(f"{log.timestamp} - {log.level}: {log.message}")
|
@ -0,0 +1,53 @@
|
||||
from swarms.prompts.prompt import Prompt
|
||||
|
||||
# Aggregator system prompt
|
||||
aggregator_system_prompt = Prompt(
|
||||
name="aggregation_prompt",
|
||||
description="Aggregate and summarize multiple agent outputs",
|
||||
content="""
|
||||
|
||||
# Multi-Agent Observer and Summarizer
|
||||
|
||||
You are an advanced AI agent tasked with observing, analyzing, and summarizing the responses of multiple other AI agents. Your primary function is to provide concise, insightful summaries of agent interactions and outputs. Follow these guidelines:
|
||||
|
||||
## Core Responsibilities:
|
||||
1. Observe and record responses from all agents in a given interaction.
|
||||
2. Analyze the content, tone, and effectiveness of each agent's contribution.
|
||||
3. Identify areas of agreement, disagreement, and unique insights among agents.
|
||||
4. Summarize key points and conclusions from the multi-agent interaction.
|
||||
5. Highlight any inconsistencies, errors, or potential biases in agent responses.
|
||||
|
||||
## Operational Guidelines:
|
||||
- Maintain strict objectivity in your observations and summaries.
|
||||
- Use clear, concise language in your reports.
|
||||
- Organize summaries in a structured format for easy comprehension.
|
||||
- Adapt your summarization style based on the context and complexity of the interaction.
|
||||
- Respect confidentiality and ethical guidelines in your reporting.
|
||||
|
||||
## Analysis Framework:
|
||||
For each agent interaction, consider the following:
|
||||
1. Relevance: How well did each agent address the given task or query?
|
||||
2. Accuracy: Were the agents' responses factually correct and logically sound?
|
||||
3. Creativity: Did any agents provide unique or innovative perspectives?
|
||||
4. Collaboration: How effectively did the agents build upon or challenge each other's ideas?
|
||||
5. Efficiency: Which agents provided the most value with the least verbose responses?
|
||||
|
||||
## Output Format:
|
||||
Your summaries should include:
|
||||
1. A brief overview of the interaction context
|
||||
2. Key points from each agent's contribution
|
||||
3. Areas of consensus and disagreement
|
||||
4. Notable insights or breakthroughs
|
||||
5. Potential improvements or areas for further exploration
|
||||
|
||||
## Self-Improvement:
|
||||
- Continuously refine your observation and summarization techniques.
|
||||
- Identify patterns in agent behaviors and interactions to enhance your analytical capabilities.
|
||||
- Adapt to various domains and types of agent interactions.
|
||||
|
||||
Remember: Your role is crucial in distilling complex multi-agent interactions into actionable insights. Strive for clarity, accuracy, and impartiality in all your summaries.
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
# print(aggregator_system_prompt.get_prompt())
|
@ -0,0 +1,237 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Literal, Union
|
||||
|
||||
from loguru import logger
|
||||
from pydantic import BaseModel, Field
|
||||
from swarms.structs.agent import Agent
|
||||
from swarms.structs.concurrent_workflow import ConcurrentWorkflow
|
||||
from swarms.structs.mixture_of_agents import MixtureOfAgents
|
||||
from swarms.structs.rearrange import AgentRearrange
|
||||
from swarms.structs.sequential_workflow import SequentialWorkflow
|
||||
from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm
|
||||
|
||||
SwarmType = Literal[
|
||||
"AgentRearrange",
|
||||
"MixtureOfAgents",
|
||||
"SpreadSheetSwarm",
|
||||
"SequentialWorkflow",
|
||||
"ConcurrentWorkflow",
|
||||
]
|
||||
|
||||
|
||||
class SwarmLog(BaseModel):
|
||||
"""
|
||||
A Pydantic model to capture log entries.
|
||||
"""
|
||||
|
||||
id: str = Field(default_factory=lambda: str(uuid.uuid4()))
|
||||
timestamp: datetime = Field(default_factory=datetime.utcnow)
|
||||
level: str
|
||||
message: str
|
||||
swarm_type: SwarmType
|
||||
task: str = ""
|
||||
metadata: Dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class SwarmRouter:
|
||||
"""
|
||||
A class to route tasks to different swarm types based on user selection.
|
||||
|
||||
This class allows users to specify a swarm type and a list of agents, then run tasks
|
||||
on the selected swarm type. It includes type validation, logging, and metadata capture.
|
||||
|
||||
Attributes:
|
||||
agents (List[Agent]): A list of Agent objects to be used in the swarm.
|
||||
swarm_type (SwarmType): The type of swarm to be used.
|
||||
swarm (Union[AgentRearrange, GraphWorkflow, MixtureOfAgents, SpreadSheetSwarm]):
|
||||
The instantiated swarm object.
|
||||
logs (List[SwarmLog]): A list of log entries captured during operations.
|
||||
|
||||
Available Swarm Types:
|
||||
- AgentRearrange: Rearranges agents for optimal task execution.
|
||||
- MixtureOfAgents: Combines different types of agents for diverse task handling.
|
||||
- SpreadSheetSwarm: Utilizes spreadsheet-like operations for task management.
|
||||
- SequentialWorkflow: Executes tasks in a sequential manner.
|
||||
- ConcurrentWorkflow: Executes tasks concurrently for parallel processing.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str = "swarm-router",
|
||||
description: str = "Routes your task to the desired swarm",
|
||||
max_loops: int = 1,
|
||||
agents: List[Agent] = None,
|
||||
swarm_type: SwarmType = None,
|
||||
*args,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
Initialize the SwarmRouter with a list of agents and a swarm type.
|
||||
|
||||
Args:
|
||||
name (str, optional): The name of the SwarmRouter instance. Defaults to None.
|
||||
description (str, optional): A description of the SwarmRouter instance. Defaults to None.
|
||||
max_loops (int, optional): The maximum number of loops to perform. Defaults to 1.
|
||||
agents (List[Agent], optional): A list of Agent objects to be used in the swarm. Defaults to None.
|
||||
swarm_type (SwarmType, optional): The type of swarm to be used. Defaults to None.
|
||||
*args: Variable length argument list.
|
||||
**kwargs: Arbitrary keyword arguments.
|
||||
|
||||
Raises:
|
||||
ValueError: If an invalid swarm type is provided.
|
||||
"""
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.max_loops = max_loops
|
||||
self.agents = agents
|
||||
self.swarm_type = swarm_type
|
||||
self.swarm = self._create_swarm(*args, **kwargs)
|
||||
self.logs = []
|
||||
|
||||
self._log(
|
||||
"info",
|
||||
f"SwarmRouter initialized with swarm type: {swarm_type}",
|
||||
)
|
||||
|
||||
def _create_swarm(self, *args, **kwargs) -> Union[
|
||||
AgentRearrange,
|
||||
MixtureOfAgents,
|
||||
SpreadSheetSwarm,
|
||||
]:
|
||||
"""
|
||||
Create and return the specified swarm type.
|
||||
|
||||
Args:
|
||||
*args: Variable length argument list.
|
||||
**kwargs: Arbitrary keyword arguments.
|
||||
|
||||
Returns:
|
||||
Union[AgentRearrange, GraphWorkflow, MixtureOfAgents, SpreadSheetSwarm]:
|
||||
The instantiated swarm object.
|
||||
|
||||
Raises:
|
||||
ValueError: If an invalid swarm type is provided.
|
||||
"""
|
||||
if self.swarm_type == "AgentRearrange":
|
||||
return AgentRearrange(
|
||||
name=self.name,
|
||||
description=self.description,
|
||||
agents=self.agents,
|
||||
max_loops=self.max_loops,
|
||||
*args,
|
||||
**kwargs,
|
||||
)
|
||||
elif self.swarm_type == "MixtureOfAgents":
|
||||
return MixtureOfAgents(
|
||||
name=self.name,
|
||||
description=self.description,
|
||||
agents=self.agents,
|
||||
aggregator_agent=[self.agents[-1]],
|
||||
layers=self.max_loops,
|
||||
*args,
|
||||
**kwargs,
|
||||
)
|
||||
elif self.swarm_type == "SpreadSheetSwarm":
|
||||
return SpreadSheetSwarm(
|
||||
name=self.name,
|
||||
description=self.description,
|
||||
agents=self.agents,
|
||||
max_loops=1,
|
||||
*args,
|
||||
**kwargs,
|
||||
)
|
||||
elif self.swarm_type == "SequentialWorkflow":
|
||||
return SequentialWorkflow(
|
||||
name=self.name,
|
||||
description=self.description,
|
||||
agents=self.agents,
|
||||
max_loops=self.max_loops,
|
||||
*args,
|
||||
**kwargs,
|
||||
)
|
||||
elif self.swarm_type == "ConcurrentWorkflow":
|
||||
return ConcurrentWorkflow(
|
||||
name=self.name,
|
||||
description=self.description,
|
||||
agents=self.agents,
|
||||
max_loops=self.max_loops,
|
||||
*args,
|
||||
**kwargs,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Invalid swarm type: {self.swarm_type}")
|
||||
|
||||
def _log(
|
||||
self,
|
||||
level: str,
|
||||
message: str,
|
||||
task: str = "",
|
||||
metadata: Dict[str, Any] = None,
|
||||
):
|
||||
"""
|
||||
Create a log entry and add it to the logs list.
|
||||
|
||||
Args:
|
||||
level (str): The log level (e.g., "info", "error").
|
||||
message (str): The log message.
|
||||
task (str, optional): The task being performed. Defaults to "".
|
||||
metadata (Dict[str, Any], optional): Additional metadata. Defaults to None.
|
||||
"""
|
||||
log_entry = SwarmLog(
|
||||
level=level,
|
||||
message=message,
|
||||
swarm_type=self.swarm_type,
|
||||
task=task,
|
||||
metadata=metadata or {},
|
||||
)
|
||||
self.logs.append(log_entry)
|
||||
logger.log(level.upper(), message)
|
||||
|
||||
def run(self, task: str, *args, **kwargs) -> Any:
|
||||
"""
|
||||
Run the specified task on the selected swarm.
|
||||
|
||||
Args:
|
||||
task (str): The task to be executed by the swarm.
|
||||
*args: Variable length argument list.
|
||||
**kwargs: Arbitrary keyword arguments.
|
||||
|
||||
Returns:
|
||||
Any: The result of the swarm's execution.
|
||||
|
||||
Raises:
|
||||
Exception: If an error occurs during task execution.
|
||||
"""
|
||||
try:
|
||||
self._log(
|
||||
"info",
|
||||
f"Running task on {self.swarm_type} swarm",
|
||||
task=task,
|
||||
metadata=kwargs,
|
||||
)
|
||||
result = self.swarm.run(task, *args, **kwargs)
|
||||
self._log(
|
||||
"success",
|
||||
f"Task completed successfully on {self.swarm_type} swarm",
|
||||
task=task,
|
||||
metadata={"result": str(result)},
|
||||
)
|
||||
return result
|
||||
except Exception as e:
|
||||
self._log(
|
||||
"error",
|
||||
f"Error occurred while running task on {self.swarm_type} swarm: {str(e)}",
|
||||
task=task,
|
||||
metadata={"error": str(e)},
|
||||
)
|
||||
raise
|
||||
|
||||
def get_logs(self) -> List[SwarmLog]:
|
||||
"""
|
||||
Retrieve all logged entries.
|
||||
|
||||
Returns:
|
||||
List[SwarmLog]: A list of all log entries.
|
||||
"""
|
||||
return self.logs
|
@ -0,0 +1,16 @@
|
||||
import os
|
||||
from swarm_models import Anthropic
|
||||
from dotenv import load_dotenv
|
||||
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
model = Anthropic(
|
||||
anthropic_api_key=os.getenv("ANTHROPIC_API_KEY"),
|
||||
temperature=0.1,
|
||||
)
|
||||
|
||||
model.run(
|
||||
"Where is the best state to open up a c corp with the lowest taxes"
|
||||
)
|
@ -0,0 +1,46 @@
|
||||
import os
|
||||
from swarms import Agent
|
||||
from swarm_models import OpenAIChat
|
||||
|
||||
from swarms.prompts.finance_agent_sys_prompt import (
|
||||
FINANCIAL_AGENT_SYS_PROMPT,
|
||||
)
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# Get the OpenAI API key from the environment variable
|
||||
api_key = os.getenv("GROQ_API_KEY")
|
||||
|
||||
# Model
|
||||
model = OpenAIChat(
|
||||
openai_api_base="https://api.groq.com/openai/v1",
|
||||
openai_api_key=api_key,
|
||||
model_name="llama-3.1-70b-versatile",
|
||||
temperature=0.1,
|
||||
)
|
||||
|
||||
# Initialize the agent
|
||||
agent = Agent(
|
||||
agent_name="Financial-Analysis-Agent",
|
||||
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
dashboard=False,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="finance_agent.json",
|
||||
user_name="swarms_corp",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
return_step_meta=False,
|
||||
# output_type="json",
|
||||
output_type="string",
|
||||
streaming_on=False,
|
||||
)
|
||||
|
||||
|
||||
agent.run(
|
||||
"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria"
|
||||
)
|
@ -0,0 +1,123 @@
|
||||
from typing import Optional, Dict
|
||||
from loguru import logger
|
||||
import os
|
||||
from swarms import Agent
|
||||
from swarm_models import OpenAIChat
|
||||
from dotenv import load_dotenv
|
||||
from linkedin_api import Linkedin
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# Get the OpenAI API key from the environment variable
|
||||
openai_api_key = os.getenv("OPENAI_API_KEY")
|
||||
|
||||
# LinkedIn credentials (use a dummy account for ethical scraping)
|
||||
linkedin_username = os.getenv("LINKEDIN_USERNAME")
|
||||
linkedin_password = os.getenv("LINKEDIN_PASSWORD")
|
||||
|
||||
# Get the OpenAI API key from the environment variable
|
||||
api_key = os.getenv("GROQ_API_KEY")
|
||||
|
||||
# Model
|
||||
model = OpenAIChat(
|
||||
openai_api_base="https://api.groq.com/openai/v1",
|
||||
openai_api_key=api_key,
|
||||
model_name="llama-3.1-70b-versatile",
|
||||
temperature=0.1,
|
||||
)
|
||||
# Define the system prompt for the LinkedIn profile summarization agent
|
||||
LINKEDIN_AGENT_SYS_PROMPT = """
|
||||
You are a LinkedIn profile summarization agent. Your task is to analyze LinkedIn profile data and provide a concise, professional summary of the individual's career, skills, and achievements. When presented with profile data:
|
||||
|
||||
1. Summarize the person's current position and company.
|
||||
2. Highlight key skills and areas of expertise.
|
||||
3. Provide a brief overview of their work history, focusing on notable roles or companies.
|
||||
4. Mention any significant educational background or certifications.
|
||||
5. If available, note any accomplishments, publications, or projects.
|
||||
|
||||
Your summary should be professional, concise, and focus on the most relevant information for a business context. Aim to capture the essence of the person's professional identity in a few paragraphs.
|
||||
"""
|
||||
|
||||
# Initialize the agent
|
||||
agent = Agent(
|
||||
agent_name="LinkedIn-Profile-Summarization-Agent",
|
||||
system_prompt=LINKEDIN_AGENT_SYS_PROMPT,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
dashboard=False,
|
||||
verbose=True,
|
||||
saved_state_path="linkedin_agent.json",
|
||||
user_name="recruiter",
|
||||
context_length=2000,
|
||||
)
|
||||
|
||||
# Initialize LinkedIn API client
|
||||
linkedin_client = Linkedin(
|
||||
linkedin_username, linkedin_password, debug=True
|
||||
)
|
||||
|
||||
|
||||
def fetch_linkedin_profile(public_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
Fetches a LinkedIn profile by its public ID.
|
||||
|
||||
Args:
|
||||
- public_id (str): The public ID of the LinkedIn profile to fetch.
|
||||
|
||||
Returns:
|
||||
- Optional[Dict]: The fetched LinkedIn profile data as a dictionary, or None if an error occurs.
|
||||
"""
|
||||
try:
|
||||
profile = linkedin_client.get_profile(public_id)
|
||||
return profile
|
||||
except Exception as e:
|
||||
print(f"Error fetching LinkedIn profile: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def summarize_profile(profile_data: Optional[Dict]) -> str:
|
||||
"""
|
||||
Summarizes a LinkedIn profile based on its data.
|
||||
|
||||
Args:
|
||||
- profile_data (Optional[Dict]): The data of the LinkedIn profile to summarize.
|
||||
|
||||
Returns:
|
||||
- str: A summary of the LinkedIn profile.
|
||||
"""
|
||||
if not profile_data:
|
||||
return "Unable to fetch profile data."
|
||||
|
||||
# Convert profile data to a string representation
|
||||
profile_str = "\n".join(
|
||||
[f"{k}: {v}" for k, v in profile_data.items() if v]
|
||||
)
|
||||
|
||||
return agent.run(
|
||||
f"Summarize this LinkedIn profile:\n\n{profile_str}"
|
||||
)
|
||||
|
||||
|
||||
def linkedin_profile_search_and_summarize(public_id: str):
|
||||
"""
|
||||
Searches for a LinkedIn profile by its public ID and summarizes it.
|
||||
|
||||
Args:
|
||||
- public_id (str): The public ID of the LinkedIn profile to search and summarize.
|
||||
"""
|
||||
print(f"Fetching LinkedIn profile for: {public_id}")
|
||||
profile_data = fetch_linkedin_profile(public_id)
|
||||
logger.info(profile_data)
|
||||
|
||||
if profile_data:
|
||||
print("\nProfile data fetched successfully.")
|
||||
summary = summarize_profile(profile_data)
|
||||
print("\nProfile Summary:")
|
||||
print(summary)
|
||||
else:
|
||||
print("Failed to fetch profile data.")
|
||||
|
||||
|
||||
# Example usage
|
||||
linkedin_profile_search_and_summarize("williamhgates")
|
Loading…
Reference in new issue