[IMPROVEMENT][AgentRearrange][Integrate concurrent agent execution in agent rearrange through the comma type] [AgentRearrange][Docs]
parent
0813594074
commit
db8437f52c
@ -1,42 +1,31 @@
|
||||
from swarms import Agent, MultiAgentRouter
|
||||
from swarms.structs.agent import Agent
|
||||
from swarms.structs.multi_agent_router import MultiAgentRouter
|
||||
|
||||
# Example usage:
|
||||
if __name__ == "__main__":
|
||||
# Define some example agents
|
||||
agents = [
|
||||
Agent(
|
||||
agent_name="ResearchAgent",
|
||||
description="Specializes in researching topics and providing detailed, factual information",
|
||||
system_prompt="You are a research specialist. Provide detailed, well-researched information about any topic, citing sources when possible.",
|
||||
model_name="openai/gpt-4o",
|
||||
),
|
||||
Agent(
|
||||
agent_name="CodeExpertAgent",
|
||||
description="Expert in writing, reviewing, and explaining code across multiple programming languages",
|
||||
system_prompt="You are a coding expert. Write, review, and explain code with a focus on best practices and clean code principles.",
|
||||
model_name="openai/gpt-4o",
|
||||
),
|
||||
Agent(
|
||||
agent_name="WritingAgent",
|
||||
description="Skilled in creative and technical writing, content creation, and editing",
|
||||
system_prompt="You are a writing specialist. Create, edit, and improve written content while maintaining appropriate tone and style.",
|
||||
model_name="openai/gpt-4o",
|
||||
),
|
||||
]
|
||||
agents = [
|
||||
Agent(
|
||||
agent_name="ResearchAgent",
|
||||
agent_description="Specializes in researching topics and providing detailed, factual information",
|
||||
system_prompt="You are a research specialist. Provide detailed, well-researched information about any topic, citing sources when possible.",
|
||||
),
|
||||
Agent(
|
||||
agent_name="CodeExpertAgent",
|
||||
agent_description="Expert in writing, reviewing, and explaining code across multiple programming languages",
|
||||
system_prompt="You are a coding expert. Write, review, and explain code with a focus on best practices and clean code principles.",
|
||||
),
|
||||
Agent(
|
||||
agent_name="WritingAgent",
|
||||
agent_description="Skilled in creative and technical writing, content creation, and editing",
|
||||
system_prompt="You are a writing specialist. Create, edit, and improve written content while maintaining appropriate tone and style.",
|
||||
),
|
||||
]
|
||||
|
||||
# Initialize routers with different configurations
|
||||
router_execute = MultiAgentRouter(
|
||||
agents=agents, execute_task=True
|
||||
)
|
||||
# Initialize routers with different configurations
|
||||
router_execute = MultiAgentRouter(
|
||||
agents=agents, temperature=0.5, model="claude-sonnet-4-20250514"
|
||||
)
|
||||
|
||||
# Example task
|
||||
task = "Write a Python function to calculate fibonacci numbers"
|
||||
|
||||
try:
|
||||
# Process the task with execution
|
||||
print("\nWith task execution:")
|
||||
result_execute = router_execute.route_task(task)
|
||||
print(result_execute)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error occurred: {str(e)}")
|
||||
# Example task: Remake the Fibonacci task
|
||||
task = "Use all the agents available to you to remake the Fibonacci function in Python, providing both an explanation and code."
|
||||
result_execute = router_execute.run(task)
|
||||
print(result_execute)
|
||||
|
@ -1,20 +1,14 @@
|
||||
from swarms import Agent
|
||||
from swarms.prompts.finance_agent_sys_prompt import (
|
||||
FINANCIAL_AGENT_SYS_PROMPT,
|
||||
)
|
||||
from swarms_tools import yahoo_finance_api
|
||||
from swarms_tools.finance.okx_tool import okx_api_tool
|
||||
|
||||
# Initialize the agent
|
||||
agent = Agent(
|
||||
agent_name="Financial-Analysis-Agent",
|
||||
agent_description="Personal finance advisor agent",
|
||||
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
|
||||
max_loops=1,
|
||||
model_name="gpt-4o-mini",
|
||||
tools=[yahoo_finance_api],
|
||||
tools=[okx_api_tool],
|
||||
dynamic_temperature_enabled=True,
|
||||
)
|
||||
|
||||
agent.run(
|
||||
"Fetch the data for nvidia and tesla both with the yahoo finance api"
|
||||
)
|
||||
agent.run("fetch the current price of bitcoin with okx")
|
||||
|
@ -0,0 +1,63 @@
|
||||
from swarms.structs.agent import Agent
|
||||
|
||||
# Agent 1: Risk Metrics Calculator
|
||||
risk_metrics_agent = Agent(
|
||||
agent_name="Risk-Metrics-Calculator",
|
||||
agent_description="Calculates key risk metrics like VaR, Sharpe ratio, and volatility",
|
||||
system_prompt="""You are a risk metrics specialist. Calculate and explain:
|
||||
- Value at Risk (VaR)
|
||||
- Sharpe ratio
|
||||
- Volatility
|
||||
- Maximum drawdown
|
||||
- Beta coefficient
|
||||
|
||||
Provide clear, numerical results with brief explanations.""",
|
||||
max_loops=1,
|
||||
model_name="gpt-4o-mini",
|
||||
dynamic_temperature_enabled=True,
|
||||
)
|
||||
|
||||
|
||||
# Agent 3: Market Risk Monitor
|
||||
market_risk_agent = Agent(
|
||||
agent_name="Market-Risk-Monitor",
|
||||
agent_description="Monitors market conditions and identifies risk factors",
|
||||
system_prompt="""You are a market risk monitor. Identify and assess:
|
||||
- Market volatility trends
|
||||
- Economic risk factors
|
||||
- Geopolitical risks
|
||||
- Interest rate risks
|
||||
- Currency risks
|
||||
|
||||
Provide current risk alerts and trends.""",
|
||||
max_loops=1,
|
||||
dynamic_temperature_enabled=True,
|
||||
)
|
||||
|
||||
|
||||
# Agent 2: Portfolio Risk Analyzer
|
||||
portfolio_risk_agent = Agent(
|
||||
agent_name="Portfolio-Risk-Analyzer",
|
||||
agent_description="Analyzes portfolio diversification and concentration risk",
|
||||
system_prompt="""You are a portfolio risk analyst. Focus on:
|
||||
- Portfolio diversification analysis
|
||||
- Concentration risk assessment
|
||||
- Correlation analysis
|
||||
- Sector/asset allocation risk
|
||||
- Liquidity risk evaluation
|
||||
|
||||
Provide actionable insights for risk reduction.""",
|
||||
max_loops=1,
|
||||
dynamic_temperature_enabled=True,
|
||||
handoffs=[
|
||||
risk_metrics_agent,
|
||||
market_risk_agent,
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
out = portfolio_risk_agent.run(
|
||||
"Calculate VaR and Sharpe ratio for a portfolio with 15% annual return and 20% volatility using the risk metrics agent and market risk agent"
|
||||
)
|
||||
|
||||
print(out)
|
@ -0,0 +1,86 @@
|
||||
from swarms import Agent, AgentRearrange
|
||||
|
||||
# Define all prompts as strings before agent initializations
|
||||
boss_agent_prompt = """
|
||||
You are the BossAgent responsible for managing and overseeing a swarm of agents analyzing company expenses.
|
||||
Your job is to dynamically assign tasks, prioritize their execution, and ensure that all agents collaborate efficiently.
|
||||
After receiving a report on the company's expenses, you will break down the work into smaller tasks,
|
||||
assigning specific tasks to each agent, such as detecting recurring high costs, categorizing expenditures,
|
||||
and identifying unnecessary transactions. Ensure the results are communicated back in a structured way
|
||||
so the finance team can take actionable steps to cut off unproductive spending. You also monitor and
|
||||
dynamically adapt the swarm to optimize their performance. Finally, you summarize their findings
|
||||
into a coherent report.
|
||||
"""
|
||||
|
||||
expense_analyzer_prompt = """
|
||||
Your task is to carefully analyze the company's expense data provided to you.
|
||||
You will focus on identifying high-cost recurring transactions, categorizing expenditures
|
||||
(e.g., marketing, operations, utilities, etc.), and flagging areas where there seems to be excessive spending.
|
||||
You will provide a detailed breakdown of each category, along with specific recommendations for cost-cutting.
|
||||
Pay close attention to monthly recurring subscriptions, office supplies, and non-essential expenditures.
|
||||
"""
|
||||
|
||||
summary_generator_prompt = """
|
||||
After receiving the detailed breakdown from the ExpenseAnalyzer,
|
||||
your task is to create a concise summary of the findings. You will focus on the most actionable insights,
|
||||
such as highlighting the specific transactions that can be immediately cut off and summarizing the areas
|
||||
where the company is overspending. Your summary will be used by the BossAgent to generate the final report.
|
||||
Be clear and to the point, emphasizing the urgency of cutting unnecessary expenses.
|
||||
"""
|
||||
|
||||
# Swarm-Level Prompt (Collaboration Prompt)
|
||||
swarm_prompt = """
|
||||
As a swarm, your collective goal is to analyze the company's expenses and identify transactions that should be cut off.
|
||||
You will work collaboratively to break down the entire process of expense analysis into manageable steps.
|
||||
The BossAgent will direct the flow and assign tasks dynamically to the agents. The ExpenseAnalyzer will first
|
||||
focus on breaking down the expense report, identifying high-cost recurring transactions, categorizing them,
|
||||
and providing recommendations for potential cost reduction. After the analysis, the SummaryGenerator will then
|
||||
consolidate all the findings into an actionable summary that the finance team can use to immediately cut off unnecessary expenses.
|
||||
Together, your collaboration is essential to streamlining and improving the company's financial health.
|
||||
"""
|
||||
|
||||
# Initialize the boss agent (Director)
|
||||
boss_agent = Agent(
|
||||
agent_name="BossAgent",
|
||||
system_prompt=boss_agent_prompt,
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Initialize worker 1: Expense Analyzer
|
||||
worker1 = Agent(
|
||||
agent_name="ExpenseAnalyzer",
|
||||
system_prompt=expense_analyzer_prompt,
|
||||
max_loops=1,
|
||||
dashboard=False,
|
||||
)
|
||||
|
||||
# Initialize worker 2: Summary Generator
|
||||
worker2 = Agent(
|
||||
agent_name="SummaryGenerator",
|
||||
system_prompt=summary_generator_prompt,
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Create a list of agents
|
||||
agents = [boss_agent, worker1, worker2]
|
||||
|
||||
# Define the flow pattern for the swarm
|
||||
flow = "BossAgent -> ExpenseAnalyzer, SummaryGenerator"
|
||||
|
||||
# Using AgentRearrange class to manage the swarm
|
||||
agent_system = AgentRearrange(agents=agents, flow=flow)
|
||||
|
||||
# Input task for the swarm
|
||||
task = f"""
|
||||
|
||||
{swarm_prompt}
|
||||
|
||||
The company has been facing a rising number of unnecessary expenses, and the finance team needs a detailed
|
||||
analysis of recent transactions to identify which expenses can be cut off to improve profitability.
|
||||
Analyze the provided transaction data and create a detailed report on cost-cutting opportunities,
|
||||
focusing on recurring transactions and non-essential expenditures.
|
||||
"""
|
||||
|
||||
# Run the swarm system with the task
|
||||
output = agent_system.run(task)
|
||||
print(output)
|
Loading…
Reference in new issue