Skip to content

Commit

Permalink
remove clusterops
Browse files Browse the repository at this point in the history
  • Loading branch information
kyegomez committed Feb 14, 2025
1 parent 43c5845 commit 07f4dd1
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 73 deletions.
84 changes: 63 additions & 21 deletions majority_voting_example.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,93 @@
from swarms import Agent, MajorityVoting
from swarms_tools.finance.sector_analysis import macro_sector_analysis

# Initialize multiple agents with a focus on asset allocation and risk management for a $50B portfolio

# print(macro_sector_analysis())

# Initialize multiple agents with different specialties
agents = [
Agent(
agent_name="Financial-Analysis-Agent",
agent_description="Personal finance advisor focused on market analysis",
system_prompt="You are a financial advisor specializing in market analysis and investment opportunities.",
agent_name="Sector-Financial-Analyst",
agent_description="Senior sector financial analyst focused on optimizing capital allocations for a $50B portfolio at BlackRock.",
system_prompt="""You are a seasoned financial analyst at BlackRock tasked with optimizing asset allocations from a $50B portfolio. Your responsibilities include:
- Conducting deep analyses of sector performance, historical trends, and financial fundamentals.
- Evaluating revenue growth, profitability, and overall market positioning to determine the optimal dollar allocation for each sector.
- Integrating risk considerations into your fiscal analysis to ensure that recommended capital assignments align with the overall risk tolerance.
- Presenting a detailed breakdown of how much money should be allocated to each sector and justifying these recommendations with data-driven insights.
Provide clear, quantitative recommendations in your output, including precise allocation figures for each sector.""",
max_loops=1,
model_name="gpt-4o",
model_name="groq/deepseek-r1-distill-qwen-32b",
max_tokens=3000,
),
Agent(
agent_name="Risk-Assessment-Agent",
agent_description="Risk analysis and portfolio management expert",
system_prompt="You are a risk assessment expert focused on evaluating investment risks and portfolio diversification.",
agent_name="Sector-Risk-Analyst",
agent_description="Expert risk management analyst focused on calibrating sector risk allocations for a $50B institutional portfolio.",
system_prompt="""You are a veteran risk analyst at BlackRock, responsible for defining and advising on risk allocation within a $50B portfolio. Your responsibilities include:
- Assessing the risk profile and volatility metrics of each market sector.
- Quantifying risk exposures, performing stress tests, and modeling adverse market scenarios.
- Recommending precise risk allocation figures (both in absolute and percentage terms) for each sector, ensuring a balanced risk profile across the portfolio.
- Integrating risk-adjusted return considerations into your analysis so that capital assignments reflect both opportunity and risk mitigation.
Provide detailed, quantitative insights and clearly articulate how much risk should be assumed per sector relative to the $50B total.""",
max_loops=1,
model_name="gpt-4o",
model_name="groq/deepseek-r1-distill-qwen-32b",
max_tokens=3000,
),
Agent(
agent_name="Tech-Investment-Agent",
agent_description="Technology sector investment specialist",
system_prompt="You are a technology investment specialist focused on AI, emerging tech, and growth opportunities.",
agent_name="Tech-Sector-Analyst",
agent_description="Specialized analyst focused on the technology sector, tasked with determining capital and risk allocations within the $50B portfolio.",
system_prompt="""You are a specialized technology sector analyst at BlackRock, focused on the high-growth potential of the tech sector as part of a $50B portfolio. Your responsibilities include:
- Evaluating current and emerging tech trends, competitive dynamics, and innovation drivers.
- Analyzing the risk/reward profile of tech investments, including both growth prospects and volatility.
- Recommending how much capital should be allocated to the technology sector, alongside quantified risk allocations suited to its inherent risk profile.
- Providing clear, data-backed insights that balance aggressive growth targets with measured risk exposures.
Deliver a detailed breakdown of your recommendations, including both dollar figures and risk metrics, tailored for the tech sector in the overall portfolio.""",
max_loops=1,
model_name="gpt-4o",
model_name="groq/deepseek-r1-distill-qwen-32b",
max_tokens=3000,
),
]


consensus_agent = Agent(
agent_name="Consensus-Agent",
agent_description="Consensus agent focused on analyzing investment advice",
system_prompt="You are a consensus agent focused on analyzing investment advice and providing a final answer.",
agent_name="Consensus-Strategist",
agent_description="Senior strategist who synthesizes allocation and risk management analyses for a cohesive $50B portfolio strategy at BlackRock.",
system_prompt="""You are a senior investment strategist at BlackRock responsible for integrating detailed sector analyses into a comprehensive $50B portfolio allocation strategy. Your tasks include:
- Synthesizing the fiscal, risk, and sector-specific insights provided by your fellow analysts.
- Balancing the recommendations to yield clear guidance on both capital allocations and corresponding risk exposure for each market sector.
- Formulating a unified strategy that specifies the optimal dollar and risk allocations per sector, ensuring that the overall portfolio adheres to BlackRock’s risk tolerance and performance objectives.
- Delivering a final narrative that includes precise allocation figures, supported by tables and quantitative data.
Ensure that your recommendations are actionable, data-driven, and well-aligned with institutional investment strategies.""",
max_loops=1,
model_name="gpt-4o",
model_name="groq/deepseek-r1-distill-qwen-32b",
max_tokens=3000,
)

# Create majority voting system
majority_voting = MajorityVoting(
name="Investment-Advisory-System",
description="Multi-agent system for investment advice",
name="Sector-Investment-Advisory-System",
description="Multi-agent system for sector analysis that determines optimal capital and risk allocations for a $50B portfolio at BlackRock.",
agents=agents,
verbose=True,
consensus_agent=consensus_agent,
)

# Run the analysis with majority voting
result = majority_voting.run(
task="Create a table of super high growth opportunities for AI. I have $40k to invest in ETFs, index funds, and more. Please create a table in markdown.",
task=f"""Evaluate the current market sectors and determine the optimal allocation of a $50B portfolio for BlackRock. Your analysis should include:
1. A detailed table that outlines each sector along with the recommended dollar allocation and corresponding risk allocation.
2. A comprehensive review for each sector covering:
- Fundamental performance metrics, historical trends, and growth outlook.
- Quantitative risk assessments including volatility measures, stress test results, and risk-adjusted return evaluations.
3. Specific recommendations on how much capital (in dollars and as a percentage of $50B) should be invested in each sector.
4. A detailed explanation of the recommended risk allocation for each sector, ensuring the overall portfolio risk stays within acceptable thresholds.
5. A consolidated strategy that integrates both fiscal performance and risk management insights to support sector-based allocation decisions.
Provide your output with a clear structure, including descriptive sections and tables for clarity.
{macro_sector_analysis()}
"""
)

print(result)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api"

[tool.poetry]
name = "swarms"
version = "7.1.9"
version = "7.2.0"
description = "Swarms - TGSC"
license = "MIT"
authors = ["Kye Gomez <[email protected]>"]
Expand Down
49 changes: 2 additions & 47 deletions swarms/structs/concurrent_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,7 @@
from swarms.structs.agent import Agent
from swarms.structs.base_swarm import BaseSwarm
from swarms.utils.file_processing import create_file_in_folder
import concurrent
from clusterops import (
execute_on_gpu,
execute_with_cpu_cores,
execute_on_multiple_gpus,
list_available_gpus,
)
import concurrent.futures
from swarms.utils.loguru_logger import initialize_logger
from swarms.structs.swarm_id_generator import generate_swarm_id

Expand Down Expand Up @@ -364,11 +358,6 @@ def run(
self,
task: Optional[str] = None,
img: Optional[str] = None,
is_last: bool = False,
device: str = "cpu", # gpu
device_id: int = 0,
all_cores: bool = True, # Defaults to using all available cores
all_gpus: bool = False,
*args,
**kwargs,
) -> Any:
Expand Down Expand Up @@ -399,41 +388,7 @@ def run(
self.tasks.append(task)

try:
logger.info(f"Attempting to run on device: {device}")
if device == "cpu":
logger.info("Device set to CPU")
if all_cores is True:
count = os.cpu_count()
logger.info(
f"Using all available CPU cores: {count}"
)
else:
count = device_id
logger.info(f"Using specific CPU core: {count}")

return execute_with_cpu_cores(
count, self._run, task, img, *args, **kwargs
)

elif device == "gpu":
logger.info("Device set to GPU")
return execute_on_gpu(
device_id, self._run, task, img, *args, **kwargs
)

elif all_gpus is True:
return execute_on_multiple_gpus(
[int(gpu) for gpu in list_available_gpus()],
self._run,
task,
img,
*args,
**kwargs,
)
else:
raise ValueError(
f"Invalid device specified: {device}. Supported devices are 'cpu' and 'gpu'."
)
return self._run(task, img, *args, **kwargs)
except ValueError as e:
logger.error(f"Invalid device specified: {e}")
raise e
Expand Down
8 changes: 4 additions & 4 deletions tests/structs/test_groupchat.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def test_basic_groupchat(report):
max_loops=2,
)

result = chat.run("Say hello!")
chat.run("Say hello!")
report.add_result(
"Basic GroupChat Test",
True,
Expand Down Expand Up @@ -194,7 +194,7 @@ def test_speaker_functions(report):
rules="1. Be unique in your responses\n2. Build on others' points\n3. Stay relevant to your expertise",
)

result = chat.run(prompt)
chat.run(prompt)
report.add_result(
f"Speaker Function - {name}",
True,
Expand Down Expand Up @@ -222,7 +222,7 @@ def test_varying_agent_counts(report):
name=f"{count}-Agent Test", agents=agents, max_loops=2
)

result = chat.run("Introduce yourselves briefly.")
chat.run("Introduce yourselves briefly.")
report.add_result(
f"Agent Count Test - {count} agents",
True,
Expand Down Expand Up @@ -352,7 +352,7 @@ def test_conversation_rules(report):
""",
)

result = chat.run(
chat.run(
"How can we ensure ethical AI development across different sectors?"
)
report.add_result(
Expand Down

0 comments on commit 07f4dd1

Please sign in to comment.